smbd: Move oplock/sharemode ops into one place
[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 {
1119         int i;
1120
1121         if(lck->data->num_share_modes == 0) {
1122                 return NT_STATUS_OK;
1123         }
1124
1125         if (is_stat_open(access_mask)) {
1126                 /* Stat open that doesn't trigger oplock breaks or share mode
1127                  * checks... ! JRA. */
1128                 return NT_STATUS_OK;
1129         }
1130
1131         /*
1132          * Check if the share modes will give us access.
1133          */
1134
1135 #if defined(DEVELOPER)
1136         for(i = 0; i < lck->data->num_share_modes; i++) {
1137                 validate_my_share_entries(conn->sconn, i,
1138                                           &lck->data->share_modes[i]);
1139         }
1140 #endif
1141
1142         /* Now we check the share modes, after any oplock breaks. */
1143         for(i = 0; i < lck->data->num_share_modes; i++) {
1144
1145                 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1146                         continue;
1147                 }
1148
1149                 /* someone else has a share lock on it, check to see if we can
1150                  * too */
1151                 if (share_conflict(&lck->data->share_modes[i],
1152                                    access_mask, share_access)) {
1153
1154                         if (share_mode_stale_pid(lck->data, i)) {
1155                                 continue;
1156                         }
1157
1158                         return NT_STATUS_SHARING_VIOLATION;
1159                 }
1160         }
1161
1162         return NT_STATUS_OK;
1163 }
1164
1165 /*
1166  * Send a break message to the oplock holder and delay the open for
1167  * our client.
1168  */
1169
1170 static NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1171                                    const struct share_mode_entry *exclusive,
1172                                    uint16_t break_to)
1173 {
1174         NTSTATUS status;
1175         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1176
1177         DEBUG(10, ("Sending break request to PID %s\n",
1178                    procid_str_static(&exclusive->pid)));
1179
1180         /* Create the message. */
1181         share_mode_entry_to_message(msg, exclusive);
1182
1183         /* Overload entry->op_type */
1184         SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1185
1186         status = messaging_send_buf(msg_ctx, exclusive->pid,
1187                                     MSG_SMB_BREAK_REQUEST,
1188                                     (uint8 *)msg, sizeof(msg));
1189         if (!NT_STATUS_IS_OK(status)) {
1190                 DEBUG(3, ("Could not send oplock break message: %s\n",
1191                           nt_errstr(status)));
1192         }
1193
1194         return status;
1195 }
1196
1197 /*
1198  * Do internal consistency checks on the share mode for a file.
1199  */
1200
1201 static bool validate_oplock_types(struct share_mode_lock *lck)
1202 {
1203         struct share_mode_data *d = lck->data;
1204         bool batch = false;
1205         bool ex_or_batch = false;
1206         bool level2 = false;
1207         bool no_oplock = false;
1208         uint32_t num_non_stat_opens = 0;
1209         uint32_t i;
1210
1211         for (i=0; i<d->num_share_modes; i++) {
1212                 struct share_mode_entry *e = &d->share_modes[i];
1213
1214                 if (!is_valid_share_mode_entry(e)) {
1215                         continue;
1216                 }
1217
1218                 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1219                         /* We ignore stat opens in the table - they
1220                            always have NO_OPLOCK and never get or
1221                            cause breaks. JRA. */
1222                         continue;
1223                 }
1224
1225                 num_non_stat_opens += 1;
1226
1227                 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1228                         /* batch - can only be one. */
1229                         if (share_mode_stale_pid(d, i)) {
1230                                 DEBUG(10, ("Found stale batch oplock\n"));
1231                                 continue;
1232                         }
1233                         if (ex_or_batch || batch || level2 || no_oplock) {
1234                                 DEBUG(0, ("Bad batch oplock entry %u.",
1235                                           (unsigned)i));
1236                                 return false;
1237                         }
1238                         batch = true;
1239                 }
1240
1241                 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1242                         if (share_mode_stale_pid(d, i)) {
1243                                 DEBUG(10, ("Found stale duplicate oplock\n"));
1244                                 continue;
1245                         }
1246                         /* Exclusive or batch - can only be one. */
1247                         if (ex_or_batch || level2 || no_oplock) {
1248                                 DEBUG(0, ("Bad exclusive or batch oplock "
1249                                           "entry %u.", (unsigned)i));
1250                                 return false;
1251                         }
1252                         ex_or_batch = true;
1253                 }
1254
1255                 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1256                         if (batch || ex_or_batch) {
1257                                 if (share_mode_stale_pid(d, i)) {
1258                                         DEBUG(10, ("Found stale LevelII "
1259                                                    "oplock\n"));
1260                                         continue;
1261                                 }
1262                                 DEBUG(0, ("Bad levelII oplock entry %u.",
1263                                           (unsigned)i));
1264                                 return false;
1265                         }
1266                         level2 = true;
1267                 }
1268
1269                 if (e->op_type == NO_OPLOCK) {
1270                         if (batch || ex_or_batch) {
1271                                 if (share_mode_stale_pid(d, i)) {
1272                                         DEBUG(10, ("Found stale NO_OPLOCK "
1273                                                    "entry\n"));
1274                                         continue;
1275                                 }
1276                                 DEBUG(0, ("Bad no oplock entry %u.",
1277                                           (unsigned)i));
1278                                 return false;
1279                         }
1280                         no_oplock = true;
1281                 }
1282         }
1283
1284         remove_stale_share_mode_entries(d);
1285
1286         if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1287                 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1288                           (int)batch, (int)ex_or_batch,
1289                           (int)d->num_share_modes));
1290                 return false;
1291         }
1292
1293         return true;
1294 }
1295
1296 static bool delay_for_oplock(files_struct *fsp,
1297                              int oplock_request,
1298                              struct share_mode_lock *lck,
1299                              bool have_sharing_violation,
1300                              uint32_t create_disposition)
1301 {
1302         struct share_mode_data *d = lck->data;
1303         struct share_mode_entry *entry;
1304         uint32_t num_non_stat_opens = 0;
1305         uint32_t i;
1306         uint16_t break_to;
1307
1308         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1309                 return false;
1310         }
1311         for (i=0; i<d->num_share_modes; i++) {
1312                 struct share_mode_entry *e = &d->share_modes[i];
1313                 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1314                         continue;
1315                 }
1316                 num_non_stat_opens += 1;
1317
1318                 /*
1319                  * We found the a non-stat open, which in the exclusive/batch
1320                  * case will be inspected further down.
1321                  */
1322                 entry = e;
1323         }
1324         if (num_non_stat_opens == 0) {
1325                 /*
1326                  * Nothing to wait for around
1327                  */
1328                 return false;
1329         }
1330         if (num_non_stat_opens != 1) {
1331                 /*
1332                  * More than one open around. There can't be any exclusive or
1333                  * batch left, this is all level2.
1334                  */
1335                 return false;
1336         }
1337
1338         if (server_id_is_disconnected(&entry->pid)) {
1339                 /*
1340                  * TODO: clean up.
1341                  * This could be achieved by sending a break message
1342                  * to ourselves. Special considerations for files
1343                  * with delete_on_close flag set!
1344                  *
1345                  * For now we keep it simple and do not
1346                  * allow delete on close for durable handles.
1347                  */
1348                 return false;
1349         }
1350
1351         switch (create_disposition) {
1352         case FILE_SUPERSEDE:
1353         case FILE_OVERWRITE_IF:
1354                 break_to = NO_OPLOCK;
1355                 break;
1356         default:
1357                 break_to = LEVEL_II_OPLOCK;
1358                 break;
1359         }
1360
1361         if (have_sharing_violation && (entry->op_type & BATCH_OPLOCK)) {
1362                 if (share_mode_stale_pid(d, 0)) {
1363                         return false;
1364                 }
1365                 send_break_message(fsp->conn->sconn->msg_ctx, entry, break_to);
1366                 return true;
1367         }
1368         if (have_sharing_violation) {
1369                 /*
1370                  * Non-batch exclusive is not broken if we have a sharing
1371                  * violation
1372                  */
1373                 return false;
1374         }
1375         if (LEVEL_II_OPLOCK_TYPE(entry->op_type) &&
1376             (break_to == NO_OPLOCK)) {
1377                 if (share_mode_stale_pid(d, 0)) {
1378                         return false;
1379                 }
1380                 DEBUG(10, ("Asynchronously breaking level2 oplock for "
1381                            "create_disposition=%u\n",
1382                            (unsigned)create_disposition));
1383                 send_break_message(fsp->conn->sconn->msg_ctx, entry, break_to);
1384                 return false;
1385         }
1386         if (!EXCLUSIVE_OPLOCK_TYPE(entry->op_type)) {
1387                 /*
1388                  * No break for NO_OPLOCK or LEVEL2_OPLOCK oplocks
1389                  */
1390                 return false;
1391         }
1392         if (share_mode_stale_pid(d, 0)) {
1393                 return false;
1394         }
1395
1396         send_break_message(fsp->conn->sconn->msg_ctx, entry, break_to);
1397         return true;
1398 }
1399
1400 static bool file_has_brlocks(files_struct *fsp)
1401 {
1402         struct byte_range_lock *br_lck;
1403
1404         br_lck = brl_get_locks_readonly(fsp);
1405         if (!br_lck)
1406                 return false;
1407
1408         return (brl_num_locks(br_lck) > 0);
1409 }
1410
1411 static void grant_fsp_oplock_type(files_struct *fsp,
1412                                   struct share_mode_lock *lck,
1413                                   int oplock_request)
1414 {
1415         bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1416                             lp_level2_oplocks(SNUM(fsp->conn));
1417         bool got_level2_oplock, got_a_none_oplock;
1418         uint32_t i;
1419
1420         /* Start by granting what the client asked for,
1421            but ensure no SAMBA_PRIVATE bits can be set. */
1422         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1423
1424         if (oplock_request & INTERNAL_OPEN_ONLY) {
1425                 /* No oplocks on internal open. */
1426                 fsp->oplock_type = NO_OPLOCK;
1427                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1428                         fsp->oplock_type, fsp_str_dbg(fsp)));
1429                 return;
1430         }
1431
1432         if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1433                 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1434                         fsp_str_dbg(fsp)));
1435                 fsp->oplock_type = NO_OPLOCK;
1436         }
1437
1438         got_level2_oplock = false;
1439         got_a_none_oplock = false;
1440
1441         for (i=0; i<lck->data->num_share_modes; i++) {
1442                 int op_type = lck->data->share_modes[i].op_type;
1443
1444                 if (LEVEL_II_OPLOCK_TYPE(op_type)) {
1445                         got_level2_oplock = true;
1446                 }
1447                 if (op_type == NO_OPLOCK) {
1448                         got_a_none_oplock = true;
1449                 }
1450         }
1451
1452         /*
1453          * Match what was requested (fsp->oplock_type) with
1454          * what was found in the existing share modes.
1455          */
1456
1457         if (got_level2_oplock || got_a_none_oplock) {
1458                 if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1459                         fsp->oplock_type = LEVEL_II_OPLOCK;
1460                 }
1461         }
1462
1463         /*
1464          * Don't grant level2 to clients that don't want them
1465          * or if we've turned them off.
1466          */
1467         if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1468                 fsp->oplock_type = NO_OPLOCK;
1469         }
1470
1471         if (fsp->oplock_type == LEVEL_II_OPLOCK && !got_level2_oplock) {
1472                 /*
1473                  * We're the first level2 oplock. Indicate that in brlock.tdb.
1474                  */
1475                 struct byte_range_lock *brl;
1476
1477                 brl = brl_get_locks(talloc_tos(), fsp);
1478                 if (brl != NULL) {
1479                         brl_set_have_read_oplocks(brl, true);
1480                         TALLOC_FREE(brl);
1481                 }
1482         }
1483
1484         DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1485                   fsp->oplock_type, fsp_str_dbg(fsp)));
1486 }
1487
1488 static bool request_timed_out(struct timeval request_time,
1489                               struct timeval timeout)
1490 {
1491         struct timeval now, end_time;
1492         GetTimeOfDay(&now);
1493         end_time = timeval_sum(&request_time, &timeout);
1494         return (timeval_compare(&end_time, &now) < 0);
1495 }
1496
1497 struct defer_open_state {
1498         struct smbd_server_connection *sconn;
1499         uint64_t mid;
1500 };
1501
1502 static void defer_open_done(struct tevent_req *req);
1503
1504 /****************************************************************************
1505  Handle the 1 second delay in returning a SHARING_VIOLATION error.
1506 ****************************************************************************/
1507
1508 static void defer_open(struct share_mode_lock *lck,
1509                        struct timeval request_time,
1510                        struct timeval timeout,
1511                        struct smb_request *req,
1512                        struct deferred_open_record *state)
1513 {
1514         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1515                   "open entry for mid %llu\n",
1516                   (unsigned int)request_time.tv_sec,
1517                   (unsigned int)request_time.tv_usec,
1518                   (unsigned long long)req->mid));
1519
1520         if (!push_deferred_open_message_smb(req, request_time, timeout,
1521                                        state->id, (char *)state, sizeof(*state))) {
1522                 TALLOC_FREE(lck);
1523                 exit_server("push_deferred_open_message_smb failed");
1524         }
1525         if (lck) {
1526                 struct defer_open_state *watch_state;
1527                 struct tevent_req *watch_req;
1528                 bool ret;
1529
1530                 watch_state = talloc(req->sconn, struct defer_open_state);
1531                 if (watch_state == NULL) {
1532                         exit_server("talloc failed");
1533                 }
1534                 watch_state->sconn = req->sconn;
1535                 watch_state->mid = req->mid;
1536
1537                 DEBUG(10, ("defering mid %llu\n",
1538                            (unsigned long long)req->mid));
1539
1540                 watch_req = dbwrap_record_watch_send(
1541                         watch_state, req->sconn->ev_ctx, lck->data->record,
1542                         req->sconn->msg_ctx);
1543                 if (watch_req == NULL) {
1544                         exit_server("Could not watch share mode record");
1545                 }
1546                 tevent_req_set_callback(watch_req, defer_open_done,
1547                                         watch_state);
1548
1549                 ret = tevent_req_set_endtime(
1550                         watch_req, req->sconn->ev_ctx,
1551                         timeval_sum(&request_time, &timeout));
1552                 SMB_ASSERT(ret);
1553         }
1554 }
1555
1556 static void defer_open_done(struct tevent_req *req)
1557 {
1558         struct defer_open_state *state = tevent_req_callback_data(
1559                 req, struct defer_open_state);
1560         NTSTATUS status;
1561         bool ret;
1562
1563         status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1564         TALLOC_FREE(req);
1565         if (!NT_STATUS_IS_OK(status)) {
1566                 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1567                           nt_errstr(status)));
1568                 /*
1569                  * Even if it failed, retry anyway. TODO: We need a way to
1570                  * tell a re-scheduled open about that error.
1571                  */
1572         }
1573
1574         DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1575
1576         ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1577         SMB_ASSERT(ret);
1578         TALLOC_FREE(state);
1579 }
1580
1581
1582 /****************************************************************************
1583  On overwrite open ensure that the attributes match.
1584 ****************************************************************************/
1585
1586 static bool open_match_attributes(connection_struct *conn,
1587                                   uint32 old_dos_attr,
1588                                   uint32 new_dos_attr,
1589                                   mode_t existing_unx_mode,
1590                                   mode_t new_unx_mode,
1591                                   mode_t *returned_unx_mode)
1592 {
1593         uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1594
1595         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1596         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1597
1598         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
1599            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1600                 *returned_unx_mode = new_unx_mode;
1601         } else {
1602                 *returned_unx_mode = (mode_t)0;
1603         }
1604
1605         DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1606                   "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1607                   "returned_unx_mode = 0%o\n",
1608                   (unsigned int)old_dos_attr,
1609                   (unsigned int)existing_unx_mode,
1610                   (unsigned int)new_dos_attr,
1611                   (unsigned int)*returned_unx_mode ));
1612
1613         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1614         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1615                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1616                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1617                         return False;
1618                 }
1619         }
1620         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1621                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1622                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1623                         return False;
1624                 }
1625         }
1626         return True;
1627 }
1628
1629 /****************************************************************************
1630  Special FCB or DOS processing in the case of a sharing violation.
1631  Try and find a duplicated file handle.
1632 ****************************************************************************/
1633
1634 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1635                                 connection_struct *conn,
1636                                 files_struct *fsp_to_dup_into,
1637                                 const struct smb_filename *smb_fname,
1638                                 struct file_id id,
1639                                 uint16 file_pid,
1640                                 uint64_t vuid,
1641                                 uint32 access_mask,
1642                                 uint32 share_access,
1643                                 uint32 create_options)
1644 {
1645         files_struct *fsp;
1646
1647         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1648                  "file %s.\n", smb_fname_str_dbg(smb_fname)));
1649
1650         for(fsp = file_find_di_first(conn->sconn, id); fsp;
1651             fsp = file_find_di_next(fsp)) {
1652
1653                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1654                           "vuid = %llu, file_pid = %u, private_options = 0x%x "
1655                           "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1656                           fsp->fh->fd, (unsigned long long)fsp->vuid,
1657                           (unsigned int)fsp->file_pid,
1658                           (unsigned int)fsp->fh->private_options,
1659                           (unsigned int)fsp->access_mask ));
1660
1661                 if (fsp != fsp_to_dup_into &&
1662                     fsp->fh->fd != -1 &&
1663                     fsp->vuid == vuid &&
1664                     fsp->file_pid == file_pid &&
1665                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1666                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1667                     (fsp->access_mask & FILE_WRITE_DATA) &&
1668                     strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1669                     strequal(fsp->fsp_name->stream_name,
1670                              smb_fname->stream_name)) {
1671                         DEBUG(10,("fcb_or_dos_open: file match\n"));
1672                         break;
1673                 }
1674         }
1675
1676         if (!fsp) {
1677                 return NT_STATUS_NOT_FOUND;
1678         }
1679
1680         /* quite an insane set of semantics ... */
1681         if (is_executable(smb_fname->base_name) &&
1682             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1683                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1684                 return NT_STATUS_INVALID_PARAMETER;
1685         }
1686
1687         /* We need to duplicate this fsp. */
1688         return dup_file_fsp(req, fsp, access_mask, share_access,
1689                             create_options, fsp_to_dup_into);
1690 }
1691
1692 static void schedule_defer_open(struct share_mode_lock *lck,
1693                                 struct timeval request_time,
1694                                 struct smb_request *req)
1695 {
1696         struct deferred_open_record state;
1697
1698         /* This is a relative time, added to the absolute
1699            request_time value to get the absolute timeout time.
1700            Note that if this is the second or greater time we enter
1701            this codepath for this particular request mid then
1702            request_time is left as the absolute time of the *first*
1703            time this request mid was processed. This is what allows
1704            the request to eventually time out. */
1705
1706         struct timeval timeout;
1707
1708         /* Normally the smbd we asked should respond within
1709          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1710          * the client did, give twice the timeout as a safety
1711          * measure here in case the other smbd is stuck
1712          * somewhere else. */
1713
1714         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1715
1716         /* Nothing actually uses state.delayed_for_oplocks
1717            but it's handy to differentiate in debug messages
1718            between a 30 second delay due to oplock break, and
1719            a 1 second delay for share mode conflicts. */
1720
1721         state.delayed_for_oplocks = True;
1722         state.async_open = false;
1723         state.id = lck->data->id;
1724
1725         if (!request_timed_out(request_time, timeout)) {
1726                 defer_open(lck, request_time, timeout, req, &state);
1727         }
1728 }
1729
1730 /****************************************************************************
1731  Reschedule an open call that went asynchronous.
1732 ****************************************************************************/
1733
1734 static void schedule_async_open(struct timeval request_time,
1735                                 struct smb_request *req)
1736 {
1737         struct deferred_open_record state;
1738         struct timeval timeout;
1739
1740         timeout = timeval_set(20, 0);
1741
1742         ZERO_STRUCT(state);
1743         state.delayed_for_oplocks = false;
1744         state.async_open = true;
1745
1746         if (!request_timed_out(request_time, timeout)) {
1747                 defer_open(NULL, request_time, timeout, req, &state);
1748         }
1749 }
1750
1751 /****************************************************************************
1752  Work out what access_mask to use from what the client sent us.
1753 ****************************************************************************/
1754
1755 static NTSTATUS smbd_calculate_maximum_allowed_access(
1756         connection_struct *conn,
1757         const struct smb_filename *smb_fname,
1758         bool use_privs,
1759         uint32_t *p_access_mask)
1760 {
1761         struct security_descriptor *sd;
1762         uint32_t access_granted;
1763         NTSTATUS status;
1764
1765         if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1766                 *p_access_mask |= FILE_GENERIC_ALL;
1767                 return NT_STATUS_OK;
1768         }
1769
1770         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1771                                     (SECINFO_OWNER |
1772                                      SECINFO_GROUP |
1773                                      SECINFO_DACL),
1774                                     talloc_tos(), &sd);
1775
1776         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1777                 /*
1778                  * File did not exist
1779                  */
1780                 *p_access_mask = FILE_GENERIC_ALL;
1781                 return NT_STATUS_OK;
1782         }
1783         if (!NT_STATUS_IS_OK(status)) {
1784                 DEBUG(10,("Could not get acl on file %s: %s\n",
1785                           smb_fname_str_dbg(smb_fname),
1786                           nt_errstr(status)));
1787                 return NT_STATUS_ACCESS_DENIED;
1788         }
1789
1790         /*
1791          * If we can access the path to this file, by
1792          * default we have FILE_READ_ATTRIBUTES from the
1793          * containing directory. See the section:
1794          * "Algorithm to Check Access to an Existing File"
1795          * in MS-FSA.pdf.
1796          *
1797          * se_file_access_check()
1798          * also takes care of owner WRITE_DAC and READ_CONTROL.
1799          */
1800         status = se_file_access_check(sd,
1801                                  get_current_nttok(conn),
1802                                  use_privs,
1803                                  (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1804                                  &access_granted);
1805
1806         TALLOC_FREE(sd);
1807
1808         if (!NT_STATUS_IS_OK(status)) {
1809                 DEBUG(10, ("Access denied on file %s: "
1810                            "when calculating maximum access\n",
1811                            smb_fname_str_dbg(smb_fname)));
1812                 return NT_STATUS_ACCESS_DENIED;
1813         }
1814         *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1815
1816         if (!(access_granted & DELETE_ACCESS)) {
1817                 if (can_delete_file_in_directory(conn, smb_fname)) {
1818                         *p_access_mask |= DELETE_ACCESS;
1819                 }
1820         }
1821
1822         return NT_STATUS_OK;
1823 }
1824
1825 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1826                                     const struct smb_filename *smb_fname,
1827                                     bool use_privs,
1828                                     uint32_t access_mask,
1829                                     uint32_t *access_mask_out)
1830 {
1831         NTSTATUS status;
1832         uint32_t orig_access_mask = access_mask;
1833         uint32_t rejected_share_access;
1834
1835         /*
1836          * Convert GENERIC bits to specific bits.
1837          */
1838
1839         se_map_generic(&access_mask, &file_generic_mapping);
1840
1841         /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1842         if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1843
1844                 status = smbd_calculate_maximum_allowed_access(
1845                         conn, smb_fname, use_privs, &access_mask);
1846
1847                 if (!NT_STATUS_IS_OK(status)) {
1848                         return status;
1849                 }
1850
1851                 access_mask &= conn->share_access;
1852         }
1853
1854         rejected_share_access = access_mask & ~(conn->share_access);
1855
1856         if (rejected_share_access) {
1857                 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1858                         "file %s: rejected by share access mask[0x%08X] "
1859                         "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1860                         smb_fname_str_dbg(smb_fname),
1861                         conn->share_access,
1862                         orig_access_mask, access_mask,
1863                         rejected_share_access));
1864                 return NT_STATUS_ACCESS_DENIED;
1865         }
1866
1867         *access_mask_out = access_mask;
1868         return NT_STATUS_OK;
1869 }
1870
1871 /****************************************************************************
1872  Remove the deferred open entry under lock.
1873 ****************************************************************************/
1874
1875 /****************************************************************************
1876  Return true if this is a state pointer to an asynchronous create.
1877 ****************************************************************************/
1878
1879 bool is_deferred_open_async(const void *ptr)
1880 {
1881         const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1882
1883         return state->async_open;
1884 }
1885
1886 static bool clear_ads(uint32_t create_disposition)
1887 {
1888         bool ret = false;
1889
1890         switch (create_disposition) {
1891         case FILE_SUPERSEDE:
1892         case FILE_OVERWRITE_IF:
1893         case FILE_OVERWRITE:
1894                 ret = true;
1895                 break;
1896         default:
1897                 break;
1898         }
1899         return ret;
1900 }
1901
1902 static int disposition_to_open_flags(uint32_t create_disposition)
1903 {
1904         int ret = 0;
1905
1906         /*
1907          * Currently we're using FILE_SUPERSEDE as the same as
1908          * FILE_OVERWRITE_IF but they really are
1909          * different. FILE_SUPERSEDE deletes an existing file
1910          * (requiring delete access) then recreates it.
1911          */
1912
1913         switch (create_disposition) {
1914         case FILE_SUPERSEDE:
1915         case FILE_OVERWRITE_IF:
1916                 /*
1917                  * If file exists replace/overwrite. If file doesn't
1918                  * exist create.
1919                  */
1920                 ret = O_CREAT|O_TRUNC;
1921                 break;
1922
1923         case FILE_OPEN:
1924                 /*
1925                  * If file exists open. If file doesn't exist error.
1926                  */
1927                 ret = 0;
1928                 break;
1929
1930         case FILE_OVERWRITE:
1931                 /*
1932                  * If file exists overwrite. If file doesn't exist
1933                  * error.
1934                  */
1935                 ret = O_TRUNC;
1936                 break;
1937
1938         case FILE_CREATE:
1939                 /*
1940                  * If file exists error. If file doesn't exist create.
1941                  */
1942                 ret = O_CREAT|O_EXCL;
1943                 break;
1944
1945         case FILE_OPEN_IF:
1946                 /*
1947                  * If file exists open. If file doesn't exist create.
1948                  */
1949                 ret = O_CREAT;
1950                 break;
1951         }
1952         return ret;
1953 }
1954
1955 static int calculate_open_access_flags(uint32_t access_mask,
1956                                        int oplock_request,
1957                                        uint32_t private_flags)
1958 {
1959         bool need_write, need_read;
1960
1961         /*
1962          * Note that we ignore the append flag as append does not
1963          * mean the same thing under DOS and Unix.
1964          */
1965
1966         need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
1967         if (!need_write) {
1968                 return O_RDONLY;
1969         }
1970
1971         /* DENY_DOS opens are always underlying read-write on the
1972            file handle, no matter what the requested access mask
1973            says. */
1974
1975         need_read =
1976                 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1977                  access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1978                                 FILE_READ_EA|FILE_EXECUTE));
1979
1980         if (!need_read) {
1981                 return O_WRONLY;
1982         }
1983         return O_RDWR;
1984 }
1985
1986 /****************************************************************************
1987  Open a file with a share mode. Passed in an already created files_struct *.
1988 ****************************************************************************/
1989
1990 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1991                             struct smb_request *req,
1992                             uint32 access_mask,         /* access bits (FILE_READ_DATA etc.) */
1993                             uint32 share_access,        /* share constants (FILE_SHARE_READ etc) */
1994                             uint32 create_disposition,  /* FILE_OPEN_IF etc. */
1995                             uint32 create_options,      /* options such as delete on close. */
1996                             uint32 new_dos_attributes,  /* attributes used for new file. */
1997                             int oplock_request,         /* internal Samba oplock codes. */
1998                                                         /* Information (FILE_EXISTS etc.) */
1999                             uint32_t private_flags,     /* Samba specific flags. */
2000                             int *pinfo,
2001                             files_struct *fsp)
2002 {
2003         struct smb_filename *smb_fname = fsp->fsp_name;
2004         int flags=0;
2005         int flags2=0;
2006         bool file_existed = VALID_STAT(smb_fname->st);
2007         bool def_acl = False;
2008         bool posix_open = False;
2009         bool new_file_created = False;
2010         bool first_open_attempt = true;
2011         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2012         mode_t new_unx_mode = (mode_t)0;
2013         mode_t unx_mode = (mode_t)0;
2014         int info;
2015         uint32 existing_dos_attributes = 0;
2016         struct timeval request_time = timeval_zero();
2017         struct share_mode_lock *lck = NULL;
2018         uint32 open_access_mask = access_mask;
2019         NTSTATUS status;
2020         char *parent_dir;
2021         SMB_STRUCT_STAT saved_stat = smb_fname->st;
2022         struct timespec old_write_time;
2023         struct file_id id;
2024
2025         if (conn->printer) {
2026                 /*
2027                  * Printers are handled completely differently.
2028                  * Most of the passed parameters are ignored.
2029                  */
2030
2031                 if (pinfo) {
2032                         *pinfo = FILE_WAS_CREATED;
2033                 }
2034
2035                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2036                            smb_fname_str_dbg(smb_fname)));
2037
2038                 if (!req) {
2039                         DEBUG(0,("open_file_ntcreate: printer open without "
2040                                 "an SMB request!\n"));
2041                         return NT_STATUS_INTERNAL_ERROR;
2042                 }
2043
2044                 return print_spool_open(fsp, smb_fname->base_name,
2045                                         req->vuid);
2046         }
2047
2048         if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2049                             NULL)) {
2050                 return NT_STATUS_NO_MEMORY;
2051         }
2052
2053         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2054                 posix_open = True;
2055                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2056                 new_dos_attributes = 0;
2057         } else {
2058                 /* Windows allows a new file to be created and
2059                    silently removes a FILE_ATTRIBUTE_DIRECTORY
2060                    sent by the client. Do the same. */
2061
2062                 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2063
2064                 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2065                  * created new. */
2066                 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2067                                      smb_fname, parent_dir);
2068         }
2069
2070         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2071                    "access_mask=0x%x share_access=0x%x "
2072                    "create_disposition = 0x%x create_options=0x%x "
2073                    "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2074                    smb_fname_str_dbg(smb_fname), new_dos_attributes,
2075                    access_mask, share_access, create_disposition,
2076                    create_options, (unsigned int)unx_mode, oplock_request,
2077                    (unsigned int)private_flags));
2078
2079         if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2080                 DEBUG(0, ("No smb request but not an internal only open!\n"));
2081                 return NT_STATUS_INTERNAL_ERROR;
2082         }
2083
2084         /*
2085          * Only non-internal opens can be deferred at all
2086          */
2087
2088         if (req) {
2089                 void *ptr;
2090                 if (get_deferred_open_message_state(req,
2091                                 &request_time,
2092                                 &ptr)) {
2093                         /* Remember the absolute time of the original
2094                            request with this mid. We'll use it later to
2095                            see if this has timed out. */
2096
2097                         /* If it was an async create retry, the file
2098                            didn't exist. */
2099
2100                         if (is_deferred_open_async(ptr)) {
2101                                 SET_STAT_INVALID(smb_fname->st);
2102                                 file_existed = false;
2103                         }
2104
2105                         /* Ensure we don't reprocess this message. */
2106                         remove_deferred_open_message_smb(req->sconn, req->mid);
2107
2108                         first_open_attempt = false;
2109                 }
2110         }
2111
2112         if (!posix_open) {
2113                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2114                 if (file_existed) {
2115                         existing_dos_attributes = dos_mode(conn, smb_fname);
2116                 }
2117         }
2118
2119         /* ignore any oplock requests if oplocks are disabled */
2120         if (!lp_oplocks(SNUM(conn)) ||
2121             IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2122                 /* Mask off everything except the private Samba bits. */
2123                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2124         }
2125
2126         /* this is for OS/2 long file names - say we don't support them */
2127         if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2128                 /* OS/2 Workplace shell fix may be main code stream in a later
2129                  * release. */
2130                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2131                          "supported.\n"));
2132                 if (use_nt_status()) {
2133                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2134                 }
2135                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2136         }
2137
2138         switch( create_disposition ) {
2139                 case FILE_OPEN:
2140                         /* If file exists open. If file doesn't exist error. */
2141                         if (!file_existed) {
2142                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2143                                          "requested for file %s and file "
2144                                          "doesn't exist.\n",
2145                                          smb_fname_str_dbg(smb_fname)));
2146                                 errno = ENOENT;
2147                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2148                         }
2149                         break;
2150
2151                 case FILE_OVERWRITE:
2152                         /* If file exists overwrite. If file doesn't exist
2153                          * error. */
2154                         if (!file_existed) {
2155                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2156                                          "requested for file %s and file "
2157                                          "doesn't exist.\n",
2158                                          smb_fname_str_dbg(smb_fname) ));
2159                                 errno = ENOENT;
2160                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2161                         }
2162                         break;
2163
2164                 case FILE_CREATE:
2165                         /* If file exists error. If file doesn't exist
2166                          * create. */
2167                         if (file_existed) {
2168                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2169                                          "requested for file %s and file "
2170                                          "already exists.\n",
2171                                          smb_fname_str_dbg(smb_fname)));
2172                                 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2173                                         errno = EISDIR;
2174                                 } else {
2175                                         errno = EEXIST;
2176                                 }
2177                                 return map_nt_error_from_unix(errno);
2178                         }
2179                         break;
2180
2181                 case FILE_SUPERSEDE:
2182                 case FILE_OVERWRITE_IF:
2183                 case FILE_OPEN_IF:
2184                         break;
2185                 default:
2186                         return NT_STATUS_INVALID_PARAMETER;
2187         }
2188
2189         flags2 = disposition_to_open_flags(create_disposition);
2190
2191         /* We only care about matching attributes on file exists and
2192          * overwrite. */
2193
2194         if (!posix_open && file_existed &&
2195             ((create_disposition == FILE_OVERWRITE) ||
2196              (create_disposition == FILE_OVERWRITE_IF))) {
2197                 if (!open_match_attributes(conn, existing_dos_attributes,
2198                                            new_dos_attributes,
2199                                            smb_fname->st.st_ex_mode,
2200                                            unx_mode, &new_unx_mode)) {
2201                         DEBUG(5,("open_file_ntcreate: attributes missmatch "
2202                                  "for file %s (%x %x) (0%o, 0%o)\n",
2203                                  smb_fname_str_dbg(smb_fname),
2204                                  existing_dos_attributes,
2205                                  new_dos_attributes,
2206                                  (unsigned int)smb_fname->st.st_ex_mode,
2207                                  (unsigned int)unx_mode ));
2208                         errno = EACCES;
2209                         return NT_STATUS_ACCESS_DENIED;
2210                 }
2211         }
2212
2213         status = smbd_calculate_access_mask(conn, smb_fname,
2214                                         false,
2215                                         access_mask,
2216                                         &access_mask); 
2217         if (!NT_STATUS_IS_OK(status)) {
2218                 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2219                         "on file %s returned %s\n",
2220                         smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2221                 return status;
2222         }
2223
2224         open_access_mask = access_mask;
2225
2226         if (flags2 & O_TRUNC) {
2227                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2228         }
2229
2230         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2231                    "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2232                     access_mask));
2233
2234         /*
2235          * Note that we ignore the append flag as append does not
2236          * mean the same thing under DOS and Unix.
2237          */
2238
2239         flags = calculate_open_access_flags(access_mask, oplock_request,
2240                                             private_flags);
2241
2242         /*
2243          * Currently we only look at FILE_WRITE_THROUGH for create options.
2244          */
2245
2246 #if defined(O_SYNC)
2247         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2248                 flags2 |= O_SYNC;
2249         }
2250 #endif /* O_SYNC */
2251
2252         if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2253                 flags2 |= O_APPEND;
2254         }
2255
2256         if (!posix_open && !CAN_WRITE(conn)) {
2257                 /*
2258                  * We should really return a permission denied error if either
2259                  * O_CREAT or O_TRUNC are set, but for compatibility with
2260                  * older versions of Samba we just AND them out.
2261                  */
2262                 flags2 &= ~(O_CREAT|O_TRUNC);
2263         }
2264
2265         if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2266                 /*
2267                  * With kernel oplocks the open breaking an oplock
2268                  * blocks until the oplock holder has given up the
2269                  * oplock or closed the file. We prevent this by first
2270                  * trying to open the file with O_NONBLOCK (see "man
2271                  * fcntl" on Linux). For the second try, triggered by
2272                  * an oplock break response, we do not need this
2273                  * anymore.
2274                  *
2275                  * This is true under the assumption that only Samba
2276                  * requests kernel oplocks. Once someone else like
2277                  * NFSv4 starts to use that API, we will have to
2278                  * modify this by communicating with the NFSv4 server.
2279                  */
2280                 flags2 |= O_NONBLOCK;
2281         }
2282
2283         /*
2284          * Ensure we can't write on a read-only share or file.
2285          */
2286
2287         if (flags != O_RDONLY && file_existed &&
2288             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2289                 DEBUG(5,("open_file_ntcreate: write access requested for "
2290                          "file %s on read only %s\n",
2291                          smb_fname_str_dbg(smb_fname),
2292                          !CAN_WRITE(conn) ? "share" : "file" ));
2293                 errno = EACCES;
2294                 return NT_STATUS_ACCESS_DENIED;
2295         }
2296
2297         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2298         fsp->share_access = share_access;
2299         fsp->fh->private_options = private_flags;
2300         fsp->access_mask = open_access_mask; /* We change this to the
2301                                               * requested access_mask after
2302                                               * the open is done. */
2303         fsp->posix_open = posix_open;
2304
2305         /* Ensure no SAMBA_PRIVATE bits can be set. */
2306         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2307
2308         if (timeval_is_zero(&request_time)) {
2309                 request_time = fsp->open_time;
2310         }
2311
2312         /*
2313          * Ensure we pay attention to default ACLs on directories if required.
2314          */
2315
2316         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2317             (def_acl = directory_has_default_acl(conn, parent_dir))) {
2318                 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2319         }
2320
2321         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2322                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2323                  (unsigned int)flags, (unsigned int)flags2,
2324                  (unsigned int)unx_mode, (unsigned int)access_mask,
2325                  (unsigned int)open_access_mask));
2326
2327         fsp_open = open_file(fsp, conn, req, parent_dir,
2328                              flags|flags2, unx_mode, access_mask,
2329                              open_access_mask, &new_file_created);
2330
2331         if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2332                 struct deferred_open_record state;
2333
2334                 /*
2335                  * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2336                  */
2337                 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2338                         DEBUG(10, ("FIFO busy\n"));
2339                         return NT_STATUS_NETWORK_BUSY;
2340                 }
2341                 if (req == NULL) {
2342                         DEBUG(10, ("Internal open busy\n"));
2343                         return NT_STATUS_NETWORK_BUSY;
2344                 }
2345
2346                 /*
2347                  * From here on we assume this is an oplock break triggered
2348                  */
2349
2350                 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2351                 if (lck == NULL) {
2352                         state.delayed_for_oplocks = false;
2353                         state.async_open = false;
2354                         state.id = fsp->file_id;
2355                         defer_open(NULL, request_time, timeval_set(0, 0),
2356                                    req, &state);
2357                         DEBUG(10, ("No share mode lock found after "
2358                                    "EWOULDBLOCK, retrying sync\n"));
2359                         return NT_STATUS_SHARING_VIOLATION;
2360                 }
2361
2362                 if (!validate_oplock_types(lck)) {
2363                         smb_panic("validate_oplock_types failed");
2364                 }
2365
2366                 if (delay_for_oplock(fsp, 0, lck, false, create_disposition)) {
2367                         schedule_defer_open(lck, request_time, req);
2368                         TALLOC_FREE(lck);
2369                         DEBUG(10, ("Sent oplock break request to kernel "
2370                                    "oplock holder\n"));
2371                         return NT_STATUS_SHARING_VIOLATION;
2372                 }
2373
2374                 /*
2375                  * No oplock from Samba around. Immediately retry with
2376                  * a blocking open.
2377                  */
2378                 state.delayed_for_oplocks = false;
2379                 state.async_open = false;
2380                 state.id = lck->data->id;
2381                 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2382                 TALLOC_FREE(lck);
2383                 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2384                            "Retrying sync\n"));
2385                 return NT_STATUS_SHARING_VIOLATION;
2386         }
2387
2388         if (!NT_STATUS_IS_OK(fsp_open)) {
2389                 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2390                         schedule_async_open(request_time, req);
2391                 }
2392                 return fsp_open;
2393         }
2394
2395         if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2396                 /*
2397                  * The file did exist, but some other (local or NFS)
2398                  * process either renamed/unlinked and re-created the
2399                  * file with different dev/ino after we walked the path,
2400                  * but before we did the open. We could retry the
2401                  * open but it's a rare enough case it's easier to
2402                  * just fail the open to prevent creating any problems
2403                  * in the open file db having the wrong dev/ino key.
2404                  */
2405                 fd_close(fsp);
2406                 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2407                         "Old (dev=0x%llu, ino =0x%llu). "
2408                         "New (dev=0x%llu, ino=0x%llu). Failing open "
2409                         " with NT_STATUS_ACCESS_DENIED.\n",
2410                          smb_fname_str_dbg(smb_fname),
2411                          (unsigned long long)saved_stat.st_ex_dev,
2412                          (unsigned long long)saved_stat.st_ex_ino,
2413                          (unsigned long long)smb_fname->st.st_ex_dev,
2414                          (unsigned long long)smb_fname->st.st_ex_ino));
2415                 return NT_STATUS_ACCESS_DENIED;
2416         }
2417
2418         old_write_time = smb_fname->st.st_ex_mtime;
2419
2420         /*
2421          * Deal with the race condition where two smbd's detect the
2422          * file doesn't exist and do the create at the same time. One
2423          * of them will win and set a share mode, the other (ie. this
2424          * one) should check if the requested share mode for this
2425          * create is allowed.
2426          */
2427
2428         /*
2429          * Now the file exists and fsp is successfully opened,
2430          * fsp->dev and fsp->inode are valid and should replace the
2431          * dev=0,inode=0 from a non existent file. Spotted by
2432          * Nadav Danieli <nadavd@exanet.com>. JRA.
2433          */
2434
2435         id = fsp->file_id;
2436
2437         lck = get_share_mode_lock(talloc_tos(), id,
2438                                   conn->connectpath,
2439                                   smb_fname, &old_write_time);
2440
2441         if (lck == NULL) {
2442                 DEBUG(0, ("open_file_ntcreate: Could not get share "
2443                           "mode lock for %s\n",
2444                           smb_fname_str_dbg(smb_fname)));
2445                 fd_close(fsp);
2446                 return NT_STATUS_SHARING_VIOLATION;
2447         }
2448
2449         /* Get the types we need to examine. */
2450         if (!validate_oplock_types(lck)) {
2451                 smb_panic("validate_oplock_types failed");
2452         }
2453
2454         if (has_delete_on_close(lck, fsp->name_hash)) {
2455                 TALLOC_FREE(lck);
2456                 fd_close(fsp);
2457                 return NT_STATUS_DELETE_PENDING;
2458         }
2459
2460         status = open_mode_check(conn, lck,
2461                                  access_mask, share_access);
2462
2463         if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2464             (lck->data->num_share_modes > 0)) {
2465                 /*
2466                  * This comes from ancient times out of open_mode_check. I
2467                  * have no clue whether this is still necessary. I can't think
2468                  * of a case where this would actually matter further down in
2469                  * this function. I leave it here for further investigation
2470                  * :-)
2471                  */
2472                 file_existed = true;
2473         }
2474
2475         if ((req != NULL) &&
2476             delay_for_oplock(
2477                     fsp, oplock_request, lck,
2478                     NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
2479                     create_disposition)) {
2480                 schedule_defer_open(lck, request_time, req);
2481                 TALLOC_FREE(lck);
2482                 fd_close(fsp);
2483                 return NT_STATUS_SHARING_VIOLATION;
2484         }
2485
2486         if (!NT_STATUS_IS_OK(status)) {
2487                 uint32 can_access_mask;
2488                 bool can_access = True;
2489
2490                 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2491
2492                 /* Check if this can be done with the deny_dos and fcb
2493                  * calls. */
2494                 if (private_flags &
2495                     (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2496                      NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2497                         if (req == NULL) {
2498                                 DEBUG(0, ("DOS open without an SMB "
2499                                           "request!\n"));
2500                                 TALLOC_FREE(lck);
2501                                 fd_close(fsp);
2502                                 return NT_STATUS_INTERNAL_ERROR;
2503                         }
2504
2505                         /* Use the client requested access mask here,
2506                          * not the one we open with. */
2507                         status = fcb_or_dos_open(req,
2508                                                  conn,
2509                                                  fsp,
2510                                                  smb_fname,
2511                                                  id,
2512                                                  req->smbpid,
2513                                                  req->vuid,
2514                                                  access_mask,
2515                                                  share_access,
2516                                                  create_options);
2517
2518                         if (NT_STATUS_IS_OK(status)) {
2519                                 TALLOC_FREE(lck);
2520                                 if (pinfo) {
2521                                         *pinfo = FILE_WAS_OPENED;
2522                                 }
2523                                 return NT_STATUS_OK;
2524                         }
2525                 }
2526
2527                 /*
2528                  * This next line is a subtlety we need for
2529                  * MS-Access. If a file open will fail due to share
2530                  * permissions and also for security (access) reasons,
2531                  * we need to return the access failed error, not the
2532                  * share error. We can't open the file due to kernel
2533                  * oplock deadlock (it's possible we failed above on
2534                  * the open_mode_check()) so use a userspace check.
2535                  */
2536
2537                 if (flags & O_RDWR) {
2538                         can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2539                 } else if (flags & O_WRONLY) {
2540                         can_access_mask = FILE_WRITE_DATA;
2541                 } else {
2542                         can_access_mask = FILE_READ_DATA;
2543                 }
2544
2545                 if (((can_access_mask & FILE_WRITE_DATA) &&
2546                      !CAN_WRITE(conn)) ||
2547                     !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2548                                                               smb_fname,
2549                                                               false,
2550                                                               can_access_mask))) {
2551                         can_access = False;
2552                 }
2553
2554                 /*
2555                  * If we're returning a share violation, ensure we
2556                  * cope with the braindead 1 second delay (SMB1 only).
2557                  */
2558
2559                 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2560                     !conn->sconn->using_smb2 &&
2561                     lp_defer_sharing_violations()) {
2562                         struct timeval timeout;
2563                         struct deferred_open_record state;
2564                         int timeout_usecs;
2565
2566                         /* this is a hack to speed up torture tests
2567                            in 'make test' */
2568                         timeout_usecs = lp_parm_int(SNUM(conn),
2569                                                     "smbd","sharedelay",
2570                                                     SHARING_VIOLATION_USEC_WAIT);
2571
2572                         /* This is a relative time, added to the absolute
2573                            request_time value to get the absolute timeout time.
2574                            Note that if this is the second or greater time we enter
2575                            this codepath for this particular request mid then
2576                            request_time is left as the absolute time of the *first*
2577                            time this request mid was processed. This is what allows
2578                            the request to eventually time out. */
2579
2580                         timeout = timeval_set(0, timeout_usecs);
2581
2582                         /* Nothing actually uses state.delayed_for_oplocks
2583                            but it's handy to differentiate in debug messages
2584                            between a 30 second delay due to oplock break, and
2585                            a 1 second delay for share mode conflicts. */
2586
2587                         state.delayed_for_oplocks = False;
2588                         state.async_open = false;
2589                         state.id = id;
2590
2591                         if ((req != NULL)
2592                             && !request_timed_out(request_time,
2593                                                   timeout)) {
2594                                 defer_open(lck, request_time, timeout,
2595                                            req, &state);
2596                         }
2597                 }
2598
2599                 TALLOC_FREE(lck);
2600                 fd_close(fsp);
2601                 if (can_access) {
2602                         /*
2603                          * We have detected a sharing violation here
2604                          * so return the correct error code
2605                          */
2606                         status = NT_STATUS_SHARING_VIOLATION;
2607                 } else {
2608                         status = NT_STATUS_ACCESS_DENIED;
2609                 }
2610                 return status;
2611         }
2612
2613         /*
2614          * We have the share entry *locked*.....
2615          */
2616
2617         /* Delete streams if create_disposition requires it */
2618         if (!new_file_created && clear_ads(create_disposition) &&
2619             !is_ntfs_stream_smb_fname(smb_fname)) {
2620                 status = delete_all_streams(conn, smb_fname->base_name);
2621                 if (!NT_STATUS_IS_OK(status)) {
2622                         TALLOC_FREE(lck);
2623                         fd_close(fsp);
2624                         return status;
2625                 }
2626         }
2627
2628         /* note that we ignore failure for the following. It is
2629            basically a hack for NFS, and NFS will never set one of
2630            these only read them. Nobody but Samba can ever set a deny
2631            mode and we have already checked our more authoritative
2632            locking database for permission to set this deny mode. If
2633            the kernel refuses the operations then the kernel is wrong.
2634            note that GPFS supports it as well - jmcd */
2635
2636         if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2637                 int ret_flock;
2638                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2639                 if(ret_flock == -1 ){
2640
2641                         TALLOC_FREE(lck);
2642                         fd_close(fsp);
2643
2644                         return NT_STATUS_SHARING_VIOLATION;
2645                 }
2646         }
2647
2648         /*
2649          * At this point onwards, we can guarantee that the share entry
2650          * is locked, whether we created the file or not, and that the
2651          * deny mode is compatible with all current opens.
2652          */
2653
2654         /*
2655          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2656          * but we don't have to store this - just ignore it on access check.
2657          */
2658         if (conn->sconn->using_smb2) {
2659                 /*
2660                  * SMB2 doesn't return it (according to Microsoft tests).
2661                  * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2662                  * File created with access = 0x7 (Read, Write, Delete)
2663                  * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2664                  */
2665                 fsp->access_mask = access_mask;
2666         } else {
2667                 /* But SMB1 does. */
2668                 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2669         }
2670
2671         if (file_existed) {
2672                 /* stat opens on existing files don't get oplocks. */
2673                 if (is_stat_open(open_access_mask)) {
2674                         oplock_request = NO_OPLOCK;
2675                 }
2676         }
2677
2678         if (new_file_created) {
2679                 info = FILE_WAS_CREATED;
2680         } else {
2681                 if (flags2 & O_TRUNC) {
2682                         info = FILE_WAS_OVERWRITTEN;
2683                 } else {
2684                         info = FILE_WAS_OPENED;
2685                 }
2686         }
2687
2688         if (pinfo) {
2689                 *pinfo = info;
2690         }
2691
2692         /*
2693          * Setup the oplock info in both the shared memory and
2694          * file structs.
2695          */
2696
2697         grant_fsp_oplock_type(fsp, lck, oplock_request);
2698
2699         status = set_file_oplock(fsp);
2700         if (!NT_STATUS_IS_OK(status)) {
2701                 /*
2702                  * Could not get the kernel oplock
2703                  */
2704                 fsp->oplock_type = NO_OPLOCK;
2705         }
2706
2707         if (!set_share_mode(lck, fsp, get_current_uid(conn),
2708                             req ? req->mid : 0,
2709                             fsp->oplock_type)) {
2710                 TALLOC_FREE(lck);
2711                 fd_close(fsp);
2712                 return NT_STATUS_NO_MEMORY;
2713         }
2714
2715         /* Handle strange delete on close create semantics. */
2716         if (create_options & FILE_DELETE_ON_CLOSE) {
2717
2718                 status = can_set_delete_on_close(fsp, new_dos_attributes);
2719
2720                 if (!NT_STATUS_IS_OK(status)) {
2721                         /* Remember to delete the mode we just added. */
2722                         del_share_mode(lck, fsp);
2723                         TALLOC_FREE(lck);
2724                         fd_close(fsp);
2725                         return status;
2726                 }
2727                 /* Note that here we set the *inital* delete on close flag,
2728                    not the regular one. The magic gets handled in close. */
2729                 fsp->initial_delete_on_close = True;
2730         }
2731
2732         if (info != FILE_WAS_OPENED) {
2733                 /* Files should be initially set as archive */
2734                 if (lp_map_archive(SNUM(conn)) ||
2735                     lp_store_dos_attributes(SNUM(conn))) {
2736                         if (!posix_open) {
2737                                 if (file_set_dosmode(conn, smb_fname,
2738                                             new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2739                                             parent_dir, true) == 0) {
2740                                         unx_mode = smb_fname->st.st_ex_mode;
2741                                 }
2742                         }
2743                 }
2744         }
2745
2746         /* Determine sparse flag. */
2747         if (posix_open) {
2748                 /* POSIX opens are sparse by default. */
2749                 fsp->is_sparse = true;
2750         } else {
2751                 fsp->is_sparse = (file_existed &&
2752                         (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2753         }
2754
2755         /*
2756          * Take care of inherited ACLs on created files - if default ACL not
2757          * selected.
2758          */
2759
2760         if (!posix_open && new_file_created && !def_acl) {
2761
2762                 int saved_errno = errno; /* We might get ENOSYS in the next
2763                                           * call.. */
2764
2765                 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2766                     errno == ENOSYS) {
2767                         errno = saved_errno; /* Ignore ENOSYS */
2768                 }
2769
2770         } else if (new_unx_mode) {
2771
2772                 int ret = -1;
2773
2774                 /* Attributes need changing. File already existed. */
2775
2776                 {
2777                         int saved_errno = errno; /* We might get ENOSYS in the
2778                                                   * next call.. */
2779                         ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2780
2781                         if (ret == -1 && errno == ENOSYS) {
2782                                 errno = saved_errno; /* Ignore ENOSYS */
2783                         } else {
2784                                 DEBUG(5, ("open_file_ntcreate: reset "
2785                                           "attributes of file %s to 0%o\n",
2786                                           smb_fname_str_dbg(smb_fname),
2787                                           (unsigned int)new_unx_mode));
2788                                 ret = 0; /* Don't do the fchmod below. */
2789                         }
2790                 }
2791
2792                 if ((ret == -1) &&
2793                     (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2794                         DEBUG(5, ("open_file_ntcreate: failed to reset "
2795                                   "attributes of file %s to 0%o\n",
2796                                   smb_fname_str_dbg(smb_fname),
2797                                   (unsigned int)new_unx_mode));
2798         }
2799
2800         TALLOC_FREE(lck);
2801
2802         return NT_STATUS_OK;
2803 }
2804
2805
2806 /****************************************************************************
2807  Open a file for for write to ensure that we can fchmod it.
2808 ****************************************************************************/
2809
2810 NTSTATUS open_file_fchmod(connection_struct *conn,
2811                           struct smb_filename *smb_fname,
2812                           files_struct **result)
2813 {
2814         if (!VALID_STAT(smb_fname->st)) {
2815                 return NT_STATUS_INVALID_PARAMETER;
2816         }
2817
2818         return SMB_VFS_CREATE_FILE(
2819                 conn,                                   /* conn */
2820                 NULL,                                   /* req */
2821                 0,                                      /* root_dir_fid */
2822                 smb_fname,                              /* fname */
2823                 FILE_WRITE_DATA,                        /* access_mask */
2824                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
2825                     FILE_SHARE_DELETE),
2826                 FILE_OPEN,                              /* create_disposition*/
2827                 0,                                      /* create_options */
2828                 0,                                      /* file_attributes */
2829                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
2830                 0,                                      /* allocation_size */
2831                 0,                                      /* private_flags */
2832                 NULL,                                   /* sd */
2833                 NULL,                                   /* ea_list */
2834                 result,                                 /* result */
2835                 NULL);                                  /* pinfo */
2836 }
2837
2838 static NTSTATUS mkdir_internal(connection_struct *conn,
2839                                struct smb_filename *smb_dname,
2840                                uint32 file_attributes)
2841 {
2842         mode_t mode;
2843         char *parent_dir = NULL;
2844         NTSTATUS status;
2845         bool posix_open = false;
2846         bool need_re_stat = false;
2847         uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2848
2849         if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2850                 DEBUG(5,("mkdir_internal: failing share access "
2851                          "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2852                 return NT_STATUS_ACCESS_DENIED;
2853         }
2854
2855         if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2856                             NULL)) {
2857                 return NT_STATUS_NO_MEMORY;
2858         }
2859
2860         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2861                 posix_open = true;
2862                 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2863         } else {
2864                 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2865         }
2866
2867         status = check_parent_access(conn,
2868                                         smb_dname,
2869                                         access_mask);
2870         if(!NT_STATUS_IS_OK(status)) {
2871                 DEBUG(5,("mkdir_internal: check_parent_access "
2872                         "on directory %s for path %s returned %s\n",
2873                         parent_dir,
2874                         smb_dname->base_name,
2875                         nt_errstr(status) ));
2876                 return status;
2877         }
2878
2879         if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2880                 return map_nt_error_from_unix(errno);
2881         }
2882
2883         /* Ensure we're checking for a symlink here.... */
2884         /* We don't want to get caught by a symlink racer. */
2885
2886         if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2887                 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2888                           smb_fname_str_dbg(smb_dname), strerror(errno)));
2889                 return map_nt_error_from_unix(errno);
2890         }
2891
2892         if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2893                 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2894                           smb_fname_str_dbg(smb_dname)));
2895                 return NT_STATUS_NOT_A_DIRECTORY;
2896         }
2897
2898         if (lp_store_dos_attributes(SNUM(conn))) {
2899                 if (!posix_open) {
2900                         file_set_dosmode(conn, smb_dname,
2901                                          file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2902                                          parent_dir, true);
2903                 }
2904         }
2905
2906         if (lp_inherit_perms(SNUM(conn))) {
2907                 inherit_access_posix_acl(conn, parent_dir,
2908                                          smb_dname->base_name, mode);
2909                 need_re_stat = true;
2910         }
2911
2912         if (!posix_open) {
2913                 /*
2914                  * Check if high bits should have been set,
2915                  * then (if bits are missing): add them.
2916                  * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2917                  * dir.
2918                  */
2919                 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2920                     (mode & ~smb_dname->st.st_ex_mode)) {
2921                         SMB_VFS_CHMOD(conn, smb_dname->base_name,
2922                                       (smb_dname->st.st_ex_mode |
2923                                           (mode & ~smb_dname->st.st_ex_mode)));
2924                         need_re_stat = true;
2925                 }
2926         }
2927
2928         /* Change the owner if required. */
2929         if (lp_inherit_owner(SNUM(conn))) {
2930                 change_dir_owner_to_parent(conn, parent_dir,
2931                                            smb_dname->base_name,
2932                                            &smb_dname->st);
2933                 need_re_stat = true;
2934         }
2935
2936         if (need_re_stat) {
2937                 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2938                         DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2939                           smb_fname_str_dbg(smb_dname), strerror(errno)));
2940                         return map_nt_error_from_unix(errno);
2941                 }
2942         }
2943
2944         notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2945                      smb_dname->base_name);
2946
2947         return NT_STATUS_OK;
2948 }
2949
2950 /****************************************************************************
2951  Open a directory from an NT SMB call.
2952 ****************************************************************************/
2953
2954 static NTSTATUS open_directory(connection_struct *conn,
2955                                struct smb_request *req,
2956                                struct smb_filename *smb_dname,
2957                                uint32 access_mask,
2958                                uint32 share_access,
2959                                uint32 create_disposition,
2960                                uint32 create_options,
2961                                uint32 file_attributes,
2962                                int *pinfo,
2963                                files_struct **result)
2964 {
2965         files_struct *fsp = NULL;
2966         bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2967         struct share_mode_lock *lck = NULL;
2968         NTSTATUS status;
2969         struct timespec mtimespec;
2970         int info = 0;
2971
2972         if (is_ntfs_stream_smb_fname(smb_dname)) {
2973                 DEBUG(2, ("open_directory: %s is a stream name!\n",
2974                           smb_fname_str_dbg(smb_dname)));
2975                 return NT_STATUS_NOT_A_DIRECTORY;
2976         }
2977
2978         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2979                 /* Ensure we have a directory attribute. */
2980                 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2981         }
2982
2983         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2984                  "share_access = 0x%x create_options = 0x%x, "
2985                  "create_disposition = 0x%x, file_attributes = 0x%x\n",
2986                  smb_fname_str_dbg(smb_dname),
2987                  (unsigned int)access_mask,
2988                  (unsigned int)share_access,
2989                  (unsigned int)create_options,
2990                  (unsigned int)create_disposition,
2991                  (unsigned int)file_attributes));
2992
2993         status = smbd_calculate_access_mask(conn, smb_dname, false,
2994                                             access_mask, &access_mask);
2995         if (!NT_STATUS_IS_OK(status)) {
2996                 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2997                         "on file %s returned %s\n",
2998                         smb_fname_str_dbg(smb_dname),
2999                         nt_errstr(status)));
3000                 return status;
3001         }
3002
3003         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3004                         !security_token_has_privilege(get_current_nttok(conn),
3005                                         SEC_PRIV_SECURITY)) {
3006                 DEBUG(10, ("open_directory: open on %s "
3007                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3008                         smb_fname_str_dbg(smb_dname)));
3009                 return NT_STATUS_PRIVILEGE_NOT_HELD;
3010         }
3011
3012         switch( create_disposition ) {
3013                 case FILE_OPEN:
3014
3015                         if (!dir_existed) {
3016                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3017                         }
3018
3019                         info = FILE_WAS_OPENED;
3020                         break;
3021
3022                 case FILE_CREATE:
3023
3024                         /* If directory exists error. If directory doesn't
3025                          * exist create. */
3026
3027                         if (dir_existed) {
3028                                 status = NT_STATUS_OBJECT_NAME_COLLISION;
3029                                 DEBUG(2, ("open_directory: unable to create "
3030                                           "%s. Error was %s\n",
3031                                           smb_fname_str_dbg(smb_dname),
3032                                           nt_errstr(status)));
3033                                 return status;
3034                         }
3035
3036                         status = mkdir_internal(conn, smb_dname,
3037                                                 file_attributes);
3038
3039                         if (!NT_STATUS_IS_OK(status)) {
3040                                 DEBUG(2, ("open_directory: unable to create "
3041                                           "%s. Error was %s\n",
3042                                           smb_fname_str_dbg(smb_dname),
3043                                           nt_errstr(status)));
3044                                 return status;
3045                         }
3046
3047                         info = FILE_WAS_CREATED;
3048                         break;
3049
3050                 case FILE_OPEN_IF:
3051                         /*
3052                          * If directory exists open. If directory doesn't
3053                          * exist create.
3054                          */
3055
3056                         if (dir_existed) {
3057                                 status = NT_STATUS_OK;
3058                                 info = FILE_WAS_OPENED;
3059                         } else {
3060                                 status = mkdir_internal(conn, smb_dname,
3061                                                 file_attributes);
3062
3063                                 if (NT_STATUS_IS_OK(status)) {
3064                                         info = FILE_WAS_CREATED;
3065                                 } else {
3066                                         /* Cope with create race. */
3067                                         if (!NT_STATUS_EQUAL(status,
3068                                                         NT_STATUS_OBJECT_NAME_COLLISION)) {
3069                                                 DEBUG(2, ("open_directory: unable to create "
3070                                                         "%s. Error was %s\n",
3071                                                         smb_fname_str_dbg(smb_dname),
3072                                                         nt_errstr(status)));
3073                                                 return status;
3074                                         }
3075                                         info = FILE_WAS_OPENED;
3076                                 }
3077                         }
3078
3079                         break;
3080
3081                 case FILE_SUPERSEDE:
3082                 case FILE_OVERWRITE:
3083                 case FILE_OVERWRITE_IF:
3084                 default:
3085                         DEBUG(5,("open_directory: invalid create_disposition "
3086                                  "0x%x for directory %s\n",
3087                                  (unsigned int)create_disposition,
3088                                  smb_fname_str_dbg(smb_dname)));
3089                         return NT_STATUS_INVALID_PARAMETER;
3090         }
3091
3092         if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3093                 DEBUG(5,("open_directory: %s is not a directory !\n",
3094                          smb_fname_str_dbg(smb_dname)));
3095                 return NT_STATUS_NOT_A_DIRECTORY;
3096         }
3097
3098         if (info == FILE_WAS_OPENED) {
3099                 status = smbd_check_access_rights(conn,
3100                                                 smb_dname,
3101                                                 false,
3102                                                 access_mask);
3103                 if (!NT_STATUS_IS_OK(status)) {
3104                         DEBUG(10, ("open_directory: smbd_check_access_rights on "
3105                                 "file %s failed with %s\n",
3106                                 smb_fname_str_dbg(smb_dname),
3107                                 nt_errstr(status)));
3108                         return status;
3109                 }
3110         }
3111
3112         status = file_new(req, conn, &fsp);
3113         if(!NT_STATUS_IS_OK(status)) {
3114                 return status;
3115         }
3116
3117         /*
3118          * Setup the files_struct for it.
3119          */
3120
3121         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3122         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3123         fsp->file_pid = req ? req->smbpid : 0;
3124         fsp->can_lock = False;
3125         fsp->can_read = False;
3126         fsp->can_write = False;
3127
3128         fsp->share_access = share_access;
3129         fsp->fh->private_options = 0;
3130         /*
3131          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3132          */
3133         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3134         fsp->print_file = NULL;
3135         fsp->modified = False;
3136         fsp->oplock_type = NO_OPLOCK;
3137         fsp->sent_oplock_break = NO_BREAK_SENT;
3138         fsp->is_directory = True;
3139         fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3140         status = fsp_set_smb_fname(fsp, smb_dname);
3141         if (!NT_STATUS_IS_OK(status)) {
3142                 file_free(req, fsp);
3143                 return status;
3144         }
3145
3146         mtimespec = smb_dname->st.st_ex_mtime;
3147
3148 #ifdef O_DIRECTORY
3149         status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3150 #else
3151         /* POSIX allows us to open a directory with O_RDONLY. */
3152         status = fd_open(conn, fsp, O_RDONLY, 0);
3153 #endif
3154         if (!NT_STATUS_IS_OK(status)) {
3155                 DEBUG(5, ("open_directory: Could not open fd for "
3156                         "%s (%s)\n",
3157                         smb_fname_str_dbg(smb_dname),
3158                         nt_errstr(status)));
3159                 file_free(req, fsp);
3160                 return status;
3161         }
3162
3163         status = vfs_stat_fsp(fsp);
3164         if (!NT_STATUS_IS_OK(status)) {
3165                 fd_close(fsp);
3166                 file_free(req, fsp);
3167                 return status;
3168         }
3169
3170         /* Ensure there was no race condition. */
3171         if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3172                 DEBUG(5,("open_directory: stat struct differs for "
3173                         "directory %s.\n",
3174                         smb_fname_str_dbg(smb_dname)));
3175                 fd_close(fsp);
3176                 file_free(req, fsp);
3177                 return NT_STATUS_ACCESS_DENIED;
3178         }
3179
3180         lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3181                                   conn->connectpath, smb_dname,
3182                                   &mtimespec);
3183
3184         if (lck == NULL) {
3185                 DEBUG(0, ("open_directory: Could not get share mode lock for "
3186                           "%s\n", smb_fname_str_dbg(smb_dname)));
3187                 fd_close(fsp);
3188                 file_free(req, fsp);
3189                 return NT_STATUS_SHARING_VIOLATION;
3190         }
3191
3192         if (has_delete_on_close(lck, fsp->name_hash)) {
3193                 TALLOC_FREE(lck);
3194                 fd_close(fsp);
3195                 file_free(req, fsp);
3196                 return NT_STATUS_DELETE_PENDING;
3197         }
3198
3199         status = open_mode_check(conn, lck,
3200                                  access_mask, share_access);
3201
3202         if (!NT_STATUS_IS_OK(status)) {
3203                 TALLOC_FREE(lck);
3204                 fd_close(fsp);
3205                 file_free(req, fsp);
3206                 return status;
3207         }
3208
3209         if (!set_share_mode(lck, fsp, get_current_uid(conn),
3210                             req ? req->mid : 0, NO_OPLOCK)) {
3211                 TALLOC_FREE(lck);
3212                 fd_close(fsp);
3213                 file_free(req, fsp);
3214                 return NT_STATUS_NO_MEMORY;
3215         }
3216
3217         /* For directories the delete on close bit at open time seems
3218            always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3219         if (create_options & FILE_DELETE_ON_CLOSE) {
3220                 status = can_set_delete_on_close(fsp, 0);
3221                 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3222                         del_share_mode(lck, fsp);
3223                         TALLOC_FREE(lck);
3224                         fd_close(fsp);
3225                         file_free(req, fsp);
3226                         return status;
3227                 }
3228
3229                 if (NT_STATUS_IS_OK(status)) {
3230                         /* Note that here we set the *inital* delete on close flag,
3231                            not the regular one. The magic gets handled in close. */
3232                         fsp->initial_delete_on_close = True;
3233                 }
3234         }
3235
3236         TALLOC_FREE(lck);
3237
3238         if (pinfo) {
3239                 *pinfo = info;
3240         }
3241
3242         *result = fsp;
3243         return NT_STATUS_OK;
3244 }
3245
3246 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3247                           struct smb_filename *smb_dname)
3248 {
3249         NTSTATUS status;
3250         files_struct *fsp;
3251
3252         status = SMB_VFS_CREATE_FILE(
3253                 conn,                                   /* conn */
3254                 req,                                    /* req */
3255                 0,                                      /* root_dir_fid */
3256                 smb_dname,                              /* fname */
3257                 FILE_READ_ATTRIBUTES,                   /* access_mask */
3258                 FILE_SHARE_NONE,                        /* share_access */
3259                 FILE_CREATE,                            /* create_disposition*/
3260                 FILE_DIRECTORY_FILE,                    /* create_options */
3261                 FILE_ATTRIBUTE_DIRECTORY,               /* file_attributes */
3262                 0,                                      /* oplock_request */
3263                 0,                                      /* allocation_size */
3264                 0,                                      /* private_flags */
3265                 NULL,                                   /* sd */
3266                 NULL,                                   /* ea_list */
3267                 &fsp,                                   /* result */
3268                 NULL);                                  /* pinfo */
3269
3270         if (NT_STATUS_IS_OK(status)) {
3271                 close_file(req, fsp, NORMAL_CLOSE);
3272         }
3273
3274         return status;
3275 }
3276
3277 /****************************************************************************
3278  Receive notification that one of our open files has been renamed by another
3279  smbd process.
3280 ****************************************************************************/
3281
3282 void msg_file_was_renamed(struct messaging_context *msg,
3283                           void *private_data,
3284                           uint32_t msg_type,
3285                           struct server_id server_id,
3286                           DATA_BLOB *data)
3287 {
3288         files_struct *fsp;
3289         char *frm = (char *)data->data;
3290         struct file_id id;
3291         const char *sharepath;
3292         const char *base_name;
3293         const char *stream_name;
3294         struct smb_filename *smb_fname = NULL;
3295         size_t sp_len, bn_len;
3296         NTSTATUS status;
3297         struct smbd_server_connection *sconn =
3298                 talloc_get_type_abort(private_data,
3299                 struct smbd_server_connection);
3300
3301         if (data->data == NULL
3302             || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3303                 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3304                           (int)data->length));
3305                 return;
3306         }
3307
3308         /* Unpack the message. */
3309         pull_file_id_24(frm, &id);
3310         sharepath = &frm[24];
3311         sp_len = strlen(sharepath);
3312         base_name = sharepath + sp_len + 1;
3313         bn_len = strlen(base_name);
3314         stream_name = sharepath + sp_len + 1 + bn_len + 1;
3315
3316         /* stream_name must always be NULL if there is no stream. */
3317         if (stream_name[0] == '\0') {
3318                 stream_name = NULL;
3319         }
3320
3321         smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3322                                         stream_name, NULL);
3323         if (smb_fname == NULL) {
3324                 return;
3325         }
3326
3327         DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3328                 "file_id %s\n",
3329                 sharepath, smb_fname_str_dbg(smb_fname),
3330                 file_id_string_tos(&id)));
3331
3332         for(fsp = file_find_di_first(sconn, id); fsp;
3333             fsp = file_find_di_next(fsp)) {
3334                 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3335
3336                         DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3337                                 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3338                                 smb_fname_str_dbg(smb_fname)));
3339                         status = fsp_set_smb_fname(fsp, smb_fname);
3340                         if (!NT_STATUS_IS_OK(status)) {
3341                                 goto out;
3342                         }
3343                 } else {
3344                         /* TODO. JRA. */
3345                         /* Now we have the complete path we can work out if this is
3346                            actually within this share and adjust newname accordingly. */
3347                         DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3348                                 "not sharepath %s) "
3349                                 "%s from %s -> %s\n",
3350                                 fsp->conn->connectpath,
3351                                 sharepath,
3352                                 fsp_fnum_dbg(fsp),
3353                                 fsp_str_dbg(fsp),
3354                                 smb_fname_str_dbg(smb_fname)));
3355                 }
3356         }
3357  out:
3358         TALLOC_FREE(smb_fname);
3359         return;
3360 }
3361
3362 /*
3363  * If a main file is opened for delete, all streams need to be checked for
3364  * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3365  * If that works, delete them all by setting the delete on close and close.
3366  */
3367
3368 NTSTATUS open_streams_for_delete(connection_struct *conn,
3369                                         const char *fname)
3370 {
3371         struct stream_struct *stream_info = NULL;
3372         files_struct **streams = NULL;
3373         int i;
3374         unsigned int num_streams = 0;
3375         TALLOC_CTX *frame = talloc_stackframe();
3376         NTSTATUS status;
3377
3378         status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3379                                 &num_streams, &stream_info);
3380
3381         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3382             || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3383                 DEBUG(10, ("no streams around\n"));
3384                 TALLOC_FREE(frame);
3385                 return NT_STATUS_OK;
3386         }
3387
3388         if (!NT_STATUS_IS_OK(status)) {
3389                 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3390                            nt_errstr(status)));
3391                 goto fail;
3392         }
3393
3394         DEBUG(10, ("open_streams_for_delete found %d streams\n",
3395                    num_streams));
3396
3397         if (num_streams == 0) {
3398                 TALLOC_FREE(frame);
3399                 return NT_STATUS_OK;
3400         }
3401
3402         streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3403         if (streams == NULL) {
3404                 DEBUG(0, ("talloc failed\n"));
3405                 status = NT_STATUS_NO_MEMORY;
3406                 goto fail;
3407         }
3408
3409         for (i=0; i<num_streams; i++) {
3410                 struct smb_filename *smb_fname;
3411
3412                 if (strequal(stream_info[i].name, "::$DATA")) {
3413                         streams[i] = NULL;
3414                         continue;
3415                 }
3416
3417                 smb_fname = synthetic_smb_fname(
3418                         talloc_tos(), fname, stream_info[i].name, NULL);
3419                 if (smb_fname == NULL) {
3420                         status = NT_STATUS_NO_MEMORY;
3421                         goto fail;
3422                 }
3423
3424                 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3425                         DEBUG(10, ("Unable to stat stream: %s\n",
3426                                    smb_fname_str_dbg(smb_fname)));
3427                 }
3428
3429                 status = SMB_VFS_CREATE_FILE(
3430                          conn,                  /* conn */
3431                          NULL,                  /* req */
3432                          0,                     /* root_dir_fid */
3433                          smb_fname,             /* fname */
3434                          DELETE_ACCESS,         /* access_mask */
3435                          (FILE_SHARE_READ |     /* share_access */
3436                              FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3437                          FILE_OPEN,             /* create_disposition*/
3438                          0,                     /* create_options */
3439                          FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3440                          0,                     /* oplock_request */
3441                          0,                     /* allocation_size */
3442                          NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3443                          NULL,                  /* sd */
3444                          NULL,                  /* ea_list */
3445                          &streams[i],           /* result */
3446                          NULL);                 /* pinfo */
3447
3448                 if (!NT_STATUS_IS_OK(status)) {
3449                         DEBUG(10, ("Could not open stream %s: %s\n",
3450                                    smb_fname_str_dbg(smb_fname),
3451                                    nt_errstr(status)));
3452
3453                         TALLOC_FREE(smb_fname);
3454                         break;
3455                 }
3456                 TALLOC_FREE(smb_fname);
3457         }
3458
3459         /*
3460          * don't touch the variable "status" beyond this point :-)
3461          */
3462
3463         for (i -= 1 ; i >= 0; i--) {
3464                 if (streams[i] == NULL) {
3465                         continue;
3466                 }
3467
3468                 DEBUG(10, ("Closing stream # %d, %s\n", i,
3469                            fsp_str_dbg(streams[i])));
3470                 close_file(NULL, streams[i], NORMAL_CLOSE);
3471         }
3472
3473  fail:
3474         TALLOC_FREE(frame);
3475         return status;
3476 }
3477
3478 /*********************************************************************
3479  Create a default ACL by inheriting from the parent. If no inheritance
3480  from the parent available, don't set anything. This will leave the actual
3481  permissions the new file or directory already got from the filesystem
3482  as the NT ACL when read.
3483 *********************************************************************/
3484
3485 static NTSTATUS inherit_new_acl(files_struct *fsp)
3486 {
3487         TALLOC_CTX *frame = talloc_stackframe();
3488         char *parent_name = NULL;
3489         struct security_descriptor *parent_desc = NULL;
3490         NTSTATUS status = NT_STATUS_OK;
3491         struct security_descriptor *psd = NULL;
3492         const struct dom_sid *owner_sid = NULL;
3493         const struct dom_sid *group_sid = NULL;
3494         uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3495         struct security_token *token = fsp->conn->session_info->security_token;
3496         bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3497         bool inheritable_components = false;
3498         bool try_builtin_administrators = false;
3499         const struct dom_sid *BA_U_sid = NULL;
3500         const struct dom_sid *BA_G_sid = NULL;
3501         bool try_system = false;
3502         const struct dom_sid *SY_U_sid = NULL;
3503         const struct dom_sid *SY_G_sid = NULL;
3504         size_t size = 0;
3505
3506         if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3507                 TALLOC_FREE(frame);
3508                 return NT_STATUS_NO_MEMORY;
3509         }
3510
3511         status = SMB_VFS_GET_NT_ACL(fsp->conn,
3512                                     parent_name,
3513                                     (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3514                                     frame,
3515                                     &parent_desc);
3516         if (!NT_STATUS_IS_OK(status)) {
3517                 TALLOC_FREE(frame);
3518                 return status;
3519         }
3520
3521         inheritable_components = sd_has_inheritable_components(parent_desc,
3522                                         fsp->is_directory);
3523
3524         if (!inheritable_components && !inherit_owner) {
3525                 TALLOC_FREE(frame);
3526                 /* Nothing to inherit and not setting owner. */
3527                 return NT_STATUS_OK;
3528         }
3529
3530         /* Create an inherited descriptor from the parent. */
3531
3532         if (DEBUGLEVEL >= 10) {
3533                 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3534                         fsp_str_dbg(fsp) ));
3535                 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3536         }
3537
3538         /* Inherit from parent descriptor if "inherit owner" set. */
3539         if (inherit_owner) {
3540                 owner_sid = parent_desc->owner_sid;
3541                 group_sid = parent_desc->group_sid;
3542         }
3543
3544         if (owner_sid == NULL) {
3545                 if (security_token_has_builtin_administrators(token)) {
3546                         try_builtin_administrators = true;
3547                 } else if (security_token_is_system(token)) {
3548                         try_builtin_administrators = true;
3549                         try_system = true;
3550                 }
3551         }
3552
3553         if (group_sid == NULL &&
3554             token->num_sids == PRIMARY_GROUP_SID_INDEX)
3555         {
3556                 if (security_token_is_system(token)) {
3557                         try_builtin_administrators = true;
3558                         try_system = true;
3559                 }
3560         }
3561
3562         if (try_builtin_administrators) {
3563                 struct unixid ids;
3564                 bool ok;
3565
3566                 ZERO_STRUCT(ids);
3567                 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3568                 if (ok) {
3569                         switch (ids.type) {
3570                         case ID_TYPE_BOTH:
3571                                 BA_U_sid = &global_sid_Builtin_Administrators;
3572                                 BA_G_sid = &global_sid_Builtin_Administrators;
3573                                 break;
3574                         case ID_TYPE_UID:
3575                                 BA_U_sid = &global_sid_Builtin_Administrators;
3576                                 break;
3577                         case ID_TYPE_GID:
3578                                 BA_G_sid = &global_sid_Builtin_Administrators;
3579                                 break;
3580                         default:
3581                                 break;
3582                         }
3583                 }
3584         }
3585
3586         if (try_system) {
3587                 struct unixid ids;
3588                 bool ok;
3589
3590                 ZERO_STRUCT(ids);
3591                 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3592                 if (ok) {
3593                         switch (ids.type) {
3594                         case ID_TYPE_BOTH:
3595                                 SY_U_sid = &global_sid_System;
3596                                 SY_G_sid = &global_sid_System;
3597                                 break;
3598                         case ID_TYPE_UID:
3599                                 SY_U_sid = &global_sid_System;
3600                                 break;
3601                         case ID_TYPE_GID:
3602                                 SY_G_sid = &global_sid_System;
3603                                 break;
3604                         default:
3605                                 break;
3606                         }
3607                 }
3608         }
3609
3610         if (owner_sid == NULL) {
3611                 owner_sid = BA_U_sid;
3612         }
3613
3614         if (owner_sid == NULL) {
3615                 owner_sid = SY_U_sid;
3616         }
3617
3618         if (group_sid == NULL) {
3619                 group_sid = SY_G_sid;
3620         }
3621
3622         if (try_system && group_sid == NULL) {
3623                 group_sid = BA_G_sid;
3624         }
3625
3626         if (owner_sid == NULL) {
3627                 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3628         }
3629         if (group_sid == NULL) {
3630                 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3631                         group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3632                 } else {
3633                         group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3634                 }
3635         }
3636
3637         status = se_create_child_secdesc(frame,
3638                         &psd,
3639                         &size,
3640                         parent_desc,
3641                         owner_sid,
3642                         group_sid,
3643                         fsp->is_directory);
3644         if (!NT_STATUS_IS_OK(status)) {
3645                 TALLOC_FREE(frame);
3646                 return status;
3647         }
3648
3649         /* If inheritable_components == false,
3650            se_create_child_secdesc()
3651            creates a security desriptor with a NULL dacl
3652            entry, but with SEC_DESC_DACL_PRESENT. We need
3653            to remove that flag. */
3654
3655         if (!inheritable_components) {
3656                 security_info_sent &= ~SECINFO_DACL;
3657                 psd->type &= ~SEC_DESC_DACL_PRESENT;
3658         }
3659
3660         if (DEBUGLEVEL >= 10) {
3661                 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3662                         fsp_str_dbg(fsp) ));
3663                 NDR_PRINT_DEBUG(security_descriptor, psd);
3664         }
3665
3666         if (inherit_owner) {
3667                 /* We need to be root to force this. */
3668                 become_root();
3669         }
3670         status = SMB_VFS_FSET_NT_ACL(fsp,
3671                         security_info_sent,
3672                         psd);
3673         if (inherit_owner) {
3674                 unbecome_root();
3675         }
3676         TALLOC_FREE(frame);
3677         return status;
3678 }
3679
3680 /*
3681  * Wrapper around open_file_ntcreate and open_directory
3682  */
3683
3684 static NTSTATUS create_file_unixpath(connection_struct *conn,
3685                                      struct smb_request *req,
3686                                      struct smb_filename *smb_fname,
3687                                      uint32_t access_mask,
3688                                      uint32_t share_access,
3689                                      uint32_t create_disposition,
3690                                      uint32_t create_options,
3691                                      uint32_t file_attributes,
3692                                      uint32_t oplock_request,
3693                                      uint64_t allocation_size,
3694                                      uint32_t private_flags,
3695                                      struct security_descriptor *sd,
3696                                      struct ea_list *ea_list,
3697
3698                                      files_struct **result,
3699                                      int *pinfo)
3700 {
3701         int info = FILE_WAS_OPENED;
3702         files_struct *base_fsp = NULL;
3703         files_struct *fsp = NULL;
3704         NTSTATUS status;
3705
3706         DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3707                   "file_attributes = 0x%x, share_access = 0x%x, "
3708                   "create_disposition = 0x%x create_options = 0x%x "
3709                   "oplock_request = 0x%x private_flags = 0x%x "
3710                   "ea_list = 0x%p, sd = 0x%p, "
3711                   "fname = %s\n",
3712                   (unsigned int)access_mask,
3713                   (unsigned int)file_attributes,
3714                   (unsigned int)share_access,
3715                   (unsigned int)create_disposition,
3716                   (unsigned int)create_options,
3717                   (unsigned int)oplock_request,
3718                   (unsigned int)private_flags,
3719                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
3720
3721         if (create_options & FILE_OPEN_BY_FILE_ID) {
3722                 status = NT_STATUS_NOT_SUPPORTED;
3723                 goto fail;
3724         }
3725
3726         if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3727                 status = NT_STATUS_INVALID_PARAMETER;
3728                 goto fail;
3729         }
3730
3731         if (req == NULL) {
3732                 oplock_request |= INTERNAL_OPEN_ONLY;
3733         }
3734
3735         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3736             && (access_mask & DELETE_ACCESS)
3737             && !is_ntfs_stream_smb_fname(smb_fname)) {
3738                 /*
3739                  * We can't open a file with DELETE access if any of the
3740                  * streams is open without FILE_SHARE_DELETE
3741                  */
3742                 status = open_streams_for_delete(conn, smb_fname->base_name);
3743
3744                 if (!NT_STATUS_IS_OK(status)) {
3745                         goto fail;
3746                 }
3747         }
3748
3749         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3750                         !security_token_has_privilege(get_current_nttok(conn),
3751                                         SEC_PRIV_SECURITY)) {
3752                 DEBUG(10, ("create_file_unixpath: open on %s "
3753                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3754                         smb_fname_str_dbg(smb_fname)));
3755                 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3756                 goto fail;
3757         }
3758
3759         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3760             && is_ntfs_stream_smb_fname(smb_fname)
3761             && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3762                 uint32 base_create_disposition;
3763                 struct smb_filename *smb_fname_base = NULL;
3764
3765                 if (create_options & FILE_DIRECTORY_FILE) {
3766                         status = NT_STATUS_NOT_A_DIRECTORY;
3767                         goto fail;
3768                 }
3769
3770                 switch (create_disposition) {
3771                 case FILE_OPEN:
3772                         base_create_disposition = FILE_OPEN;
3773                         break;
3774                 default:
3775                         base_create_disposition = FILE_OPEN_IF;
3776                         break;
3777                 }
3778
3779                 /* Create an smb_filename with stream_name == NULL. */
3780                 smb_fname_base = synthetic_smb_fname(talloc_tos(),
3781                                                      smb_fname->base_name,
3782                                                      NULL, NULL);
3783                 if (smb_fname_base == NULL) {
3784                         status = NT_STATUS_NO_MEMORY;
3785                         goto fail;
3786                 }
3787
3788                 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3789                         DEBUG(10, ("Unable to stat stream: %s\n",
3790                                    smb_fname_str_dbg(smb_fname_base)));
3791                 }
3792
3793                 /* Open the base file. */
3794                 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3795                                               FILE_SHARE_READ
3796                                               | FILE_SHARE_WRITE
3797                                               | FILE_SHARE_DELETE,
3798                                               base_create_disposition,
3799                                               0, 0, 0, 0, 0, NULL, NULL,
3800                                               &base_fsp, NULL);
3801                 TALLOC_FREE(smb_fname_base);
3802
3803                 if (!NT_STATUS_IS_OK(status)) {
3804                         DEBUG(10, ("create_file_unixpath for base %s failed: "
3805                                    "%s\n", smb_fname->base_name,
3806                                    nt_errstr(status)));
3807                         goto fail;
3808                 }
3809                 /* we don't need to low level fd */
3810                 fd_close(base_fsp);
3811         }
3812
3813         /*
3814          * If it's a request for a directory open, deal with it separately.
3815          */
3816
3817         if (create_options & FILE_DIRECTORY_FILE) {
3818
3819                 if (create_options & FILE_NON_DIRECTORY_FILE) {
3820                         status = NT_STATUS_INVALID_PARAMETER;
3821                         goto fail;
3822                 }
3823
3824                 /* Can't open a temp directory. IFS kit test. */
3825                 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3826                      (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3827                         status = NT_STATUS_INVALID_PARAMETER;
3828                         goto fail;
3829                 }
3830
3831                 /*
3832                  * We will get a create directory here if the Win32
3833                  * app specified a security descriptor in the
3834                  * CreateDirectory() call.
3835                  */
3836
3837                 oplock_request = 0;
3838                 status = open_directory(
3839                         conn, req, smb_fname, access_mask, share_access,
3840                         create_disposition, create_options, file_attributes,
3841                         &info, &fsp);
3842         } else {
3843
3844                 /*
3845                  * Ordinary file case.
3846                  */
3847
3848                 status = file_new(req, conn, &fsp);
3849                 if(!NT_STATUS_IS_OK(status)) {
3850                         goto fail;
3851                 }
3852
3853                 status = fsp_set_smb_fname(fsp, smb_fname);
3854                 if (!NT_STATUS_IS_OK(status)) {
3855                         goto fail;
3856                 }
3857
3858                 if (base_fsp) {
3859                         /*
3860                          * We're opening the stream element of a
3861                          * base_fsp we already opened. Set up the
3862                          * base_fsp pointer.
3863                          */
3864                         fsp->base_fsp = base_fsp;
3865                 }
3866
3867                 if (allocation_size) {
3868                         fsp->initial_allocation_size = smb_roundup(fsp->conn,
3869                                                         allocation_size);
3870                 }
3871
3872                 status = open_file_ntcreate(conn,
3873                                             req,
3874                                             access_mask,
3875                                             share_access,
3876                                             create_disposition,
3877                                             create_options,
3878                                             file_attributes,
3879                                             oplock_request,
3880                                             private_flags,
3881                                             &info,
3882                                             fsp);
3883
3884                 if(!NT_STATUS_IS_OK(status)) {
3885                         file_free(req, fsp);
3886                         fsp = NULL;
3887                 }
3888
3889                 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3890
3891                         /* A stream open never opens a directory */
3892
3893                         if (base_fsp) {
3894                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3895                                 goto fail;
3896                         }
3897
3898                         /*
3899                          * Fail the open if it was explicitly a non-directory
3900                          * file.
3901                          */
3902
3903                         if (create_options & FILE_NON_DIRECTORY_FILE) {
3904                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3905                                 goto fail;
3906                         }
3907
3908                         oplock_request = 0;
3909                         status = open_directory(
3910                                 conn, req, smb_fname, access_mask,
3911                                 share_access, create_disposition,
3912                                 create_options, file_attributes,
3913                                 &info, &fsp);
3914                 }
3915         }
3916
3917         if (!NT_STATUS_IS_OK(status)) {
3918                 goto fail;
3919         }
3920
3921         fsp->base_fsp = base_fsp;
3922
3923         if ((ea_list != NULL) &&
3924             ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3925                 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3926                 if (!NT_STATUS_IS_OK(status)) {
3927                         goto fail;
3928                 }
3929         }
3930
3931         if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3932                 status = NT_STATUS_ACCESS_DENIED;
3933                 goto fail;
3934         }
3935
3936         /* Save the requested allocation size. */
3937         if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3938                 if (allocation_size
3939                     && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3940                         fsp->initial_allocation_size = smb_roundup(
3941                                 fsp->conn, allocation_size);
3942                         if (fsp->is_directory) {
3943                                 /* Can't set allocation size on a directory. */
3944                                 status = NT_STATUS_ACCESS_DENIED;
3945                                 goto fail;
3946                         }
3947                         if (vfs_allocate_file_space(
3948                                     fsp, fsp->initial_allocation_size) == -1) {
3949                                 status = NT_STATUS_DISK_FULL;
3950                                 goto fail;
3951                         }
3952                 } else {
3953                         fsp->initial_allocation_size = smb_roundup(
3954                                 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3955                 }
3956         } else {
3957                 fsp->initial_allocation_size = 0;
3958         }
3959
3960         if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3961                                 fsp->base_fsp == NULL) {
3962                 if (sd != NULL) {
3963                         /*
3964                          * According to the MS documentation, the only time the security
3965                          * descriptor is applied to the opened file is iff we *created* the
3966                          * file; an existing file stays the same.
3967                          *
3968                          * Also, it seems (from observation) that you can open the file with
3969                          * any access mask but you can still write the sd. We need to override
3970                          * the granted access before we call set_sd
3971                          * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3972                          */
3973
3974                         uint32_t sec_info_sent;
3975                         uint32_t saved_access_mask = fsp->access_mask;
3976
3977                         sec_info_sent = get_sec_info(sd);
3978
3979                         fsp->access_mask = FILE_GENERIC_ALL;
3980
3981                         if (sec_info_sent & (SECINFO_OWNER|
3982                                                 SECINFO_GROUP|
3983                                                 SECINFO_DACL|
3984                                                 SECINFO_SACL)) {
3985                                 status = set_sd(fsp, sd, sec_info_sent);
3986                         }
3987
3988                         fsp->access_mask = saved_access_mask;
3989
3990                         if (!NT_STATUS_IS_OK(status)) {
3991                                 goto fail;
3992                         }
3993                 } else if (lp_inherit_acls(SNUM(conn))) {
3994                         /* Inherit from parent. Errors here are not fatal. */
3995                         status = inherit_new_acl(fsp);
3996                         if (!NT_STATUS_IS_OK(status)) {
3997                                 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3998                                         fsp_str_dbg(fsp),
3999                                         nt_errstr(status) ));
4000                         }
4001                 }
4002         }
4003
4004         DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4005
4006         *result = fsp;
4007         if (pinfo != NULL) {
4008                 *pinfo = info;
4009         }
4010
4011         smb_fname->st = fsp->fsp_name->st;
4012
4013         return NT_STATUS_OK;
4014
4015  fail:
4016         DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4017
4018         if (fsp != NULL) {
4019                 if (base_fsp && fsp->base_fsp == base_fsp) {
4020                         /*
4021                          * The close_file below will close
4022                          * fsp->base_fsp.
4023                          */
4024                         base_fsp = NULL;
4025                 }
4026                 close_file(req, fsp, ERROR_CLOSE);
4027                 fsp = NULL;
4028         }
4029         if (base_fsp != NULL) {
4030                 close_file(req, base_fsp, ERROR_CLOSE);
4031                 base_fsp = NULL;
4032         }
4033         return status;
4034 }
4035
4036 /*
4037  * Calculate the full path name given a relative fid.
4038  */
4039 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4040                                    struct smb_request *req,
4041                                    uint16_t root_dir_fid,
4042                                    const struct smb_filename *smb_fname,
4043                                    struct smb_filename **smb_fname_out)
4044 {
4045         files_struct *dir_fsp;
4046         char *parent_fname = NULL;
4047         char *new_base_name = NULL;
4048         NTSTATUS status;
4049
4050         if (root_dir_fid == 0 || !smb_fname) {
4051                 status = NT_STATUS_INTERNAL_ERROR;
4052                 goto out;
4053         }
4054
4055         dir_fsp = file_fsp(req, root_dir_fid);
4056
4057         if (dir_fsp == NULL) {
4058                 status = NT_STATUS_INVALID_HANDLE;
4059                 goto out;
4060         }
4061
4062         if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4063                 status = NT_STATUS_INVALID_HANDLE;
4064                 goto out;
4065         }
4066
4067         if (!dir_fsp->is_directory) {
4068
4069                 /*
4070                  * Check to see if this is a mac fork of some kind.
4071                  */
4072
4073                 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4074                     is_ntfs_stream_smb_fname(smb_fname)) {
4075                         status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4076                         goto out;
4077                 }
4078
4079                 /*
4080                   we need to handle the case when we get a
4081                   relative open relative to a file and the
4082                   pathname is blank - this is a reopen!
4083                   (hint from demyn plantenberg)
4084                 */
4085
4086                 status = NT_STATUS_INVALID_HANDLE;
4087                 goto out;
4088         }
4089
4090         if (ISDOT(dir_fsp->fsp_name->base_name)) {
4091                 /*
4092                  * We're at the toplevel dir, the final file name
4093                  * must not contain ./, as this is filtered out
4094                  * normally by srvstr_get_path and unix_convert
4095                  * explicitly rejects paths containing ./.
4096                  */
4097                 parent_fname = talloc_strdup(talloc_tos(), "");
4098                 if (parent_fname == NULL) {
4099                         status = NT_STATUS_NO_MEMORY;
4100                         goto out;
4101                 }
4102         } else {
4103                 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4104
4105                 /*
4106                  * Copy in the base directory name.
4107                  */
4108
4109                 parent_fname = talloc_array(talloc_tos(), char,
4110                     dir_name_len+2);
4111                 if (parent_fname == NULL) {
4112                         status = NT_STATUS_NO_MEMORY;
4113                         goto out;
4114                 }
4115                 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4116                     dir_name_len+1);
4117
4118                 /*
4119                  * Ensure it ends in a '/'.
4120                  * We used TALLOC_SIZE +2 to add space for the '/'.
4121                  */
4122
4123                 if(dir_name_len
4124                     && (parent_fname[dir_name_len-1] != '\\')
4125                     && (parent_fname[dir_name_len-1] != '/')) {
4126                         parent_fname[dir_name_len] = '/';
4127                         parent_fname[dir_name_len+1] = '\0';
4128                 }
4129         }
4130
4131         new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4132                                         smb_fname->base_name);
4133         if (new_base_name == NULL) {
4134                 status = NT_STATUS_NO_MEMORY;
4135                 goto out;
4136         }
4137
4138         status = filename_convert(req,
4139                                 conn,
4140                                 req->flags2 & FLAGS2_DFS_PATHNAMES,
4141                                 new_base_name,
4142                                 0,
4143                                 NULL,
4144                                 smb_fname_out);
4145         if (!NT_STATUS_IS_OK(status)) {
4146                 goto out;
4147         }
4148
4149  out:
4150         TALLOC_FREE(parent_fname);
4151         TALLOC_FREE(new_base_name);
4152         return status;
4153 }
4154
4155 NTSTATUS create_file_default(connection_struct *conn,
4156                              struct smb_request *req,
4157                              uint16_t root_dir_fid,
4158                              struct smb_filename *smb_fname,
4159                              uint32_t access_mask,
4160                              uint32_t share_access,
4161                              uint32_t create_disposition,
4162                              uint32_t create_options,
4163                              uint32_t file_attributes,
4164                              uint32_t oplock_request,
4165                              uint64_t allocation_size,
4166                              uint32_t private_flags,
4167                              struct security_descriptor *sd,
4168                              struct ea_list *ea_list,
4169                              files_struct **result,
4170                              int *pinfo)
4171 {
4172         int info = FILE_WAS_OPENED;
4173         files_struct *fsp = NULL;
4174         NTSTATUS status;
4175         bool stream_name = false;
4176
4177         DEBUG(10,("create_file: access_mask = 0x%x "
4178                   "file_attributes = 0x%x, share_access = 0x%x, "
4179                   "create_disposition = 0x%x create_options = 0x%x "
4180                   "oplock_request = 0x%x "
4181                   "private_flags = 0x%x "
4182                   "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4183                   "fname = %s\n",
4184                   (unsigned int)access_mask,
4185                   (unsigned int)file_attributes,
4186                   (unsigned int)share_access,
4187                   (unsigned int)create_disposition,
4188                   (unsigned int)create_options,
4189                   (unsigned int)oplock_request,
4190                   (unsigned int)private_flags,
4191                   (unsigned int)root_dir_fid,
4192                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
4193
4194         /*
4195          * Calculate the filename from the root_dir_if if necessary.
4196          */
4197
4198         if (root_dir_fid != 0) {
4199                 struct smb_filename *smb_fname_out = NULL;
4200                 status = get_relative_fid_filename(conn, req, root_dir_fid,
4201                                                    smb_fname, &smb_fname_out);
4202                 if (!NT_STATUS_IS_OK(status)) {
4203                         goto fail;
4204                 }
4205                 smb_fname = smb_fname_out;
4206         }
4207
4208         /*
4209          * Check to see if this is a mac fork of some kind.
4210          */
4211
4212         stream_name = is_ntfs_stream_smb_fname(smb_fname);
4213         if (stream_name) {
4214                 enum FAKE_FILE_TYPE fake_file_type;
4215
4216                 fake_file_type = is_fake_file(smb_fname);
4217
4218                 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4219
4220                         /*
4221                          * Here we go! support for changing the disk quotas
4222                          * --metze
4223                          *
4224                          * We need to fake up to open this MAGIC QUOTA file
4225                          * and return a valid FID.
4226                          *
4227                          * w2k close this file directly after openening xp
4228                          * also tries a QUERY_FILE_INFO on the file and then
4229                          * close it
4230                          */
4231                         status = open_fake_file(req, conn, req->vuid,
4232                                                 fake_file_type, smb_fname,
4233                                                 access_mask, &fsp);
4234                         if (!NT_STATUS_IS_OK(status)) {
4235                                 goto fail;
4236                         }
4237
4238                         ZERO_STRUCT(smb_fname->st);
4239                         goto done;
4240                 }
4241
4242                 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4243                         status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4244                         goto fail;
4245                 }
4246         }
4247
4248         if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4249                 int ret;
4250                 smb_fname->stream_name = NULL;
4251                 /* We have to handle this error here. */
4252                 if (create_options & FILE_DIRECTORY_FILE) {
4253                         status = NT_STATUS_NOT_A_DIRECTORY;
4254                         goto fail;
4255                 }
4256                 if (lp_posix_pathnames()) {
4257                         ret = SMB_VFS_LSTAT(conn, smb_fname);
4258                 } else {
4259                         ret = SMB_VFS_STAT(conn, smb_fname);
4260                 }
4261
4262                 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4263                         status = NT_STATUS_FILE_IS_A_DIRECTORY;
4264                         goto fail;
4265                 }
4266         }
4267
4268         status = create_file_unixpath(
4269                 conn, req, smb_fname, access_mask, share_access,
4270                 create_disposition, create_options, file_attributes,
4271                 oplock_request, allocation_size, private_flags,
4272                 sd, ea_list,
4273                 &fsp, &info);
4274
4275         if (!NT_STATUS_IS_OK(status)) {
4276                 goto fail;
4277         }
4278
4279  done:
4280         DEBUG(10, ("create_file: info=%d\n", info));
4281
4282         *result = fsp;
4283         if (pinfo != NULL) {
4284                 *pinfo = info;
4285         }
4286         return NT_STATUS_OK;
4287
4288  fail:
4289         DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4290
4291         if (fsp != NULL) {
4292                 close_file(req, fsp, ERROR_CLOSE);
4293                 fsp = NULL;
4294         }
4295         return status;
4296 }