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