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