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