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