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