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