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