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