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