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