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