93b69d5afd7549b719a1134fc8c9ebb81ddd0f52
[mat/samba.git] / source3 / smbd / open.c
1 /* 
2    Unix SMB/CIFS implementation.
3    file opening and share modes
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2004
6    Copyright (C) Volker Lendecke 2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "printing.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "../librpc/gen_ndr/open_files.h"
31 #include "../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                                 bool *file_existed)
1119 {
1120         int i;
1121
1122         if(lck->data->num_share_modes == 0) {
1123                 return NT_STATUS_OK;
1124         }
1125
1126         if (is_stat_open(access_mask)) {
1127                 /* Stat open that doesn't trigger oplock breaks or share mode
1128                  * checks... ! JRA. */
1129                 return NT_STATUS_OK;
1130         }
1131
1132         /*
1133          * Check if the share modes will give us access.
1134          */
1135
1136 #if defined(DEVELOPER)
1137         for(i = 0; i < lck->data->num_share_modes; i++) {
1138                 validate_my_share_entries(conn->sconn, i,
1139                                           &lck->data->share_modes[i]);
1140         }
1141 #endif
1142
1143         /* Now we check the share modes, after any oplock breaks. */
1144         for(i = 0; i < lck->data->num_share_modes; i++) {
1145
1146                 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1147                         continue;
1148                 }
1149
1150                 /* someone else has a share lock on it, check to see if we can
1151                  * too */
1152                 if (share_conflict(&lck->data->share_modes[i],
1153                                    access_mask, share_access)) {
1154
1155                         if (share_mode_stale_pid(lck->data, i)) {
1156                                 continue;
1157                         }
1158
1159                         *file_existed = true;
1160
1161                         return NT_STATUS_SHARING_VIOLATION;
1162                 }
1163         }
1164
1165         if (lck->data->num_share_modes != 0) {
1166                 *file_existed = true;
1167         }
1168
1169         return NT_STATUS_OK;
1170 }
1171
1172 /*
1173  * Send a break message to the oplock holder and delay the open for
1174  * our client.
1175  */
1176
1177 static NTSTATUS send_break_message(files_struct *fsp,
1178                                         struct share_mode_entry *exclusive,
1179                                         uint64_t mid,
1180                                         int oplock_request)
1181 {
1182         NTSTATUS status;
1183         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1184
1185         DEBUG(10, ("Sending break request to PID %s\n",
1186                    procid_str_static(&exclusive->pid)));
1187         exclusive->op_mid = mid;
1188
1189         /* Create the message. */
1190         share_mode_entry_to_message(msg, exclusive);
1191
1192         status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1193                                     MSG_SMB_BREAK_REQUEST,
1194                                     (uint8 *)msg, sizeof(msg));
1195         if (!NT_STATUS_IS_OK(status)) {
1196                 DEBUG(3, ("Could not send oplock break message: %s\n",
1197                           nt_errstr(status)));
1198         }
1199
1200         return status;
1201 }
1202
1203 /*
1204  * Return share_mode_entry pointers for :
1205  * 1). Batch oplock entry.
1206  * 2). Batch or exclusive oplock entry (may be identical to #1).
1207  * bool have_level2_oplock
1208  * bool have_no_oplock.
1209  * Do internal consistency checks on the share mode for a file.
1210  */
1211
1212 static void find_oplock_types(files_struct *fsp,
1213                                 int oplock_request,
1214                                 const struct share_mode_lock *lck,
1215                                 struct share_mode_entry **pp_batch,
1216                                 struct share_mode_entry **pp_ex_or_batch,
1217                                 bool *got_level2,
1218                                 bool *got_no_oplock)
1219 {
1220         int i;
1221
1222         *pp_batch = NULL;
1223         *pp_ex_or_batch = NULL;
1224         *got_level2 = false;
1225         *got_no_oplock = false;
1226
1227         /* Ignore stat or internal opens, as is done in
1228                 delay_for_batch_oplocks() and
1229                 delay_for_exclusive_oplocks().
1230          */
1231         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1232                 return;
1233         }
1234
1235         for (i=0; i<lck->data->num_share_modes; i++) {
1236                 struct share_mode_entry *e = &lck->data->share_modes[i];
1237
1238                 if (!is_valid_share_mode_entry(e)) {
1239                         continue;
1240                 }
1241
1242                 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1243                         /* We ignore stat opens in the table - they
1244                            always have NO_OPLOCK and never get or
1245                            cause breaks. JRA. */
1246                         continue;
1247                 }
1248
1249                 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1250                         /* batch - can only be one. */
1251                         if (share_mode_stale_pid(lck->data, i)) {
1252                                 DEBUG(10, ("Found stale batch oplock\n"));
1253                                 continue;
1254                         }
1255                         if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1256                                 smb_panic("Bad batch oplock entry.");
1257                         }
1258                         *pp_batch = e;
1259                 }
1260
1261                 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1262                         if (share_mode_stale_pid(lck->data, i)) {
1263                                 DEBUG(10, ("Found stale duplicate oplock\n"));
1264                                 continue;
1265                         }
1266                         /* Exclusive or batch - can only be one. */
1267                         if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1268                                 smb_panic("Bad exclusive or batch oplock entry.");
1269                         }
1270                         *pp_ex_or_batch = e;
1271                 }
1272
1273                 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1274                         if (*pp_batch || *pp_ex_or_batch) {
1275                                 if (share_mode_stale_pid(lck->data, i)) {
1276                                         DEBUG(10, ("Found stale LevelII "
1277                                                    "oplock\n"));
1278                                         continue;
1279                                 }
1280                                 smb_panic("Bad levelII oplock entry.");
1281                         }
1282                         *got_level2 = true;
1283                 }
1284
1285                 if (e->op_type == NO_OPLOCK) {
1286                         if (*pp_batch || *pp_ex_or_batch) {
1287                                 if (share_mode_stale_pid(lck->data, i)) {
1288                                         DEBUG(10, ("Found stale NO_OPLOCK "
1289                                                    "entry\n"));
1290                                         continue;
1291                                 }
1292                                 smb_panic("Bad no oplock entry.");
1293                         }
1294                         *got_no_oplock = true;
1295                 }
1296         }
1297 }
1298
1299 static bool delay_for_batch_oplocks(files_struct *fsp,
1300                                         uint64_t mid,
1301                                         int oplock_request,
1302                                         struct share_mode_entry *batch_entry)
1303 {
1304         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1305                 return false;
1306         }
1307         if (batch_entry == NULL) {
1308                 return false;
1309         }
1310
1311         if (server_id_is_disconnected(&batch_entry->pid)) {
1312                 /*
1313                  * TODO: clean up.
1314                  * This could be achieved by sending a break message
1315                  * to ourselves. Special considerations for files
1316                  * with delete_on_close flag set!
1317                  *
1318                  * For now we keep it simple and do not
1319                  * allow delete on close for durable handles.
1320                  */
1321                 return false;
1322         }
1323
1324         /* Found a batch oplock */
1325         send_break_message(fsp, batch_entry, mid, oplock_request);
1326         return true;
1327 }
1328
1329 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1330                                         uint64_t mid,
1331                                         int oplock_request,
1332                                         struct share_mode_entry *ex_entry)
1333 {
1334         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1335                 return false;
1336         }
1337         if (ex_entry == NULL) {
1338                 return false;
1339         }
1340
1341         if (server_id_is_disconnected(&ex_entry->pid)) {
1342                 /*
1343                  * since only durable handles can get disconnected,
1344                  * and we can only get durable handles with batch oplocks,
1345                  * this should actually never be reached...
1346                  */
1347                 return false;
1348         }
1349
1350         send_break_message(fsp, ex_entry, mid, oplock_request);
1351         return true;
1352 }
1353
1354 static bool file_has_brlocks(files_struct *fsp)
1355 {
1356         struct byte_range_lock *br_lck;
1357
1358         br_lck = brl_get_locks_readonly(fsp);
1359         if (!br_lck)
1360                 return false;
1361
1362         return (brl_num_locks(br_lck) > 0);
1363 }
1364
1365 static void grant_fsp_oplock_type(files_struct *fsp,
1366                                 int oplock_request,
1367                                 bool got_level2_oplock,
1368                                 bool got_a_none_oplock)
1369 {
1370         bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1371                             lp_level2_oplocks(SNUM(fsp->conn));
1372
1373         /* Start by granting what the client asked for,
1374            but ensure no SAMBA_PRIVATE bits can be set. */
1375         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1376
1377         if (oplock_request & INTERNAL_OPEN_ONLY) {
1378                 /* No oplocks on internal open. */
1379                 fsp->oplock_type = NO_OPLOCK;
1380                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1381                         fsp->oplock_type, fsp_str_dbg(fsp)));
1382                 return;
1383         }
1384
1385         if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1386                 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1387                         fsp_str_dbg(fsp)));
1388                 fsp->oplock_type = NO_OPLOCK;
1389         }
1390
1391         if (is_stat_open(fsp->access_mask)) {
1392                 /* Leave the value already set. */
1393                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1394                         fsp->oplock_type, fsp_str_dbg(fsp)));
1395                 return;
1396         }
1397
1398         /*
1399          * Match what was requested (fsp->oplock_type) with
1400          * what was found in the existing share modes.
1401          */
1402
1403         if (got_level2_oplock || got_a_none_oplock) {
1404                 if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1405                         fsp->oplock_type = LEVEL_II_OPLOCK;
1406                 }
1407         }
1408
1409         /*
1410          * Don't grant level2 to clients that don't want them
1411          * or if we've turned them off.
1412          */
1413         if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1414                 fsp->oplock_type = NO_OPLOCK;
1415         }
1416
1417         if (fsp->oplock_type == LEVEL_II_OPLOCK && !got_level2_oplock) {
1418                 /*
1419                  * We're the first level2 oplock. Indicate that in brlock.tdb.
1420                  */
1421                 struct byte_range_lock *brl;
1422
1423                 brl = brl_get_locks(talloc_tos(), fsp);
1424                 if (brl != NULL) {
1425                         brl_set_have_read_oplocks(brl, true);
1426                         TALLOC_FREE(brl);
1427                 }
1428         }
1429
1430         DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1431                   fsp->oplock_type, fsp_str_dbg(fsp)));
1432 }
1433
1434 static bool request_timed_out(struct timeval request_time,
1435                               struct timeval timeout)
1436 {
1437         struct timeval now, end_time;
1438         GetTimeOfDay(&now);
1439         end_time = timeval_sum(&request_time, &timeout);
1440         return (timeval_compare(&end_time, &now) < 0);
1441 }
1442
1443 struct defer_open_state {
1444         struct smbd_server_connection *sconn;
1445         uint64_t mid;
1446 };
1447
1448 static void defer_open_done(struct tevent_req *req);
1449
1450 /****************************************************************************
1451  Handle the 1 second delay in returning a SHARING_VIOLATION error.
1452 ****************************************************************************/
1453
1454 static void defer_open(struct share_mode_lock *lck,
1455                        struct timeval request_time,
1456                        struct timeval timeout,
1457                        struct smb_request *req,
1458                        struct deferred_open_record *state)
1459 {
1460         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1461                   "open entry for mid %llu\n",
1462                   (unsigned int)request_time.tv_sec,
1463                   (unsigned int)request_time.tv_usec,
1464                   (unsigned long long)req->mid));
1465
1466         if (!push_deferred_open_message_smb(req, request_time, timeout,
1467                                        state->id, (char *)state, sizeof(*state))) {
1468                 TALLOC_FREE(lck);
1469                 exit_server("push_deferred_open_message_smb failed");
1470         }
1471         if (lck) {
1472                 struct defer_open_state *watch_state;
1473                 struct tevent_req *watch_req;
1474                 bool ret;
1475
1476                 watch_state = talloc(req->sconn, struct defer_open_state);
1477                 if (watch_state == NULL) {
1478                         exit_server("talloc failed");
1479                 }
1480                 watch_state->sconn = req->sconn;
1481                 watch_state->mid = req->mid;
1482
1483                 DEBUG(10, ("defering mid %llu\n",
1484                            (unsigned long long)req->mid));
1485
1486                 watch_req = dbwrap_record_watch_send(
1487                         watch_state, req->sconn->ev_ctx, lck->data->record,
1488                         req->sconn->msg_ctx);
1489                 if (watch_req == NULL) {
1490                         exit_server("Could not watch share mode record");
1491                 }
1492                 tevent_req_set_callback(watch_req, defer_open_done,
1493                                         watch_state);
1494
1495                 ret = tevent_req_set_endtime(
1496                         watch_req, req->sconn->ev_ctx,
1497                         timeval_sum(&request_time, &timeout));
1498                 SMB_ASSERT(ret);
1499         }
1500 }
1501
1502 static void defer_open_done(struct tevent_req *req)
1503 {
1504         struct defer_open_state *state = tevent_req_callback_data(
1505                 req, struct defer_open_state);
1506         NTSTATUS status;
1507         bool ret;
1508
1509         status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1510         TALLOC_FREE(req);
1511         if (!NT_STATUS_IS_OK(status)) {
1512                 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1513                           nt_errstr(status)));
1514                 /*
1515                  * Even if it failed, retry anyway. TODO: We need a way to
1516                  * tell a re-scheduled open about that error.
1517                  */
1518         }
1519
1520         DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1521
1522         ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1523         SMB_ASSERT(ret);
1524         TALLOC_FREE(state);
1525 }
1526
1527
1528 /****************************************************************************
1529  On overwrite open ensure that the attributes match.
1530 ****************************************************************************/
1531
1532 static bool open_match_attributes(connection_struct *conn,
1533                                   uint32 old_dos_attr,
1534                                   uint32 new_dos_attr,
1535                                   mode_t existing_unx_mode,
1536                                   mode_t new_unx_mode,
1537                                   mode_t *returned_unx_mode)
1538 {
1539         uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1540
1541         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1542         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1543
1544         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
1545            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1546                 *returned_unx_mode = new_unx_mode;
1547         } else {
1548                 *returned_unx_mode = (mode_t)0;
1549         }
1550
1551         DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1552                   "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1553                   "returned_unx_mode = 0%o\n",
1554                   (unsigned int)old_dos_attr,
1555                   (unsigned int)existing_unx_mode,
1556                   (unsigned int)new_dos_attr,
1557                   (unsigned int)*returned_unx_mode ));
1558
1559         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1560         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1561                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1562                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1563                         return False;
1564                 }
1565         }
1566         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1567                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1568                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1569                         return False;
1570                 }
1571         }
1572         return True;
1573 }
1574
1575 /****************************************************************************
1576  Special FCB or DOS processing in the case of a sharing violation.
1577  Try and find a duplicated file handle.
1578 ****************************************************************************/
1579
1580 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1581                                 connection_struct *conn,
1582                                 files_struct *fsp_to_dup_into,
1583                                 const struct smb_filename *smb_fname,
1584                                 struct file_id id,
1585                                 uint16 file_pid,
1586                                 uint64_t vuid,
1587                                 uint32 access_mask,
1588                                 uint32 share_access,
1589                                 uint32 create_options)
1590 {
1591         files_struct *fsp;
1592
1593         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1594                  "file %s.\n", smb_fname_str_dbg(smb_fname)));
1595
1596         for(fsp = file_find_di_first(conn->sconn, id); fsp;
1597             fsp = file_find_di_next(fsp)) {
1598
1599                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1600                           "vuid = %llu, file_pid = %u, private_options = 0x%x "
1601                           "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1602                           fsp->fh->fd, (unsigned long long)fsp->vuid,
1603                           (unsigned int)fsp->file_pid,
1604                           (unsigned int)fsp->fh->private_options,
1605                           (unsigned int)fsp->access_mask ));
1606
1607                 if (fsp != fsp_to_dup_into &&
1608                     fsp->fh->fd != -1 &&
1609                     fsp->vuid == vuid &&
1610                     fsp->file_pid == file_pid &&
1611                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1612                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1613                     (fsp->access_mask & FILE_WRITE_DATA) &&
1614                     strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1615                     strequal(fsp->fsp_name->stream_name,
1616                              smb_fname->stream_name)) {
1617                         DEBUG(10,("fcb_or_dos_open: file match\n"));
1618                         break;
1619                 }
1620         }
1621
1622         if (!fsp) {
1623                 return NT_STATUS_NOT_FOUND;
1624         }
1625
1626         /* quite an insane set of semantics ... */
1627         if (is_executable(smb_fname->base_name) &&
1628             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1629                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1630                 return NT_STATUS_INVALID_PARAMETER;
1631         }
1632
1633         /* We need to duplicate this fsp. */
1634         return dup_file_fsp(req, fsp, access_mask, share_access,
1635                             create_options, fsp_to_dup_into);
1636 }
1637
1638 static void schedule_defer_open(struct share_mode_lock *lck,
1639                                 struct timeval request_time,
1640                                 struct smb_request *req)
1641 {
1642         struct deferred_open_record state;
1643
1644         /* This is a relative time, added to the absolute
1645            request_time value to get the absolute timeout time.
1646            Note that if this is the second or greater time we enter
1647            this codepath for this particular request mid then
1648            request_time is left as the absolute time of the *first*
1649            time this request mid was processed. This is what allows
1650            the request to eventually time out. */
1651
1652         struct timeval timeout;
1653
1654         /* Normally the smbd we asked should respond within
1655          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1656          * the client did, give twice the timeout as a safety
1657          * measure here in case the other smbd is stuck
1658          * somewhere else. */
1659
1660         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1661
1662         /* Nothing actually uses state.delayed_for_oplocks
1663            but it's handy to differentiate in debug messages
1664            between a 30 second delay due to oplock break, and
1665            a 1 second delay for share mode conflicts. */
1666
1667         state.delayed_for_oplocks = True;
1668         state.async_open = false;
1669         state.id = lck->data->id;
1670
1671         if (!request_timed_out(request_time, timeout)) {
1672                 defer_open(lck, request_time, timeout, req, &state);
1673         }
1674 }
1675
1676 /****************************************************************************
1677  Reschedule an open call that went asynchronous.
1678 ****************************************************************************/
1679
1680 static void schedule_async_open(struct timeval request_time,
1681                                 struct smb_request *req)
1682 {
1683         struct deferred_open_record state;
1684         struct timeval timeout;
1685
1686         timeout = timeval_set(20, 0);
1687
1688         ZERO_STRUCT(state);
1689         state.delayed_for_oplocks = false;
1690         state.async_open = true;
1691
1692         if (!request_timed_out(request_time, timeout)) {
1693                 defer_open(NULL, request_time, timeout, req, &state);
1694         }
1695 }
1696
1697 /****************************************************************************
1698  Work out what access_mask to use from what the client sent us.
1699 ****************************************************************************/
1700
1701 static NTSTATUS smbd_calculate_maximum_allowed_access(
1702         connection_struct *conn,
1703         const struct smb_filename *smb_fname,
1704         bool use_privs,
1705         uint32_t *p_access_mask)
1706 {
1707         struct security_descriptor *sd;
1708         uint32_t access_granted;
1709         NTSTATUS status;
1710
1711         if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1712                 *p_access_mask |= FILE_GENERIC_ALL;
1713                 return NT_STATUS_OK;
1714         }
1715
1716         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1717                                     (SECINFO_OWNER |
1718                                      SECINFO_GROUP |
1719                                      SECINFO_DACL),
1720                                     talloc_tos(), &sd);
1721
1722         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1723                 /*
1724                  * File did not exist
1725                  */
1726                 *p_access_mask = FILE_GENERIC_ALL;
1727                 return NT_STATUS_OK;
1728         }
1729         if (!NT_STATUS_IS_OK(status)) {
1730                 DEBUG(10,("Could not get acl on file %s: %s\n",
1731                           smb_fname_str_dbg(smb_fname),
1732                           nt_errstr(status)));
1733                 return NT_STATUS_ACCESS_DENIED;
1734         }
1735
1736         /*
1737          * If we can access the path to this file, by
1738          * default we have FILE_READ_ATTRIBUTES from the
1739          * containing directory. See the section:
1740          * "Algorithm to Check Access to an Existing File"
1741          * in MS-FSA.pdf.
1742          *
1743          * se_file_access_check()
1744          * also takes care of owner WRITE_DAC and READ_CONTROL.
1745          */
1746         status = se_file_access_check(sd,
1747                                  get_current_nttok(conn),
1748                                  use_privs,
1749                                  (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1750                                  &access_granted);
1751
1752         TALLOC_FREE(sd);
1753
1754         if (!NT_STATUS_IS_OK(status)) {
1755                 DEBUG(10, ("Access denied on file %s: "
1756                            "when calculating maximum access\n",
1757                            smb_fname_str_dbg(smb_fname)));
1758                 return NT_STATUS_ACCESS_DENIED;
1759         }
1760         *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1761
1762         if (!(access_granted & DELETE_ACCESS)) {
1763                 if (can_delete_file_in_directory(conn, smb_fname)) {
1764                         *p_access_mask |= DELETE_ACCESS;
1765                 }
1766         }
1767
1768         return NT_STATUS_OK;
1769 }
1770
1771 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1772                                     const struct smb_filename *smb_fname,
1773                                     bool use_privs,
1774                                     uint32_t access_mask,
1775                                     uint32_t *access_mask_out)
1776 {
1777         NTSTATUS status;
1778         uint32_t orig_access_mask = access_mask;
1779         uint32_t rejected_share_access;
1780
1781         /*
1782          * Convert GENERIC bits to specific bits.
1783          */
1784
1785         se_map_generic(&access_mask, &file_generic_mapping);
1786
1787         /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1788         if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1789
1790                 status = smbd_calculate_maximum_allowed_access(
1791                         conn, smb_fname, use_privs, &access_mask);
1792
1793                 if (!NT_STATUS_IS_OK(status)) {
1794                         return status;
1795                 }
1796
1797                 access_mask &= conn->share_access;
1798         }
1799
1800         rejected_share_access = access_mask & ~(conn->share_access);
1801
1802         if (rejected_share_access) {
1803                 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1804                         "file %s: rejected by share access mask[0x%08X] "
1805                         "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1806                         smb_fname_str_dbg(smb_fname),
1807                         conn->share_access,
1808                         orig_access_mask, access_mask,
1809                         rejected_share_access));
1810                 return NT_STATUS_ACCESS_DENIED;
1811         }
1812
1813         *access_mask_out = access_mask;
1814         return NT_STATUS_OK;
1815 }
1816
1817 /****************************************************************************
1818  Remove the deferred open entry under lock.
1819 ****************************************************************************/
1820
1821 /****************************************************************************
1822  Return true if this is a state pointer to an asynchronous create.
1823 ****************************************************************************/
1824
1825 bool is_deferred_open_async(const void *ptr)
1826 {
1827         const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1828
1829         return state->async_open;
1830 }
1831
1832 static bool clear_ads(uint32_t create_disposition)
1833 {
1834         bool ret = false;
1835
1836         switch (create_disposition) {
1837         case FILE_SUPERSEDE:
1838         case FILE_OVERWRITE_IF:
1839         case FILE_OVERWRITE:
1840                 ret = true;
1841                 break;
1842         default:
1843                 break;
1844         }
1845         return ret;
1846 }
1847
1848 static int disposition_to_open_flags(uint32_t create_disposition)
1849 {
1850         int ret = 0;
1851
1852         /*
1853          * Currently we're using FILE_SUPERSEDE as the same as
1854          * FILE_OVERWRITE_IF but they really are
1855          * different. FILE_SUPERSEDE deletes an existing file
1856          * (requiring delete access) then recreates it.
1857          */
1858
1859         switch (create_disposition) {
1860         case FILE_SUPERSEDE:
1861         case FILE_OVERWRITE_IF:
1862                 /*
1863                  * If file exists replace/overwrite. If file doesn't
1864                  * exist create.
1865                  */
1866                 ret = O_CREAT|O_TRUNC;
1867                 break;
1868
1869         case FILE_OPEN:
1870                 /*
1871                  * If file exists open. If file doesn't exist error.
1872                  */
1873                 ret = 0;
1874                 break;
1875
1876         case FILE_OVERWRITE:
1877                 /*
1878                  * If file exists overwrite. If file doesn't exist
1879                  * error.
1880                  */
1881                 ret = O_TRUNC;
1882                 break;
1883
1884         case FILE_CREATE:
1885                 /*
1886                  * If file exists error. If file doesn't exist create.
1887                  */
1888                 ret = O_CREAT|O_EXCL;
1889                 break;
1890
1891         case FILE_OPEN_IF:
1892                 /*
1893                  * If file exists open. If file doesn't exist create.
1894                  */
1895                 ret = O_CREAT;
1896                 break;
1897         }
1898         return ret;
1899 }
1900
1901 static int calculate_open_access_flags(uint32_t access_mask,
1902                                        int oplock_request,
1903                                        uint32_t private_flags)
1904 {
1905         bool need_write, need_read;
1906
1907         /*
1908          * Note that we ignore the append flag as append does not
1909          * mean the same thing under DOS and Unix.
1910          */
1911
1912         need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
1913         if (!need_write) {
1914                 return O_RDONLY;
1915         }
1916
1917         /* DENY_DOS opens are always underlying read-write on the
1918            file handle, no matter what the requested access mask
1919            says. */
1920
1921         need_read =
1922                 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1923                  access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1924                                 FILE_READ_EA|FILE_EXECUTE));
1925
1926         if (!need_read) {
1927                 return O_WRONLY;
1928         }
1929         return O_RDWR;
1930 }
1931
1932 /****************************************************************************
1933  Open a file with a share mode. Passed in an already created files_struct *.
1934 ****************************************************************************/
1935
1936 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1937                             struct smb_request *req,
1938                             uint32 access_mask,         /* access bits (FILE_READ_DATA etc.) */
1939                             uint32 share_access,        /* share constants (FILE_SHARE_READ etc) */
1940                             uint32 create_disposition,  /* FILE_OPEN_IF etc. */
1941                             uint32 create_options,      /* options such as delete on close. */
1942                             uint32 new_dos_attributes,  /* attributes used for new file. */
1943                             int oplock_request,         /* internal Samba oplock codes. */
1944                                                         /* Information (FILE_EXISTS etc.) */
1945                             uint32_t private_flags,     /* Samba specific flags. */
1946                             int *pinfo,
1947                             files_struct *fsp)
1948 {
1949         struct smb_filename *smb_fname = fsp->fsp_name;
1950         int flags=0;
1951         int flags2=0;
1952         bool file_existed = VALID_STAT(smb_fname->st);
1953         bool def_acl = False;
1954         bool posix_open = False;
1955         bool new_file_created = False;
1956         bool first_open_attempt = true;
1957         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1958         mode_t new_unx_mode = (mode_t)0;
1959         mode_t unx_mode = (mode_t)0;
1960         int info;
1961         uint32 existing_dos_attributes = 0;
1962         struct timeval request_time = timeval_zero();
1963         struct share_mode_lock *lck = NULL;
1964         uint32 open_access_mask = access_mask;
1965         NTSTATUS status;
1966         char *parent_dir;
1967         SMB_STRUCT_STAT saved_stat = smb_fname->st;
1968         struct share_mode_entry *batch_entry = NULL;
1969         struct share_mode_entry *exclusive_entry = NULL;
1970         bool got_level2_oplock = false;
1971         bool got_a_none_oplock = false;
1972         struct timespec old_write_time;
1973         struct file_id id;
1974
1975         if (conn->printer) {
1976                 /*
1977                  * Printers are handled completely differently.
1978                  * Most of the passed parameters are ignored.
1979                  */
1980
1981                 if (pinfo) {
1982                         *pinfo = FILE_WAS_CREATED;
1983                 }
1984
1985                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
1986                            smb_fname_str_dbg(smb_fname)));
1987
1988                 if (!req) {
1989                         DEBUG(0,("open_file_ntcreate: printer open without "
1990                                 "an SMB request!\n"));
1991                         return NT_STATUS_INTERNAL_ERROR;
1992                 }
1993
1994                 return print_spool_open(fsp, smb_fname->base_name,
1995                                         req->vuid);
1996         }
1997
1998         if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
1999                             NULL)) {
2000                 return NT_STATUS_NO_MEMORY;
2001         }
2002
2003         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2004                 posix_open = True;
2005                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2006                 new_dos_attributes = 0;
2007         } else {
2008                 /* Windows allows a new file to be created and
2009                    silently removes a FILE_ATTRIBUTE_DIRECTORY
2010                    sent by the client. Do the same. */
2011
2012                 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2013
2014                 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2015                  * created new. */
2016                 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2017                                      smb_fname, parent_dir);
2018         }
2019
2020         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2021                    "access_mask=0x%x share_access=0x%x "
2022                    "create_disposition = 0x%x create_options=0x%x "
2023                    "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2024                    smb_fname_str_dbg(smb_fname), new_dos_attributes,
2025                    access_mask, share_access, create_disposition,
2026                    create_options, (unsigned int)unx_mode, oplock_request,
2027                    (unsigned int)private_flags));
2028
2029         if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2030                 DEBUG(0, ("No smb request but not an internal only open!\n"));
2031                 return NT_STATUS_INTERNAL_ERROR;
2032         }
2033
2034         /*
2035          * Only non-internal opens can be deferred at all
2036          */
2037
2038         if (req) {
2039                 void *ptr;
2040                 if (get_deferred_open_message_state(req,
2041                                 &request_time,
2042                                 &ptr)) {
2043                         /* Remember the absolute time of the original
2044                            request with this mid. We'll use it later to
2045                            see if this has timed out. */
2046
2047                         /* If it was an async create retry, the file
2048                            didn't exist. */
2049
2050                         if (is_deferred_open_async(ptr)) {
2051                                 SET_STAT_INVALID(smb_fname->st);
2052                                 file_existed = false;
2053                         }
2054
2055                         /* Ensure we don't reprocess this message. */
2056                         remove_deferred_open_message_smb(req->sconn, req->mid);
2057
2058                         first_open_attempt = false;
2059                 }
2060         }
2061
2062         if (!posix_open) {
2063                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2064                 if (file_existed) {
2065                         existing_dos_attributes = dos_mode(conn, smb_fname);
2066                 }
2067         }
2068
2069         /* ignore any oplock requests if oplocks are disabled */
2070         if (!lp_oplocks(SNUM(conn)) ||
2071             IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2072                 /* Mask off everything except the private Samba bits. */
2073                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2074         }
2075
2076         /* this is for OS/2 long file names - say we don't support them */
2077         if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2078                 /* OS/2 Workplace shell fix may be main code stream in a later
2079                  * release. */
2080                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2081                          "supported.\n"));
2082                 if (use_nt_status()) {
2083                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2084                 }
2085                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2086         }
2087
2088         switch( create_disposition ) {
2089                 case FILE_OPEN:
2090                         /* If file exists open. If file doesn't exist error. */
2091                         if (!file_existed) {
2092                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2093                                          "requested for file %s and file "
2094                                          "doesn't exist.\n",
2095                                          smb_fname_str_dbg(smb_fname)));
2096                                 errno = ENOENT;
2097                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2098                         }
2099                         break;
2100
2101                 case FILE_OVERWRITE:
2102                         /* If file exists overwrite. If file doesn't exist
2103                          * error. */
2104                         if (!file_existed) {
2105                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2106                                          "requested for file %s and file "
2107                                          "doesn't exist.\n",
2108                                          smb_fname_str_dbg(smb_fname) ));
2109                                 errno = ENOENT;
2110                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2111                         }
2112                         break;
2113
2114                 case FILE_CREATE:
2115                         /* If file exists error. If file doesn't exist
2116                          * create. */
2117                         if (file_existed) {
2118                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2119                                          "requested for file %s and file "
2120                                          "already exists.\n",
2121                                          smb_fname_str_dbg(smb_fname)));
2122                                 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2123                                         errno = EISDIR;
2124                                 } else {
2125                                         errno = EEXIST;
2126                                 }
2127                                 return map_nt_error_from_unix(errno);
2128                         }
2129                         break;
2130
2131                 case FILE_SUPERSEDE:
2132                 case FILE_OVERWRITE_IF:
2133                 case FILE_OPEN_IF:
2134                         break;
2135                 default:
2136                         return NT_STATUS_INVALID_PARAMETER;
2137         }
2138
2139         flags2 = disposition_to_open_flags(create_disposition);
2140
2141         /* We only care about matching attributes on file exists and
2142          * overwrite. */
2143
2144         if (!posix_open && file_existed &&
2145             ((create_disposition == FILE_OVERWRITE) ||
2146              (create_disposition == FILE_OVERWRITE_IF))) {
2147                 if (!open_match_attributes(conn, existing_dos_attributes,
2148                                            new_dos_attributes,
2149                                            smb_fname->st.st_ex_mode,
2150                                            unx_mode, &new_unx_mode)) {
2151                         DEBUG(5,("open_file_ntcreate: attributes missmatch "
2152                                  "for file %s (%x %x) (0%o, 0%o)\n",
2153                                  smb_fname_str_dbg(smb_fname),
2154                                  existing_dos_attributes,
2155                                  new_dos_attributes,
2156                                  (unsigned int)smb_fname->st.st_ex_mode,
2157                                  (unsigned int)unx_mode ));
2158                         errno = EACCES;
2159                         return NT_STATUS_ACCESS_DENIED;
2160                 }
2161         }
2162
2163         status = smbd_calculate_access_mask(conn, smb_fname,
2164                                         false,
2165                                         access_mask,
2166                                         &access_mask); 
2167         if (!NT_STATUS_IS_OK(status)) {
2168                 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2169                         "on file %s returned %s\n",
2170                         smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2171                 return status;
2172         }
2173
2174         open_access_mask = access_mask;
2175
2176         if (flags2 & O_TRUNC) {
2177                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2178         }
2179
2180         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2181                    "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2182                     access_mask));
2183
2184         /*
2185          * Note that we ignore the append flag as append does not
2186          * mean the same thing under DOS and Unix.
2187          */
2188
2189         flags = calculate_open_access_flags(access_mask, oplock_request,
2190                                             private_flags);
2191
2192         /*
2193          * Currently we only look at FILE_WRITE_THROUGH for create options.
2194          */
2195
2196 #if defined(O_SYNC)
2197         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2198                 flags2 |= O_SYNC;
2199         }
2200 #endif /* O_SYNC */
2201
2202         if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2203                 flags2 |= O_APPEND;
2204         }
2205
2206         if (!posix_open && !CAN_WRITE(conn)) {
2207                 /*
2208                  * We should really return a permission denied error if either
2209                  * O_CREAT or O_TRUNC are set, but for compatibility with
2210                  * older versions of Samba we just AND them out.
2211                  */
2212                 flags2 &= ~(O_CREAT|O_TRUNC);
2213         }
2214
2215         if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2216                 /*
2217                  * With kernel oplocks the open breaking an oplock
2218                  * blocks until the oplock holder has given up the
2219                  * oplock or closed the file. We prevent this by first
2220                  * trying to open the file with O_NONBLOCK (see "man
2221                  * fcntl" on Linux). For the second try, triggered by
2222                  * an oplock break response, we do not need this
2223                  * anymore.
2224                  *
2225                  * This is true under the assumption that only Samba
2226                  * requests kernel oplocks. Once someone else like
2227                  * NFSv4 starts to use that API, we will have to
2228                  * modify this by communicating with the NFSv4 server.
2229                  */
2230                 flags2 |= O_NONBLOCK;
2231         }
2232
2233         /*
2234          * Ensure we can't write on a read-only share or file.
2235          */
2236
2237         if (flags != O_RDONLY && file_existed &&
2238             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2239                 DEBUG(5,("open_file_ntcreate: write access requested for "
2240                          "file %s on read only %s\n",
2241                          smb_fname_str_dbg(smb_fname),
2242                          !CAN_WRITE(conn) ? "share" : "file" ));
2243                 errno = EACCES;
2244                 return NT_STATUS_ACCESS_DENIED;
2245         }
2246
2247         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2248         fsp->share_access = share_access;
2249         fsp->fh->private_options = private_flags;
2250         fsp->access_mask = open_access_mask; /* We change this to the
2251                                               * requested access_mask after
2252                                               * the open is done. */
2253         fsp->posix_open = posix_open;
2254
2255         /* Ensure no SAMBA_PRIVATE bits can be set. */
2256         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2257
2258         if (timeval_is_zero(&request_time)) {
2259                 request_time = fsp->open_time;
2260         }
2261
2262         /*
2263          * Ensure we pay attention to default ACLs on directories if required.
2264          */
2265
2266         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2267             (def_acl = directory_has_default_acl(conn, parent_dir))) {
2268                 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2269         }
2270
2271         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2272                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2273                  (unsigned int)flags, (unsigned int)flags2,
2274                  (unsigned int)unx_mode, (unsigned int)access_mask,
2275                  (unsigned int)open_access_mask));
2276
2277         fsp_open = open_file(fsp, conn, req, parent_dir,
2278                              flags|flags2, unx_mode, access_mask,
2279                              open_access_mask, &new_file_created);
2280
2281         if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2282                 struct deferred_open_record state;
2283
2284                 /*
2285                  * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2286                  */
2287                 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2288                         DEBUG(10, ("FIFO busy\n"));
2289                         return NT_STATUS_NETWORK_BUSY;
2290                 }
2291                 if (req == NULL) {
2292                         DEBUG(10, ("Internal open busy\n"));
2293                         return NT_STATUS_NETWORK_BUSY;
2294                 }
2295
2296                 /*
2297                  * From here on we assume this is an oplock break triggered
2298                  */
2299
2300                 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2301                 if (lck == NULL) {
2302                         state.delayed_for_oplocks = false;
2303                         state.async_open = false;
2304                         state.id = fsp->file_id;
2305                         defer_open(NULL, request_time, timeval_set(0, 0),
2306                                    req, &state);
2307                         DEBUG(10, ("No share mode lock found after "
2308                                    "EWOULDBLOCK, retrying sync\n"));
2309                         return NT_STATUS_SHARING_VIOLATION;
2310                 }
2311
2312                 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2313                                   &got_level2_oplock, &got_a_none_oplock);
2314
2315                 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2316                     delay_for_exclusive_oplocks(fsp, req->mid, 0,
2317                                                 exclusive_entry)) {
2318                         schedule_defer_open(lck, request_time, req);
2319                         TALLOC_FREE(lck);
2320                         DEBUG(10, ("Sent oplock break request to kernel "
2321                                    "oplock holder\n"));
2322                         return NT_STATUS_SHARING_VIOLATION;
2323                 }
2324
2325                 /*
2326                  * No oplock from Samba around. Immediately retry with
2327                  * a blocking open.
2328                  */
2329                 state.delayed_for_oplocks = false;
2330                 state.async_open = false;
2331                 state.id = lck->data->id;
2332                 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2333                 TALLOC_FREE(lck);
2334                 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2335                            "Retrying sync\n"));
2336                 return NT_STATUS_SHARING_VIOLATION;
2337         }
2338
2339         if (!NT_STATUS_IS_OK(fsp_open)) {
2340                 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2341                         schedule_async_open(request_time, req);
2342                 }
2343                 return fsp_open;
2344         }
2345
2346         if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2347                 /*
2348                  * The file did exist, but some other (local or NFS)
2349                  * process either renamed/unlinked and re-created the
2350                  * file with different dev/ino after we walked the path,
2351                  * but before we did the open. We could retry the
2352                  * open but it's a rare enough case it's easier to
2353                  * just fail the open to prevent creating any problems
2354                  * in the open file db having the wrong dev/ino key.
2355                  */
2356                 fd_close(fsp);
2357                 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2358                         "Old (dev=0x%llu, ino =0x%llu). "
2359                         "New (dev=0x%llu, ino=0x%llu). Failing open "
2360                         " with NT_STATUS_ACCESS_DENIED.\n",
2361                          smb_fname_str_dbg(smb_fname),
2362                          (unsigned long long)saved_stat.st_ex_dev,
2363                          (unsigned long long)saved_stat.st_ex_ino,
2364                          (unsigned long long)smb_fname->st.st_ex_dev,
2365                          (unsigned long long)smb_fname->st.st_ex_ino));
2366                 return NT_STATUS_ACCESS_DENIED;
2367         }
2368
2369         old_write_time = smb_fname->st.st_ex_mtime;
2370
2371         /*
2372          * Deal with the race condition where two smbd's detect the
2373          * file doesn't exist and do the create at the same time. One
2374          * of them will win and set a share mode, the other (ie. this
2375          * one) should check if the requested share mode for this
2376          * create is allowed.
2377          */
2378
2379         /*
2380          * Now the file exists and fsp is successfully opened,
2381          * fsp->dev and fsp->inode are valid and should replace the
2382          * dev=0,inode=0 from a non existent file. Spotted by
2383          * Nadav Danieli <nadavd@exanet.com>. JRA.
2384          */
2385
2386         id = fsp->file_id;
2387
2388         lck = get_share_mode_lock(talloc_tos(), id,
2389                                   conn->connectpath,
2390                                   smb_fname, &old_write_time);
2391
2392         if (lck == NULL) {
2393                 DEBUG(0, ("open_file_ntcreate: Could not get share "
2394                           "mode lock for %s\n",
2395                           smb_fname_str_dbg(smb_fname)));
2396                 fd_close(fsp);
2397                 return NT_STATUS_SHARING_VIOLATION;
2398         }
2399
2400         /* Get the types we need to examine. */
2401         find_oplock_types(fsp,
2402                           oplock_request,
2403                           lck,
2404                           &batch_entry,
2405                           &exclusive_entry,
2406                           &got_level2_oplock,
2407                           &got_a_none_oplock);
2408
2409         if (has_delete_on_close(lck, fsp->name_hash)) {
2410                 TALLOC_FREE(lck);
2411                 fd_close(fsp);
2412                 return NT_STATUS_DELETE_PENDING;
2413         }
2414
2415         /* First pass - send break only on batch oplocks. */
2416         if ((req != NULL) &&
2417             delay_for_batch_oplocks(fsp,
2418                                     req->mid,
2419                                     oplock_request,
2420                                     batch_entry)) {
2421                 schedule_defer_open(lck, request_time, req);
2422                 TALLOC_FREE(lck);
2423                 fd_close(fsp);
2424                 return NT_STATUS_SHARING_VIOLATION;
2425         }
2426
2427         status = open_mode_check(conn, lck,
2428                                  access_mask, share_access,
2429                                  &file_existed);
2430
2431         if (NT_STATUS_IS_OK(status)) {
2432                 /* We might be going to allow this open. Check oplock
2433                  * status again. */
2434                 /* Second pass - send break for both batch or
2435                  * exclusive oplocks. */
2436                 if ((req != NULL) &&
2437                     delay_for_exclusive_oplocks(
2438                             fsp,
2439                             req->mid,
2440                             oplock_request,
2441                             exclusive_entry)) {
2442                         schedule_defer_open(lck, request_time, req);
2443                         TALLOC_FREE(lck);
2444                         fd_close(fsp);
2445                         return NT_STATUS_SHARING_VIOLATION;
2446                 }
2447         }
2448
2449         if (!NT_STATUS_IS_OK(status)) {
2450                 uint32 can_access_mask;
2451                 bool can_access = True;
2452
2453                 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2454
2455                 /* Check if this can be done with the deny_dos and fcb
2456                  * calls. */
2457                 if (private_flags &
2458                     (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2459                      NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2460                         if (req == NULL) {
2461                                 DEBUG(0, ("DOS open without an SMB "
2462                                           "request!\n"));
2463                                 TALLOC_FREE(lck);
2464                                 fd_close(fsp);
2465                                 return NT_STATUS_INTERNAL_ERROR;
2466                         }
2467
2468                         /* Use the client requested access mask here,
2469                          * not the one we open with. */
2470                         status = fcb_or_dos_open(req,
2471                                                  conn,
2472                                                  fsp,
2473                                                  smb_fname,
2474                                                  id,
2475                                                  req->smbpid,
2476                                                  req->vuid,
2477                                                  access_mask,
2478                                                  share_access,
2479                                                  create_options);
2480
2481                         if (NT_STATUS_IS_OK(status)) {
2482                                 TALLOC_FREE(lck);
2483                                 if (pinfo) {
2484                                         *pinfo = FILE_WAS_OPENED;
2485                                 }
2486                                 return NT_STATUS_OK;
2487                         }
2488                 }
2489
2490                 /*
2491                  * This next line is a subtlety we need for
2492                  * MS-Access. If a file open will fail due to share
2493                  * permissions and also for security (access) reasons,
2494                  * we need to return the access failed error, not the
2495                  * share error. We can't open the file due to kernel
2496                  * oplock deadlock (it's possible we failed above on
2497                  * the open_mode_check()) so use a userspace check.
2498                  */
2499
2500                 if (flags & O_RDWR) {
2501                         can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2502                 } else if (flags & O_WRONLY) {
2503                         can_access_mask = FILE_WRITE_DATA;
2504                 } else {
2505                         can_access_mask = FILE_READ_DATA;
2506                 }
2507
2508                 if (((can_access_mask & FILE_WRITE_DATA) &&
2509                      !CAN_WRITE(conn)) ||
2510                     !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2511                                                               smb_fname,
2512                                                               false,
2513                                                               can_access_mask))) {
2514                         can_access = False;
2515                 }
2516
2517                 /*
2518                  * If we're returning a share violation, ensure we
2519                  * cope with the braindead 1 second delay (SMB1 only).
2520                  */
2521
2522                 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2523                     !conn->sconn->using_smb2 &&
2524                     lp_defer_sharing_violations()) {
2525                         struct timeval timeout;
2526                         struct deferred_open_record state;
2527                         int timeout_usecs;
2528
2529                         /* this is a hack to speed up torture tests
2530                            in 'make test' */
2531                         timeout_usecs = lp_parm_int(SNUM(conn),
2532                                                     "smbd","sharedelay",
2533                                                     SHARING_VIOLATION_USEC_WAIT);
2534
2535                         /* This is a relative time, added to the absolute
2536                            request_time value to get the absolute timeout time.
2537                            Note that if this is the second or greater time we enter
2538                            this codepath for this particular request mid then
2539                            request_time is left as the absolute time of the *first*
2540                            time this request mid was processed. This is what allows
2541                            the request to eventually time out. */
2542
2543                         timeout = timeval_set(0, timeout_usecs);
2544
2545                         /* Nothing actually uses state.delayed_for_oplocks
2546                            but it's handy to differentiate in debug messages
2547                            between a 30 second delay due to oplock break, and
2548                            a 1 second delay for share mode conflicts. */
2549
2550                         state.delayed_for_oplocks = False;
2551                         state.async_open = false;
2552                         state.id = id;
2553
2554                         if ((req != NULL)
2555                             && !request_timed_out(request_time,
2556                                                   timeout)) {
2557                                 defer_open(lck, request_time, timeout,
2558                                            req, &state);
2559                         }
2560                 }
2561
2562                 TALLOC_FREE(lck);
2563                 fd_close(fsp);
2564                 if (can_access) {
2565                         /*
2566                          * We have detected a sharing violation here
2567                          * so return the correct error code
2568                          */
2569                         status = NT_STATUS_SHARING_VIOLATION;
2570                 } else {
2571                         status = NT_STATUS_ACCESS_DENIED;
2572                 }
2573                 return status;
2574         }
2575
2576         grant_fsp_oplock_type(fsp,
2577                               oplock_request,
2578                               got_level2_oplock,
2579                               got_a_none_oplock);
2580
2581         /*
2582          * We have the share entry *locked*.....
2583          */
2584
2585         /* Delete streams if create_disposition requires it */
2586         if (!new_file_created && clear_ads(create_disposition) &&
2587             !is_ntfs_stream_smb_fname(smb_fname)) {
2588                 status = delete_all_streams(conn, smb_fname->base_name);
2589                 if (!NT_STATUS_IS_OK(status)) {
2590                         TALLOC_FREE(lck);
2591                         fd_close(fsp);
2592                         return status;
2593                 }
2594         }
2595
2596         /* note that we ignore failure for the following. It is
2597            basically a hack for NFS, and NFS will never set one of
2598            these only read them. Nobody but Samba can ever set a deny
2599            mode and we have already checked our more authoritative
2600            locking database for permission to set this deny mode. If
2601            the kernel refuses the operations then the kernel is wrong.
2602            note that GPFS supports it as well - jmcd */
2603
2604         if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2605                 int ret_flock;
2606                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2607                 if(ret_flock == -1 ){
2608
2609                         TALLOC_FREE(lck);
2610                         fd_close(fsp);
2611
2612                         return NT_STATUS_SHARING_VIOLATION;
2613                 }
2614         }
2615
2616         /*
2617          * At this point onwards, we can guarantee that the share entry
2618          * is locked, whether we created the file or not, and that the
2619          * deny mode is compatible with all current opens.
2620          */
2621
2622         /*
2623          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2624          * but we don't have to store this - just ignore it on access check.
2625          */
2626         if (conn->sconn->using_smb2) {
2627                 /*
2628                  * SMB2 doesn't return it (according to Microsoft tests).
2629                  * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2630                  * File created with access = 0x7 (Read, Write, Delete)
2631                  * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2632                  */
2633                 fsp->access_mask = access_mask;
2634         } else {
2635                 /* But SMB1 does. */
2636                 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2637         }
2638
2639         if (file_existed) {
2640                 /* stat opens on existing files don't get oplocks. */
2641                 if (is_stat_open(open_access_mask)) {
2642                         fsp->oplock_type = NO_OPLOCK;
2643                 }
2644         }
2645
2646         if (new_file_created) {
2647                 info = FILE_WAS_CREATED;
2648         } else {
2649                 if (flags2 & O_TRUNC) {
2650                         info = FILE_WAS_OVERWRITTEN;
2651                 } else {
2652                         info = FILE_WAS_OPENED;
2653                 }
2654         }
2655
2656         if (pinfo) {
2657                 *pinfo = info;
2658         }
2659
2660         /*
2661          * Setup the oplock info in both the shared memory and
2662          * file structs.
2663          */
2664
2665         status = set_file_oplock(fsp, fsp->oplock_type);
2666         if (!NT_STATUS_IS_OK(status)) {
2667                 /*
2668                  * Could not get the kernel oplock
2669                  */
2670                 fsp->oplock_type = NO_OPLOCK;
2671         }
2672
2673         if (!set_share_mode(lck, fsp, get_current_uid(conn),
2674                             req ? req->mid : 0,
2675                             fsp->oplock_type)) {
2676                 TALLOC_FREE(lck);
2677                 fd_close(fsp);
2678                 return NT_STATUS_NO_MEMORY;
2679         }
2680
2681         /* Handle strange delete on close create semantics. */
2682         if (create_options & FILE_DELETE_ON_CLOSE) {
2683
2684                 status = can_set_delete_on_close(fsp, new_dos_attributes);
2685
2686                 if (!NT_STATUS_IS_OK(status)) {
2687                         /* Remember to delete the mode we just added. */
2688                         del_share_mode(lck, fsp);
2689                         TALLOC_FREE(lck);
2690                         fd_close(fsp);
2691                         return status;
2692                 }
2693                 /* Note that here we set the *inital* delete on close flag,
2694                    not the regular one. The magic gets handled in close. */
2695                 fsp->initial_delete_on_close = True;
2696         }
2697
2698         if (info != FILE_WAS_OPENED) {
2699                 /* Files should be initially set as archive */
2700                 if (lp_map_archive(SNUM(conn)) ||
2701                     lp_store_dos_attributes(SNUM(conn))) {
2702                         if (!posix_open) {
2703                                 if (file_set_dosmode(conn, smb_fname,
2704                                             new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2705                                             parent_dir, true) == 0) {
2706                                         unx_mode = smb_fname->st.st_ex_mode;
2707                                 }
2708                         }
2709                 }
2710         }
2711
2712         /* Determine sparse flag. */
2713         if (posix_open) {
2714                 /* POSIX opens are sparse by default. */
2715                 fsp->is_sparse = true;
2716         } else {
2717                 fsp->is_sparse = (file_existed &&
2718                         (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2719         }
2720
2721         /*
2722          * Take care of inherited ACLs on created files - if default ACL not
2723          * selected.
2724          */
2725
2726         if (!posix_open && new_file_created && !def_acl) {
2727
2728                 int saved_errno = errno; /* We might get ENOSYS in the next
2729                                           * call.. */
2730
2731                 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2732                     errno == ENOSYS) {
2733                         errno = saved_errno; /* Ignore ENOSYS */
2734                 }
2735
2736         } else if (new_unx_mode) {
2737
2738                 int ret = -1;
2739
2740                 /* Attributes need changing. File already existed. */
2741
2742                 {
2743                         int saved_errno = errno; /* We might get ENOSYS in the
2744                                                   * next call.. */
2745                         ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2746
2747                         if (ret == -1 && errno == ENOSYS) {
2748                                 errno = saved_errno; /* Ignore ENOSYS */
2749                         } else {
2750                                 DEBUG(5, ("open_file_ntcreate: reset "
2751                                           "attributes of file %s to 0%o\n",
2752                                           smb_fname_str_dbg(smb_fname),
2753                                           (unsigned int)new_unx_mode));
2754                                 ret = 0; /* Don't do the fchmod below. */
2755                         }
2756                 }
2757
2758                 if ((ret == -1) &&
2759                     (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2760                         DEBUG(5, ("open_file_ntcreate: failed to reset "
2761                                   "attributes of file %s to 0%o\n",
2762                                   smb_fname_str_dbg(smb_fname),
2763                                   (unsigned int)new_unx_mode));
2764         }
2765
2766         TALLOC_FREE(lck);
2767
2768         return NT_STATUS_OK;
2769 }
2770
2771
2772 /****************************************************************************
2773  Open a file for for write to ensure that we can fchmod it.
2774 ****************************************************************************/
2775
2776 NTSTATUS open_file_fchmod(connection_struct *conn,
2777                           struct smb_filename *smb_fname,
2778                           files_struct **result)
2779 {
2780         if (!VALID_STAT(smb_fname->st)) {
2781                 return NT_STATUS_INVALID_PARAMETER;
2782         }
2783
2784         return SMB_VFS_CREATE_FILE(
2785                 conn,                                   /* conn */
2786                 NULL,                                   /* req */
2787                 0,                                      /* root_dir_fid */
2788                 smb_fname,                              /* fname */
2789                 FILE_WRITE_DATA,                        /* access_mask */
2790                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
2791                     FILE_SHARE_DELETE),
2792                 FILE_OPEN,                              /* create_disposition*/
2793                 0,                                      /* create_options */
2794                 0,                                      /* file_attributes */
2795                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
2796                 0,                                      /* allocation_size */
2797                 0,                                      /* private_flags */
2798                 NULL,                                   /* sd */
2799                 NULL,                                   /* ea_list */
2800                 result,                                 /* result */
2801                 NULL);                                  /* pinfo */
2802 }
2803
2804 static NTSTATUS mkdir_internal(connection_struct *conn,
2805                                struct smb_filename *smb_dname,
2806                                uint32 file_attributes)
2807 {
2808         mode_t mode;
2809         char *parent_dir = NULL;
2810         NTSTATUS status;
2811         bool posix_open = false;
2812         bool need_re_stat = false;
2813         uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2814
2815         if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2816                 DEBUG(5,("mkdir_internal: failing share access "
2817                          "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2818                 return NT_STATUS_ACCESS_DENIED;
2819         }
2820
2821         if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2822                             NULL)) {
2823                 return NT_STATUS_NO_MEMORY;
2824         }
2825
2826         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2827                 posix_open = true;
2828                 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2829         } else {
2830                 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2831         }
2832
2833         status = check_parent_access(conn,
2834                                         smb_dname,
2835                                         access_mask);
2836         if(!NT_STATUS_IS_OK(status)) {
2837                 DEBUG(5,("mkdir_internal: check_parent_access "
2838                         "on directory %s for path %s returned %s\n",
2839                         parent_dir,
2840                         smb_dname->base_name,
2841                         nt_errstr(status) ));
2842                 return status;
2843         }
2844
2845         if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2846                 return map_nt_error_from_unix(errno);
2847         }
2848
2849         /* Ensure we're checking for a symlink here.... */
2850         /* We don't want to get caught by a symlink racer. */
2851
2852         if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2853                 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2854                           smb_fname_str_dbg(smb_dname), strerror(errno)));
2855                 return map_nt_error_from_unix(errno);
2856         }
2857
2858         if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2859                 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2860                           smb_fname_str_dbg(smb_dname)));
2861                 return NT_STATUS_NOT_A_DIRECTORY;
2862         }
2863
2864         if (lp_store_dos_attributes(SNUM(conn))) {
2865                 if (!posix_open) {
2866                         file_set_dosmode(conn, smb_dname,
2867                                          file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2868                                          parent_dir, true);
2869                 }
2870         }
2871
2872         if (lp_inherit_perms(SNUM(conn))) {
2873                 inherit_access_posix_acl(conn, parent_dir,
2874                                          smb_dname->base_name, mode);
2875                 need_re_stat = true;
2876         }
2877
2878         if (!posix_open) {
2879                 /*
2880                  * Check if high bits should have been set,
2881                  * then (if bits are missing): add them.
2882                  * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2883                  * dir.
2884                  */
2885                 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2886                     (mode & ~smb_dname->st.st_ex_mode)) {
2887                         SMB_VFS_CHMOD(conn, smb_dname->base_name,
2888                                       (smb_dname->st.st_ex_mode |
2889                                           (mode & ~smb_dname->st.st_ex_mode)));
2890                         need_re_stat = true;
2891                 }
2892         }
2893
2894         /* Change the owner if required. */
2895         if (lp_inherit_owner(SNUM(conn))) {
2896                 change_dir_owner_to_parent(conn, parent_dir,
2897                                            smb_dname->base_name,
2898                                            &smb_dname->st);
2899                 need_re_stat = true;
2900         }
2901
2902         if (need_re_stat) {
2903                 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2904                         DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2905                           smb_fname_str_dbg(smb_dname), strerror(errno)));
2906                         return map_nt_error_from_unix(errno);
2907                 }
2908         }
2909
2910         notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2911                      smb_dname->base_name);
2912
2913         return NT_STATUS_OK;
2914 }
2915
2916 /****************************************************************************
2917  Open a directory from an NT SMB call.
2918 ****************************************************************************/
2919
2920 static NTSTATUS open_directory(connection_struct *conn,
2921                                struct smb_request *req,
2922                                struct smb_filename *smb_dname,
2923                                uint32 access_mask,
2924                                uint32 share_access,
2925                                uint32 create_disposition,
2926                                uint32 create_options,
2927                                uint32 file_attributes,
2928                                int *pinfo,
2929                                files_struct **result)
2930 {
2931         files_struct *fsp = NULL;
2932         bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2933         struct share_mode_lock *lck = NULL;
2934         NTSTATUS status;
2935         struct timespec mtimespec;
2936         int info = 0;
2937
2938         if (is_ntfs_stream_smb_fname(smb_dname)) {
2939                 DEBUG(2, ("open_directory: %s is a stream name!\n",
2940                           smb_fname_str_dbg(smb_dname)));
2941                 return NT_STATUS_NOT_A_DIRECTORY;
2942         }
2943
2944         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2945                 /* Ensure we have a directory attribute. */
2946                 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2947         }
2948
2949         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2950                  "share_access = 0x%x create_options = 0x%x, "
2951                  "create_disposition = 0x%x, file_attributes = 0x%x\n",
2952                  smb_fname_str_dbg(smb_dname),
2953                  (unsigned int)access_mask,
2954                  (unsigned int)share_access,
2955                  (unsigned int)create_options,
2956                  (unsigned int)create_disposition,
2957                  (unsigned int)file_attributes));
2958
2959         status = smbd_calculate_access_mask(conn, smb_dname, false,
2960                                             access_mask, &access_mask);
2961         if (!NT_STATUS_IS_OK(status)) {
2962                 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2963                         "on file %s returned %s\n",
2964                         smb_fname_str_dbg(smb_dname),
2965                         nt_errstr(status)));
2966                 return status;
2967         }
2968
2969         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2970                         !security_token_has_privilege(get_current_nttok(conn),
2971                                         SEC_PRIV_SECURITY)) {
2972                 DEBUG(10, ("open_directory: open on %s "
2973                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2974                         smb_fname_str_dbg(smb_dname)));
2975                 return NT_STATUS_PRIVILEGE_NOT_HELD;
2976         }
2977
2978         switch( create_disposition ) {
2979                 case FILE_OPEN:
2980
2981                         if (!dir_existed) {
2982                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2983                         }
2984
2985                         info = FILE_WAS_OPENED;
2986                         break;
2987
2988                 case FILE_CREATE:
2989
2990                         /* If directory exists error. If directory doesn't
2991                          * exist create. */
2992
2993                         if (dir_existed) {
2994                                 status = NT_STATUS_OBJECT_NAME_COLLISION;
2995                                 DEBUG(2, ("open_directory: unable to create "
2996                                           "%s. Error was %s\n",
2997                                           smb_fname_str_dbg(smb_dname),
2998                                           nt_errstr(status)));
2999                                 return status;
3000                         }
3001
3002                         status = mkdir_internal(conn, smb_dname,
3003                                                 file_attributes);
3004
3005                         if (!NT_STATUS_IS_OK(status)) {
3006                                 DEBUG(2, ("open_directory: unable to create "
3007                                           "%s. Error was %s\n",
3008                                           smb_fname_str_dbg(smb_dname),
3009                                           nt_errstr(status)));
3010                                 return status;
3011                         }
3012
3013                         info = FILE_WAS_CREATED;
3014                         break;
3015
3016                 case FILE_OPEN_IF:
3017                         /*
3018                          * If directory exists open. If directory doesn't
3019                          * exist create.
3020                          */
3021
3022                         if (dir_existed) {
3023                                 status = NT_STATUS_OK;
3024                                 info = FILE_WAS_OPENED;
3025                         } else {
3026                                 status = mkdir_internal(conn, smb_dname,
3027                                                 file_attributes);
3028
3029                                 if (NT_STATUS_IS_OK(status)) {
3030                                         info = FILE_WAS_CREATED;
3031                                 } else {
3032                                         /* Cope with create race. */
3033                                         if (!NT_STATUS_EQUAL(status,
3034                                                         NT_STATUS_OBJECT_NAME_COLLISION)) {
3035                                                 DEBUG(2, ("open_directory: unable to create "
3036                                                         "%s. Error was %s\n",
3037                                                         smb_fname_str_dbg(smb_dname),
3038                                                         nt_errstr(status)));
3039                                                 return status;
3040                                         }
3041                                         info = FILE_WAS_OPENED;
3042                                 }
3043                         }
3044
3045                         break;
3046
3047                 case FILE_SUPERSEDE:
3048                 case FILE_OVERWRITE:
3049                 case FILE_OVERWRITE_IF:
3050                 default:
3051                         DEBUG(5,("open_directory: invalid create_disposition "
3052                                  "0x%x for directory %s\n",
3053                                  (unsigned int)create_disposition,
3054                                  smb_fname_str_dbg(smb_dname)));
3055                         return NT_STATUS_INVALID_PARAMETER;
3056         }
3057
3058         if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3059                 DEBUG(5,("open_directory: %s is not a directory !\n",
3060                          smb_fname_str_dbg(smb_dname)));
3061                 return NT_STATUS_NOT_A_DIRECTORY;
3062         }
3063
3064         if (info == FILE_WAS_OPENED) {
3065                 status = smbd_check_access_rights(conn,
3066                                                 smb_dname,
3067                                                 false,
3068                                                 access_mask);
3069                 if (!NT_STATUS_IS_OK(status)) {
3070                         DEBUG(10, ("open_directory: smbd_check_access_rights on "
3071                                 "file %s failed with %s\n",
3072                                 smb_fname_str_dbg(smb_dname),
3073                                 nt_errstr(status)));
3074                         return status;
3075                 }
3076         }
3077
3078         status = file_new(req, conn, &fsp);
3079         if(!NT_STATUS_IS_OK(status)) {
3080                 return status;
3081         }
3082
3083         /*
3084          * Setup the files_struct for it.
3085          */
3086
3087         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3088         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3089         fsp->file_pid = req ? req->smbpid : 0;
3090         fsp->can_lock = False;
3091         fsp->can_read = False;
3092         fsp->can_write = False;
3093
3094         fsp->share_access = share_access;
3095         fsp->fh->private_options = 0;
3096         /*
3097          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3098          */
3099         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3100         fsp->print_file = NULL;
3101         fsp->modified = False;
3102         fsp->oplock_type = NO_OPLOCK;
3103         fsp->sent_oplock_break = NO_BREAK_SENT;
3104         fsp->is_directory = True;
3105         fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3106         status = fsp_set_smb_fname(fsp, smb_dname);
3107         if (!NT_STATUS_IS_OK(status)) {
3108                 file_free(req, fsp);
3109                 return status;
3110         }
3111
3112         mtimespec = smb_dname->st.st_ex_mtime;
3113
3114 #ifdef O_DIRECTORY
3115         status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3116 #else
3117         /* POSIX allows us to open a directory with O_RDONLY. */
3118         status = fd_open(conn, fsp, O_RDONLY, 0);
3119 #endif
3120         if (!NT_STATUS_IS_OK(status)) {
3121                 DEBUG(5, ("open_directory: Could not open fd for "
3122                         "%s (%s)\n",
3123                         smb_fname_str_dbg(smb_dname),
3124                         nt_errstr(status)));
3125                 file_free(req, fsp);
3126                 return status;
3127         }
3128
3129         status = vfs_stat_fsp(fsp);
3130         if (!NT_STATUS_IS_OK(status)) {
3131                 fd_close(fsp);
3132                 file_free(req, fsp);
3133                 return status;
3134         }
3135
3136         /* Ensure there was no race condition. */
3137         if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3138                 DEBUG(5,("open_directory: stat struct differs for "
3139                         "directory %s.\n",
3140                         smb_fname_str_dbg(smb_dname)));
3141                 fd_close(fsp);
3142                 file_free(req, fsp);
3143                 return NT_STATUS_ACCESS_DENIED;
3144         }
3145
3146         lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3147                                   conn->connectpath, smb_dname,
3148                                   &mtimespec);
3149
3150         if (lck == NULL) {
3151                 DEBUG(0, ("open_directory: Could not get share mode lock for "
3152                           "%s\n", smb_fname_str_dbg(smb_dname)));
3153                 fd_close(fsp);
3154                 file_free(req, fsp);
3155                 return NT_STATUS_SHARING_VIOLATION;
3156         }
3157
3158         if (has_delete_on_close(lck, fsp->name_hash)) {
3159                 TALLOC_FREE(lck);
3160                 fd_close(fsp);
3161                 file_free(req, fsp);
3162                 return NT_STATUS_DELETE_PENDING;
3163         }
3164
3165         status = open_mode_check(conn, lck,
3166                                 access_mask, share_access,
3167                                  &dir_existed);
3168
3169         if (!NT_STATUS_IS_OK(status)) {
3170                 TALLOC_FREE(lck);
3171                 fd_close(fsp);
3172                 file_free(req, fsp);
3173                 return status;
3174         }
3175
3176         if (!set_share_mode(lck, fsp, get_current_uid(conn),
3177                             req ? req->mid : 0, NO_OPLOCK)) {
3178                 TALLOC_FREE(lck);
3179                 fd_close(fsp);
3180                 file_free(req, fsp);
3181                 return NT_STATUS_NO_MEMORY;
3182         }
3183
3184         /* For directories the delete on close bit at open time seems
3185            always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3186         if (create_options & FILE_DELETE_ON_CLOSE) {
3187                 status = can_set_delete_on_close(fsp, 0);
3188                 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3189                         del_share_mode(lck, fsp);
3190                         TALLOC_FREE(lck);
3191                         fd_close(fsp);
3192                         file_free(req, fsp);
3193                         return status;
3194                 }
3195
3196                 if (NT_STATUS_IS_OK(status)) {
3197                         /* Note that here we set the *inital* delete on close flag,
3198                            not the regular one. The magic gets handled in close. */
3199                         fsp->initial_delete_on_close = True;
3200                 }
3201         }
3202
3203         TALLOC_FREE(lck);
3204
3205         if (pinfo) {
3206                 *pinfo = info;
3207         }
3208
3209         *result = fsp;
3210         return NT_STATUS_OK;
3211 }
3212
3213 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3214                           struct smb_filename *smb_dname)
3215 {
3216         NTSTATUS status;
3217         files_struct *fsp;
3218
3219         status = SMB_VFS_CREATE_FILE(
3220                 conn,                                   /* conn */
3221                 req,                                    /* req */
3222                 0,                                      /* root_dir_fid */
3223                 smb_dname,                              /* fname */
3224                 FILE_READ_ATTRIBUTES,                   /* access_mask */
3225                 FILE_SHARE_NONE,                        /* share_access */
3226                 FILE_CREATE,                            /* create_disposition*/
3227                 FILE_DIRECTORY_FILE,                    /* create_options */
3228                 FILE_ATTRIBUTE_DIRECTORY,               /* file_attributes */
3229                 0,                                      /* oplock_request */
3230                 0,                                      /* allocation_size */
3231                 0,                                      /* private_flags */
3232                 NULL,                                   /* sd */
3233                 NULL,                                   /* ea_list */
3234                 &fsp,                                   /* result */
3235                 NULL);                                  /* pinfo */
3236
3237         if (NT_STATUS_IS_OK(status)) {
3238                 close_file(req, fsp, NORMAL_CLOSE);
3239         }
3240
3241         return status;
3242 }
3243
3244 /****************************************************************************
3245  Receive notification that one of our open files has been renamed by another
3246  smbd process.
3247 ****************************************************************************/
3248
3249 void msg_file_was_renamed(struct messaging_context *msg,
3250                           void *private_data,
3251                           uint32_t msg_type,
3252                           struct server_id server_id,
3253                           DATA_BLOB *data)
3254 {
3255         files_struct *fsp;
3256         char *frm = (char *)data->data;
3257         struct file_id id;
3258         const char *sharepath;
3259         const char *base_name;
3260         const char *stream_name;
3261         struct smb_filename *smb_fname = NULL;
3262         size_t sp_len, bn_len;
3263         NTSTATUS status;
3264         struct smbd_server_connection *sconn =
3265                 talloc_get_type_abort(private_data,
3266                 struct smbd_server_connection);
3267
3268         if (data->data == NULL
3269             || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3270                 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3271                           (int)data->length));
3272                 return;
3273         }
3274
3275         /* Unpack the message. */
3276         pull_file_id_24(frm, &id);
3277         sharepath = &frm[24];
3278         sp_len = strlen(sharepath);
3279         base_name = sharepath + sp_len + 1;
3280         bn_len = strlen(base_name);
3281         stream_name = sharepath + sp_len + 1 + bn_len + 1;
3282
3283         /* stream_name must always be NULL if there is no stream. */
3284         if (stream_name[0] == '\0') {
3285                 stream_name = NULL;
3286         }
3287
3288         smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3289                                         stream_name, NULL);
3290         if (smb_fname == NULL) {
3291                 return;
3292         }
3293
3294         DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3295                 "file_id %s\n",
3296                 sharepath, smb_fname_str_dbg(smb_fname),
3297                 file_id_string_tos(&id)));
3298
3299         for(fsp = file_find_di_first(sconn, id); fsp;
3300             fsp = file_find_di_next(fsp)) {
3301                 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3302
3303                         DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3304                                 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3305                                 smb_fname_str_dbg(smb_fname)));
3306                         status = fsp_set_smb_fname(fsp, smb_fname);
3307                         if (!NT_STATUS_IS_OK(status)) {
3308                                 goto out;
3309                         }
3310                 } else {
3311                         /* TODO. JRA. */
3312                         /* Now we have the complete path we can work out if this is
3313                            actually within this share and adjust newname accordingly. */
3314                         DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3315                                 "not sharepath %s) "
3316                                 "%s from %s -> %s\n",
3317                                 fsp->conn->connectpath,
3318                                 sharepath,
3319                                 fsp_fnum_dbg(fsp),
3320                                 fsp_str_dbg(fsp),
3321                                 smb_fname_str_dbg(smb_fname)));
3322                 }
3323         }
3324  out:
3325         TALLOC_FREE(smb_fname);
3326         return;
3327 }
3328
3329 /*
3330  * If a main file is opened for delete, all streams need to be checked for
3331  * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3332  * If that works, delete them all by setting the delete on close and close.
3333  */
3334
3335 NTSTATUS open_streams_for_delete(connection_struct *conn,
3336                                         const char *fname)
3337 {
3338         struct stream_struct *stream_info = NULL;
3339         files_struct **streams = NULL;
3340         int i;
3341         unsigned int num_streams = 0;
3342         TALLOC_CTX *frame = talloc_stackframe();
3343         NTSTATUS status;
3344
3345         status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3346                                 &num_streams, &stream_info);
3347
3348         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3349             || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3350                 DEBUG(10, ("no streams around\n"));
3351                 TALLOC_FREE(frame);
3352                 return NT_STATUS_OK;
3353         }
3354
3355         if (!NT_STATUS_IS_OK(status)) {
3356                 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3357                            nt_errstr(status)));
3358                 goto fail;
3359         }
3360
3361         DEBUG(10, ("open_streams_for_delete found %d streams\n",
3362                    num_streams));
3363
3364         if (num_streams == 0) {
3365                 TALLOC_FREE(frame);
3366                 return NT_STATUS_OK;
3367         }
3368
3369         streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3370         if (streams == NULL) {
3371                 DEBUG(0, ("talloc failed\n"));
3372                 status = NT_STATUS_NO_MEMORY;
3373                 goto fail;
3374         }
3375
3376         for (i=0; i<num_streams; i++) {
3377                 struct smb_filename *smb_fname;
3378
3379                 if (strequal(stream_info[i].name, "::$DATA")) {
3380                         streams[i] = NULL;
3381                         continue;
3382                 }
3383
3384                 smb_fname = synthetic_smb_fname(
3385                         talloc_tos(), fname, stream_info[i].name, NULL);
3386                 if (smb_fname == NULL) {
3387                         status = NT_STATUS_NO_MEMORY;
3388                         goto fail;
3389                 }
3390
3391                 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3392                         DEBUG(10, ("Unable to stat stream: %s\n",
3393                                    smb_fname_str_dbg(smb_fname)));
3394                 }
3395
3396                 status = SMB_VFS_CREATE_FILE(
3397                          conn,                  /* conn */
3398                          NULL,                  /* req */
3399                          0,                     /* root_dir_fid */
3400                          smb_fname,             /* fname */
3401                          DELETE_ACCESS,         /* access_mask */
3402                          (FILE_SHARE_READ |     /* share_access */
3403                              FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3404                          FILE_OPEN,             /* create_disposition*/
3405                          0,                     /* create_options */
3406                          FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3407                          0,                     /* oplock_request */
3408                          0,                     /* allocation_size */
3409                          NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3410                          NULL,                  /* sd */
3411                          NULL,                  /* ea_list */
3412                          &streams[i],           /* result */
3413                          NULL);                 /* pinfo */
3414
3415                 if (!NT_STATUS_IS_OK(status)) {
3416                         DEBUG(10, ("Could not open stream %s: %s\n",
3417                                    smb_fname_str_dbg(smb_fname),
3418                                    nt_errstr(status)));
3419
3420                         TALLOC_FREE(smb_fname);
3421                         break;
3422                 }
3423                 TALLOC_FREE(smb_fname);
3424         }
3425
3426         /*
3427          * don't touch the variable "status" beyond this point :-)
3428          */
3429
3430         for (i -= 1 ; i >= 0; i--) {
3431                 if (streams[i] == NULL) {
3432                         continue;
3433                 }
3434
3435                 DEBUG(10, ("Closing stream # %d, %s\n", i,
3436                            fsp_str_dbg(streams[i])));
3437                 close_file(NULL, streams[i], NORMAL_CLOSE);
3438         }
3439
3440  fail:
3441         TALLOC_FREE(frame);
3442         return status;
3443 }
3444
3445 /*********************************************************************
3446  Create a default ACL by inheriting from the parent. If no inheritance
3447  from the parent available, don't set anything. This will leave the actual
3448  permissions the new file or directory already got from the filesystem
3449  as the NT ACL when read.
3450 *********************************************************************/
3451
3452 static NTSTATUS inherit_new_acl(files_struct *fsp)
3453 {
3454         TALLOC_CTX *frame = talloc_stackframe();
3455         char *parent_name = NULL;
3456         struct security_descriptor *parent_desc = NULL;
3457         NTSTATUS status = NT_STATUS_OK;
3458         struct security_descriptor *psd = NULL;
3459         const struct dom_sid *owner_sid = NULL;
3460         const struct dom_sid *group_sid = NULL;
3461         uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3462         struct security_token *token = fsp->conn->session_info->security_token;
3463         bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3464         bool inheritable_components = false;
3465         bool try_builtin_administrators = false;
3466         const struct dom_sid *BA_U_sid = NULL;
3467         const struct dom_sid *BA_G_sid = NULL;
3468         bool try_system = false;
3469         const struct dom_sid *SY_U_sid = NULL;
3470         const struct dom_sid *SY_G_sid = NULL;
3471         size_t size = 0;
3472
3473         if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3474                 TALLOC_FREE(frame);
3475                 return NT_STATUS_NO_MEMORY;
3476         }
3477
3478         status = SMB_VFS_GET_NT_ACL(fsp->conn,
3479                                     parent_name,
3480                                     (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3481                                     frame,
3482                                     &parent_desc);
3483         if (!NT_STATUS_IS_OK(status)) {
3484                 TALLOC_FREE(frame);
3485                 return status;
3486         }
3487
3488         inheritable_components = sd_has_inheritable_components(parent_desc,
3489                                         fsp->is_directory);
3490
3491         if (!inheritable_components && !inherit_owner) {
3492                 TALLOC_FREE(frame);
3493                 /* Nothing to inherit and not setting owner. */
3494                 return NT_STATUS_OK;
3495         }
3496
3497         /* Create an inherited descriptor from the parent. */
3498
3499         if (DEBUGLEVEL >= 10) {
3500                 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3501                         fsp_str_dbg(fsp) ));
3502                 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3503         }
3504
3505         /* Inherit from parent descriptor if "inherit owner" set. */
3506         if (inherit_owner) {
3507                 owner_sid = parent_desc->owner_sid;
3508                 group_sid = parent_desc->group_sid;
3509         }
3510
3511         if (owner_sid == NULL) {
3512                 if (security_token_has_builtin_administrators(token)) {
3513                         try_builtin_administrators = true;
3514                 } else if (security_token_is_system(token)) {
3515                         try_builtin_administrators = true;
3516                         try_system = true;
3517                 }
3518         }
3519
3520         if (group_sid == NULL &&
3521             token->num_sids == PRIMARY_GROUP_SID_INDEX)
3522         {
3523                 if (security_token_is_system(token)) {
3524                         try_builtin_administrators = true;
3525                         try_system = true;
3526                 }
3527         }
3528
3529         if (try_builtin_administrators) {
3530                 struct unixid ids;
3531                 bool ok;
3532
3533                 ZERO_STRUCT(ids);
3534                 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3535                 if (ok) {
3536                         switch (ids.type) {
3537                         case ID_TYPE_BOTH:
3538                                 BA_U_sid = &global_sid_Builtin_Administrators;
3539                                 BA_G_sid = &global_sid_Builtin_Administrators;
3540                                 break;
3541                         case ID_TYPE_UID:
3542                                 BA_U_sid = &global_sid_Builtin_Administrators;
3543                                 break;
3544                         case ID_TYPE_GID:
3545                                 BA_G_sid = &global_sid_Builtin_Administrators;
3546                                 break;
3547                         default:
3548                                 break;
3549                         }
3550                 }
3551         }
3552
3553         if (try_system) {
3554                 struct unixid ids;
3555                 bool ok;
3556
3557                 ZERO_STRUCT(ids);
3558                 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3559                 if (ok) {
3560                         switch (ids.type) {
3561                         case ID_TYPE_BOTH:
3562                                 SY_U_sid = &global_sid_System;
3563                                 SY_G_sid = &global_sid_System;
3564                                 break;
3565                         case ID_TYPE_UID:
3566                                 SY_U_sid = &global_sid_System;
3567                                 break;
3568                         case ID_TYPE_GID:
3569                                 SY_G_sid = &global_sid_System;
3570                                 break;
3571                         default:
3572                                 break;
3573                         }
3574                 }
3575         }
3576
3577         if (owner_sid == NULL) {
3578                 owner_sid = BA_U_sid;
3579         }
3580
3581         if (owner_sid == NULL) {
3582                 owner_sid = SY_U_sid;
3583         }
3584
3585         if (group_sid == NULL) {
3586                 group_sid = SY_G_sid;
3587         }
3588
3589         if (try_system && group_sid == NULL) {
3590                 group_sid = BA_G_sid;
3591         }
3592
3593         if (owner_sid == NULL) {
3594                 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3595         }
3596         if (group_sid == NULL) {
3597                 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3598                         group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3599                 } else {
3600                         group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3601                 }
3602         }
3603
3604         status = se_create_child_secdesc(frame,
3605                         &psd,
3606                         &size,
3607                         parent_desc,
3608                         owner_sid,
3609                         group_sid,
3610                         fsp->is_directory);
3611         if (!NT_STATUS_IS_OK(status)) {
3612                 TALLOC_FREE(frame);
3613                 return status;
3614         }
3615
3616         /* If inheritable_components == false,
3617            se_create_child_secdesc()
3618            creates a security desriptor with a NULL dacl
3619            entry, but with SEC_DESC_DACL_PRESENT. We need
3620            to remove that flag. */
3621
3622         if (!inheritable_components) {
3623                 security_info_sent &= ~SECINFO_DACL;
3624                 psd->type &= ~SEC_DESC_DACL_PRESENT;
3625         }
3626
3627         if (DEBUGLEVEL >= 10) {
3628                 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3629                         fsp_str_dbg(fsp) ));
3630                 NDR_PRINT_DEBUG(security_descriptor, psd);
3631         }
3632
3633         if (inherit_owner) {
3634                 /* We need to be root to force this. */
3635                 become_root();
3636         }
3637         status = SMB_VFS_FSET_NT_ACL(fsp,
3638                         security_info_sent,
3639                         psd);
3640         if (inherit_owner) {
3641                 unbecome_root();
3642         }
3643         TALLOC_FREE(frame);
3644         return status;
3645 }
3646
3647 /*
3648  * Wrapper around open_file_ntcreate and open_directory
3649  */
3650
3651 static NTSTATUS create_file_unixpath(connection_struct *conn,
3652                                      struct smb_request *req,
3653                                      struct smb_filename *smb_fname,
3654                                      uint32_t access_mask,
3655                                      uint32_t share_access,
3656                                      uint32_t create_disposition,
3657                                      uint32_t create_options,
3658                                      uint32_t file_attributes,
3659                                      uint32_t oplock_request,
3660                                      uint64_t allocation_size,
3661                                      uint32_t private_flags,
3662                                      struct security_descriptor *sd,
3663                                      struct ea_list *ea_list,
3664
3665                                      files_struct **result,
3666                                      int *pinfo)
3667 {
3668         int info = FILE_WAS_OPENED;
3669         files_struct *base_fsp = NULL;
3670         files_struct *fsp = NULL;
3671         NTSTATUS status;
3672
3673         DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3674                   "file_attributes = 0x%x, share_access = 0x%x, "
3675                   "create_disposition = 0x%x create_options = 0x%x "
3676                   "oplock_request = 0x%x private_flags = 0x%x "
3677                   "ea_list = 0x%p, sd = 0x%p, "
3678                   "fname = %s\n",
3679                   (unsigned int)access_mask,
3680                   (unsigned int)file_attributes,
3681                   (unsigned int)share_access,
3682                   (unsigned int)create_disposition,
3683                   (unsigned int)create_options,
3684                   (unsigned int)oplock_request,
3685                   (unsigned int)private_flags,
3686                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
3687
3688         if (create_options & FILE_OPEN_BY_FILE_ID) {
3689                 status = NT_STATUS_NOT_SUPPORTED;
3690                 goto fail;
3691         }
3692
3693         if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3694                 status = NT_STATUS_INVALID_PARAMETER;
3695                 goto fail;
3696         }
3697
3698         if (req == NULL) {
3699                 oplock_request |= INTERNAL_OPEN_ONLY;
3700         }
3701
3702         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3703             && (access_mask & DELETE_ACCESS)
3704             && !is_ntfs_stream_smb_fname(smb_fname)) {
3705                 /*
3706                  * We can't open a file with DELETE access if any of the
3707                  * streams is open without FILE_SHARE_DELETE
3708                  */
3709                 status = open_streams_for_delete(conn, smb_fname->base_name);
3710
3711                 if (!NT_STATUS_IS_OK(status)) {
3712                         goto fail;
3713                 }
3714         }
3715
3716         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3717                         !security_token_has_privilege(get_current_nttok(conn),
3718                                         SEC_PRIV_SECURITY)) {
3719                 DEBUG(10, ("create_file_unixpath: open on %s "
3720                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3721                         smb_fname_str_dbg(smb_fname)));
3722                 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3723                 goto fail;
3724         }
3725
3726         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3727             && is_ntfs_stream_smb_fname(smb_fname)
3728             && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3729                 uint32 base_create_disposition;
3730                 struct smb_filename *smb_fname_base = NULL;
3731
3732                 if (create_options & FILE_DIRECTORY_FILE) {
3733                         status = NT_STATUS_NOT_A_DIRECTORY;
3734                         goto fail;
3735                 }
3736
3737                 switch (create_disposition) {
3738                 case FILE_OPEN:
3739                         base_create_disposition = FILE_OPEN;
3740                         break;
3741                 default:
3742                         base_create_disposition = FILE_OPEN_IF;
3743                         break;
3744                 }
3745
3746                 /* Create an smb_filename with stream_name == NULL. */
3747                 smb_fname_base = synthetic_smb_fname(talloc_tos(),
3748                                                      smb_fname->base_name,
3749                                                      NULL, NULL);
3750                 if (smb_fname_base == NULL) {
3751                         status = NT_STATUS_NO_MEMORY;
3752                         goto fail;
3753                 }
3754
3755                 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3756                         DEBUG(10, ("Unable to stat stream: %s\n",
3757                                    smb_fname_str_dbg(smb_fname_base)));
3758                 }
3759
3760                 /* Open the base file. */
3761                 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3762                                               FILE_SHARE_READ
3763                                               | FILE_SHARE_WRITE
3764                                               | FILE_SHARE_DELETE,
3765                                               base_create_disposition,
3766                                               0, 0, 0, 0, 0, NULL, NULL,
3767                                               &base_fsp, NULL);
3768                 TALLOC_FREE(smb_fname_base);
3769
3770                 if (!NT_STATUS_IS_OK(status)) {
3771                         DEBUG(10, ("create_file_unixpath for base %s failed: "
3772                                    "%s\n", smb_fname->base_name,
3773                                    nt_errstr(status)));
3774                         goto fail;
3775                 }
3776                 /* we don't need to low level fd */
3777                 fd_close(base_fsp);
3778         }
3779
3780         /*
3781          * If it's a request for a directory open, deal with it separately.
3782          */
3783
3784         if (create_options & FILE_DIRECTORY_FILE) {
3785
3786                 if (create_options & FILE_NON_DIRECTORY_FILE) {
3787                         status = NT_STATUS_INVALID_PARAMETER;
3788                         goto fail;
3789                 }
3790
3791                 /* Can't open a temp directory. IFS kit test. */
3792                 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3793                      (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3794                         status = NT_STATUS_INVALID_PARAMETER;
3795                         goto fail;
3796                 }
3797
3798                 /*
3799                  * We will get a create directory here if the Win32
3800                  * app specified a security descriptor in the
3801                  * CreateDirectory() call.
3802                  */
3803
3804                 oplock_request = 0;
3805                 status = open_directory(
3806                         conn, req, smb_fname, access_mask, share_access,
3807                         create_disposition, create_options, file_attributes,
3808                         &info, &fsp);
3809         } else {
3810
3811                 /*
3812                  * Ordinary file case.
3813                  */
3814
3815                 status = file_new(req, conn, &fsp);
3816                 if(!NT_STATUS_IS_OK(status)) {
3817                         goto fail;
3818                 }
3819
3820                 status = fsp_set_smb_fname(fsp, smb_fname);
3821                 if (!NT_STATUS_IS_OK(status)) {
3822                         goto fail;
3823                 }
3824
3825                 if (base_fsp) {
3826                         /*
3827                          * We're opening the stream element of a
3828                          * base_fsp we already opened. Set up the
3829                          * base_fsp pointer.
3830                          */
3831                         fsp->base_fsp = base_fsp;
3832                 }
3833
3834                 if (allocation_size) {
3835                         fsp->initial_allocation_size = smb_roundup(fsp->conn,
3836                                                         allocation_size);
3837                 }
3838
3839                 status = open_file_ntcreate(conn,
3840                                             req,
3841                                             access_mask,
3842                                             share_access,
3843                                             create_disposition,
3844                                             create_options,
3845                                             file_attributes,
3846                                             oplock_request,
3847                                             private_flags,
3848                                             &info,
3849                                             fsp);
3850
3851                 if(!NT_STATUS_IS_OK(status)) {
3852                         file_free(req, fsp);
3853                         fsp = NULL;
3854                 }
3855
3856                 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3857
3858                         /* A stream open never opens a directory */
3859
3860                         if (base_fsp) {
3861                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3862                                 goto fail;
3863                         }
3864
3865                         /*
3866                          * Fail the open if it was explicitly a non-directory
3867                          * file.
3868                          */
3869
3870                         if (create_options & FILE_NON_DIRECTORY_FILE) {
3871                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3872                                 goto fail;
3873                         }
3874
3875                         oplock_request = 0;
3876                         status = open_directory(
3877                                 conn, req, smb_fname, access_mask,
3878                                 share_access, create_disposition,
3879                                 create_options, file_attributes,
3880                                 &info, &fsp);
3881                 }
3882         }
3883
3884         if (!NT_STATUS_IS_OK(status)) {
3885                 goto fail;
3886         }
3887
3888         fsp->base_fsp = base_fsp;
3889
3890         if ((ea_list != NULL) &&
3891             ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3892                 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3893                 if (!NT_STATUS_IS_OK(status)) {
3894                         goto fail;
3895                 }
3896         }
3897
3898         if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3899                 status = NT_STATUS_ACCESS_DENIED;
3900                 goto fail;
3901         }
3902
3903         /* Save the requested allocation size. */
3904         if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3905                 if (allocation_size
3906                     && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3907                         fsp->initial_allocation_size = smb_roundup(
3908                                 fsp->conn, allocation_size);
3909                         if (fsp->is_directory) {
3910                                 /* Can't set allocation size on a directory. */
3911                                 status = NT_STATUS_ACCESS_DENIED;
3912                                 goto fail;
3913                         }
3914                         if (vfs_allocate_file_space(
3915                                     fsp, fsp->initial_allocation_size) == -1) {
3916                                 status = NT_STATUS_DISK_FULL;
3917                                 goto fail;
3918                         }
3919                 } else {
3920                         fsp->initial_allocation_size = smb_roundup(
3921                                 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3922                 }
3923         } else {
3924                 fsp->initial_allocation_size = 0;
3925         }
3926
3927         if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3928                                 fsp->base_fsp == NULL) {
3929                 if (sd != NULL) {
3930                         /*
3931                          * According to the MS documentation, the only time the security
3932                          * descriptor is applied to the opened file is iff we *created* the
3933                          * file; an existing file stays the same.
3934                          *
3935                          * Also, it seems (from observation) that you can open the file with
3936                          * any access mask but you can still write the sd. We need to override
3937                          * the granted access before we call set_sd
3938                          * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3939                          */
3940
3941                         uint32_t sec_info_sent;
3942                         uint32_t saved_access_mask = fsp->access_mask;
3943
3944                         sec_info_sent = get_sec_info(sd);
3945
3946                         fsp->access_mask = FILE_GENERIC_ALL;
3947
3948                         if (sec_info_sent & (SECINFO_OWNER|
3949                                                 SECINFO_GROUP|
3950                                                 SECINFO_DACL|
3951                                                 SECINFO_SACL)) {
3952                                 status = set_sd(fsp, sd, sec_info_sent);
3953                         }
3954
3955                         fsp->access_mask = saved_access_mask;
3956
3957                         if (!NT_STATUS_IS_OK(status)) {
3958                                 goto fail;
3959                         }
3960                 } else if (lp_inherit_acls(SNUM(conn))) {
3961                         /* Inherit from parent. Errors here are not fatal. */
3962                         status = inherit_new_acl(fsp);
3963                         if (!NT_STATUS_IS_OK(status)) {
3964                                 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3965                                         fsp_str_dbg(fsp),
3966                                         nt_errstr(status) ));
3967                         }
3968                 }
3969         }
3970
3971         DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3972
3973         *result = fsp;
3974         if (pinfo != NULL) {
3975                 *pinfo = info;
3976         }
3977
3978         smb_fname->st = fsp->fsp_name->st;
3979
3980         return NT_STATUS_OK;
3981
3982  fail:
3983         DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3984
3985         if (fsp != NULL) {
3986                 if (base_fsp && fsp->base_fsp == base_fsp) {
3987                         /*
3988                          * The close_file below will close
3989                          * fsp->base_fsp.
3990                          */
3991                         base_fsp = NULL;
3992                 }
3993                 close_file(req, fsp, ERROR_CLOSE);
3994                 fsp = NULL;
3995         }
3996         if (base_fsp != NULL) {
3997                 close_file(req, base_fsp, ERROR_CLOSE);
3998                 base_fsp = NULL;
3999         }
4000         return status;
4001 }
4002
4003 /*
4004  * Calculate the full path name given a relative fid.
4005  */
4006 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4007                                    struct smb_request *req,
4008                                    uint16_t root_dir_fid,
4009                                    const struct smb_filename *smb_fname,
4010                                    struct smb_filename **smb_fname_out)
4011 {
4012         files_struct *dir_fsp;
4013         char *parent_fname = NULL;
4014         char *new_base_name = NULL;
4015         NTSTATUS status;
4016
4017         if (root_dir_fid == 0 || !smb_fname) {
4018                 status = NT_STATUS_INTERNAL_ERROR;
4019                 goto out;
4020         }
4021
4022         dir_fsp = file_fsp(req, root_dir_fid);
4023
4024         if (dir_fsp == NULL) {
4025                 status = NT_STATUS_INVALID_HANDLE;
4026                 goto out;
4027         }
4028
4029         if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4030                 status = NT_STATUS_INVALID_HANDLE;
4031                 goto out;
4032         }
4033
4034         if (!dir_fsp->is_directory) {
4035
4036                 /*
4037                  * Check to see if this is a mac fork of some kind.
4038                  */
4039
4040                 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4041                     is_ntfs_stream_smb_fname(smb_fname)) {
4042                         status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4043                         goto out;
4044                 }
4045
4046                 /*
4047                   we need to handle the case when we get a
4048                   relative open relative to a file and the
4049                   pathname is blank - this is a reopen!
4050                   (hint from demyn plantenberg)
4051                 */
4052
4053                 status = NT_STATUS_INVALID_HANDLE;
4054                 goto out;
4055         }
4056
4057         if (ISDOT(dir_fsp->fsp_name->base_name)) {
4058                 /*
4059                  * We're at the toplevel dir, the final file name
4060                  * must not contain ./, as this is filtered out
4061                  * normally by srvstr_get_path and unix_convert
4062                  * explicitly rejects paths containing ./.
4063                  */
4064                 parent_fname = talloc_strdup(talloc_tos(), "");
4065                 if (parent_fname == NULL) {
4066                         status = NT_STATUS_NO_MEMORY;
4067                         goto out;
4068                 }
4069         } else {
4070                 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4071
4072                 /*
4073                  * Copy in the base directory name.
4074                  */
4075
4076                 parent_fname = talloc_array(talloc_tos(), char,
4077                     dir_name_len+2);
4078                 if (parent_fname == NULL) {
4079                         status = NT_STATUS_NO_MEMORY;
4080                         goto out;
4081                 }
4082                 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4083                     dir_name_len+1);
4084
4085                 /*
4086                  * Ensure it ends in a '/'.
4087                  * We used TALLOC_SIZE +2 to add space for the '/'.
4088                  */
4089
4090                 if(dir_name_len
4091                     && (parent_fname[dir_name_len-1] != '\\')
4092                     && (parent_fname[dir_name_len-1] != '/')) {
4093                         parent_fname[dir_name_len] = '/';
4094                         parent_fname[dir_name_len+1] = '\0';
4095                 }
4096         }
4097
4098         new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4099                                         smb_fname->base_name);
4100         if (new_base_name == NULL) {
4101                 status = NT_STATUS_NO_MEMORY;
4102                 goto out;
4103         }
4104
4105         status = filename_convert(req,
4106                                 conn,
4107                                 req->flags2 & FLAGS2_DFS_PATHNAMES,
4108                                 new_base_name,
4109                                 0,
4110                                 NULL,
4111                                 smb_fname_out);
4112         if (!NT_STATUS_IS_OK(status)) {
4113                 goto out;
4114         }
4115
4116  out:
4117         TALLOC_FREE(parent_fname);
4118         TALLOC_FREE(new_base_name);
4119         return status;
4120 }
4121
4122 NTSTATUS create_file_default(connection_struct *conn,
4123                              struct smb_request *req,
4124                              uint16_t root_dir_fid,
4125                              struct smb_filename *smb_fname,
4126                              uint32_t access_mask,
4127                              uint32_t share_access,
4128                              uint32_t create_disposition,
4129                              uint32_t create_options,
4130                              uint32_t file_attributes,
4131                              uint32_t oplock_request,
4132                              uint64_t allocation_size,
4133                              uint32_t private_flags,
4134                              struct security_descriptor *sd,
4135                              struct ea_list *ea_list,
4136                              files_struct **result,
4137                              int *pinfo)
4138 {
4139         int info = FILE_WAS_OPENED;
4140         files_struct *fsp = NULL;
4141         NTSTATUS status;
4142         bool stream_name = false;
4143
4144         DEBUG(10,("create_file: access_mask = 0x%x "
4145                   "file_attributes = 0x%x, share_access = 0x%x, "
4146                   "create_disposition = 0x%x create_options = 0x%x "
4147                   "oplock_request = 0x%x "
4148                   "private_flags = 0x%x "
4149                   "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4150                   "fname = %s\n",
4151                   (unsigned int)access_mask,
4152                   (unsigned int)file_attributes,
4153                   (unsigned int)share_access,
4154                   (unsigned int)create_disposition,
4155                   (unsigned int)create_options,
4156                   (unsigned int)oplock_request,
4157                   (unsigned int)private_flags,
4158                   (unsigned int)root_dir_fid,
4159                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
4160
4161         /*
4162          * Calculate the filename from the root_dir_if if necessary.
4163          */
4164
4165         if (root_dir_fid != 0) {
4166                 struct smb_filename *smb_fname_out = NULL;
4167                 status = get_relative_fid_filename(conn, req, root_dir_fid,
4168                                                    smb_fname, &smb_fname_out);
4169                 if (!NT_STATUS_IS_OK(status)) {
4170                         goto fail;
4171                 }
4172                 smb_fname = smb_fname_out;
4173         }
4174
4175         /*
4176          * Check to see if this is a mac fork of some kind.
4177          */
4178
4179         stream_name = is_ntfs_stream_smb_fname(smb_fname);
4180         if (stream_name) {
4181                 enum FAKE_FILE_TYPE fake_file_type;
4182
4183                 fake_file_type = is_fake_file(smb_fname);
4184
4185                 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4186
4187                         /*
4188                          * Here we go! support for changing the disk quotas
4189                          * --metze
4190                          *
4191                          * We need to fake up to open this MAGIC QUOTA file
4192                          * and return a valid FID.
4193                          *
4194                          * w2k close this file directly after openening xp
4195                          * also tries a QUERY_FILE_INFO on the file and then
4196                          * close it
4197                          */
4198                         status = open_fake_file(req, conn, req->vuid,
4199                                                 fake_file_type, smb_fname,
4200                                                 access_mask, &fsp);
4201                         if (!NT_STATUS_IS_OK(status)) {
4202                                 goto fail;
4203                         }
4204
4205                         ZERO_STRUCT(smb_fname->st);
4206                         goto done;
4207                 }
4208
4209                 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4210                         status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4211                         goto fail;
4212                 }
4213         }
4214
4215         if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4216                 int ret;
4217                 smb_fname->stream_name = NULL;
4218                 /* We have to handle this error here. */
4219                 if (create_options & FILE_DIRECTORY_FILE) {
4220                         status = NT_STATUS_NOT_A_DIRECTORY;
4221                         goto fail;
4222                 }
4223                 if (lp_posix_pathnames()) {
4224                         ret = SMB_VFS_LSTAT(conn, smb_fname);
4225                 } else {
4226                         ret = SMB_VFS_STAT(conn, smb_fname);
4227                 }
4228
4229                 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4230                         status = NT_STATUS_FILE_IS_A_DIRECTORY;
4231                         goto fail;
4232                 }
4233         }
4234
4235         status = create_file_unixpath(
4236                 conn, req, smb_fname, access_mask, share_access,
4237                 create_disposition, create_options, file_attributes,
4238                 oplock_request, allocation_size, private_flags,
4239                 sd, ea_list,
4240                 &fsp, &info);
4241
4242         if (!NT_STATUS_IS_OK(status)) {
4243                 goto fail;
4244         }
4245
4246  done:
4247         DEBUG(10, ("create_file: info=%d\n", info));
4248
4249         *result = fsp;
4250         if (pinfo != NULL) {
4251                 *pinfo = info;
4252         }
4253         return NT_STATUS_OK;
4254
4255  fail:
4256         DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4257
4258         if (fsp != NULL) {
4259                 close_file(req, fsp, ERROR_CLOSE);
4260                 fsp = NULL;
4261         }
4262         return status;
4263 }