s3:smbd: let SMB_VFS_GETXATTRAT_SEND() do explicit impersonation
[kamenim/samba-autobuild/.git] / source3 / modules / vfs_default.c
1 /*
2    Unix SMB/CIFS implementation.
3    Wrap disk only vfs functions to sidestep dodgy compilers.
4    Copyright (C) Tim Potter 1998
5    Copyright (C) Jeremy Allison 2007
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/time.h"
23 #include "system/filesys.h"
24 #include "smbd/smbd.h"
25 #include "smbd/globals.h"
26 #include "ntioctl.h"
27 #include "smbprofile.h"
28 #include "../libcli/security/security.h"
29 #include "passdb/lookup_sid.h"
30 #include "source3/include/msdfs.h"
31 #include "librpc/gen_ndr/ndr_dfsblobs.h"
32 #include "lib/util/tevent_unix.h"
33 #include "lib/util/tevent_ntstatus.h"
34 #include "lib/util/sys_rw.h"
35 #include "lib/pthreadpool/pthreadpool_tevent.h"
36 #include "librpc/gen_ndr/ndr_ioctl.h"
37 #include "offload_token.h"
38
39 #undef DBGC_CLASS
40 #define DBGC_CLASS DBGC_VFS
41
42 /* Check for NULL pointer parameters in vfswrap_* functions */
43
44 /* We don't want to have NULL function pointers lying around.  Someone
45    is sure to try and execute them.  These stubs are used to prevent
46    this possibility. */
47
48 static int vfswrap_connect(vfs_handle_struct *handle, const char *service, const char *user)
49 {
50     return 0;    /* Return >= 0 for success */
51 }
52
53 static void vfswrap_disconnect(vfs_handle_struct *handle)
54 {
55 }
56
57 /* Disk operations */
58
59 static uint64_t vfswrap_disk_free(vfs_handle_struct *handle,
60                                 const struct smb_filename *smb_fname,
61                                 uint64_t *bsize,
62                                 uint64_t *dfree,
63                                 uint64_t *dsize)
64 {
65         if (sys_fsusage(smb_fname->base_name, dfree, dsize) != 0) {
66                 return (uint64_t)-1;
67         }
68
69         *bsize = 512;
70         return *dfree / 2;
71 }
72
73 static int vfswrap_get_quota(struct vfs_handle_struct *handle,
74                                 const struct smb_filename *smb_fname,
75                                 enum SMB_QUOTA_TYPE qtype,
76                                 unid_t id,
77                                 SMB_DISK_QUOTA *qt)
78 {
79 #ifdef HAVE_SYS_QUOTAS
80         int result;
81
82         START_PROFILE(syscall_get_quota);
83         result = sys_get_quota(smb_fname->base_name, qtype, id, qt);
84         END_PROFILE(syscall_get_quota);
85         return result;
86 #else
87         errno = ENOSYS;
88         return -1;
89 #endif
90 }
91
92 static int vfswrap_set_quota(struct vfs_handle_struct *handle, enum SMB_QUOTA_TYPE qtype, unid_t id, SMB_DISK_QUOTA *qt)
93 {
94 #ifdef HAVE_SYS_QUOTAS
95         int result;
96
97         START_PROFILE(syscall_set_quota);
98         result = sys_set_quota(handle->conn->connectpath, qtype, id, qt);
99         END_PROFILE(syscall_set_quota);
100         return result;
101 #else
102         errno = ENOSYS;
103         return -1;
104 #endif
105 }
106
107 static int vfswrap_get_shadow_copy_data(struct vfs_handle_struct *handle,
108                                         struct files_struct *fsp,
109                                         struct shadow_copy_data *shadow_copy_data,
110                                         bool labels)
111 {
112         errno = ENOSYS;
113         return -1;  /* Not implemented. */
114 }
115
116 static int vfswrap_statvfs(struct vfs_handle_struct *handle,
117                                 const struct smb_filename *smb_fname,
118                                 vfs_statvfs_struct *statbuf)
119 {
120         return sys_statvfs(smb_fname->base_name, statbuf);
121 }
122
123 static uint32_t vfswrap_fs_capabilities(struct vfs_handle_struct *handle,
124                 enum timestamp_set_resolution *p_ts_res)
125 {
126         connection_struct *conn = handle->conn;
127         uint32_t caps = FILE_CASE_SENSITIVE_SEARCH | FILE_CASE_PRESERVED_NAMES;
128         struct smb_filename *smb_fname_cpath = NULL;
129         struct vfs_statvfs_struct statbuf;
130         int ret;
131
132         smb_fname_cpath = synthetic_smb_fname(talloc_tos(), conn->connectpath,
133                                               NULL, NULL, 0);
134         if (smb_fname_cpath == NULL) {
135                 return caps;
136         }
137
138         ZERO_STRUCT(statbuf);
139         ret = SMB_VFS_STATVFS(conn, smb_fname_cpath, &statbuf);
140         if (ret == 0) {
141                 caps = statbuf.FsCapabilities;
142         }
143
144         *p_ts_res = TIMESTAMP_SET_SECONDS;
145
146         /* Work out what timestamp resolution we can
147          * use when setting a timestamp. */
148
149         ret = SMB_VFS_STAT(conn, smb_fname_cpath);
150         if (ret == -1) {
151                 TALLOC_FREE(smb_fname_cpath);
152                 return caps;
153         }
154
155         if (smb_fname_cpath->st.st_ex_mtime.tv_nsec ||
156                         smb_fname_cpath->st.st_ex_atime.tv_nsec ||
157                         smb_fname_cpath->st.st_ex_ctime.tv_nsec) {
158                 /* If any of the normal UNIX directory timestamps
159                  * have a non-zero tv_nsec component assume
160                  * we might be able to set sub-second timestamps.
161                  * See what filetime set primitives we have.
162                  */
163 #if defined(HAVE_UTIMENSAT)
164                 *p_ts_res = TIMESTAMP_SET_NT_OR_BETTER;
165 #elif defined(HAVE_UTIMES)
166                 /* utimes allows msec timestamps to be set. */
167                 *p_ts_res = TIMESTAMP_SET_MSEC;
168 #elif defined(HAVE_UTIME)
169                 /* utime only allows sec timestamps to be set. */
170                 *p_ts_res = TIMESTAMP_SET_SECONDS;
171 #endif
172
173                 DEBUG(10,("vfswrap_fs_capabilities: timestamp "
174                         "resolution of %s "
175                         "available on share %s, directory %s\n",
176                         *p_ts_res == TIMESTAMP_SET_MSEC ? "msec" : "sec",
177                         lp_servicename(talloc_tos(), conn->params->service),
178                         conn->connectpath ));
179         }
180         TALLOC_FREE(smb_fname_cpath);
181         return caps;
182 }
183
184 static NTSTATUS vfswrap_get_dfs_referrals(struct vfs_handle_struct *handle,
185                                           struct dfs_GetDFSReferral *r)
186 {
187         struct junction_map *junction = NULL;
188         int consumedcnt = 0;
189         bool self_referral = false;
190         char *pathnamep = NULL;
191         char *local_dfs_path = NULL;
192         NTSTATUS status;
193         int i;
194         uint16_t max_referral_level = r->in.req.max_referral_level;
195
196         if (DEBUGLVL(10)) {
197                 NDR_PRINT_IN_DEBUG(dfs_GetDFSReferral, r);
198         }
199
200         /* get the junction entry */
201         if (r->in.req.servername == NULL) {
202                 return NT_STATUS_NOT_FOUND;
203         }
204
205         /*
206          * Trim pathname sent by client so it begins with only one backslash.
207          * Two backslashes confuse some dfs clients
208          */
209
210         local_dfs_path = talloc_strdup(r, r->in.req.servername);
211         if (local_dfs_path == NULL) {
212                 return NT_STATUS_NO_MEMORY;
213         }
214         pathnamep = local_dfs_path;
215         while (IS_DIRECTORY_SEP(pathnamep[0]) &&
216                IS_DIRECTORY_SEP(pathnamep[1])) {
217                 pathnamep++;
218         }
219
220         junction = talloc_zero(r, struct junction_map);
221         if (junction == NULL) {
222                 return NT_STATUS_NO_MEMORY;
223         }
224
225         /* The following call can change cwd. */
226         status = get_referred_path(r, pathnamep,
227                                    handle->conn->sconn->remote_address,
228                                    handle->conn->sconn->local_address,
229                                    !handle->conn->sconn->using_smb2,
230                                    junction, &consumedcnt, &self_referral);
231         if (!NT_STATUS_IS_OK(status)) {
232                 struct smb_filename connectpath_fname = {
233                         .base_name = handle->conn->connectpath
234                 };
235                 vfs_ChDir(handle->conn, &connectpath_fname);
236                 return status;
237         }
238         {
239                 struct smb_filename connectpath_fname = {
240                         .base_name = handle->conn->connectpath
241                 };
242                 vfs_ChDir(handle->conn, &connectpath_fname);
243         }
244
245         if (!self_referral) {
246                 pathnamep[consumedcnt] = '\0';
247
248                 if (DEBUGLVL(3)) {
249                         dbgtext("Path %s to alternate path(s):",
250                                 pathnamep);
251                         for (i=0; i < junction->referral_count; i++) {
252                                 dbgtext(" %s",
253                                 junction->referral_list[i].alternate_path);
254                         }
255                         dbgtext(".\n");
256                 }
257         }
258
259         if (r->in.req.max_referral_level <= 2) {
260                 max_referral_level = 2;
261         }
262         if (r->in.req.max_referral_level >= 3) {
263                 max_referral_level = 3;
264         }
265
266         r->out.resp = talloc_zero(r, struct dfs_referral_resp);
267         if (r->out.resp == NULL) {
268                 return NT_STATUS_NO_MEMORY;
269         }
270
271         r->out.resp->path_consumed = strlen_m(pathnamep) * 2;
272         r->out.resp->nb_referrals = junction->referral_count;
273
274         r->out.resp->header_flags = DFS_HEADER_FLAG_STORAGE_SVR;
275         if (self_referral) {
276                 r->out.resp->header_flags |= DFS_HEADER_FLAG_REFERAL_SVR;
277         }
278
279         r->out.resp->referral_entries = talloc_zero_array(r,
280                                 struct dfs_referral_type,
281                                 r->out.resp->nb_referrals);
282         if (r->out.resp->referral_entries == NULL) {
283                 return NT_STATUS_NO_MEMORY;
284         }
285
286         switch (max_referral_level) {
287         case 2:
288                 for(i=0; i < junction->referral_count; i++) {
289                         struct referral *ref = &junction->referral_list[i];
290                         TALLOC_CTX *mem_ctx = r->out.resp->referral_entries;
291                         struct dfs_referral_type *t =
292                                 &r->out.resp->referral_entries[i];
293                         struct dfs_referral_v2 *v2 = &t->referral.v2;
294
295                         t->version = 2;
296                         v2->size = VERSION2_REFERRAL_SIZE;
297                         if (self_referral) {
298                                 v2->server_type = DFS_SERVER_ROOT;
299                         } else {
300                                 v2->server_type = DFS_SERVER_NON_ROOT;
301                         }
302                         v2->entry_flags = 0;
303                         v2->proximity = ref->proximity;
304                         v2->ttl = ref->ttl;
305                         v2->DFS_path = talloc_strdup(mem_ctx, pathnamep);
306                         if (v2->DFS_path == NULL) {
307                                 return NT_STATUS_NO_MEMORY;
308                         }
309                         v2->DFS_alt_path = talloc_strdup(mem_ctx, pathnamep);
310                         if (v2->DFS_alt_path == NULL) {
311                                 return NT_STATUS_NO_MEMORY;
312                         }
313                         v2->netw_address = talloc_strdup(mem_ctx,
314                                                          ref->alternate_path);
315                         if (v2->netw_address == NULL) {
316                                 return NT_STATUS_NO_MEMORY;
317                         }
318                 }
319
320                 break;
321         case 3:
322                 for(i=0; i < junction->referral_count; i++) {
323                         struct referral *ref = &junction->referral_list[i];
324                         TALLOC_CTX *mem_ctx = r->out.resp->referral_entries;
325                         struct dfs_referral_type *t =
326                                 &r->out.resp->referral_entries[i];
327                         struct dfs_referral_v3 *v3 = &t->referral.v3;
328                         struct dfs_normal_referral *r1 = &v3->referrals.r1;
329
330                         t->version = 3;
331                         v3->size = VERSION3_REFERRAL_SIZE;
332                         if (self_referral) {
333                                 v3->server_type = DFS_SERVER_ROOT;
334                         } else {
335                                 v3->server_type = DFS_SERVER_NON_ROOT;
336                         }
337                         v3->entry_flags = 0;
338                         v3->ttl = ref->ttl;
339                         r1->DFS_path = talloc_strdup(mem_ctx, pathnamep);
340                         if (r1->DFS_path == NULL) {
341                                 return NT_STATUS_NO_MEMORY;
342                         }
343                         r1->DFS_alt_path = talloc_strdup(mem_ctx, pathnamep);
344                         if (r1->DFS_alt_path == NULL) {
345                                 return NT_STATUS_NO_MEMORY;
346                         }
347                         r1->netw_address = talloc_strdup(mem_ctx,
348                                                          ref->alternate_path);
349                         if (r1->netw_address == NULL) {
350                                 return NT_STATUS_NO_MEMORY;
351                         }
352                 }
353                 break;
354         default:
355                 DEBUG(0,("Invalid dfs referral version: %d\n",
356                         max_referral_level));
357                 return NT_STATUS_INVALID_LEVEL;
358         }
359
360         if (DEBUGLVL(10)) {
361                 NDR_PRINT_OUT_DEBUG(dfs_GetDFSReferral, r);
362         }
363
364         return NT_STATUS_OK;
365 }
366
367 static NTSTATUS vfswrap_snap_check_path(struct vfs_handle_struct *handle,
368                                         TALLOC_CTX *mem_ctx,
369                                         const char *service_path,
370                                         char **base_volume)
371 {
372         return NT_STATUS_NOT_SUPPORTED;
373 }
374
375 static NTSTATUS vfswrap_snap_create(struct vfs_handle_struct *handle,
376                                     TALLOC_CTX *mem_ctx,
377                                     const char *base_volume,
378                                     time_t *tstamp,
379                                     bool rw,
380                                     char **base_path,
381                                     char **snap_path)
382 {
383         return NT_STATUS_NOT_SUPPORTED;
384 }
385
386 static NTSTATUS vfswrap_snap_delete(struct vfs_handle_struct *handle,
387                                     TALLOC_CTX *mem_ctx,
388                                     char *base_path,
389                                     char *snap_path)
390 {
391         return NT_STATUS_NOT_SUPPORTED;
392 }
393
394 /* Directory operations */
395
396 static DIR *vfswrap_opendir(vfs_handle_struct *handle,
397                                 const struct smb_filename *smb_fname,
398                                 const char *mask,
399                                 uint32_t attr)
400 {
401         DIR *result;
402
403         START_PROFILE(syscall_opendir);
404         result = opendir(smb_fname->base_name);
405         END_PROFILE(syscall_opendir);
406         return result;
407 }
408
409 static DIR *vfswrap_fdopendir(vfs_handle_struct *handle,
410                         files_struct *fsp,
411                         const char *mask,
412                         uint32_t attr)
413 {
414         DIR *result;
415
416         START_PROFILE(syscall_fdopendir);
417         result = sys_fdopendir(fsp->fh->fd);
418         END_PROFILE(syscall_fdopendir);
419         return result;
420 }
421
422
423 static struct dirent *vfswrap_readdir(vfs_handle_struct *handle,
424                                           DIR *dirp,
425                                           SMB_STRUCT_STAT *sbuf)
426 {
427         struct dirent *result;
428
429         START_PROFILE(syscall_readdir);
430         result = readdir(dirp);
431         END_PROFILE(syscall_readdir);
432         if (sbuf) {
433                 /* Default Posix readdir() does not give us stat info.
434                  * Set to invalid to indicate we didn't return this info. */
435                 SET_STAT_INVALID(*sbuf);
436 #if defined(HAVE_DIRFD) && defined(HAVE_FSTATAT)
437                 if (result != NULL) {
438                         /* See if we can efficiently return this. */
439                         struct stat st;
440                         int flags = AT_SYMLINK_NOFOLLOW;
441                         int ret = fstatat(dirfd(dirp),
442                                         result->d_name,
443                                         &st,
444                                         flags);
445                         /*
446                          * As this is an optimization,
447                          * ignore it if we stat'ed a
448                          * symlink. Make the caller
449                          * do it again as we don't
450                          * know if they wanted the link
451                          * info, or its target info.
452                          */
453                         if ((ret == 0) && (!S_ISLNK(st.st_mode))) {
454                                 init_stat_ex_from_stat(sbuf,
455                                         &st,
456                                         lp_fake_directory_create_times(
457                                                 SNUM(handle->conn)));
458                         }
459                 }
460 #endif
461         }
462         return result;
463 }
464
465 static NTSTATUS vfswrap_readdir_attr(struct vfs_handle_struct *handle,
466                                      const struct smb_filename *fname,
467                                      TALLOC_CTX *mem_ctx,
468                                      struct readdir_attr_data **attr_data)
469 {
470         return NT_STATUS_NOT_SUPPORTED;
471 }
472
473 static void vfswrap_seekdir(vfs_handle_struct *handle, DIR *dirp, long offset)
474 {
475         START_PROFILE(syscall_seekdir);
476         seekdir(dirp, offset);
477         END_PROFILE(syscall_seekdir);
478 }
479
480 static long vfswrap_telldir(vfs_handle_struct *handle, DIR *dirp)
481 {
482         long result;
483         START_PROFILE(syscall_telldir);
484         result = telldir(dirp);
485         END_PROFILE(syscall_telldir);
486         return result;
487 }
488
489 static void vfswrap_rewinddir(vfs_handle_struct *handle, DIR *dirp)
490 {
491         START_PROFILE(syscall_rewinddir);
492         rewinddir(dirp);
493         END_PROFILE(syscall_rewinddir);
494 }
495
496 static int vfswrap_mkdir(vfs_handle_struct *handle,
497                         const struct smb_filename *smb_fname,
498                         mode_t mode)
499 {
500         int result;
501         const char *path = smb_fname->base_name;
502         char *parent = NULL;
503
504         START_PROFILE(syscall_mkdir);
505
506         if (lp_inherit_acls(SNUM(handle->conn))
507             && parent_dirname(talloc_tos(), path, &parent, NULL)
508             && directory_has_default_acl(handle->conn, parent)) {
509                 mode = (0777 & lp_directory_mask(SNUM(handle->conn)));
510         }
511
512         TALLOC_FREE(parent);
513
514         result = mkdir(path, mode);
515
516         END_PROFILE(syscall_mkdir);
517         return result;
518 }
519
520 static int vfswrap_rmdir(vfs_handle_struct *handle,
521                         const struct smb_filename *smb_fname)
522 {
523         int result;
524
525         START_PROFILE(syscall_rmdir);
526         result = rmdir(smb_fname->base_name);
527         END_PROFILE(syscall_rmdir);
528         return result;
529 }
530
531 static int vfswrap_closedir(vfs_handle_struct *handle, DIR *dirp)
532 {
533         int result;
534
535         START_PROFILE(syscall_closedir);
536         result = closedir(dirp);
537         END_PROFILE(syscall_closedir);
538         return result;
539 }
540
541 /* File operations */
542
543 static int vfswrap_open(vfs_handle_struct *handle,
544                         struct smb_filename *smb_fname,
545                         files_struct *fsp, int flags, mode_t mode)
546 {
547         int result = -1;
548
549         START_PROFILE(syscall_open);
550
551         if (smb_fname->stream_name) {
552                 errno = ENOENT;
553                 goto out;
554         }
555
556         result = open(smb_fname->base_name, flags, mode);
557  out:
558         END_PROFILE(syscall_open);
559         return result;
560 }
561
562 static NTSTATUS vfswrap_create_file(vfs_handle_struct *handle,
563                                     struct smb_request *req,
564                                     uint16_t root_dir_fid,
565                                     struct smb_filename *smb_fname,
566                                     uint32_t access_mask,
567                                     uint32_t share_access,
568                                     uint32_t create_disposition,
569                                     uint32_t create_options,
570                                     uint32_t file_attributes,
571                                     uint32_t oplock_request,
572                                     struct smb2_lease *lease,
573                                     uint64_t allocation_size,
574                                     uint32_t private_flags,
575                                     struct security_descriptor *sd,
576                                     struct ea_list *ea_list,
577                                     files_struct **result,
578                                     int *pinfo,
579                                     const struct smb2_create_blobs *in_context_blobs,
580                                     struct smb2_create_blobs *out_context_blobs)
581 {
582         return create_file_default(handle->conn, req, root_dir_fid, smb_fname,
583                                    access_mask, share_access,
584                                    create_disposition, create_options,
585                                    file_attributes, oplock_request, lease,
586                                    allocation_size, private_flags,
587                                    sd, ea_list, result,
588                                    pinfo, in_context_blobs, out_context_blobs);
589 }
590
591 static int vfswrap_close(vfs_handle_struct *handle, files_struct *fsp)
592 {
593         int result;
594
595         START_PROFILE(syscall_close);
596         result = fd_close_posix(fsp);
597         END_PROFILE(syscall_close);
598         return result;
599 }
600
601 static ssize_t vfswrap_pread(vfs_handle_struct *handle, files_struct *fsp, void *data,
602                         size_t n, off_t offset)
603 {
604         ssize_t result;
605
606 #if defined(HAVE_PREAD) || defined(HAVE_PREAD64)
607         START_PROFILE_BYTES(syscall_pread, n);
608         result = sys_pread(fsp->fh->fd, data, n, offset);
609         END_PROFILE_BYTES(syscall_pread);
610
611         if (result == -1 && errno == ESPIPE) {
612                 /* Maintain the fiction that pipes can be seeked (sought?) on. */
613                 result = sys_read(fsp->fh->fd, data, n);
614                 fsp->fh->pos = 0;
615         }
616
617 #else /* HAVE_PREAD */
618         errno = ENOSYS;
619         result = -1;
620 #endif /* HAVE_PREAD */
621
622         return result;
623 }
624
625 static ssize_t vfswrap_pwrite(vfs_handle_struct *handle, files_struct *fsp, const void *data,
626                         size_t n, off_t offset)
627 {
628         ssize_t result;
629
630 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
631         START_PROFILE_BYTES(syscall_pwrite, n);
632         result = sys_pwrite(fsp->fh->fd, data, n, offset);
633         END_PROFILE_BYTES(syscall_pwrite);
634
635         if (result == -1 && errno == ESPIPE) {
636                 /* Maintain the fiction that pipes can be sought on. */
637                 result = sys_write(fsp->fh->fd, data, n);
638         }
639
640 #else /* HAVE_PWRITE */
641         errno = ENOSYS;
642         result = -1;
643 #endif /* HAVE_PWRITE */
644
645         return result;
646 }
647
648 struct vfswrap_pread_state {
649         ssize_t ret;
650         int fd;
651         void *buf;
652         size_t count;
653         off_t offset;
654
655         struct vfs_aio_state vfs_aio_state;
656         SMBPROFILE_BYTES_ASYNC_STATE(profile_bytes);
657 };
658
659 static void vfs_pread_do(void *private_data);
660 static void vfs_pread_done(struct tevent_req *subreq);
661 static int vfs_pread_state_destructor(struct vfswrap_pread_state *state);
662
663 static struct tevent_req *vfswrap_pread_send(struct vfs_handle_struct *handle,
664                                              TALLOC_CTX *mem_ctx,
665                                              struct tevent_context *ev,
666                                              struct files_struct *fsp,
667                                              void *data,
668                                              size_t n, off_t offset)
669 {
670         struct tevent_req *req, *subreq;
671         struct vfswrap_pread_state *state;
672
673         req = tevent_req_create(mem_ctx, &state, struct vfswrap_pread_state);
674         if (req == NULL) {
675                 return NULL;
676         }
677
678         state->ret = -1;
679         state->fd = fsp->fh->fd;
680         state->buf = data;
681         state->count = n;
682         state->offset = offset;
683
684         SMBPROFILE_BYTES_ASYNC_START(syscall_asys_pread, profile_p,
685                                      state->profile_bytes, n);
686         SMBPROFILE_BYTES_ASYNC_SET_IDLE(state->profile_bytes);
687
688         subreq = pthreadpool_tevent_job_send(
689                 state, ev, handle->conn->sconn->raw_thread_pool,
690                 vfs_pread_do, state);
691         if (tevent_req_nomem(subreq, req)) {
692                 return tevent_req_post(req, ev);
693         }
694         tevent_req_set_callback(subreq, vfs_pread_done, req);
695
696         talloc_set_destructor(state, vfs_pread_state_destructor);
697
698         return req;
699 }
700
701 static void vfs_pread_do(void *private_data)
702 {
703         struct vfswrap_pread_state *state = talloc_get_type_abort(
704                 private_data, struct vfswrap_pread_state);
705         struct timespec start_time;
706         struct timespec end_time;
707
708         SMBPROFILE_BYTES_ASYNC_SET_BUSY(state->profile_bytes);
709
710         PROFILE_TIMESTAMP(&start_time);
711
712         do {
713                 state->ret = pread(state->fd, state->buf, state->count,
714                                    state->offset);
715         } while ((state->ret == -1) && (errno == EINTR));
716
717         if (state->ret == -1) {
718                 state->vfs_aio_state.error = errno;
719         }
720
721         PROFILE_TIMESTAMP(&end_time);
722
723         state->vfs_aio_state.duration = nsec_time_diff(&end_time, &start_time);
724
725         SMBPROFILE_BYTES_ASYNC_SET_IDLE(state->profile_bytes);
726 }
727
728 static int vfs_pread_state_destructor(struct vfswrap_pread_state *state)
729 {
730         return -1;
731 }
732
733 static void vfs_pread_done(struct tevent_req *subreq)
734 {
735         struct tevent_req *req = tevent_req_callback_data(
736                 subreq, struct tevent_req);
737         struct vfswrap_pread_state *state = tevent_req_data(
738                 req, struct vfswrap_pread_state);
739         int ret;
740
741         ret = pthreadpool_tevent_job_recv(subreq);
742         TALLOC_FREE(subreq);
743         SMBPROFILE_BYTES_ASYNC_END(state->profile_bytes);
744         talloc_set_destructor(state, NULL);
745         if (tevent_req_error(req, ret)) {
746                 return;
747         }
748
749         tevent_req_done(req);
750 }
751
752 static ssize_t vfswrap_pread_recv(struct tevent_req *req,
753                                   struct vfs_aio_state *vfs_aio_state)
754 {
755         struct vfswrap_pread_state *state = tevent_req_data(
756                 req, struct vfswrap_pread_state);
757
758         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
759                 return -1;
760         }
761
762         *vfs_aio_state = state->vfs_aio_state;
763         return state->ret;
764 }
765
766 struct vfswrap_pwrite_state {
767         ssize_t ret;
768         int fd;
769         const void *buf;
770         size_t count;
771         off_t offset;
772
773         struct vfs_aio_state vfs_aio_state;
774         SMBPROFILE_BYTES_ASYNC_STATE(profile_bytes);
775 };
776
777 static void vfs_pwrite_do(void *private_data);
778 static void vfs_pwrite_done(struct tevent_req *subreq);
779 static int vfs_pwrite_state_destructor(struct vfswrap_pwrite_state *state);
780
781 static struct tevent_req *vfswrap_pwrite_send(struct vfs_handle_struct *handle,
782                                               TALLOC_CTX *mem_ctx,
783                                               struct tevent_context *ev,
784                                               struct files_struct *fsp,
785                                               const void *data,
786                                               size_t n, off_t offset)
787 {
788         struct tevent_req *req, *subreq;
789         struct vfswrap_pwrite_state *state;
790
791         req = tevent_req_create(mem_ctx, &state, struct vfswrap_pwrite_state);
792         if (req == NULL) {
793                 return NULL;
794         }
795
796         state->ret = -1;
797         state->fd = fsp->fh->fd;
798         state->buf = data;
799         state->count = n;
800         state->offset = offset;
801
802         SMBPROFILE_BYTES_ASYNC_START(syscall_asys_pwrite, profile_p,
803                                      state->profile_bytes, n);
804         SMBPROFILE_BYTES_ASYNC_SET_IDLE(state->profile_bytes);
805
806         subreq = pthreadpool_tevent_job_send(
807                 state, ev, handle->conn->sconn->raw_thread_pool,
808                 vfs_pwrite_do, state);
809         if (tevent_req_nomem(subreq, req)) {
810                 return tevent_req_post(req, ev);
811         }
812         tevent_req_set_callback(subreq, vfs_pwrite_done, req);
813
814         talloc_set_destructor(state, vfs_pwrite_state_destructor);
815
816         return req;
817 }
818
819 static void vfs_pwrite_do(void *private_data)
820 {
821         struct vfswrap_pwrite_state *state = talloc_get_type_abort(
822                 private_data, struct vfswrap_pwrite_state);
823         struct timespec start_time;
824         struct timespec end_time;
825
826         SMBPROFILE_BYTES_ASYNC_SET_BUSY(state->profile_bytes);
827
828         PROFILE_TIMESTAMP(&start_time);
829
830         do {
831                 state->ret = pwrite(state->fd, state->buf, state->count,
832                                    state->offset);
833         } while ((state->ret == -1) && (errno == EINTR));
834
835         if (state->ret == -1) {
836                 state->vfs_aio_state.error = errno;
837         }
838
839         PROFILE_TIMESTAMP(&end_time);
840
841         state->vfs_aio_state.duration = nsec_time_diff(&end_time, &start_time);
842
843         SMBPROFILE_BYTES_ASYNC_SET_IDLE(state->profile_bytes);
844 }
845
846 static int vfs_pwrite_state_destructor(struct vfswrap_pwrite_state *state)
847 {
848         return -1;
849 }
850
851 static void vfs_pwrite_done(struct tevent_req *subreq)
852 {
853         struct tevent_req *req = tevent_req_callback_data(
854                 subreq, struct tevent_req);
855         struct vfswrap_pwrite_state *state = tevent_req_data(
856                 req, struct vfswrap_pwrite_state);
857         int ret;
858
859         ret = pthreadpool_tevent_job_recv(subreq);
860         TALLOC_FREE(subreq);
861         SMBPROFILE_BYTES_ASYNC_END(state->profile_bytes);
862         talloc_set_destructor(state, NULL);
863         if (tevent_req_error(req, ret)) {
864                 return;
865         }
866
867         tevent_req_done(req);
868 }
869
870 static ssize_t vfswrap_pwrite_recv(struct tevent_req *req,
871                                    struct vfs_aio_state *vfs_aio_state)
872 {
873         struct vfswrap_pwrite_state *state = tevent_req_data(
874                 req, struct vfswrap_pwrite_state);
875
876         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
877                 return -1;
878         }
879
880         *vfs_aio_state = state->vfs_aio_state;
881         return state->ret;
882 }
883
884 struct vfswrap_fsync_state {
885         ssize_t ret;
886         int fd;
887
888         struct vfs_aio_state vfs_aio_state;
889         SMBPROFILE_BYTES_ASYNC_STATE(profile_bytes);
890 };
891
892 static void vfs_fsync_do(void *private_data);
893 static void vfs_fsync_done(struct tevent_req *subreq);
894 static int vfs_fsync_state_destructor(struct vfswrap_fsync_state *state);
895
896 static struct tevent_req *vfswrap_fsync_send(struct vfs_handle_struct *handle,
897                                              TALLOC_CTX *mem_ctx,
898                                              struct tevent_context *ev,
899                                              struct files_struct *fsp)
900 {
901         struct tevent_req *req, *subreq;
902         struct vfswrap_fsync_state *state;
903
904         req = tevent_req_create(mem_ctx, &state, struct vfswrap_fsync_state);
905         if (req == NULL) {
906                 return NULL;
907         }
908
909         state->ret = -1;
910         state->fd = fsp->fh->fd;
911
912         SMBPROFILE_BYTES_ASYNC_START(syscall_asys_fsync, profile_p,
913                                      state->profile_bytes, 0);
914         SMBPROFILE_BYTES_ASYNC_SET_IDLE(state->profile_bytes);
915
916         subreq = pthreadpool_tevent_job_send(
917                 state, ev, handle->conn->sconn->raw_thread_pool,
918                 vfs_fsync_do, state);
919         if (tevent_req_nomem(subreq, req)) {
920                 return tevent_req_post(req, ev);
921         }
922         tevent_req_set_callback(subreq, vfs_fsync_done, req);
923
924         talloc_set_destructor(state, vfs_fsync_state_destructor);
925
926         return req;
927 }
928
929 static void vfs_fsync_do(void *private_data)
930 {
931         struct vfswrap_fsync_state *state = talloc_get_type_abort(
932                 private_data, struct vfswrap_fsync_state);
933         struct timespec start_time;
934         struct timespec end_time;
935
936         SMBPROFILE_BYTES_ASYNC_SET_BUSY(state->profile_bytes);
937
938         PROFILE_TIMESTAMP(&start_time);
939
940         do {
941                 state->ret = fsync(state->fd);
942         } while ((state->ret == -1) && (errno == EINTR));
943
944         if (state->ret == -1) {
945                 state->vfs_aio_state.error = errno;
946         }
947
948         PROFILE_TIMESTAMP(&end_time);
949
950         state->vfs_aio_state.duration = nsec_time_diff(&end_time, &start_time);
951
952         SMBPROFILE_BYTES_ASYNC_SET_IDLE(state->profile_bytes);
953 }
954
955 static int vfs_fsync_state_destructor(struct vfswrap_fsync_state *state)
956 {
957         return -1;
958 }
959
960 static void vfs_fsync_done(struct tevent_req *subreq)
961 {
962         struct tevent_req *req = tevent_req_callback_data(
963                 subreq, struct tevent_req);
964         struct vfswrap_fsync_state *state = tevent_req_data(
965                 req, struct vfswrap_fsync_state);
966         int ret;
967
968         ret = pthreadpool_tevent_job_recv(subreq);
969         TALLOC_FREE(subreq);
970         SMBPROFILE_BYTES_ASYNC_END(state->profile_bytes);
971         talloc_set_destructor(state, NULL);
972         if (tevent_req_error(req, ret)) {
973                 return;
974         }
975
976         tevent_req_done(req);
977 }
978
979 static int vfswrap_fsync_recv(struct tevent_req *req,
980                               struct vfs_aio_state *vfs_aio_state)
981 {
982         struct vfswrap_fsync_state *state = tevent_req_data(
983                 req, struct vfswrap_fsync_state);
984
985         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
986                 return -1;
987         }
988
989         *vfs_aio_state = state->vfs_aio_state;
990         return state->ret;
991 }
992
993 static off_t vfswrap_lseek(vfs_handle_struct *handle, files_struct *fsp, off_t offset, int whence)
994 {
995         off_t result = 0;
996
997         START_PROFILE(syscall_lseek);
998
999         /* Cope with 'stat' file opens. */
1000         if (fsp->fh->fd != -1)
1001                 result = lseek(fsp->fh->fd, offset, whence);
1002
1003         /*
1004          * We want to maintain the fiction that we can seek
1005          * on a fifo for file system purposes. This allows
1006          * people to set up UNIX fifo's that feed data to Windows
1007          * applications. JRA.
1008          */
1009
1010         if((result == -1) && (errno == ESPIPE)) {
1011                 result = 0;
1012                 errno = 0;
1013         }
1014
1015         END_PROFILE(syscall_lseek);
1016         return result;
1017 }
1018
1019 static ssize_t vfswrap_sendfile(vfs_handle_struct *handle, int tofd, files_struct *fromfsp, const DATA_BLOB *hdr,
1020                         off_t offset, size_t n)
1021 {
1022         ssize_t result;
1023
1024         START_PROFILE_BYTES(syscall_sendfile, n);
1025         result = sys_sendfile(tofd, fromfsp->fh->fd, hdr, offset, n);
1026         END_PROFILE_BYTES(syscall_sendfile);
1027         return result;
1028 }
1029
1030 static ssize_t vfswrap_recvfile(vfs_handle_struct *handle,
1031                         int fromfd,
1032                         files_struct *tofsp,
1033                         off_t offset,
1034                         size_t n)
1035 {
1036         ssize_t result;
1037
1038         START_PROFILE_BYTES(syscall_recvfile, n);
1039         result = sys_recvfile(fromfd, tofsp->fh->fd, offset, n);
1040         END_PROFILE_BYTES(syscall_recvfile);
1041         return result;
1042 }
1043
1044 static int vfswrap_rename(vfs_handle_struct *handle,
1045                           const struct smb_filename *smb_fname_src,
1046                           const struct smb_filename *smb_fname_dst)
1047 {
1048         int result = -1;
1049
1050         START_PROFILE(syscall_rename);
1051
1052         if (smb_fname_src->stream_name || smb_fname_dst->stream_name) {
1053                 errno = ENOENT;
1054                 goto out;
1055         }
1056
1057         result = rename(smb_fname_src->base_name, smb_fname_dst->base_name);
1058
1059  out:
1060         END_PROFILE(syscall_rename);
1061         return result;
1062 }
1063
1064 static int vfswrap_stat(vfs_handle_struct *handle,
1065                         struct smb_filename *smb_fname)
1066 {
1067         int result = -1;
1068
1069         START_PROFILE(syscall_stat);
1070
1071         if (smb_fname->stream_name) {
1072                 errno = ENOENT;
1073                 goto out;
1074         }
1075
1076         result = sys_stat(smb_fname->base_name, &smb_fname->st,
1077                           lp_fake_directory_create_times(SNUM(handle->conn)));
1078  out:
1079         END_PROFILE(syscall_stat);
1080         return result;
1081 }
1082
1083 static int vfswrap_fstat(vfs_handle_struct *handle, files_struct *fsp, SMB_STRUCT_STAT *sbuf)
1084 {
1085         int result;
1086
1087         START_PROFILE(syscall_fstat);
1088         result = sys_fstat(fsp->fh->fd,
1089                            sbuf, lp_fake_directory_create_times(SNUM(handle->conn)));
1090         END_PROFILE(syscall_fstat);
1091         return result;
1092 }
1093
1094 static int vfswrap_lstat(vfs_handle_struct *handle,
1095                          struct smb_filename *smb_fname)
1096 {
1097         int result = -1;
1098
1099         START_PROFILE(syscall_lstat);
1100
1101         if (smb_fname->stream_name) {
1102                 errno = ENOENT;
1103                 goto out;
1104         }
1105
1106         result = sys_lstat(smb_fname->base_name, &smb_fname->st,
1107                            lp_fake_directory_create_times(SNUM(handle->conn)));
1108  out:
1109         END_PROFILE(syscall_lstat);
1110         return result;
1111 }
1112
1113 static NTSTATUS vfswrap_translate_name(struct vfs_handle_struct *handle,
1114                                        const char *name,
1115                                        enum vfs_translate_direction direction,
1116                                        TALLOC_CTX *mem_ctx,
1117                                        char **mapped_name)
1118 {
1119         return NT_STATUS_NONE_MAPPED;
1120 }
1121
1122 /*
1123  * Implement the default fsctl operation.
1124  */
1125 static bool vfswrap_logged_ioctl_message = false;
1126
1127 static NTSTATUS vfswrap_fsctl(struct vfs_handle_struct *handle,
1128                               struct files_struct *fsp,
1129                               TALLOC_CTX *ctx,
1130                               uint32_t function,
1131                               uint16_t req_flags, /* Needed for UNICODE ... */
1132                               const uint8_t *_in_data,
1133                               uint32_t in_len,
1134                               uint8_t **_out_data,
1135                               uint32_t max_out_len,
1136                               uint32_t *out_len)
1137 {
1138         const char *in_data = (const char *)_in_data;
1139         char **out_data = (char **)_out_data;
1140         NTSTATUS status;
1141
1142         switch (function) {
1143         case FSCTL_SET_SPARSE:
1144         {
1145                 bool set_sparse = true;
1146
1147                 if (in_len >= 1 && in_data[0] == 0) {
1148                         set_sparse = false;
1149                 }
1150
1151                 status = file_set_sparse(handle->conn, fsp, set_sparse);
1152
1153                 DEBUG(NT_STATUS_IS_OK(status) ? 10 : 9,
1154                       ("FSCTL_SET_SPARSE: fname[%s] set[%u] - %s\n",
1155                        smb_fname_str_dbg(fsp->fsp_name), set_sparse,
1156                        nt_errstr(status)));
1157
1158                 return status;
1159         }
1160
1161         case FSCTL_CREATE_OR_GET_OBJECT_ID:
1162         {
1163                 unsigned char objid[16];
1164                 char *return_data = NULL;
1165
1166                 /* This should return the object-id on this file.
1167                  * I think I'll make this be the inode+dev. JRA.
1168                  */
1169
1170                 DEBUG(10,("FSCTL_CREATE_OR_GET_OBJECT_ID: called on %s\n",
1171                           fsp_fnum_dbg(fsp)));
1172
1173                 *out_len = MIN(max_out_len, 64);
1174
1175                 /* Hmmm, will this cause problems if less data asked for? */
1176                 return_data = talloc_array(ctx, char, 64);
1177                 if (return_data == NULL) {
1178                         return NT_STATUS_NO_MEMORY;
1179                 }
1180
1181                 /* For backwards compatibility only store the dev/inode. */
1182                 push_file_id_16(return_data, &fsp->file_id);
1183                 memcpy(return_data+16,create_volume_objectid(fsp->conn,objid),16);
1184                 push_file_id_16(return_data+32, &fsp->file_id);
1185                 memset(return_data+48, 0, 16);
1186                 *out_data = return_data;
1187                 return NT_STATUS_OK;
1188         }
1189
1190         case FSCTL_GET_REPARSE_POINT:
1191         {
1192                 /* Fail it with STATUS_NOT_A_REPARSE_POINT */
1193                 DEBUG(10, ("FSCTL_GET_REPARSE_POINT: called on %s. "
1194                            "Status: NOT_IMPLEMENTED\n", fsp_fnum_dbg(fsp)));
1195                 return NT_STATUS_NOT_A_REPARSE_POINT;
1196         }
1197
1198         case FSCTL_SET_REPARSE_POINT:
1199         {
1200                 /* Fail it with STATUS_NOT_A_REPARSE_POINT */
1201                 DEBUG(10, ("FSCTL_SET_REPARSE_POINT: called on %s. "
1202                            "Status: NOT_IMPLEMENTED\n", fsp_fnum_dbg(fsp)));
1203                 return NT_STATUS_NOT_A_REPARSE_POINT;
1204         }
1205
1206         case FSCTL_GET_SHADOW_COPY_DATA:
1207         {
1208                 /*
1209                  * This is called to retrieve the number of Shadow Copies (a.k.a. snapshots)
1210                  * and return their volume names.  If max_data_count is 16, then it is just
1211                  * asking for the number of volumes and length of the combined names.
1212                  *
1213                  * pdata is the data allocated by our caller, but that uses
1214                  * total_data_count (which is 0 in our case) rather than max_data_count.
1215                  * Allocate the correct amount and return the pointer to let
1216                  * it be deallocated when we return.
1217                  */
1218                 struct shadow_copy_data *shadow_data = NULL;
1219                 bool labels = False;
1220                 uint32_t labels_data_count = 0;
1221                 uint32_t i;
1222                 char *cur_pdata = NULL;
1223
1224                 if (max_out_len < 16) {
1225                         DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) < 16 is invalid!\n",
1226                                 max_out_len));
1227                         return NT_STATUS_INVALID_PARAMETER;
1228                 }
1229
1230                 if (max_out_len > 16) {
1231                         labels = True;
1232                 }
1233
1234                 shadow_data = talloc_zero(ctx, struct shadow_copy_data);
1235                 if (shadow_data == NULL) {
1236                         DEBUG(0,("TALLOC_ZERO() failed!\n"));
1237                         return NT_STATUS_NO_MEMORY;
1238                 }
1239
1240                 /*
1241                  * Call the VFS routine to actually do the work.
1242                  */
1243                 if (SMB_VFS_GET_SHADOW_COPY_DATA(fsp, shadow_data, labels)!=0) {
1244                         int log_lev = 0;
1245                         if (errno == 0) {
1246                                 /* broken module didn't set errno on error */
1247                                 status = NT_STATUS_UNSUCCESSFUL;
1248                         } else {
1249                                 status = map_nt_error_from_unix(errno);
1250                                 if (NT_STATUS_EQUAL(status,
1251                                                     NT_STATUS_NOT_SUPPORTED)) {
1252                                         log_lev = 5;
1253                                 }
1254                         }
1255                         DEBUG(log_lev, ("FSCTL_GET_SHADOW_COPY_DATA: "
1256                                         "connectpath %s, failed - %s.\n",
1257                                         fsp->conn->connectpath,
1258                                         nt_errstr(status)));
1259                         TALLOC_FREE(shadow_data);
1260                         return status;
1261                 }
1262
1263                 labels_data_count = (shadow_data->num_volumes * 2 *
1264                                         sizeof(SHADOW_COPY_LABEL)) + 2;
1265
1266                 if (!labels) {
1267                         *out_len = 16;
1268                 } else {
1269                         *out_len = 12 + labels_data_count;
1270                 }
1271
1272                 if (max_out_len < *out_len) {
1273                         DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) too small (%u) bytes needed!\n",
1274                                 max_out_len, *out_len));
1275                         TALLOC_FREE(shadow_data);
1276                         return NT_STATUS_BUFFER_TOO_SMALL;
1277                 }
1278
1279                 cur_pdata = talloc_zero_array(ctx, char, *out_len);
1280                 if (cur_pdata == NULL) {
1281                         TALLOC_FREE(shadow_data);
1282                         return NT_STATUS_NO_MEMORY;
1283                 }
1284
1285                 *out_data = cur_pdata;
1286
1287                 /* num_volumes 4 bytes */
1288                 SIVAL(cur_pdata, 0, shadow_data->num_volumes);
1289
1290                 if (labels) {
1291                         /* num_labels 4 bytes */
1292                         SIVAL(cur_pdata, 4, shadow_data->num_volumes);
1293                 }
1294
1295                 /* needed_data_count 4 bytes */
1296                 SIVAL(cur_pdata, 8, labels_data_count);
1297
1298                 cur_pdata += 12;
1299
1300                 DEBUG(10,("FSCTL_GET_SHADOW_COPY_DATA: %u volumes for path[%s].\n",
1301                           shadow_data->num_volumes, fsp_str_dbg(fsp)));
1302                 if (labels && shadow_data->labels) {
1303                         for (i=0; i<shadow_data->num_volumes; i++) {
1304                                 size_t len = 0;
1305                                 status = srvstr_push(cur_pdata, req_flags,
1306                                             cur_pdata, shadow_data->labels[i],
1307                                             2 * sizeof(SHADOW_COPY_LABEL),
1308                                             STR_UNICODE|STR_TERMINATE, &len);
1309                                 if (!NT_STATUS_IS_OK(status)) {
1310                                         TALLOC_FREE(*out_data);
1311                                         TALLOC_FREE(shadow_data);
1312                                         return status;
1313                                 }
1314                                 cur_pdata += 2 * sizeof(SHADOW_COPY_LABEL);
1315                                 DEBUGADD(10,("Label[%u]: '%s'\n",i,shadow_data->labels[i]));
1316                         }
1317                 }
1318
1319                 TALLOC_FREE(shadow_data);
1320
1321                 return NT_STATUS_OK;
1322         }
1323
1324         case FSCTL_FIND_FILES_BY_SID:
1325         {
1326                 /* pretend this succeeded -
1327                  *
1328                  * we have to send back a list with all files owned by this SID
1329                  *
1330                  * but I have to check that --metze
1331                  */
1332                 struct dom_sid sid;
1333                 struct dom_sid_buf buf;
1334                 uid_t uid;
1335                 size_t sid_len;
1336
1337                 DEBUG(10, ("FSCTL_FIND_FILES_BY_SID: called on %s\n",
1338                            fsp_fnum_dbg(fsp)));
1339
1340                 if (in_len < 8) {
1341                         /* NT_STATUS_BUFFER_TOO_SMALL maybe? */
1342                         return NT_STATUS_INVALID_PARAMETER;
1343                 }
1344
1345                 sid_len = MIN(in_len - 4,SID_MAX_SIZE);
1346
1347                 /* unknown 4 bytes: this is not the length of the sid :-(  */
1348                 /*unknown = IVAL(pdata,0);*/
1349
1350                 if (!sid_parse(_in_data + 4, sid_len, &sid)) {
1351                         return NT_STATUS_INVALID_PARAMETER;
1352                 }
1353                 DEBUGADD(10, ("for SID: %s\n",
1354                               dom_sid_str_buf(&sid, &buf)));
1355
1356                 if (!sid_to_uid(&sid, &uid)) {
1357                         DEBUG(0,("sid_to_uid: failed, sid[%s] sid_len[%lu]\n",
1358                                  dom_sid_str_buf(&sid, &buf),
1359                                  (unsigned long)sid_len));
1360                         uid = (-1);
1361                 }
1362
1363                 /* we can take a look at the find source :-)
1364                  *
1365                  * find ./ -uid $uid  -name '*'   is what we need here
1366                  *
1367                  *
1368                  * and send 4bytes len and then NULL terminated unicode strings
1369                  * for each file
1370                  *
1371                  * but I don't know how to deal with the paged results
1372                  * (maybe we can hang the result anywhere in the fsp struct)
1373                  *
1374                  * but I don't know how to deal with the paged results
1375                  * (maybe we can hang the result anywhere in the fsp struct)
1376                  *
1377                  * we don't send all files at once
1378                  * and at the next we should *not* start from the beginning,
1379                  * so we have to cache the result
1380                  *
1381                  * --metze
1382                  */
1383
1384                 /* this works for now... */
1385                 return NT_STATUS_OK;
1386         }
1387
1388         case FSCTL_QUERY_ALLOCATED_RANGES:
1389         {
1390                 /* FIXME: This is just a dummy reply, telling that all of the
1391                  * file is allocated. MKS cp needs that.
1392                  * Adding the real allocated ranges via FIEMAP on Linux
1393                  * and SEEK_DATA/SEEK_HOLE on Solaris is needed to make
1394                  * this FSCTL correct for sparse files.
1395                  */
1396                 uint64_t offset, length;
1397                 char *out_data_tmp = NULL;
1398
1399                 if (in_len != 16) {
1400                         DEBUG(0,("FSCTL_QUERY_ALLOCATED_RANGES: data_count(%u) != 16 is invalid!\n",
1401                                 in_len));
1402                         return NT_STATUS_INVALID_PARAMETER;
1403                 }
1404
1405                 if (max_out_len < 16) {
1406                         DEBUG(0,("FSCTL_QUERY_ALLOCATED_RANGES: max_out_len (%u) < 16 is invalid!\n",
1407                                 max_out_len));
1408                         return NT_STATUS_INVALID_PARAMETER;
1409                 }
1410
1411                 offset = BVAL(in_data,0);
1412                 length = BVAL(in_data,8);
1413
1414                 if (offset + length < offset) {
1415                         /* No 64-bit integer wrap. */
1416                         return NT_STATUS_INVALID_PARAMETER;
1417                 }
1418
1419                 /* Shouldn't this be SMB_VFS_STAT ... ? */
1420                 status = vfs_stat_fsp(fsp);
1421                 if (!NT_STATUS_IS_OK(status)) {
1422                         return status;
1423                 }
1424
1425                 *out_len = 16;
1426                 out_data_tmp = talloc_array(ctx, char, *out_len);
1427                 if (out_data_tmp == NULL) {
1428                         DEBUG(10, ("unable to allocate memory for response\n"));
1429                         return NT_STATUS_NO_MEMORY;
1430                 }
1431
1432                 if (offset > fsp->fsp_name->st.st_ex_size ||
1433                                 fsp->fsp_name->st.st_ex_size == 0 ||
1434                                 length == 0) {
1435                         memset(out_data_tmp, 0, *out_len);
1436                 } else {
1437                         uint64_t end = offset + length;
1438                         end = MIN(end, fsp->fsp_name->st.st_ex_size);
1439                         SBVAL(out_data_tmp, 0, 0);
1440                         SBVAL(out_data_tmp, 8, end);
1441                 }
1442
1443                 *out_data = out_data_tmp;
1444
1445                 return NT_STATUS_OK;
1446         }
1447
1448         case FSCTL_IS_VOLUME_DIRTY:
1449         {
1450                 DEBUG(10,("FSCTL_IS_VOLUME_DIRTY: called on %s "
1451                           "(but remotely not supported)\n", fsp_fnum_dbg(fsp)));
1452                 /*
1453                  * http://msdn.microsoft.com/en-us/library/cc232128%28PROT.10%29.aspx
1454                  * says we have to respond with NT_STATUS_INVALID_PARAMETER
1455                  */
1456                 return NT_STATUS_INVALID_PARAMETER;
1457         }
1458
1459         default:
1460                 /*
1461                  * Only print once ... unfortunately there could be lots of
1462                  * different FSCTLs that are called.
1463                  */
1464                 if (!vfswrap_logged_ioctl_message) {
1465                         vfswrap_logged_ioctl_message = true;
1466                         DEBUG(2, ("%s (0x%x): Currently not implemented.\n",
1467                         __func__, function));
1468                 }
1469         }
1470
1471         return NT_STATUS_NOT_SUPPORTED;
1472 }
1473
1474 static bool vfswrap_is_offline(struct vfs_handle_struct *handle,
1475                                const struct smb_filename *fname,
1476                                SMB_STRUCT_STAT *sbuf);
1477
1478 static NTSTATUS vfswrap_get_dos_attributes(struct vfs_handle_struct *handle,
1479                                            struct smb_filename *smb_fname,
1480                                            uint32_t *dosmode)
1481 {
1482         bool offline;
1483
1484         offline = vfswrap_is_offline(handle, smb_fname, &smb_fname->st);
1485         if (offline) {
1486                 *dosmode |= FILE_ATTRIBUTE_OFFLINE;
1487         }
1488
1489         return get_ea_dos_attribute(handle->conn, smb_fname, dosmode);
1490 }
1491
1492 struct vfswrap_get_dos_attributes_state {
1493         struct vfs_aio_state aio_state;
1494         connection_struct *conn;
1495         TALLOC_CTX *mem_ctx;
1496         struct tevent_context *ev;
1497         files_struct *dir_fsp;
1498         struct smb_filename *smb_fname;
1499         uint32_t dosmode;
1500         bool as_root;
1501 };
1502
1503 static void vfswrap_get_dos_attributes_getxattr_done(struct tevent_req *subreq);
1504
1505 static struct tevent_req *vfswrap_get_dos_attributes_send(
1506                         TALLOC_CTX *mem_ctx,
1507                         const struct smb_vfs_ev_glue *evg,
1508                         struct vfs_handle_struct *handle,
1509                         files_struct *dir_fsp,
1510                         struct smb_filename *smb_fname)
1511 {
1512         struct tevent_context *ev = dir_fsp->conn->sconn->raw_ev_ctx;
1513         struct tevent_req *req = NULL;
1514         struct tevent_req *subreq = NULL;
1515         struct vfswrap_get_dos_attributes_state *state = NULL;
1516
1517         req = tevent_req_create(mem_ctx, &state,
1518                                 struct vfswrap_get_dos_attributes_state);
1519         if (req == NULL) {
1520                 return NULL;
1521         }
1522
1523         *state = (struct vfswrap_get_dos_attributes_state) {
1524                 .conn = dir_fsp->conn,
1525                 .mem_ctx = mem_ctx,
1526                 .ev = ev,
1527                 .dir_fsp = dir_fsp,
1528                 .smb_fname = smb_fname,
1529         };
1530
1531         subreq = SMB_VFS_GETXATTRAT_SEND(state,
1532                                          ev,
1533                                          dir_fsp,
1534                                          smb_fname,
1535                                          SAMBA_XATTR_DOS_ATTRIB,
1536                                          sizeof(fstring));
1537         if (tevent_req_nomem(subreq, req)) {
1538                 return tevent_req_post(req, ev);
1539         }
1540         tevent_req_set_callback(subreq,
1541                                 vfswrap_get_dos_attributes_getxattr_done,
1542                                 req);
1543
1544         return req;
1545 }
1546
1547 static void vfswrap_get_dos_attributes_getxattr_done(struct tevent_req *subreq)
1548 {
1549         struct tevent_req *req =
1550                 tevent_req_callback_data(subreq,
1551                 struct tevent_req);
1552         struct vfswrap_get_dos_attributes_state *state =
1553                 tevent_req_data(req,
1554                 struct vfswrap_get_dos_attributes_state);
1555         ssize_t xattr_size;
1556         DATA_BLOB blob = {0};
1557         NTSTATUS status;
1558
1559         xattr_size = SMB_VFS_GETXATTRAT_RECV(subreq,
1560                                              &state->aio_state,
1561                                              state,
1562                                              &blob.data);
1563         TALLOC_FREE(subreq);
1564         if (xattr_size == -1) {
1565                 status = map_nt_error_from_unix(state->aio_state.error);
1566
1567                 if (state->as_root) {
1568                         tevent_req_nterror(req, status);
1569                         return;
1570                 }
1571                 if (!NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
1572                         tevent_req_nterror(req, status);
1573                         return;
1574                 }
1575
1576                 state->as_root = true;
1577
1578                 become_root();
1579                 subreq = SMB_VFS_GETXATTRAT_SEND(state,
1580                                                  state->ev,
1581                                                  state->dir_fsp,
1582                                                  state->smb_fname,
1583                                                  SAMBA_XATTR_DOS_ATTRIB,
1584                                                  sizeof(fstring));
1585                 unbecome_root();
1586                 if (tevent_req_nomem(subreq, req)) {
1587                         return;
1588                 }
1589                 tevent_req_set_callback(subreq,
1590                                         vfswrap_get_dos_attributes_getxattr_done,
1591                                         req);
1592                 return;
1593         }
1594
1595         blob.length = xattr_size;
1596
1597         status = parse_dos_attribute_blob(state->smb_fname,
1598                                           blob,
1599                                           &state->dosmode);
1600         if (!NT_STATUS_IS_OK(status)) {
1601                 tevent_req_nterror(req, status);
1602                 return;
1603         }
1604
1605         tevent_req_done(req);
1606         return;
1607 }
1608
1609 static NTSTATUS vfswrap_get_dos_attributes_recv(struct tevent_req *req,
1610                                                 struct vfs_aio_state *aio_state,
1611                                                 uint32_t *dosmode)
1612 {
1613         struct vfswrap_get_dos_attributes_state *state =
1614                 tevent_req_data(req,
1615                 struct vfswrap_get_dos_attributes_state);
1616         NTSTATUS status;
1617
1618         if (tevent_req_is_nterror(req, &status)) {
1619                 tevent_req_received(req);
1620                 return status;
1621         }
1622
1623         *aio_state = state->aio_state;
1624         *dosmode = state->dosmode;
1625         tevent_req_received(req);
1626         return NT_STATUS_OK;
1627 }
1628
1629 static NTSTATUS vfswrap_fget_dos_attributes(struct vfs_handle_struct *handle,
1630                                             struct files_struct *fsp,
1631                                             uint32_t *dosmode)
1632 {
1633         bool offline;
1634
1635         offline = vfswrap_is_offline(handle, fsp->fsp_name, &fsp->fsp_name->st);
1636         if (offline) {
1637                 *dosmode |= FILE_ATTRIBUTE_OFFLINE;
1638         }
1639
1640         return get_ea_dos_attribute(handle->conn, fsp->fsp_name, dosmode);
1641 }
1642
1643 static NTSTATUS vfswrap_set_dos_attributes(struct vfs_handle_struct *handle,
1644                                            const struct smb_filename *smb_fname,
1645                                            uint32_t dosmode)
1646 {
1647         return set_ea_dos_attribute(handle->conn, smb_fname, dosmode);
1648 }
1649
1650 static NTSTATUS vfswrap_fset_dos_attributes(struct vfs_handle_struct *handle,
1651                                             struct files_struct *fsp,
1652                                             uint32_t dosmode)
1653 {
1654         return set_ea_dos_attribute(handle->conn, fsp->fsp_name, dosmode);
1655 }
1656
1657 static struct vfs_offload_ctx *vfswrap_offload_ctx;
1658
1659 struct vfswrap_offload_read_state {
1660         DATA_BLOB token;
1661 };
1662
1663 static struct tevent_req *vfswrap_offload_read_send(
1664         TALLOC_CTX *mem_ctx,
1665         struct tevent_context *ev,
1666         struct vfs_handle_struct *handle,
1667         struct files_struct *fsp,
1668         uint32_t fsctl,
1669         uint32_t ttl,
1670         off_t offset,
1671         size_t to_copy)
1672 {
1673         struct tevent_req *req = NULL;
1674         struct vfswrap_offload_read_state *state = NULL;
1675         NTSTATUS status;
1676
1677         req = tevent_req_create(mem_ctx, &state,
1678                                 struct vfswrap_offload_read_state);
1679         if (req == NULL) {
1680                 return NULL;
1681         }
1682
1683         status = vfs_offload_token_ctx_init(fsp->conn->sconn->client,
1684                                             &vfswrap_offload_ctx);
1685         if (tevent_req_nterror(req, status)) {
1686                 return tevent_req_post(req, ev);
1687         }
1688
1689         if (fsctl != FSCTL_SRV_REQUEST_RESUME_KEY) {
1690                 tevent_req_nterror(req, NT_STATUS_INVALID_DEVICE_REQUEST);
1691                 return tevent_req_post(req, ev);
1692         }
1693
1694         status = vfs_offload_token_create_blob(state, fsp, fsctl,
1695                                                &state->token);
1696         if (tevent_req_nterror(req, status)) {
1697                 return tevent_req_post(req, ev);
1698         }
1699
1700         status = vfs_offload_token_db_store_fsp(vfswrap_offload_ctx, fsp,
1701                                                 &state->token);
1702         if (tevent_req_nterror(req, status)) {
1703                 return tevent_req_post(req, ev);
1704         }
1705
1706         tevent_req_done(req);
1707         return tevent_req_post(req, ev);
1708 }
1709
1710 static NTSTATUS vfswrap_offload_read_recv(struct tevent_req *req,
1711                                           struct vfs_handle_struct *handle,
1712                                           TALLOC_CTX *mem_ctx,
1713                                           DATA_BLOB *token)
1714 {
1715         struct vfswrap_offload_read_state *state = tevent_req_data(
1716                 req, struct vfswrap_offload_read_state);
1717         NTSTATUS status;
1718
1719         if (tevent_req_is_nterror(req, &status)) {
1720                 tevent_req_received(req);
1721                 return status;
1722         }
1723
1724         token->length = state->token.length;
1725         token->data = talloc_move(mem_ctx, &state->token.data);
1726
1727         tevent_req_received(req);
1728         return NT_STATUS_OK;
1729 }
1730
1731 struct vfswrap_offload_write_state {
1732         uint8_t *buf;
1733         bool read_lck_locked;
1734         bool write_lck_locked;
1735         DATA_BLOB *token;
1736         struct tevent_context *src_ev;
1737         struct files_struct *src_fsp;
1738         off_t src_off;
1739         struct tevent_context *dst_ev;
1740         struct files_struct *dst_fsp;
1741         off_t dst_off;
1742         off_t to_copy;
1743         off_t remaining;
1744         size_t next_io_size;
1745 };
1746
1747 static void vfswrap_offload_write_cleanup(struct tevent_req *req,
1748                                           enum tevent_req_state req_state)
1749 {
1750         struct vfswrap_offload_write_state *state = tevent_req_data(
1751                 req, struct vfswrap_offload_write_state);
1752         bool ok;
1753
1754         if (state->dst_fsp == NULL) {
1755                 return;
1756         }
1757
1758         ok = change_to_user_by_fsp(state->dst_fsp);
1759         SMB_ASSERT(ok);
1760         state->dst_fsp = NULL;
1761 }
1762
1763 static NTSTATUS vfswrap_offload_write_loop(struct tevent_req *req);
1764
1765 static struct tevent_req *vfswrap_offload_write_send(
1766         struct vfs_handle_struct *handle,
1767         TALLOC_CTX *mem_ctx,
1768         struct tevent_context *ev,
1769         uint32_t fsctl,
1770         DATA_BLOB *token,
1771         off_t transfer_offset,
1772         struct files_struct *dest_fsp,
1773         off_t dest_off,
1774         off_t to_copy)
1775 {
1776         struct tevent_req *req;
1777         struct vfswrap_offload_write_state *state = NULL;
1778         size_t num = MIN(to_copy, COPYCHUNK_MAX_TOTAL_LEN);
1779         files_struct *src_fsp = NULL;
1780         NTSTATUS status;
1781         bool ok;
1782
1783         req = tevent_req_create(mem_ctx, &state,
1784                                 struct vfswrap_offload_write_state);
1785         if (req == NULL) {
1786                 return NULL;
1787         }
1788
1789         *state = (struct vfswrap_offload_write_state) {
1790                 .token = token,
1791                 .src_off = transfer_offset,
1792                 .dst_ev = ev,
1793                 .dst_fsp = dest_fsp,
1794                 .dst_off = dest_off,
1795                 .to_copy = to_copy,
1796                 .remaining = to_copy,
1797         };
1798
1799         tevent_req_set_cleanup_fn(req, vfswrap_offload_write_cleanup);
1800
1801         switch (fsctl) {
1802         case FSCTL_SRV_COPYCHUNK:
1803         case FSCTL_SRV_COPYCHUNK_WRITE:
1804                 break;
1805
1806         case FSCTL_OFFLOAD_WRITE:
1807                 tevent_req_nterror(req, NT_STATUS_NOT_IMPLEMENTED);
1808                 return tevent_req_post(req, ev);
1809
1810         case FSCTL_DUP_EXTENTS_TO_FILE:
1811                 DBG_DEBUG("COW clones not supported by vfs_default\n");
1812                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1813                 return tevent_req_post(req, ev);
1814
1815         default:
1816                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1817                 return tevent_req_post(req, ev);
1818         }
1819
1820         /*
1821          * From here on we assume a copy-chunk fsctl
1822          */
1823
1824         if (to_copy == 0) {
1825                 tevent_req_done(req);
1826                 return tevent_req_post(req, ev);
1827         }
1828
1829         status = vfs_offload_token_db_fetch_fsp(vfswrap_offload_ctx,
1830                                                 token, &src_fsp);
1831         if (tevent_req_nterror(req, status)) {
1832                 return tevent_req_post(req, ev);
1833         }
1834
1835         DBG_DEBUG("server side copy chunk of length %" PRIu64 "\n", to_copy);
1836
1837         status = vfs_offload_token_check_handles(fsctl, src_fsp, dest_fsp);
1838         if (!NT_STATUS_IS_OK(status)) {
1839                 tevent_req_nterror(req, status);
1840                 return tevent_req_post(req, ev);
1841         }
1842
1843         ok = change_to_user_by_fsp(src_fsp);
1844         if (!ok) {
1845                 tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
1846                 return tevent_req_post(req, ev);
1847         }
1848
1849         state->src_ev = src_fsp->conn->user_ev_ctx;
1850         state->src_fsp = src_fsp;
1851
1852         state->buf = talloc_array(state, uint8_t, num);
1853         if (tevent_req_nomem(state->buf, req)) {
1854                 return tevent_req_post(req, ev);
1855         }
1856
1857         status = vfs_stat_fsp(src_fsp);
1858         if (tevent_req_nterror(req, status)) {
1859                 return tevent_req_post(req, ev);
1860         }
1861
1862         if (src_fsp->fsp_name->st.st_ex_size < state->src_off + num) {
1863                 /*
1864                  * [MS-SMB2] 3.3.5.15.6 Handling a Server-Side Data Copy Request
1865                  *   If the SourceOffset or SourceOffset + Length extends beyond
1866                  *   the end of file, the server SHOULD<240> treat this as a
1867                  *   STATUS_END_OF_FILE error.
1868                  * ...
1869                  *   <240> Section 3.3.5.15.6: Windows servers will return
1870                  *   STATUS_INVALID_VIEW_SIZE instead of STATUS_END_OF_FILE.
1871                  */
1872                 tevent_req_nterror(req, NT_STATUS_INVALID_VIEW_SIZE);
1873                 return tevent_req_post(req, ev);
1874         }
1875
1876         status = vfswrap_offload_write_loop(req);
1877         if (!NT_STATUS_IS_OK(status)) {
1878                 tevent_req_nterror(req, status);
1879                 return tevent_req_post(req, ev);
1880         }
1881
1882         return req;
1883 }
1884
1885 static void vfswrap_offload_write_read_done(struct tevent_req *subreq);
1886
1887 static NTSTATUS vfswrap_offload_write_loop(struct tevent_req *req)
1888 {
1889         struct vfswrap_offload_write_state *state = tevent_req_data(
1890                 req, struct vfswrap_offload_write_state);
1891         struct tevent_req *subreq = NULL;
1892         struct lock_struct read_lck;
1893         bool ok;
1894
1895         /*
1896          * This is called under the context of state->src_fsp.
1897          */
1898
1899         state->next_io_size = MIN(state->remaining, talloc_array_length(state->buf));
1900
1901         init_strict_lock_struct(state->src_fsp,
1902                                 state->src_fsp->op->global->open_persistent_id,
1903                                 state->src_off,
1904                                 state->next_io_size,
1905                                 READ_LOCK,
1906                                 &read_lck);
1907
1908         ok = SMB_VFS_STRICT_LOCK_CHECK(state->src_fsp->conn,
1909                                  state->src_fsp,
1910                                  &read_lck);
1911         if (!ok) {
1912                 return NT_STATUS_FILE_LOCK_CONFLICT;
1913         }
1914
1915         subreq = SMB_VFS_PREAD_SEND(state,
1916                                     state->src_ev,
1917                                     state->src_fsp,
1918                                     state->buf,
1919                                     state->next_io_size,
1920                                     state->src_off);
1921         if (subreq == NULL) {
1922                 return NT_STATUS_NO_MEMORY;
1923         }
1924         tevent_req_set_callback(subreq, vfswrap_offload_write_read_done, req);
1925
1926         return NT_STATUS_OK;
1927 }
1928
1929 static void vfswrap_offload_write_write_done(struct tevent_req *subreq);
1930
1931 static void vfswrap_offload_write_read_done(struct tevent_req *subreq)
1932 {
1933         struct tevent_req *req = tevent_req_callback_data(
1934                 subreq, struct tevent_req);
1935         struct vfswrap_offload_write_state *state = tevent_req_data(
1936                 req, struct vfswrap_offload_write_state);
1937         struct vfs_aio_state aio_state;
1938         struct lock_struct write_lck;
1939         ssize_t nread;
1940         bool ok;
1941
1942         nread = SMB_VFS_PREAD_RECV(subreq, &aio_state);
1943         TALLOC_FREE(subreq);
1944         if (nread == -1) {
1945                 DBG_ERR("read failed: %s\n", strerror(errno));
1946                 tevent_req_nterror(req, map_nt_error_from_unix(aio_state.error));
1947                 return;
1948         }
1949         if (nread != state->next_io_size) {
1950                 DBG_ERR("Short read, only %zd of %zu\n",
1951                         nread, state->next_io_size);
1952                 tevent_req_nterror(req, NT_STATUS_IO_DEVICE_ERROR);
1953                 return;
1954         }
1955
1956         state->src_off += nread;
1957
1958         ok = change_to_user_by_fsp(state->dst_fsp);
1959         if (!ok) {
1960                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1961                 return;
1962         }
1963
1964         init_strict_lock_struct(state->dst_fsp,
1965                                 state->dst_fsp->op->global->open_persistent_id,
1966                                 state->dst_off,
1967                                 state->next_io_size,
1968                                 WRITE_LOCK,
1969                                 &write_lck);
1970
1971         ok = SMB_VFS_STRICT_LOCK_CHECK(state->dst_fsp->conn,
1972                                  state->dst_fsp,
1973                                  &write_lck);
1974         if (!ok) {
1975                 tevent_req_nterror(req, NT_STATUS_FILE_LOCK_CONFLICT);
1976                 return;
1977         }
1978
1979         subreq = SMB_VFS_PWRITE_SEND(state,
1980                                      state->dst_ev,
1981                                      state->dst_fsp,
1982                                      state->buf,
1983                                      state->next_io_size,
1984                                      state->dst_off);
1985         if (subreq == NULL) {
1986                 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
1987                 return;
1988         }
1989         tevent_req_set_callback(subreq, vfswrap_offload_write_write_done, req);
1990 }
1991
1992 static void vfswrap_offload_write_write_done(struct tevent_req *subreq)
1993 {
1994         struct tevent_req *req = tevent_req_callback_data(
1995                 subreq, struct tevent_req);
1996         struct vfswrap_offload_write_state *state = tevent_req_data(
1997                 req, struct vfswrap_offload_write_state);
1998         struct vfs_aio_state aio_state;
1999         ssize_t nwritten;
2000         NTSTATUS status;
2001         bool ok;
2002
2003         nwritten = SMB_VFS_PWRITE_RECV(subreq, &aio_state);
2004         TALLOC_FREE(subreq);
2005         if (nwritten == -1) {
2006                 DBG_ERR("write failed: %s\n", strerror(errno));
2007                 tevent_req_nterror(req, map_nt_error_from_unix(aio_state.error));
2008                 return;
2009         }
2010         if (nwritten != state->next_io_size) {
2011                 DBG_ERR("Short write, only %zd of %zu\n", nwritten, state->next_io_size);
2012                 tevent_req_nterror(req, NT_STATUS_IO_DEVICE_ERROR);
2013                 return;
2014         }
2015
2016         state->dst_off += nwritten;
2017
2018         if (state->remaining < nwritten) {
2019                 /* Paranoia check */
2020                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
2021                 return;
2022         }
2023         state->remaining -= nwritten;
2024         if (state->remaining == 0) {
2025                 tevent_req_done(req);
2026                 return;
2027         }
2028
2029         ok = change_to_user_by_fsp(state->src_fsp);
2030         if (!ok) {
2031                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
2032                 return;
2033         }
2034
2035         status = vfswrap_offload_write_loop(req);
2036         if (!NT_STATUS_IS_OK(status)) {
2037                 tevent_req_nterror(req, status);
2038                 return;
2039         }
2040
2041         return;
2042 }
2043
2044 static NTSTATUS vfswrap_offload_write_recv(struct vfs_handle_struct *handle,
2045                                         struct tevent_req *req,
2046                                         off_t *copied)
2047 {
2048         struct vfswrap_offload_write_state *state = tevent_req_data(
2049                 req, struct vfswrap_offload_write_state);
2050         NTSTATUS status;
2051
2052         if (tevent_req_is_nterror(req, &status)) {
2053                 DBG_DEBUG("copy chunk failed: %s\n", nt_errstr(status));
2054                 *copied = 0;
2055                 tevent_req_received(req);
2056                 return status;
2057         }
2058
2059         *copied = state->to_copy;
2060         DBG_DEBUG("copy chunk copied %lu\n", (unsigned long)*copied);
2061         tevent_req_received(req);
2062
2063         return NT_STATUS_OK;
2064 }
2065
2066 static NTSTATUS vfswrap_get_compression(struct vfs_handle_struct *handle,
2067                                         TALLOC_CTX *mem_ctx,
2068                                         struct files_struct *fsp,
2069                                         struct smb_filename *smb_fname,
2070                                         uint16_t *_compression_fmt)
2071 {
2072         return NT_STATUS_INVALID_DEVICE_REQUEST;
2073 }
2074
2075 static NTSTATUS vfswrap_set_compression(struct vfs_handle_struct *handle,
2076                                         TALLOC_CTX *mem_ctx,
2077                                         struct files_struct *fsp,
2078                                         uint16_t compression_fmt)
2079 {
2080         return NT_STATUS_INVALID_DEVICE_REQUEST;
2081 }
2082
2083 /********************************************************************
2084  Given a stat buffer return the allocated size on disk, taking into
2085  account sparse files.
2086 ********************************************************************/
2087 static uint64_t vfswrap_get_alloc_size(vfs_handle_struct *handle,
2088                                        struct files_struct *fsp,
2089                                        const SMB_STRUCT_STAT *sbuf)
2090 {
2091         uint64_t result;
2092
2093         START_PROFILE(syscall_get_alloc_size);
2094
2095         if(S_ISDIR(sbuf->st_ex_mode)) {
2096                 result = 0;
2097                 goto out;
2098         }
2099
2100 #if defined(HAVE_STAT_ST_BLOCKS) && defined(STAT_ST_BLOCKSIZE)
2101         /* The type of st_blocksize is blkcnt_t which *MUST* be
2102            signed (according to POSIX) and can be less than 64-bits.
2103            Ensure when we're converting to 64 bits wide we don't
2104            sign extend. */
2105 #if defined(SIZEOF_BLKCNT_T_8)
2106         result = (uint64_t)STAT_ST_BLOCKSIZE * (uint64_t)sbuf->st_ex_blocks;
2107 #elif defined(SIZEOF_BLKCNT_T_4)
2108         {
2109                 uint64_t bs = ((uint64_t)sbuf->st_ex_blocks) & 0xFFFFFFFFLL;
2110                 result = (uint64_t)STAT_ST_BLOCKSIZE * bs;
2111         }
2112 #else
2113 #error SIZEOF_BLKCNT_T_NOT_A_SUPPORTED_VALUE
2114 #endif
2115         if (result == 0) {
2116                 /*
2117                  * Some file systems do not allocate a block for very
2118                  * small files. But for non-empty file should report a
2119                  * positive size.
2120                  */
2121
2122                 uint64_t filesize = get_file_size_stat(sbuf);
2123                 if (filesize > 0) {
2124                         result = MIN((uint64_t)STAT_ST_BLOCKSIZE, filesize);
2125                 }
2126         }
2127 #else
2128         result = get_file_size_stat(sbuf);
2129 #endif
2130
2131         if (fsp && fsp->initial_allocation_size)
2132                 result = MAX(result,fsp->initial_allocation_size);
2133
2134         result = smb_roundup(handle->conn, result);
2135
2136  out:
2137         END_PROFILE(syscall_get_alloc_size);
2138         return result;
2139 }
2140
2141 static int vfswrap_unlink(vfs_handle_struct *handle,
2142                           const struct smb_filename *smb_fname)
2143 {
2144         int result = -1;
2145
2146         START_PROFILE(syscall_unlink);
2147
2148         if (smb_fname->stream_name) {
2149                 errno = ENOENT;
2150                 goto out;
2151         }
2152         result = unlink(smb_fname->base_name);
2153
2154  out:
2155         END_PROFILE(syscall_unlink);
2156         return result;
2157 }
2158
2159 static int vfswrap_chmod(vfs_handle_struct *handle,
2160                         const struct smb_filename *smb_fname,
2161                         mode_t mode)
2162 {
2163         int result;
2164
2165         START_PROFILE(syscall_chmod);
2166         result = chmod(smb_fname->base_name, mode);
2167         END_PROFILE(syscall_chmod);
2168         return result;
2169 }
2170
2171 static int vfswrap_fchmod(vfs_handle_struct *handle, files_struct *fsp, mode_t mode)
2172 {
2173         int result;
2174
2175         START_PROFILE(syscall_fchmod);
2176 #if defined(HAVE_FCHMOD)
2177         result = fchmod(fsp->fh->fd, mode);
2178 #else
2179         result = -1;
2180         errno = ENOSYS;
2181 #endif
2182
2183         END_PROFILE(syscall_fchmod);
2184         return result;
2185 }
2186
2187 static int vfswrap_chown(vfs_handle_struct *handle,
2188                         const struct smb_filename *smb_fname,
2189                         uid_t uid,
2190                         gid_t gid)
2191 {
2192         int result;
2193
2194         START_PROFILE(syscall_chown);
2195         result = chown(smb_fname->base_name, uid, gid);
2196         END_PROFILE(syscall_chown);
2197         return result;
2198 }
2199
2200 static int vfswrap_fchown(vfs_handle_struct *handle, files_struct *fsp, uid_t uid, gid_t gid)
2201 {
2202 #ifdef HAVE_FCHOWN
2203         int result;
2204
2205         START_PROFILE(syscall_fchown);
2206         result = fchown(fsp->fh->fd, uid, gid);
2207         END_PROFILE(syscall_fchown);
2208         return result;
2209 #else
2210         errno = ENOSYS;
2211         return -1;
2212 #endif
2213 }
2214
2215 static int vfswrap_lchown(vfs_handle_struct *handle,
2216                         const struct smb_filename *smb_fname,
2217                         uid_t uid,
2218                         gid_t gid)
2219 {
2220         int result;
2221
2222         START_PROFILE(syscall_lchown);
2223         result = lchown(smb_fname->base_name, uid, gid);
2224         END_PROFILE(syscall_lchown);
2225         return result;
2226 }
2227
2228 static int vfswrap_chdir(vfs_handle_struct *handle,
2229                         const struct smb_filename *smb_fname)
2230 {
2231         int result;
2232
2233         START_PROFILE(syscall_chdir);
2234         result = chdir(smb_fname->base_name);
2235         END_PROFILE(syscall_chdir);
2236         return result;
2237 }
2238
2239 static struct smb_filename *vfswrap_getwd(vfs_handle_struct *handle,
2240                                 TALLOC_CTX *ctx)
2241 {
2242         char *result;
2243         struct smb_filename *smb_fname = NULL;
2244
2245         START_PROFILE(syscall_getwd);
2246         result = sys_getwd();
2247         END_PROFILE(syscall_getwd);
2248
2249         if (result == NULL) {
2250                 return NULL;
2251         }
2252         smb_fname = synthetic_smb_fname(ctx,
2253                                 result,
2254                                 NULL,
2255                                 NULL,
2256                                 0);
2257         /*
2258          * sys_getwd() *always* returns malloced memory.
2259          * We must free here to avoid leaks:
2260          * BUG:https://bugzilla.samba.org/show_bug.cgi?id=13372
2261          */
2262         SAFE_FREE(result);
2263         return smb_fname;
2264 }
2265
2266 /*********************************************************************
2267  nsec timestamp resolution call. Convert down to whatever the underlying
2268  system will support.
2269 **********************************************************************/
2270
2271 static int vfswrap_ntimes(vfs_handle_struct *handle,
2272                           const struct smb_filename *smb_fname,
2273                           struct smb_file_time *ft)
2274 {
2275         int result = -1;
2276
2277         START_PROFILE(syscall_ntimes);
2278
2279         if (smb_fname->stream_name) {
2280                 errno = ENOENT;
2281                 goto out;
2282         }
2283
2284         if (ft != NULL) {
2285                 if (null_timespec(ft->atime)) {
2286                         ft->atime= smb_fname->st.st_ex_atime;
2287                 }
2288
2289                 if (null_timespec(ft->mtime)) {
2290                         ft->mtime = smb_fname->st.st_ex_mtime;
2291                 }
2292
2293                 if (!null_timespec(ft->create_time)) {
2294                         set_create_timespec_ea(handle->conn,
2295                                                smb_fname,
2296                                                ft->create_time);
2297                 }
2298
2299                 if ((timespec_compare(&ft->atime,
2300                                       &smb_fname->st.st_ex_atime) == 0) &&
2301                     (timespec_compare(&ft->mtime,
2302                                       &smb_fname->st.st_ex_mtime) == 0)) {
2303                         return 0;
2304                 }
2305         }
2306
2307 #if defined(HAVE_UTIMENSAT)
2308         if (ft != NULL) {
2309                 struct timespec ts[2];
2310                 ts[0] = ft->atime;
2311                 ts[1] = ft->mtime;
2312                 result = utimensat(AT_FDCWD, smb_fname->base_name, ts, 0);
2313         } else {
2314                 result = utimensat(AT_FDCWD, smb_fname->base_name, NULL, 0);
2315         }
2316         if (!((result == -1) && (errno == ENOSYS))) {
2317                 goto out;
2318         }
2319 #endif
2320 #if defined(HAVE_UTIMES)
2321         if (ft != NULL) {
2322                 struct timeval tv[2];
2323                 tv[0] = convert_timespec_to_timeval(ft->atime);
2324                 tv[1] = convert_timespec_to_timeval(ft->mtime);
2325                 result = utimes(smb_fname->base_name, tv);
2326         } else {
2327                 result = utimes(smb_fname->base_name, NULL);
2328         }
2329         if (!((result == -1) && (errno == ENOSYS))) {
2330                 goto out;
2331         }
2332 #endif
2333 #if defined(HAVE_UTIME)
2334         if (ft != NULL) {
2335                 struct utimbuf times;
2336                 times.actime = convert_timespec_to_time_t(ft->atime);
2337                 times.modtime = convert_timespec_to_time_t(ft->mtime);
2338                 result = utime(smb_fname->base_name, &times);
2339         } else {
2340                 result = utime(smb_fname->base_name, NULL);
2341         }
2342         if (!((result == -1) && (errno == ENOSYS))) {
2343                 goto out;
2344         }
2345 #endif
2346         errno = ENOSYS;
2347         result = -1;
2348
2349  out:
2350         END_PROFILE(syscall_ntimes);
2351         return result;
2352 }
2353
2354 /*********************************************************************
2355  A version of ftruncate that will write the space on disk if strict
2356  allocate is set.
2357 **********************************************************************/
2358
2359 static int strict_allocate_ftruncate(vfs_handle_struct *handle, files_struct *fsp, off_t len)
2360 {
2361         off_t space_to_write;
2362         uint64_t space_avail;
2363         uint64_t bsize,dfree,dsize;
2364         int ret;
2365         NTSTATUS status;
2366         SMB_STRUCT_STAT *pst;
2367
2368         status = vfs_stat_fsp(fsp);
2369         if (!NT_STATUS_IS_OK(status)) {
2370                 return -1;
2371         }
2372         pst = &fsp->fsp_name->st;
2373
2374 #ifdef S_ISFIFO
2375         if (S_ISFIFO(pst->st_ex_mode))
2376                 return 0;
2377 #endif
2378
2379         if (pst->st_ex_size == len)
2380                 return 0;
2381
2382         /* Shrink - just ftruncate. */
2383         if (pst->st_ex_size > len)
2384                 return ftruncate(fsp->fh->fd, len);
2385
2386         space_to_write = len - pst->st_ex_size;
2387
2388         /* for allocation try fallocate first. This can fail on some
2389            platforms e.g. when the filesystem doesn't support it and no
2390            emulation is being done by the libc (like on AIX with JFS1). In that
2391            case we do our own emulation. fallocate implementations can
2392            return ENOTSUP or EINVAL in cases like that. */
2393         ret = SMB_VFS_FALLOCATE(fsp, 0, pst->st_ex_size, space_to_write);
2394         if (ret == -1 && errno == ENOSPC) {
2395                 return -1;
2396         }
2397         if (ret == 0) {
2398                 return 0;
2399         }
2400         DEBUG(10,("strict_allocate_ftruncate: SMB_VFS_FALLOCATE failed with "
2401                 "error %d. Falling back to slow manual allocation\n", errno));
2402
2403         /* available disk space is enough or not? */
2404         space_avail =
2405             get_dfree_info(fsp->conn, fsp->fsp_name, &bsize, &dfree, &dsize);
2406         /* space_avail is 1k blocks */
2407         if (space_avail == (uint64_t)-1 ||
2408                         ((uint64_t)space_to_write/1024 > space_avail) ) {
2409                 errno = ENOSPC;
2410                 return -1;
2411         }
2412
2413         /* Write out the real space on disk. */
2414         ret = vfs_slow_fallocate(fsp, pst->st_ex_size, space_to_write);
2415         if (ret != 0) {
2416                 return -1;
2417         }
2418
2419         return 0;
2420 }
2421
2422 static int vfswrap_ftruncate(vfs_handle_struct *handle, files_struct *fsp, off_t len)
2423 {
2424         int result = -1;
2425         SMB_STRUCT_STAT *pst;
2426         NTSTATUS status;
2427         char c = 0;
2428
2429         START_PROFILE(syscall_ftruncate);
2430
2431         if (lp_strict_allocate(SNUM(fsp->conn)) && !fsp->is_sparse) {
2432                 result = strict_allocate_ftruncate(handle, fsp, len);
2433                 END_PROFILE(syscall_ftruncate);
2434                 return result;
2435         }
2436
2437         /* we used to just check HAVE_FTRUNCATE_EXTEND and only use
2438            ftruncate if the system supports it. Then I discovered that
2439            you can have some filesystems that support ftruncate
2440            expansion and some that don't! On Linux fat can't do
2441            ftruncate extend but ext2 can. */
2442
2443         result = ftruncate(fsp->fh->fd, len);
2444
2445         /* According to W. R. Stevens advanced UNIX prog. Pure 4.3 BSD cannot
2446            extend a file with ftruncate. Provide alternate implementation
2447            for this */
2448
2449         /* Do an fstat to see if the file is longer than the requested
2450            size in which case the ftruncate above should have
2451            succeeded or shorter, in which case seek to len - 1 and
2452            write 1 byte of zero */
2453         status = vfs_stat_fsp(fsp);
2454         if (!NT_STATUS_IS_OK(status)) {
2455                 goto done;
2456         }
2457
2458         /* We need to update the files_struct after successful ftruncate */
2459         if (result == 0) {
2460                 goto done;
2461         }
2462
2463         pst = &fsp->fsp_name->st;
2464
2465 #ifdef S_ISFIFO
2466         if (S_ISFIFO(pst->st_ex_mode)) {
2467                 result = 0;
2468                 goto done;
2469         }
2470 #endif
2471
2472         if (pst->st_ex_size == len) {
2473                 result = 0;
2474                 goto done;
2475         }
2476
2477         if (pst->st_ex_size > len) {
2478                 /* the ftruncate should have worked */
2479                 goto done;
2480         }
2481
2482         if (SMB_VFS_PWRITE(fsp, &c, 1, len-1)!=1) {
2483                 goto done;
2484         }
2485
2486         result = 0;
2487
2488   done:
2489
2490         END_PROFILE(syscall_ftruncate);
2491         return result;
2492 }
2493
2494 static int vfswrap_fallocate(vfs_handle_struct *handle,
2495                         files_struct *fsp,
2496                         uint32_t mode,
2497                         off_t offset,
2498                         off_t len)
2499 {
2500         int result;
2501
2502         START_PROFILE(syscall_fallocate);
2503         if (mode == 0) {
2504                 result = sys_posix_fallocate(fsp->fh->fd, offset, len);
2505                 /*
2506                  * posix_fallocate returns 0 on success, errno on error
2507                  * and doesn't set errno. Make it behave like fallocate()
2508                  * which returns -1, and sets errno on failure.
2509                  */
2510                 if (result != 0) {
2511                         errno = result;
2512                         result = -1;
2513                 }
2514         } else {
2515                 /* sys_fallocate handles filtering of unsupported mode flags */
2516                 result = sys_fallocate(fsp->fh->fd, mode, offset, len);
2517         }
2518         END_PROFILE(syscall_fallocate);
2519         return result;
2520 }
2521
2522 static bool vfswrap_lock(vfs_handle_struct *handle, files_struct *fsp, int op, off_t offset, off_t count, int type)
2523 {
2524         bool result;
2525
2526         START_PROFILE(syscall_fcntl_lock);
2527
2528         if (fsp->use_ofd_locks || !lp_parm_bool(SNUM(fsp->conn),
2529                                                 "smbd",
2530                                                 "force process locks",
2531                                                 false)) {
2532                 op = map_process_lock_to_ofd_lock(op, &fsp->use_ofd_locks);
2533         }
2534
2535         result =  fcntl_lock(fsp->fh->fd, op, offset, count, type);
2536         END_PROFILE(syscall_fcntl_lock);
2537         return result;
2538 }
2539
2540 static int vfswrap_kernel_flock(vfs_handle_struct *handle, files_struct *fsp,
2541                                 uint32_t share_mode, uint32_t access_mask)
2542 {
2543         START_PROFILE(syscall_kernel_flock);
2544         kernel_flock(fsp->fh->fd, share_mode, access_mask);
2545         END_PROFILE(syscall_kernel_flock);
2546         return 0;
2547 }
2548
2549 static bool vfswrap_getlock(vfs_handle_struct *handle, files_struct *fsp, off_t *poffset, off_t *pcount, int *ptype, pid_t *ppid)
2550 {
2551         bool result;
2552         int op = F_GETLK;
2553
2554         START_PROFILE(syscall_fcntl_getlock);
2555
2556         if (fsp->use_ofd_locks || !lp_parm_bool(SNUM(fsp->conn),
2557                                                 "smbd",
2558                                                 "force process locks",
2559                                                 false)) {
2560                 op = map_process_lock_to_ofd_lock(op, &fsp->use_ofd_locks);
2561         }
2562
2563         result = fcntl_getlock(fsp->fh->fd, op, poffset, pcount, ptype, ppid);
2564         END_PROFILE(syscall_fcntl_getlock);
2565         return result;
2566 }
2567
2568 static int vfswrap_linux_setlease(vfs_handle_struct *handle, files_struct *fsp,
2569                                 int leasetype)
2570 {
2571         int result = -1;
2572
2573         START_PROFILE(syscall_linux_setlease);
2574
2575 #ifdef HAVE_KERNEL_OPLOCKS_LINUX
2576         result = linux_setlease(fsp->fh->fd, leasetype);
2577 #else
2578         errno = ENOSYS;
2579 #endif
2580         END_PROFILE(syscall_linux_setlease);
2581         return result;
2582 }
2583
2584 static int vfswrap_symlink(vfs_handle_struct *handle,
2585                         const char *link_target,
2586                         const struct smb_filename *new_smb_fname)
2587 {
2588         int result;
2589
2590         START_PROFILE(syscall_symlink);
2591         result = symlink(link_target, new_smb_fname->base_name);
2592         END_PROFILE(syscall_symlink);
2593         return result;
2594 }
2595
2596 static int vfswrap_readlink(vfs_handle_struct *handle,
2597                         const struct smb_filename *smb_fname,
2598                         char *buf,
2599                         size_t bufsiz)
2600 {
2601         int result;
2602
2603         START_PROFILE(syscall_readlink);
2604         result = readlink(smb_fname->base_name, buf, bufsiz);
2605         END_PROFILE(syscall_readlink);
2606         return result;
2607 }
2608
2609 static int vfswrap_link(vfs_handle_struct *handle,
2610                         const struct smb_filename *old_smb_fname,
2611                         const struct smb_filename *new_smb_fname)
2612 {
2613         int result;
2614
2615         START_PROFILE(syscall_link);
2616         result = link(old_smb_fname->base_name, new_smb_fname->base_name);
2617         END_PROFILE(syscall_link);
2618         return result;
2619 }
2620
2621 static int vfswrap_mknod(vfs_handle_struct *handle,
2622                         const struct smb_filename *smb_fname,
2623                         mode_t mode,
2624                         SMB_DEV_T dev)
2625 {
2626         int result;
2627
2628         START_PROFILE(syscall_mknod);
2629         result = sys_mknod(smb_fname->base_name, mode, dev);
2630         END_PROFILE(syscall_mknod);
2631         return result;
2632 }
2633
2634 static struct smb_filename *vfswrap_realpath(vfs_handle_struct *handle,
2635                         TALLOC_CTX *ctx,
2636                         const struct smb_filename *smb_fname)
2637 {
2638         char *result;
2639         struct smb_filename *result_fname = NULL;
2640
2641         START_PROFILE(syscall_realpath);
2642         result = sys_realpath(smb_fname->base_name);
2643         END_PROFILE(syscall_realpath);
2644         if (result) {
2645                 result_fname = synthetic_smb_fname(ctx, result, NULL, NULL, 0);
2646                 SAFE_FREE(result);
2647         }
2648         return result_fname;
2649 }
2650
2651 static int vfswrap_chflags(vfs_handle_struct *handle,
2652                         const struct smb_filename *smb_fname,
2653                         unsigned int flags)
2654 {
2655 #ifdef HAVE_CHFLAGS
2656         return chflags(smb_fname->base_name, flags);
2657 #else
2658         errno = ENOSYS;
2659         return -1;
2660 #endif
2661 }
2662
2663 static struct file_id vfswrap_file_id_create(struct vfs_handle_struct *handle,
2664                                              const SMB_STRUCT_STAT *sbuf)
2665 {
2666         struct file_id key;
2667
2668         /* the ZERO_STRUCT ensures padding doesn't break using the key as a
2669          * blob */
2670         ZERO_STRUCT(key);
2671
2672         key.devid = sbuf->st_ex_dev;
2673         key.inode = sbuf->st_ex_ino;
2674         /* key.extid is unused by default. */
2675
2676         return key;
2677 }
2678
2679 static NTSTATUS vfswrap_streaminfo(vfs_handle_struct *handle,
2680                                    struct files_struct *fsp,
2681                                    const struct smb_filename *smb_fname,
2682                                    TALLOC_CTX *mem_ctx,
2683                                    unsigned int *pnum_streams,
2684                                    struct stream_struct **pstreams)
2685 {
2686         SMB_STRUCT_STAT sbuf;
2687         struct stream_struct *tmp_streams = NULL;
2688         int ret;
2689
2690         if ((fsp != NULL) && (fsp->is_directory)) {
2691                 /*
2692                  * No default streams on directories
2693                  */
2694                 goto done;
2695         }
2696
2697         if ((fsp != NULL) && (fsp->fh->fd != -1)) {
2698                 ret = SMB_VFS_FSTAT(fsp, &sbuf);
2699         }
2700         else {
2701                 struct smb_filename smb_fname_cp;
2702
2703                 ZERO_STRUCT(smb_fname_cp);
2704                 smb_fname_cp.base_name = discard_const_p(char,
2705                                         smb_fname->base_name);
2706                 smb_fname_cp.flags = smb_fname->flags;
2707
2708                 if (smb_fname_cp.flags & SMB_FILENAME_POSIX_PATH) {
2709                         ret = SMB_VFS_LSTAT(handle->conn, &smb_fname_cp);
2710                 } else {
2711                         ret = SMB_VFS_STAT(handle->conn, &smb_fname_cp);
2712                 }
2713                 sbuf = smb_fname_cp.st;
2714         }
2715
2716         if (ret == -1) {
2717                 return map_nt_error_from_unix(errno);
2718         }
2719
2720         if (S_ISDIR(sbuf.st_ex_mode)) {
2721                 goto done;
2722         }
2723
2724         tmp_streams = talloc_realloc(mem_ctx, *pstreams, struct stream_struct,
2725                                         (*pnum_streams) + 1);
2726         if (tmp_streams == NULL) {
2727                 return NT_STATUS_NO_MEMORY;
2728         }
2729         tmp_streams[*pnum_streams].name = talloc_strdup(tmp_streams, "::$DATA");
2730         if (tmp_streams[*pnum_streams].name == NULL) {
2731                 return NT_STATUS_NO_MEMORY;
2732         }
2733         tmp_streams[*pnum_streams].size = sbuf.st_ex_size;
2734         tmp_streams[*pnum_streams].alloc_size = SMB_VFS_GET_ALLOC_SIZE(handle->conn, fsp, &sbuf);
2735
2736         *pnum_streams += 1;
2737         *pstreams = tmp_streams;
2738  done:
2739         return NT_STATUS_OK;
2740 }
2741
2742 static int vfswrap_get_real_filename(struct vfs_handle_struct *handle,
2743                                      const char *path,
2744                                      const char *name,
2745                                      TALLOC_CTX *mem_ctx,
2746                                      char **found_name)
2747 {
2748         /*
2749          * Don't fall back to get_real_filename so callers can differentiate
2750          * between a full directory scan and an actual case-insensitive stat.
2751          */
2752         errno = EOPNOTSUPP;
2753         return -1;
2754 }
2755
2756 static const char *vfswrap_connectpath(struct vfs_handle_struct *handle,
2757                                    const struct smb_filename *smb_fname)
2758 {
2759         return handle->conn->connectpath;
2760 }
2761
2762 static NTSTATUS vfswrap_brl_lock_windows(struct vfs_handle_struct *handle,
2763                                          struct byte_range_lock *br_lck,
2764                                          struct lock_struct *plock,
2765                                          bool blocking_lock)
2766 {
2767         SMB_ASSERT(plock->lock_flav == WINDOWS_LOCK);
2768
2769         /* Note: blr is not used in the default implementation. */
2770         return brl_lock_windows_default(br_lck, plock, blocking_lock);
2771 }
2772
2773 static bool vfswrap_brl_unlock_windows(struct vfs_handle_struct *handle,
2774                                        struct messaging_context *msg_ctx,
2775                                        struct byte_range_lock *br_lck,
2776                                        const struct lock_struct *plock)
2777 {
2778         SMB_ASSERT(plock->lock_flav == WINDOWS_LOCK);
2779
2780         return brl_unlock_windows_default(msg_ctx, br_lck, plock);
2781 }
2782
2783 static bool vfswrap_brl_cancel_windows(struct vfs_handle_struct *handle,
2784                                        struct byte_range_lock *br_lck,
2785                                        struct lock_struct *plock)
2786 {
2787         SMB_ASSERT(plock->lock_flav == WINDOWS_LOCK);
2788
2789         /* Note: blr is not used in the default implementation. */
2790         return brl_lock_cancel_default(br_lck, plock);
2791 }
2792
2793 static bool vfswrap_strict_lock_check(struct vfs_handle_struct *handle,
2794                                       files_struct *fsp,
2795                                       struct lock_struct *plock)
2796 {
2797         SMB_ASSERT(plock->lock_type == READ_LOCK ||
2798             plock->lock_type == WRITE_LOCK);
2799
2800         return strict_lock_check_default(fsp, plock);
2801 }
2802
2803 /* NT ACL operations. */
2804
2805 static NTSTATUS vfswrap_fget_nt_acl(vfs_handle_struct *handle,
2806                                     files_struct *fsp,
2807                                     uint32_t security_info,
2808                                     TALLOC_CTX *mem_ctx,
2809                                     struct security_descriptor **ppdesc)
2810 {
2811         NTSTATUS result;
2812
2813         START_PROFILE(fget_nt_acl);
2814         result = posix_fget_nt_acl(fsp, security_info,
2815                                    mem_ctx, ppdesc);
2816         END_PROFILE(fget_nt_acl);
2817         return result;
2818 }
2819
2820 static NTSTATUS vfswrap_get_nt_acl(vfs_handle_struct *handle,
2821                                    const struct smb_filename *smb_fname,
2822                                    uint32_t security_info,
2823                                    TALLOC_CTX *mem_ctx,
2824                                    struct security_descriptor **ppdesc)
2825 {
2826         NTSTATUS result;
2827
2828         START_PROFILE(get_nt_acl);
2829         result = posix_get_nt_acl(handle->conn,
2830                                 smb_fname,
2831                                 security_info,
2832                                 mem_ctx,
2833                                 ppdesc);
2834         END_PROFILE(get_nt_acl);
2835         return result;
2836 }
2837
2838 static NTSTATUS vfswrap_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp, uint32_t security_info_sent, const struct security_descriptor *psd)
2839 {
2840         NTSTATUS result;
2841
2842         START_PROFILE(fset_nt_acl);
2843         result = set_nt_acl(fsp, security_info_sent, psd);
2844         END_PROFILE(fset_nt_acl);
2845         return result;
2846 }
2847
2848 static NTSTATUS vfswrap_audit_file(struct vfs_handle_struct *handle,
2849                                    struct smb_filename *file,
2850                                    struct security_acl *sacl,
2851                                    uint32_t access_requested,
2852                                    uint32_t access_denied)
2853 {
2854         return NT_STATUS_OK; /* Nothing to do here ... */
2855 }
2856
2857 static SMB_ACL_T vfswrap_sys_acl_get_file(vfs_handle_struct *handle,
2858                                           const struct smb_filename *smb_fname,
2859                                           SMB_ACL_TYPE_T type,
2860                                           TALLOC_CTX *mem_ctx)
2861 {
2862         return sys_acl_get_file(handle, smb_fname, type, mem_ctx);
2863 }
2864
2865 static SMB_ACL_T vfswrap_sys_acl_get_fd(vfs_handle_struct *handle,
2866                                         files_struct *fsp,
2867                                         TALLOC_CTX *mem_ctx)
2868 {
2869         return sys_acl_get_fd(handle, fsp, mem_ctx);
2870 }
2871
2872 static int vfswrap_sys_acl_set_file(vfs_handle_struct *handle,
2873                                 const struct smb_filename *smb_fname,
2874                                 SMB_ACL_TYPE_T acltype,
2875                                 SMB_ACL_T theacl)
2876 {
2877         return sys_acl_set_file(handle, smb_fname, acltype, theacl);
2878 }
2879
2880 static int vfswrap_sys_acl_set_fd(vfs_handle_struct *handle, files_struct *fsp, SMB_ACL_T theacl)
2881 {
2882         return sys_acl_set_fd(handle, fsp, theacl);
2883 }
2884
2885 static int vfswrap_sys_acl_delete_def_file(vfs_handle_struct *handle,
2886                         const struct smb_filename *smb_fname)
2887 {
2888         return sys_acl_delete_def_file(handle, smb_fname);
2889 }
2890
2891 /****************************************************************
2892  Extended attribute operations.
2893 *****************************************************************/
2894
2895 static ssize_t vfswrap_getxattr(struct vfs_handle_struct *handle,
2896                         const struct smb_filename *smb_fname,
2897                         const char *name,
2898                         void *value,
2899                         size_t size)
2900 {
2901         return getxattr(smb_fname->base_name, name, value, size);
2902 }
2903
2904 struct vfswrap_getxattrat_state {
2905         struct tevent_context *ev;
2906         files_struct *dir_fsp;
2907         const struct smb_filename *smb_fname;
2908         struct tevent_req *req;
2909
2910         /*
2911          * The following variables are talloced off "state" which is protected
2912          * by a destructor and thus are guaranteed to be safe to be used in the
2913          * job function in the worker thread.
2914          */
2915         char *name;
2916         const char *xattr_name;
2917         uint8_t *xattr_value;
2918         struct security_unix_token *token;
2919
2920         ssize_t xattr_size;
2921         struct vfs_aio_state vfs_aio_state;
2922         SMBPROFILE_BYTES_ASYNC_STATE(profile_bytes);
2923 };
2924
2925 static int vfswrap_getxattrat_state_destructor(
2926                 struct vfswrap_getxattrat_state *state)
2927 {
2928         return -1;
2929 }
2930
2931 static void vfswrap_getxattrat_do_sync(struct tevent_req *req);
2932 static void vfswrap_getxattrat_do_async(void *private_data);
2933 static void vfswrap_getxattrat_done(struct tevent_req *subreq);
2934
2935 static struct tevent_req *vfswrap_getxattrat_send(
2936                         TALLOC_CTX *mem_ctx,
2937                         struct tevent_context *ev,
2938                         struct vfs_handle_struct *handle,
2939                         files_struct *dir_fsp,
2940                         const struct smb_filename *smb_fname,
2941                         const char *xattr_name,
2942                         size_t alloc_hint)
2943 {
2944         struct tevent_req *req = NULL;
2945         struct tevent_req *subreq = NULL;
2946         struct vfswrap_getxattrat_state *state = NULL;
2947         size_t max_threads = 0;
2948         bool have_per_thread_cwd = false;
2949         bool have_per_thread_creds = false;
2950         bool do_async = false;
2951
2952         req = tevent_req_create(mem_ctx, &state,
2953                                 struct vfswrap_getxattrat_state);
2954         if (req == NULL) {
2955                 return NULL;
2956         }
2957         *state = (struct vfswrap_getxattrat_state) {
2958                 .ev = ev,
2959                 .dir_fsp = dir_fsp,
2960                 .smb_fname = smb_fname,
2961                 .req = req,
2962         };
2963
2964         max_threads = pthreadpool_tevent_max_threads(dir_fsp->conn->sconn->pool);
2965         if (max_threads >= 1) {
2966                 /*
2967                  * We need a non sync threadpool!
2968                  */
2969                 have_per_thread_cwd = per_thread_cwd_supported();
2970         }
2971 #ifdef HAVE_LINUX_THREAD_CREDENTIALS
2972         have_per_thread_creds = true;
2973 #endif
2974         if (have_per_thread_cwd && have_per_thread_creds) {
2975                 do_async = true;
2976         }
2977
2978         SMBPROFILE_BYTES_ASYNC_START(syscall_asys_getxattrat, profile_p,
2979                                      state->profile_bytes, 0);
2980
2981         if (dir_fsp->fh->fd == -1) {
2982                 DBG_ERR("Need a valid directory fd\n");
2983                 tevent_req_error(req, EINVAL);
2984                 return tevent_req_post(req, ev);
2985         }
2986
2987         if (alloc_hint > 0) {
2988                 state->xattr_value = talloc_zero_array(state,
2989                                                        uint8_t,
2990                                                        alloc_hint);
2991                 if (tevent_req_nomem(state->xattr_value, req)) {
2992                         return tevent_req_post(req, ev);
2993                 }
2994         }
2995
2996         if (!do_async) {
2997                 vfswrap_getxattrat_do_sync(req);
2998                 return tevent_req_post(req, ev);
2999         }
3000
3001         /*
3002          * Now allocate all parameters from a memory context that won't go away
3003          * no matter what. These paremeters will get used in threads and we
3004          * can't reliably cancel threads, so all buffers passed to the threads
3005          * must not be freed before all referencing threads terminate.
3006          */
3007
3008         state->name = talloc_strdup(state, smb_fname->base_name);
3009         if (tevent_req_nomem(state->name, req)) {
3010                 return tevent_req_post(req, ev);
3011         }
3012
3013         state->xattr_name = talloc_strdup(state, xattr_name);
3014         if (tevent_req_nomem(state->xattr_name, req)) {
3015                 return tevent_req_post(req, ev);
3016         }
3017
3018         /*
3019          * This is a hot codepath so at first glance one might think we should
3020          * somehow optimize away the token allocation and do a
3021          * talloc_reference() or similar black magic instead. But due to the
3022          * talloc_stackframe pool per SMB2 request this should be a simple copy
3023          * without a malloc in most cases.
3024          */
3025         if (geteuid() == sec_initial_uid()) {
3026                 state->token = root_unix_token(state);
3027         } else {
3028                 state->token = copy_unix_token(
3029                                         state,
3030                                         dir_fsp->conn->session_info->unix_token);
3031         }
3032         if (tevent_req_nomem(state->token, req)) {
3033                 return tevent_req_post(req, ev);
3034         }
3035
3036         SMBPROFILE_BYTES_ASYNC_SET_IDLE(state->profile_bytes);
3037
3038         subreq = pthreadpool_tevent_job_send(
3039                         state,
3040                         ev,
3041                         dir_fsp->conn->sconn->raw_thread_pool,
3042                         vfswrap_getxattrat_do_async,
3043                         state);
3044         if (tevent_req_nomem(subreq, req)) {
3045                 return tevent_req_post(req, ev);
3046         }
3047         tevent_req_set_callback(subreq, vfswrap_getxattrat_done, req);
3048
3049         talloc_set_destructor(state, vfswrap_getxattrat_state_destructor);
3050
3051         return req;
3052 }
3053
3054 static void vfswrap_getxattrat_do_sync(struct tevent_req *req)
3055 {
3056         struct vfswrap_getxattrat_state *state = talloc_get_type_abort(
3057                 req, struct vfswrap_getxattrat_state);
3058         char *path = NULL;
3059         char *tofree = NULL;
3060         char pathbuf[PATH_MAX+1];
3061         size_t pathlen;
3062         int err;