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