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