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