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