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