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