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