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