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