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