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