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