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