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