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