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