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