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