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