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