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