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