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