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