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