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