a28ad19fa4e3f377e5e0f3366459a4737dc135fe
[amitay/samba.git] / source3 / modules / vfs_fruit.c
1 /*
2  * OS X and Netatalk interoperability VFS module for Samba-3.x
3  *
4  * Copyright (C) Ralph Boehme, 2013, 2014
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "includes.h"
21 #include "MacExtensions.h"
22 #include "smbd/smbd.h"
23 #include "system/filesys.h"
24 #include "lib/util/time.h"
25 #include "system/shmem.h"
26 #include "locking/proto.h"
27 #include "smbd/globals.h"
28 #include "messages.h"
29 #include "libcli/security/security.h"
30 #include "../libcli/smb/smb2_create_ctx.h"
31 #include "lib/util/tevent_ntstatus.h"
32 #include "lib/util/tevent_unix.h"
33 #include "offload_token.h"
34 #include "string_replace.h"
35 #include "hash_inode.h"
36 #include "lib/adouble.h"
37 #include "lib/util_macstreams.h"
38
39 /*
40  * Enhanced OS X and Netatalk compatibility
41  * ========================================
42  *
43  * This modules takes advantage of vfs_streams_xattr and
44  * vfs_catia. VFS modules vfs_fruit and vfs_streams_xattr must be
45  * loaded in the correct order:
46  *
47  *   vfs modules = catia fruit streams_xattr
48  *
49  * The module intercepts the OS X special streams "AFP_AfpInfo" and
50  * "AFP_Resource" and handles them in a special way. All other named
51  * streams are deferred to vfs_streams_xattr.
52  *
53  * The OS X client maps all NTFS illegal characters to the Unicode
54  * private range. This module optionally stores the characters using
55  * their native ASCII encoding using vfs_catia. If you're not enabling
56  * this feature, you can skip catia from vfs modules.
57  *
58  * Finally, open modes are optionally checked against Netatalk AFP
59  * share modes.
60  *
61  * The "AFP_AfpInfo" named stream is a binary blob containing OS X
62  * extended metadata for files and directories. This module optionally
63  * reads and stores this metadata in a way compatible with Netatalk 3
64  * which stores the metadata in an EA "org.netatalk.metadata". Cf
65  * source3/include/MacExtensions.h for a description of the binary
66  * blobs content.
67  *
68  * The "AFP_Resource" named stream may be arbitrarily large, thus it
69  * can't be stored in an xattr on most filesystem. ZFS on Solaris is
70  * the only available filesystem where xattrs can be of any size and
71  * the OS supports using the file APIs for xattrs.
72  *
73  * The AFP_Resource stream is stored in an AppleDouble file prepending
74  * "._" to the filename. On Solaris with ZFS the stream is optionally
75  * stored in an EA "org.netatalk.resource".
76  *
77  *
78  * Extended Attributes
79  * ===================
80  *
81  * The OS X SMB client sends xattrs as ADS too. For xattr interop with
82  * other protocols you may want to adjust the xattr names the VFS
83  * module vfs_streams_xattr uses for storing ADS's. This defaults to
84  * user.DosStream.ADS_NAME:$DATA and can be changed by specifying
85  * these module parameters:
86  *
87  *   streams_xattr:prefix = user.
88  *   streams_xattr:store_stream_type = false
89  *
90  *
91  * TODO
92  * ====
93  *
94  * - log diagnostic if any needed VFS module is not loaded
95  *   (eg with lp_vfs_objects())
96  * - add tests
97  */
98
99 static int vfs_fruit_debug_level = DBGC_VFS;
100
101 static struct global_fruit_config {
102         bool nego_aapl; /* client negotiated AAPL */
103
104 } global_fruit_config;
105
106 #undef DBGC_CLASS
107 #define DBGC_CLASS vfs_fruit_debug_level
108
109 #define FRUIT_PARAM_TYPE_NAME "fruit"
110
111 enum apple_fork {APPLE_FORK_DATA, APPLE_FORK_RSRC};
112
113 enum fruit_rsrc {FRUIT_RSRC_STREAM, FRUIT_RSRC_ADFILE, FRUIT_RSRC_XATTR};
114 enum fruit_meta {FRUIT_META_STREAM, FRUIT_META_NETATALK};
115 enum fruit_locking {FRUIT_LOCKING_NETATALK, FRUIT_LOCKING_NONE};
116 enum fruit_encoding {FRUIT_ENC_NATIVE, FRUIT_ENC_PRIVATE};
117
118 struct fruit_config_data {
119         enum fruit_rsrc rsrc;
120         enum fruit_meta meta;
121         enum fruit_locking locking;
122         enum fruit_encoding encoding;
123         bool use_aapl;          /* config from smb.conf */
124         bool use_copyfile;
125         bool readdir_attr_enabled;
126         bool unix_info_enabled;
127         bool copyfile_enabled;
128         bool veto_appledouble;
129         bool posix_rename;
130         bool aapl_zero_file_id;
131         const char *model;
132         bool time_machine;
133         off_t time_machine_max_size;
134         bool wipe_intentionally_left_blank_rfork;
135         bool delete_empty_adfiles;
136
137         /*
138          * Additional options, all enabled by default,
139          * possibly useful for analyzing performance. The associated
140          * operations with each of them may be expensive, so having
141          * the chance to disable them individually gives a chance
142          * tweaking the setup for the particular usecase.
143          */
144         bool readdir_attr_rsize;
145         bool readdir_attr_finder_info;
146         bool readdir_attr_max_access;
147 };
148
149 static const struct enum_list fruit_rsrc[] = {
150         {FRUIT_RSRC_STREAM, "stream"}, /* pass on to vfs_streams_xattr */
151         {FRUIT_RSRC_ADFILE, "file"}, /* ._ AppleDouble file */
152         {FRUIT_RSRC_XATTR, "xattr"}, /* Netatalk compatible xattr (ZFS only) */
153         { -1, NULL}
154 };
155
156 static const struct enum_list fruit_meta[] = {
157         {FRUIT_META_STREAM, "stream"}, /* pass on to vfs_streams_xattr */
158         {FRUIT_META_NETATALK, "netatalk"}, /* Netatalk compatible xattr */
159         { -1, NULL}
160 };
161
162 static const struct enum_list fruit_locking[] = {
163         {FRUIT_LOCKING_NETATALK, "netatalk"}, /* synchronize locks with Netatalk */
164         {FRUIT_LOCKING_NONE, "none"},
165         { -1, NULL}
166 };
167
168 static const struct enum_list fruit_encoding[] = {
169         {FRUIT_ENC_NATIVE, "native"}, /* map unicode private chars to ASCII */
170         {FRUIT_ENC_PRIVATE, "private"}, /* keep unicode private chars */
171         { -1, NULL}
172 };
173
174 struct fio {
175         /* tcon config handle */
176         struct fruit_config_data *config;
177
178         /* Denote stream type, meta or rsrc */
179         adouble_type_t type;
180
181         /* Whether the create created the stream */
182         bool created;
183
184         /*
185          * AFP_AfpInfo stream created, but not written yet, thus still a fake
186          * pipe fd. This is set to true in fruit_open_meta if there was no
187          * existing stream but the caller requested O_CREAT. It is later set to
188          * false when we get a write on the stream that then does open and
189          * create the stream.
190          */
191         bool fake_fd;
192         int flags;
193         int mode;
194 };
195
196 /*****************************************************************************
197  * Helper functions
198  *****************************************************************************/
199
200 /**
201  * Initialize config struct from our smb.conf config parameters
202  **/
203 static int init_fruit_config(vfs_handle_struct *handle)
204 {
205         struct fruit_config_data *config;
206         int enumval;
207         const char *tm_size_str = NULL;
208
209         config = talloc_zero(handle->conn, struct fruit_config_data);
210         if (!config) {
211                 DEBUG(1, ("talloc_zero() failed\n"));
212                 errno = ENOMEM;
213                 return -1;
214         }
215
216         /*
217          * Versions up to Samba 4.5.x had a spelling bug in the
218          * fruit:resource option calling lp_parm_enum with
219          * "res*s*ource" (ie two s).
220          *
221          * In Samba 4.6 we accept both the wrong and the correct
222          * spelling, in Samba 4.7 the bad spelling will be removed.
223          */
224         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
225                                "ressource", fruit_rsrc, FRUIT_RSRC_ADFILE);
226         if (enumval == -1) {
227                 DEBUG(1, ("value for %s: resource type unknown\n",
228                           FRUIT_PARAM_TYPE_NAME));
229                 return -1;
230         }
231         config->rsrc = (enum fruit_rsrc)enumval;
232
233         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
234                                "resource", fruit_rsrc, enumval);
235         if (enumval == -1) {
236                 DEBUG(1, ("value for %s: resource type unknown\n",
237                           FRUIT_PARAM_TYPE_NAME));
238                 return -1;
239         }
240         config->rsrc = (enum fruit_rsrc)enumval;
241
242         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
243                                "metadata", fruit_meta, FRUIT_META_NETATALK);
244         if (enumval == -1) {
245                 DEBUG(1, ("value for %s: metadata type unknown\n",
246                           FRUIT_PARAM_TYPE_NAME));
247                 return -1;
248         }
249         config->meta = (enum fruit_meta)enumval;
250
251         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
252                                "locking", fruit_locking, FRUIT_LOCKING_NONE);
253         if (enumval == -1) {
254                 DEBUG(1, ("value for %s: locking type unknown\n",
255                           FRUIT_PARAM_TYPE_NAME));
256                 return -1;
257         }
258         config->locking = (enum fruit_locking)enumval;
259
260         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
261                                "encoding", fruit_encoding, FRUIT_ENC_PRIVATE);
262         if (enumval == -1) {
263                 DEBUG(1, ("value for %s: encoding type unknown\n",
264                           FRUIT_PARAM_TYPE_NAME));
265                 return -1;
266         }
267         config->encoding = (enum fruit_encoding)enumval;
268
269         if (config->rsrc == FRUIT_RSRC_ADFILE) {
270                 config->veto_appledouble = lp_parm_bool(SNUM(handle->conn),
271                                                         FRUIT_PARAM_TYPE_NAME,
272                                                         "veto_appledouble",
273                                                         true);
274         }
275
276         config->use_aapl = lp_parm_bool(
277                 -1, FRUIT_PARAM_TYPE_NAME, "aapl", true);
278
279         config->time_machine = lp_parm_bool(
280                 SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME, "time machine", false);
281
282         config->unix_info_enabled = lp_parm_bool(
283                 -1, FRUIT_PARAM_TYPE_NAME, "nfs_aces", true);
284
285         config->use_copyfile = lp_parm_bool(-1, FRUIT_PARAM_TYPE_NAME,
286                                            "copyfile", false);
287
288         config->posix_rename = lp_parm_bool(
289                 SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME, "posix_rename", true);
290
291         config->aapl_zero_file_id =
292             lp_parm_bool(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
293                          "zero_file_id", false);
294
295         config->readdir_attr_rsize = lp_parm_bool(
296                 SNUM(handle->conn), "readdir_attr", "aapl_rsize", true);
297
298         config->readdir_attr_finder_info = lp_parm_bool(
299                 SNUM(handle->conn), "readdir_attr", "aapl_finder_info", true);
300
301         config->readdir_attr_max_access = lp_parm_bool(
302                 SNUM(handle->conn), "readdir_attr", "aapl_max_access", true);
303
304         config->model = lp_parm_const_string(
305                 -1, FRUIT_PARAM_TYPE_NAME, "model", "MacSamba");
306
307         tm_size_str = lp_parm_const_string(
308                 SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
309                 "time machine max size", NULL);
310         if (tm_size_str != NULL) {
311                 config->time_machine_max_size = conv_str_size(tm_size_str);
312         }
313
314         config->wipe_intentionally_left_blank_rfork = lp_parm_bool(
315                 SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
316                 "wipe_intentionally_left_blank_rfork", false);
317
318         config->delete_empty_adfiles = lp_parm_bool(
319                 SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
320                 "delete_empty_adfiles", false);
321
322         SMB_VFS_HANDLE_SET_DATA(handle, config,
323                                 NULL, struct fruit_config_data,
324                                 return -1);
325
326         return 0;
327 }
328
329 static bool add_fruit_stream(TALLOC_CTX *mem_ctx, unsigned int *num_streams,
330                              struct stream_struct **streams,
331                              const char *name, off_t size,
332                              off_t alloc_size)
333 {
334         struct stream_struct *tmp;
335
336         tmp = talloc_realloc(mem_ctx, *streams, struct stream_struct,
337                              (*num_streams)+1);
338         if (tmp == NULL) {
339                 return false;
340         }
341
342         tmp[*num_streams].name = talloc_asprintf(tmp, "%s:$DATA", name);
343         if (tmp[*num_streams].name == NULL) {
344                 return false;
345         }
346
347         tmp[*num_streams].size = size;
348         tmp[*num_streams].alloc_size = alloc_size;
349
350         *streams = tmp;
351         *num_streams += 1;
352         return true;
353 }
354
355 static bool filter_empty_rsrc_stream(unsigned int *num_streams,
356                                      struct stream_struct **streams)
357 {
358         struct stream_struct *tmp = *streams;
359         unsigned int i;
360
361         if (*num_streams == 0) {
362                 return true;
363         }
364
365         for (i = 0; i < *num_streams; i++) {
366                 if (strequal_m(tmp[i].name, AFPRESOURCE_STREAM)) {
367                         break;
368                 }
369         }
370
371         if (i == *num_streams) {
372                 return true;
373         }
374
375         if (tmp[i].size > 0) {
376                 return true;
377         }
378
379         TALLOC_FREE(tmp[i].name);
380         ARRAY_DEL_ELEMENT(tmp, i, *num_streams);
381         *num_streams -= 1;
382         return true;
383 }
384
385 static bool del_fruit_stream(TALLOC_CTX *mem_ctx, unsigned int *num_streams,
386                              struct stream_struct **streams,
387                              const char *name)
388 {
389         struct stream_struct *tmp = *streams;
390         unsigned int i;
391
392         if (*num_streams == 0) {
393                 return true;
394         }
395
396         for (i = 0; i < *num_streams; i++) {
397                 if (strequal_m(tmp[i].name, name)) {
398                         break;
399                 }
400         }
401
402         if (i == *num_streams) {
403                 return true;
404         }
405
406         TALLOC_FREE(tmp[i].name);
407         ARRAY_DEL_ELEMENT(tmp, i, *num_streams);
408         *num_streams -= 1;
409         return true;
410 }
411
412 static bool ad_empty_finderinfo(const struct adouble *ad)
413 {
414         int cmp;
415         char emptybuf[ADEDLEN_FINDERI] = {0};
416         char *fi = NULL;
417
418         fi = ad_get_entry(ad, ADEID_FINDERI);
419         if (fi == NULL) {
420                 DBG_ERR("Missing FinderInfo in struct adouble [%p]\n", ad);
421                 return false;
422         }
423
424         cmp = memcmp(emptybuf, fi, ADEDLEN_FINDERI);
425         return (cmp == 0);
426 }
427
428 static bool ai_empty_finderinfo(const AfpInfo *ai)
429 {
430         int cmp;
431         char emptybuf[ADEDLEN_FINDERI] = {0};
432
433         cmp = memcmp(emptybuf, &ai->afpi_FinderInfo[0], ADEDLEN_FINDERI);
434         return (cmp == 0);
435 }
436
437 /**
438  * Update btime with btime from Netatalk
439  **/
440 static void update_btime(vfs_handle_struct *handle,
441                          struct smb_filename *smb_fname)
442 {
443         uint32_t t;
444         struct timespec creation_time = {0};
445         struct adouble *ad;
446         struct fruit_config_data *config = NULL;
447
448         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
449                                 return);
450
451         switch (config->meta) {
452         case FRUIT_META_STREAM:
453                 return;
454         case FRUIT_META_NETATALK:
455                 /* Handled below */
456                 break;
457         default:
458                 DBG_ERR("Unexpected meta config [%d]\n", config->meta);
459                 return;
460         }
461
462         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
463         if (ad == NULL) {
464                 return;
465         }
466         if (ad_getdate(ad, AD_DATE_UNIX | AD_DATE_CREATE, &t) != 0) {
467                 TALLOC_FREE(ad);
468                 return;
469         }
470         TALLOC_FREE(ad);
471
472         creation_time.tv_sec = convert_uint32_t_to_time_t(t);
473         update_stat_ex_create_time(&smb_fname->st, creation_time);
474
475         return;
476 }
477
478 /**
479  * Map an access mask to a Netatalk single byte byte range lock
480  **/
481 static off_t access_to_netatalk_brl(enum apple_fork fork_type,
482                                     uint32_t access_mask)
483 {
484         off_t offset;
485
486         switch (access_mask) {
487         case FILE_READ_DATA:
488                 offset = AD_FILELOCK_OPEN_RD;
489                 break;
490
491         case FILE_WRITE_DATA:
492         case FILE_APPEND_DATA:
493                 offset = AD_FILELOCK_OPEN_WR;
494                 break;
495
496         default:
497                 offset = AD_FILELOCK_OPEN_NONE;
498                 break;
499         }
500
501         if (fork_type == APPLE_FORK_RSRC) {
502                 if (offset == AD_FILELOCK_OPEN_NONE) {
503                         offset = AD_FILELOCK_RSRC_OPEN_NONE;
504                 } else {
505                         offset += 2;
506                 }
507         }
508
509         return offset;
510 }
511
512 /**
513  * Map a deny mode to a Netatalk brl
514  **/
515 static off_t denymode_to_netatalk_brl(enum apple_fork fork_type,
516                                       uint32_t deny_mode)
517 {
518         off_t offset = 0;
519
520         switch (deny_mode) {
521         case DENY_READ:
522                 offset = AD_FILELOCK_DENY_RD;
523                 break;
524
525         case DENY_WRITE:
526                 offset = AD_FILELOCK_DENY_WR;
527                 break;
528
529         default:
530                 smb_panic("denymode_to_netatalk_brl: bad deny mode\n");
531         }
532
533         if (fork_type == APPLE_FORK_RSRC) {
534                 offset += 2;
535         }
536
537         return offset;
538 }
539
540 /**
541  * Call fcntl() with an exclusive F_GETLK request in order to
542  * determine if there's an existing shared lock
543  *
544  * @return true if the requested lock was found or any error occurred
545  *         false if the lock was not found
546  **/
547 static bool test_netatalk_lock(files_struct *fsp, off_t in_offset)
548 {
549         bool result;
550         off_t offset = in_offset;
551         off_t len = 1;
552         int type = F_WRLCK;
553         pid_t pid = 0;
554
555         result = SMB_VFS_GETLOCK(fsp, &offset, &len, &type, &pid);
556         if (result == false) {
557                 return true;
558         }
559
560         if (type != F_UNLCK) {
561                 return true;
562         }
563
564         return false;
565 }
566
567 static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
568                                    files_struct *fsp,
569                                    uint32_t access_mask,
570                                    uint32_t share_mode)
571 {
572         NTSTATUS status = NT_STATUS_OK;
573         off_t off;
574         bool share_for_read = (share_mode & FILE_SHARE_READ);
575         bool share_for_write = (share_mode & FILE_SHARE_WRITE);
576         bool netatalk_already_open_for_reading = false;
577         bool netatalk_already_open_for_writing = false;
578         bool netatalk_already_open_with_deny_read = false;
579         bool netatalk_already_open_with_deny_write = false;
580         struct GUID req_guid = GUID_random();
581
582         /* FIXME: hardcoded data fork, add resource fork */
583         enum apple_fork fork_type = APPLE_FORK_DATA;
584
585         DBG_DEBUG("fruit_check_access: %s, am: %s/%s, sm: 0x%x\n",
586                   fsp_str_dbg(fsp),
587                   access_mask & FILE_READ_DATA ? "READ" :"-",
588                   access_mask & FILE_WRITE_DATA ? "WRITE" : "-",
589                   share_mode);
590
591         if (fsp->fh->fd == -1) {
592                 return NT_STATUS_OK;
593         }
594
595         /* Read NetATalk opens and deny modes on the file. */
596         netatalk_already_open_for_reading = test_netatalk_lock(fsp,
597                                 access_to_netatalk_brl(fork_type,
598                                         FILE_READ_DATA));
599
600         netatalk_already_open_with_deny_read = test_netatalk_lock(fsp,
601                                 denymode_to_netatalk_brl(fork_type,
602                                         DENY_READ));
603
604         netatalk_already_open_for_writing = test_netatalk_lock(fsp,
605                                 access_to_netatalk_brl(fork_type,
606                                         FILE_WRITE_DATA));
607
608         netatalk_already_open_with_deny_write = test_netatalk_lock(fsp,
609                                 denymode_to_netatalk_brl(fork_type,
610                                         DENY_WRITE));
611
612         /* If there are any conflicts - sharing violation. */
613         if ((access_mask & FILE_READ_DATA) &&
614                         netatalk_already_open_with_deny_read) {
615                 return NT_STATUS_SHARING_VIOLATION;
616         }
617
618         if (!share_for_read &&
619                         netatalk_already_open_for_reading) {
620                 return NT_STATUS_SHARING_VIOLATION;
621         }
622
623         if ((access_mask & FILE_WRITE_DATA) &&
624                         netatalk_already_open_with_deny_write) {
625                 return NT_STATUS_SHARING_VIOLATION;
626         }
627
628         if (!share_for_write &&
629                         netatalk_already_open_for_writing) {
630                 return NT_STATUS_SHARING_VIOLATION;
631         }
632
633         if (!(access_mask & FILE_READ_DATA)) {
634                 /*
635                  * Nothing we can do here, we need read access
636                  * to set locks.
637                  */
638                 return NT_STATUS_OK;
639         }
640
641         /* Set NetAtalk locks matching our access */
642         if (access_mask & FILE_READ_DATA) {
643                 off = access_to_netatalk_brl(fork_type, FILE_READ_DATA);
644                 req_guid.time_hi_and_version = __LINE__;
645                 status = do_lock(
646                         fsp,
647                         talloc_tos(),
648                         &req_guid,
649                         fsp->op->global->open_persistent_id,
650                         1,
651                         off,
652                         READ_LOCK,
653                         POSIX_LOCK,
654                         NULL,
655                         NULL);
656
657                 if (!NT_STATUS_IS_OK(status))  {
658                         return status;
659                 }
660         }
661
662         if (!share_for_read) {
663                 off = denymode_to_netatalk_brl(fork_type, DENY_READ);
664                 req_guid.time_hi_and_version = __LINE__;
665                 status = do_lock(
666                         fsp,
667                         talloc_tos(),
668                         &req_guid,
669                         fsp->op->global->open_persistent_id,
670                         1,
671                         off,
672                         READ_LOCK,
673                         POSIX_LOCK,
674                         NULL,
675                         NULL);
676
677                 if (!NT_STATUS_IS_OK(status)) {
678                         return status;
679                 }
680         }
681
682         if (access_mask & FILE_WRITE_DATA) {
683                 off = access_to_netatalk_brl(fork_type, FILE_WRITE_DATA);
684                 req_guid.time_hi_and_version = __LINE__;
685                 status = do_lock(
686                         fsp,
687                         talloc_tos(),
688                         &req_guid,
689                         fsp->op->global->open_persistent_id,
690                         1,
691                         off,
692                         READ_LOCK,
693                         POSIX_LOCK,
694                         NULL,
695                         NULL);
696
697                 if (!NT_STATUS_IS_OK(status)) {
698                         return status;
699                 }
700         }
701
702         if (!share_for_write) {
703                 off = denymode_to_netatalk_brl(fork_type, DENY_WRITE);
704                 req_guid.time_hi_and_version = __LINE__;
705                 status = do_lock(
706                         fsp,
707                         talloc_tos(),
708                         &req_guid,
709                         fsp->op->global->open_persistent_id,
710                         1,
711                         off,
712                         READ_LOCK,
713                         POSIX_LOCK,
714                         NULL,
715                         NULL);
716
717                 if (!NT_STATUS_IS_OK(status)) {
718                         return status;
719                 }
720         }
721
722         return NT_STATUS_OK;
723 }
724
725 static NTSTATUS check_aapl(vfs_handle_struct *handle,
726                            struct smb_request *req,
727                            const struct smb2_create_blobs *in_context_blobs,
728                            struct smb2_create_blobs *out_context_blobs)
729 {
730         struct fruit_config_data *config;
731         NTSTATUS status;
732         struct smb2_create_blob *aapl = NULL;
733         uint32_t cmd;
734         bool ok;
735         uint8_t p[16];
736         DATA_BLOB blob = data_blob_talloc(req, NULL, 0);
737         uint64_t req_bitmap, client_caps;
738         uint64_t server_caps = SMB2_CRTCTX_AAPL_UNIX_BASED;
739         smb_ucs2_t *model;
740         size_t modellen;
741
742         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
743                                 return NT_STATUS_UNSUCCESSFUL);
744
745         if (!config->use_aapl
746             || in_context_blobs == NULL
747             || out_context_blobs == NULL) {
748                 return NT_STATUS_OK;
749         }
750
751         aapl = smb2_create_blob_find(in_context_blobs,
752                                      SMB2_CREATE_TAG_AAPL);
753         if (aapl == NULL) {
754                 return NT_STATUS_OK;
755         }
756
757         if (aapl->data.length != 24) {
758                 DEBUG(1, ("unexpected AAPL ctxt length: %ju\n",
759                           (uintmax_t)aapl->data.length));
760                 return NT_STATUS_INVALID_PARAMETER;
761         }
762
763         cmd = IVAL(aapl->data.data, 0);
764         if (cmd != SMB2_CRTCTX_AAPL_SERVER_QUERY) {
765                 DEBUG(1, ("unsupported AAPL cmd: %d\n", cmd));
766                 return NT_STATUS_INVALID_PARAMETER;
767         }
768
769         req_bitmap = BVAL(aapl->data.data, 8);
770         client_caps = BVAL(aapl->data.data, 16);
771
772         SIVAL(p, 0, SMB2_CRTCTX_AAPL_SERVER_QUERY);
773         SIVAL(p, 4, 0);
774         SBVAL(p, 8, req_bitmap);
775         ok = data_blob_append(req, &blob, p, 16);
776         if (!ok) {
777                 return NT_STATUS_UNSUCCESSFUL;
778         }
779
780         if (req_bitmap & SMB2_CRTCTX_AAPL_SERVER_CAPS) {
781                 if ((client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR) &&
782                     (handle->conn->tcon->compat->fs_capabilities & FILE_NAMED_STREAMS)) {
783                         server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR;
784                         config->readdir_attr_enabled = true;
785                 }
786
787                 if (config->use_copyfile) {
788                         server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_OSX_COPYFILE;
789                         config->copyfile_enabled = true;
790                 }
791
792                 /*
793                  * The client doesn't set the flag, so we can't check
794                  * for it and just set it unconditionally
795                  */
796                 if (config->unix_info_enabled) {
797                         server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_NFS_ACE;
798                 }
799
800                 SBVAL(p, 0, server_caps);
801                 ok = data_blob_append(req, &blob, p, 8);
802                 if (!ok) {
803                         return NT_STATUS_UNSUCCESSFUL;
804                 }
805         }
806
807         if (req_bitmap & SMB2_CRTCTX_AAPL_VOLUME_CAPS) {
808                 int val = lp_case_sensitive(SNUM(handle->conn->tcon->compat));
809                 uint64_t caps = 0;
810
811                 switch (val) {
812                 case Auto:
813                         break;
814
815                 case True:
816                         caps |= SMB2_CRTCTX_AAPL_CASE_SENSITIVE;
817                         break;
818
819                 default:
820                         break;
821                 }
822
823                 if (config->time_machine) {
824                         caps |= SMB2_CRTCTX_AAPL_FULL_SYNC;
825                 }
826
827                 SBVAL(p, 0, caps);
828
829                 ok = data_blob_append(req, &blob, p, 8);
830                 if (!ok) {
831                         return NT_STATUS_UNSUCCESSFUL;
832                 }
833         }
834
835         if (req_bitmap & SMB2_CRTCTX_AAPL_MODEL_INFO) {
836                 ok = convert_string_talloc(req,
837                                            CH_UNIX, CH_UTF16LE,
838                                            config->model, strlen(config->model),
839                                            &model, &modellen);
840                 if (!ok) {
841                         return NT_STATUS_UNSUCCESSFUL;
842                 }
843
844                 SIVAL(p, 0, 0);
845                 SIVAL(p + 4, 0, modellen);
846                 ok = data_blob_append(req, &blob, p, 8);
847                 if (!ok) {
848                         talloc_free(model);
849                         return NT_STATUS_UNSUCCESSFUL;
850                 }
851
852                 ok = data_blob_append(req, &blob, model, modellen);
853                 talloc_free(model);
854                 if (!ok) {
855                         return NT_STATUS_UNSUCCESSFUL;
856                 }
857         }
858
859         status = smb2_create_blob_add(out_context_blobs,
860                                       out_context_blobs,
861                                       SMB2_CREATE_TAG_AAPL,
862                                       blob);
863         if (NT_STATUS_IS_OK(status)) {
864                 global_fruit_config.nego_aapl = true;
865         }
866
867         return status;
868 }
869
870 static bool readdir_attr_meta_finderi_stream(
871         struct vfs_handle_struct *handle,
872         const struct smb_filename *smb_fname,
873         AfpInfo *ai)
874 {
875         struct smb_filename *stream_name = NULL;
876         files_struct *fsp = NULL;
877         ssize_t nread;
878         NTSTATUS status;
879         int ret;
880         bool ok;
881         uint8_t buf[AFP_INFO_SIZE];
882
883         stream_name = synthetic_smb_fname(talloc_tos(),
884                                           smb_fname->base_name,
885                                           AFPINFO_STREAM_NAME,
886                                           NULL,
887                                           smb_fname->flags);
888         if (stream_name == NULL) {
889                 return false;
890         }
891
892         ret = SMB_VFS_STAT(handle->conn, stream_name);
893         if (ret != 0) {
894                 return false;
895         }
896
897         status = SMB_VFS_CREATE_FILE(
898                 handle->conn,                           /* conn */
899                 NULL,                                   /* req */
900                 0,                                      /* root_dir_fid */
901                 stream_name,                            /* fname */
902                 FILE_READ_DATA,                         /* access_mask */
903                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
904                         FILE_SHARE_DELETE),
905                 FILE_OPEN,                              /* create_disposition*/
906                 0,                                      /* create_options */
907                 0,                                      /* file_attributes */
908                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
909                 NULL,                                   /* lease */
910                 0,                                      /* allocation_size */
911                 0,                                      /* private_flags */
912                 NULL,                                   /* sd */
913                 NULL,                                   /* ea_list */
914                 &fsp,                                   /* result */
915                 NULL,                                   /* pinfo */
916                 NULL, NULL);                            /* create context */
917
918         TALLOC_FREE(stream_name);
919
920         if (!NT_STATUS_IS_OK(status)) {
921                 return false;
922         }
923
924         nread = SMB_VFS_PREAD(fsp, &buf[0], AFP_INFO_SIZE, 0);
925         if (nread != AFP_INFO_SIZE) {
926                 DBG_ERR("short read [%s] [%zd/%d]\n",
927                         smb_fname_str_dbg(stream_name), nread, AFP_INFO_SIZE);
928                 ok = false;
929                 goto fail;
930         }
931
932         memcpy(&ai->afpi_FinderInfo[0], &buf[AFP_OFF_FinderInfo],
933                AFP_FinderSize);
934
935         ok = true;
936
937 fail:
938         if (fsp != NULL) {
939                 close_file(NULL, fsp, NORMAL_CLOSE);
940         }
941
942         return ok;
943 }
944
945 static bool readdir_attr_meta_finderi_netatalk(
946         struct vfs_handle_struct *handle,
947         const struct smb_filename *smb_fname,
948         AfpInfo *ai)
949 {
950         struct adouble *ad = NULL;
951         char *p = NULL;
952
953         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
954         if (ad == NULL) {
955                 return false;
956         }
957
958         p = ad_get_entry(ad, ADEID_FINDERI);
959         if (p == NULL) {
960                 DBG_ERR("No ADEID_FINDERI for [%s]\n", smb_fname->base_name);
961                 TALLOC_FREE(ad);
962                 return false;
963         }
964
965         memcpy(&ai->afpi_FinderInfo[0], p, AFP_FinderSize);
966         TALLOC_FREE(ad);
967         return true;
968 }
969
970 static bool readdir_attr_meta_finderi(struct vfs_handle_struct *handle,
971                                       const struct smb_filename *smb_fname,
972                                       struct readdir_attr_data *attr_data)
973 {
974         struct fruit_config_data *config = NULL;
975         uint32_t date_added;
976         AfpInfo ai = {0};
977         bool ok;
978
979         SMB_VFS_HANDLE_GET_DATA(handle, config,
980                                 struct fruit_config_data,
981                                 return false);
982
983         switch (config->meta) {
984         case FRUIT_META_NETATALK:
985                 ok = readdir_attr_meta_finderi_netatalk(
986                         handle, smb_fname, &ai);
987                 break;
988
989         case FRUIT_META_STREAM:
990                 ok = readdir_attr_meta_finderi_stream(
991                         handle, smb_fname, &ai);
992                 break;
993
994         default:
995                 DBG_ERR("Unexpected meta config [%d]\n", config->meta);
996                 return false;
997         }
998
999         if (!ok) {
1000                 /* Don't bother with errors, it's likely ENOENT */
1001                 return true;
1002         }
1003
1004         if (S_ISREG(smb_fname->st.st_ex_mode)) {
1005                 /* finder_type */
1006                 memcpy(&attr_data->attr_data.aapl.finder_info[0],
1007                        &ai.afpi_FinderInfo[0], 4);
1008
1009                 /* finder_creator */
1010                 memcpy(&attr_data->attr_data.aapl.finder_info[0] + 4,
1011                        &ai.afpi_FinderInfo[4], 4);
1012         }
1013
1014         /* finder_flags */
1015         memcpy(&attr_data->attr_data.aapl.finder_info[0] + 8,
1016                &ai.afpi_FinderInfo[8], 2);
1017
1018         /* finder_ext_flags */
1019         memcpy(&attr_data->attr_data.aapl.finder_info[0] + 10,
1020                &ai.afpi_FinderInfo[24], 2);
1021
1022         /* creation date */
1023         date_added = convert_time_t_to_uint32_t(
1024                 smb_fname->st.st_ex_btime.tv_sec - AD_DATE_DELTA);
1025
1026         RSIVAL(&attr_data->attr_data.aapl.finder_info[0], 12, date_added);
1027
1028         return true;
1029 }
1030
1031 static uint64_t readdir_attr_rfork_size_adouble(
1032         struct vfs_handle_struct *handle,
1033         const struct smb_filename *smb_fname)
1034 {
1035         struct adouble *ad = NULL;
1036         uint64_t rfork_size;
1037
1038         ad = ad_get(talloc_tos(), handle, smb_fname,
1039                     ADOUBLE_RSRC);
1040         if (ad == NULL) {
1041                 return 0;
1042         }
1043
1044         rfork_size = ad_getentrylen(ad, ADEID_RFORK);
1045         TALLOC_FREE(ad);
1046
1047         return rfork_size;
1048 }
1049
1050 static uint64_t readdir_attr_rfork_size_stream(
1051         struct vfs_handle_struct *handle,
1052         const struct smb_filename *smb_fname)
1053 {
1054         struct smb_filename *stream_name = NULL;
1055         int ret;
1056         uint64_t rfork_size;
1057
1058         stream_name = synthetic_smb_fname(talloc_tos(),
1059                                           smb_fname->base_name,
1060                                           AFPRESOURCE_STREAM_NAME,
1061                                           NULL,
1062                                           0);
1063         if (stream_name == NULL) {
1064                 return 0;
1065         }
1066
1067         ret = SMB_VFS_STAT(handle->conn, stream_name);
1068         if (ret != 0) {
1069                 TALLOC_FREE(stream_name);
1070                 return 0;
1071         }
1072
1073         rfork_size = stream_name->st.st_ex_size;
1074         TALLOC_FREE(stream_name);
1075
1076         return rfork_size;
1077 }
1078
1079 static uint64_t readdir_attr_rfork_size(struct vfs_handle_struct *handle,
1080                                         const struct smb_filename *smb_fname)
1081 {
1082         struct fruit_config_data *config = NULL;
1083         uint64_t rfork_size;
1084
1085         SMB_VFS_HANDLE_GET_DATA(handle, config,
1086                                 struct fruit_config_data,
1087                                 return 0);
1088
1089         switch (config->rsrc) {
1090         case FRUIT_RSRC_ADFILE:
1091                 rfork_size = readdir_attr_rfork_size_adouble(handle,
1092                                                              smb_fname);
1093                 break;
1094
1095         case FRUIT_RSRC_XATTR:
1096         case FRUIT_RSRC_STREAM:
1097                 rfork_size = readdir_attr_rfork_size_stream(handle,
1098                                                             smb_fname);
1099                 break;
1100
1101         default:
1102                 DBG_ERR("Unexpected rsrc config [%d]\n", config->rsrc);
1103                 rfork_size = 0;
1104                 break;
1105         }
1106
1107         return rfork_size;
1108 }
1109
1110 static NTSTATUS readdir_attr_macmeta(struct vfs_handle_struct *handle,
1111                                      const struct smb_filename *smb_fname,
1112                                      struct readdir_attr_data *attr_data)
1113 {
1114         NTSTATUS status = NT_STATUS_OK;
1115         struct fruit_config_data *config = NULL;
1116         bool ok;
1117
1118         SMB_VFS_HANDLE_GET_DATA(handle, config,
1119                                 struct fruit_config_data,
1120                                 return NT_STATUS_UNSUCCESSFUL);
1121
1122
1123         /* Ensure we return a default value in the creation_date field */
1124         RSIVAL(&attr_data->attr_data.aapl.finder_info, 12, AD_DATE_START);
1125
1126         /*
1127          * Resource fork length
1128          */
1129
1130         if (config->readdir_attr_rsize) {
1131                 uint64_t rfork_size;
1132
1133                 rfork_size = readdir_attr_rfork_size(handle, smb_fname);
1134                 attr_data->attr_data.aapl.rfork_size = rfork_size;
1135         }
1136
1137         /*
1138          * FinderInfo
1139          */
1140
1141         if (config->readdir_attr_finder_info) {
1142                 ok = readdir_attr_meta_finderi(handle, smb_fname, attr_data);
1143                 if (!ok) {
1144                         status = NT_STATUS_INTERNAL_ERROR;
1145                 }
1146         }
1147
1148         return status;
1149 }
1150
1151 static NTSTATUS remove_virtual_nfs_aces(struct security_descriptor *psd)
1152 {
1153         NTSTATUS status;
1154         uint32_t i;
1155
1156         if (psd->dacl == NULL) {
1157                 return NT_STATUS_OK;
1158         }
1159
1160         for (i = 0; i < psd->dacl->num_aces; i++) {
1161                 /* MS NFS style mode/uid/gid */
1162                 int cmp = dom_sid_compare_domain(
1163                                 &global_sid_Unix_NFS,
1164                                 &psd->dacl->aces[i].trustee);
1165                 if (cmp != 0) {
1166                         /* Normal ACE entry. */
1167                         continue;
1168                 }
1169
1170                 /*
1171                  * security_descriptor_dacl_del()
1172                  * *must* return NT_STATUS_OK as we know
1173                  * we have something to remove.
1174                  */
1175
1176                 status = security_descriptor_dacl_del(psd,
1177                                 &psd->dacl->aces[i].trustee);
1178                 if (!NT_STATUS_IS_OK(status)) {
1179                         DBG_WARNING("failed to remove MS NFS style ACE: %s\n",
1180                                 nt_errstr(status));
1181                         return status;
1182                 }
1183
1184                 /*
1185                  * security_descriptor_dacl_del() may delete more
1186                  * then one entry subsequent to this one if the
1187                  * SID matches, but we only need to ensure that
1188                  * we stay looking at the same element in the array.
1189                  */
1190                 i--;
1191         }
1192         return NT_STATUS_OK;
1193 }
1194
1195 /* Search MS NFS style ACE with UNIX mode */
1196 static NTSTATUS check_ms_nfs(vfs_handle_struct *handle,
1197                              files_struct *fsp,
1198                              struct security_descriptor *psd,
1199                              mode_t *pmode,
1200                              bool *pdo_chmod)
1201 {
1202         uint32_t i;
1203         struct fruit_config_data *config = NULL;
1204
1205         *pdo_chmod = false;
1206
1207         SMB_VFS_HANDLE_GET_DATA(handle, config,
1208                                 struct fruit_config_data,
1209                                 return NT_STATUS_UNSUCCESSFUL);
1210
1211         if (!global_fruit_config.nego_aapl) {
1212                 return NT_STATUS_OK;
1213         }
1214         if (psd->dacl == NULL || !config->unix_info_enabled) {
1215                 return NT_STATUS_OK;
1216         }
1217
1218         for (i = 0; i < psd->dacl->num_aces; i++) {
1219                 if (dom_sid_compare_domain(
1220                             &global_sid_Unix_NFS_Mode,
1221                             &psd->dacl->aces[i].trustee) == 0) {
1222                         *pmode = (mode_t)psd->dacl->aces[i].trustee.sub_auths[2];
1223                         *pmode &= (S_IRWXU | S_IRWXG | S_IRWXO);
1224                         *pdo_chmod = true;
1225
1226                         DEBUG(10, ("MS NFS chmod request %s, %04o\n",
1227                                    fsp_str_dbg(fsp), (unsigned)(*pmode)));
1228                         break;
1229                 }
1230         }
1231
1232         /*
1233          * Remove any incoming virtual ACE entries generated by
1234          * fruit_fget_nt_acl().
1235          */
1236
1237         return remove_virtual_nfs_aces(psd);
1238 }
1239
1240 /****************************************************************************
1241  * VFS ops
1242  ****************************************************************************/
1243
1244 static int fruit_connect(vfs_handle_struct *handle,
1245                          const char *service,
1246                          const char *user)
1247 {
1248         int rc;
1249         char *list = NULL, *newlist = NULL;
1250         struct fruit_config_data *config;
1251         const struct loadparm_substitution *lp_sub =
1252                 loadparm_s3_global_substitution();
1253
1254         DEBUG(10, ("fruit_connect\n"));
1255
1256         rc = SMB_VFS_NEXT_CONNECT(handle, service, user);
1257         if (rc < 0) {
1258                 return rc;
1259         }
1260
1261         rc = init_fruit_config(handle);
1262         if (rc != 0) {
1263                 return rc;
1264         }
1265
1266         SMB_VFS_HANDLE_GET_DATA(handle, config,
1267                                 struct fruit_config_data, return -1);
1268
1269         if (config->veto_appledouble) {
1270                 list = lp_veto_files(talloc_tos(), lp_sub, SNUM(handle->conn));
1271
1272                 if (list) {
1273                         if (strstr(list, "/" ADOUBLE_NAME_PREFIX "*/") == NULL) {
1274                                 newlist = talloc_asprintf(
1275                                         list,
1276                                         "%s/" ADOUBLE_NAME_PREFIX "*/",
1277                                         list);
1278                                 lp_do_parameter(SNUM(handle->conn),
1279                                                 "veto files",
1280                                                 newlist);
1281                         }
1282                 } else {
1283                         lp_do_parameter(SNUM(handle->conn),
1284                                         "veto files",
1285                                         "/" ADOUBLE_NAME_PREFIX "*/");
1286                 }
1287
1288                 TALLOC_FREE(list);
1289         }
1290
1291         if (config->encoding == FRUIT_ENC_NATIVE) {
1292                 lp_do_parameter(SNUM(handle->conn),
1293                                 "catia:mappings",
1294                                 macos_string_replace_map);
1295         }
1296
1297         if (config->time_machine) {
1298                 DBG_NOTICE("Enabling durable handles for Time Machine "
1299                            "support on [%s]\n", service);
1300                 lp_do_parameter(SNUM(handle->conn), "durable handles", "yes");
1301                 lp_do_parameter(SNUM(handle->conn), "kernel oplocks", "no");
1302                 lp_do_parameter(SNUM(handle->conn), "kernel share modes", "no");
1303                 if (!lp_strict_sync(SNUM(handle->conn))) {
1304                         DBG_WARNING("Time Machine without strict sync is not "
1305                                     "recommended!\n");
1306                 }
1307                 lp_do_parameter(SNUM(handle->conn), "posix locking", "no");
1308         }
1309
1310         return rc;
1311 }
1312
1313 static int fruit_fake_fd(void)
1314 {
1315         int pipe_fds[2];
1316         int fd;
1317         int ret;
1318
1319         /*
1320          * Return a valid fd, but ensure any attempt to use it returns
1321          * an error (EPIPE). Once we get a write on the handle, we open
1322          * the real fd.
1323          */
1324         ret = pipe(pipe_fds);
1325         if (ret != 0) {
1326                 return -1;
1327         }
1328         fd = pipe_fds[0];
1329         close(pipe_fds[1]);
1330
1331         return fd;
1332 }
1333
1334 static int fruit_open_meta_stream(vfs_handle_struct *handle,
1335                                   struct smb_filename *smb_fname,
1336                                   files_struct *fsp,
1337                                   int flags,
1338                                   mode_t mode)
1339 {
1340         struct fruit_config_data *config = NULL;
1341         struct fio *fio = NULL;
1342         int open_flags = flags & ~O_CREAT;
1343         int fd;
1344
1345         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
1346
1347         SMB_VFS_HANDLE_GET_DATA(handle, config,
1348                                 struct fruit_config_data, return -1);
1349
1350         fio = VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
1351         fio->type = ADOUBLE_META;
1352         fio->config = config;
1353
1354         fd = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, open_flags, mode);
1355         if (fd != -1) {
1356                 return fd;
1357         }
1358
1359         if (!(flags & O_CREAT)) {
1360                 VFS_REMOVE_FSP_EXTENSION(handle, fsp);
1361                 return -1;
1362         }
1363
1364         fd = fruit_fake_fd();
1365         if (fd == -1) {
1366                 VFS_REMOVE_FSP_EXTENSION(handle, fsp);
1367                 return -1;
1368         }
1369
1370         fio->fake_fd = true;
1371         fio->flags = flags;
1372         fio->mode = mode;
1373
1374         return fd;
1375 }
1376
1377 static int fruit_open_meta_netatalk(vfs_handle_struct *handle,
1378                                     struct smb_filename *smb_fname,
1379                                     files_struct *fsp,
1380                                     int flags,
1381                                     mode_t mode)
1382 {
1383         struct fruit_config_data *config = NULL;
1384         struct fio *fio = NULL;
1385         struct adouble *ad = NULL;
1386         bool meta_exists = false;
1387         int fd;
1388
1389         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
1390
1391         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
1392         if (ad != NULL) {
1393                 meta_exists = true;
1394         }
1395
1396         TALLOC_FREE(ad);
1397
1398         if (!meta_exists && !(flags & O_CREAT)) {
1399                 errno = ENOENT;
1400                 return -1;
1401         }
1402
1403         fd = fruit_fake_fd();
1404         if (fd == -1) {
1405                 return -1;
1406         }
1407
1408         SMB_VFS_HANDLE_GET_DATA(handle, config,
1409                                 struct fruit_config_data, return -1);
1410
1411         fio = VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
1412         fio->type = ADOUBLE_META;
1413         fio->config = config;
1414         fio->fake_fd = true;
1415         fio->flags = flags;
1416         fio->mode = mode;
1417
1418         return fd;
1419 }
1420
1421 static int fruit_open_meta(vfs_handle_struct *handle,
1422                            struct smb_filename *smb_fname,
1423                            files_struct *fsp, int flags, mode_t mode)
1424 {
1425         int fd;
1426         struct fruit_config_data *config = NULL;
1427
1428         DBG_DEBUG("path [%s]\n", smb_fname_str_dbg(smb_fname));
1429
1430         SMB_VFS_HANDLE_GET_DATA(handle, config,
1431                                 struct fruit_config_data, return -1);
1432
1433         switch (config->meta) {
1434         case FRUIT_META_STREAM:
1435                 fd = fruit_open_meta_stream(handle, smb_fname,
1436                                             fsp, flags, mode);
1437                 break;
1438
1439         case FRUIT_META_NETATALK:
1440                 fd = fruit_open_meta_netatalk(handle, smb_fname,
1441                                               fsp, flags, mode);
1442                 break;
1443
1444         default:
1445                 DBG_ERR("Unexpected meta config [%d]\n", config->meta);
1446                 return -1;
1447         }
1448
1449         DBG_DEBUG("path [%s] fd [%d]\n", smb_fname_str_dbg(smb_fname), fd);
1450
1451         return fd;
1452 }
1453
1454 static int fruit_open_rsrc_adouble(vfs_handle_struct *handle,
1455                                    struct smb_filename *smb_fname,
1456                                    files_struct *fsp,
1457                                    int flags,
1458                                    mode_t mode)
1459 {
1460         int rc = 0;
1461         struct adouble *ad = NULL;
1462         struct smb_filename *smb_fname_base = NULL;
1463         struct fruit_config_data *config = NULL;
1464         int hostfd = -1;
1465
1466         SMB_VFS_HANDLE_GET_DATA(handle, config,
1467                                 struct fruit_config_data, return -1);
1468
1469         if ((!(flags & O_CREAT)) &&
1470             S_ISDIR(fsp->base_fsp->fsp_name->st.st_ex_mode))
1471         {
1472                 /* sorry, but directories don't habe a resource fork */
1473                 rc = -1;
1474                 goto exit;
1475         }
1476
1477         rc = adouble_path(talloc_tos(), smb_fname, &smb_fname_base);
1478         if (rc != 0) {
1479                 goto exit;
1480         }
1481
1482         /* We always need read/write access for the metadata header too */
1483         flags &= ~(O_RDONLY | O_WRONLY);
1484         flags |= O_RDWR;
1485
1486         hostfd = SMB_VFS_NEXT_OPEN(handle, smb_fname_base, fsp,
1487                                    flags, mode);
1488         if (hostfd == -1) {
1489                 rc = -1;
1490                 goto exit;
1491         }
1492
1493         if (flags & (O_CREAT | O_TRUNC)) {
1494                 ad = ad_init(fsp, ADOUBLE_RSRC);
1495                 if (ad == NULL) {
1496                         rc = -1;
1497                         goto exit;
1498                 }
1499
1500                 fsp->fh->fd = hostfd;
1501
1502                 rc = ad_fset(handle, ad, fsp);
1503                 fsp->fh->fd = -1;
1504                 if (rc != 0) {
1505                         rc = -1;
1506                         goto exit;
1507                 }
1508                 TALLOC_FREE(ad);
1509         }
1510
1511 exit:
1512
1513         TALLOC_FREE(smb_fname_base);
1514
1515         DEBUG(10, ("fruit_open resource fork: rc=%d, fd=%d\n", rc, hostfd));
1516         if (rc != 0) {
1517                 int saved_errno = errno;
1518                 if (hostfd >= 0) {
1519                         /*
1520                          * BUGBUGBUG -- we would need to call
1521                          * fd_close_posix here, but we don't have a
1522                          * full fsp yet
1523                          */
1524                         fsp->fh->fd = hostfd;
1525                         SMB_VFS_CLOSE(fsp);
1526                 }
1527                 hostfd = -1;
1528                 errno = saved_errno;
1529         }
1530         return hostfd;
1531 }
1532
1533 static int fruit_open_rsrc_xattr(vfs_handle_struct *handle,
1534                                  struct smb_filename *smb_fname,
1535                                  files_struct *fsp,
1536                                  int flags,
1537                                  mode_t mode)
1538 {
1539 #ifdef HAVE_ATTROPEN
1540         int fd = -1;
1541
1542         fd = attropen(smb_fname->base_name,
1543                       AFPRESOURCE_EA_NETATALK,
1544                       flags,
1545                       mode);
1546         if (fd == -1) {
1547                 return -1;
1548         }
1549
1550         return fd;
1551
1552 #else
1553         errno = ENOSYS;
1554         return -1;
1555 #endif
1556 }
1557
1558 static int fruit_open_rsrc(vfs_handle_struct *handle,
1559                            struct smb_filename *smb_fname,
1560                            files_struct *fsp, int flags, mode_t mode)
1561 {
1562         int fd;
1563         struct fruit_config_data *config = NULL;
1564         struct fio *fio = NULL;
1565
1566         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
1567
1568         SMB_VFS_HANDLE_GET_DATA(handle, config,
1569                                 struct fruit_config_data, return -1);
1570
1571         switch (config->rsrc) {
1572         case FRUIT_RSRC_STREAM:
1573                 fd = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
1574                 break;
1575
1576         case FRUIT_RSRC_ADFILE:
1577                 fd = fruit_open_rsrc_adouble(handle, smb_fname,
1578                                              fsp, flags, mode);
1579                 break;
1580
1581         case FRUIT_RSRC_XATTR:
1582                 fd = fruit_open_rsrc_xattr(handle, smb_fname,
1583                                            fsp, flags, mode);
1584                 break;
1585
1586         default:
1587                 DBG_ERR("Unexpected rsrc config [%d]\n", config->rsrc);
1588                 return -1;
1589         }
1590
1591         DBG_DEBUG("Path [%s] fd [%d]\n", smb_fname_str_dbg(smb_fname), fd);
1592
1593         if (fd == -1) {
1594                 return -1;
1595         }
1596
1597         fio = VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
1598         fio->type = ADOUBLE_RSRC;
1599         fio->config = config;
1600
1601         return fd;
1602 }
1603
1604 static int fruit_open(vfs_handle_struct *handle,
1605                       struct smb_filename *smb_fname,
1606                       files_struct *fsp, int flags, mode_t mode)
1607 {
1608         int fd;
1609
1610         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
1611
1612         if (!is_named_stream(smb_fname)) {
1613                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
1614         }
1615
1616         if (is_afpinfo_stream(smb_fname->stream_name)) {
1617                 fd = fruit_open_meta(handle, smb_fname, fsp, flags, mode);
1618         } else if (is_afpresource_stream(smb_fname->stream_name)) {
1619                 fd = fruit_open_rsrc(handle, smb_fname, fsp, flags, mode);
1620         } else {
1621                 fd = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
1622         }
1623
1624         DBG_DEBUG("Path [%s] fd [%d]\n", smb_fname_str_dbg(smb_fname), fd);
1625
1626         return fd;
1627 }
1628
1629 static int fruit_close_meta(vfs_handle_struct *handle,
1630                             files_struct *fsp)
1631 {
1632         int ret;
1633         struct fruit_config_data *config = NULL;
1634
1635         SMB_VFS_HANDLE_GET_DATA(handle, config,
1636                                 struct fruit_config_data, return -1);
1637
1638         switch (config->meta) {
1639         case FRUIT_META_STREAM:
1640                 ret = SMB_VFS_NEXT_CLOSE(handle, fsp);
1641                 break;
1642
1643         case FRUIT_META_NETATALK:
1644                 ret = close(fsp->fh->fd);
1645                 fsp->fh->fd = -1;
1646                 break;
1647
1648         default:
1649                 DBG_ERR("Unexpected meta config [%d]\n", config->meta);
1650                 return -1;
1651         }
1652
1653         return ret;
1654 }
1655
1656
1657 static int fruit_close_rsrc(vfs_handle_struct *handle,
1658                             files_struct *fsp)
1659 {
1660         int ret;
1661         struct fruit_config_data *config = NULL;
1662
1663         SMB_VFS_HANDLE_GET_DATA(handle, config,
1664                                 struct fruit_config_data, return -1);
1665
1666         switch (config->rsrc) {
1667         case FRUIT_RSRC_STREAM:
1668         case FRUIT_RSRC_ADFILE:
1669                 ret = SMB_VFS_NEXT_CLOSE(handle, fsp);
1670                 break;
1671
1672         case FRUIT_RSRC_XATTR:
1673                 ret = close(fsp->fh->fd);
1674                 fsp->fh->fd = -1;
1675                 break;
1676
1677         default:
1678                 DBG_ERR("Unexpected rsrc config [%d]\n", config->rsrc);
1679                 return -1;
1680         }
1681
1682         return ret;
1683 }
1684
1685 static int fruit_close(vfs_handle_struct *handle,
1686                        files_struct *fsp)
1687 {
1688         int ret;
1689         int fd;
1690
1691         fd = fsp->fh->fd;
1692
1693         DBG_DEBUG("Path [%s] fd [%d]\n", smb_fname_str_dbg(fsp->fsp_name), fd);
1694
1695         if (!is_named_stream(fsp->fsp_name)) {
1696                 return SMB_VFS_NEXT_CLOSE(handle, fsp);
1697         }
1698
1699         if (is_afpinfo_stream(fsp->fsp_name->stream_name)) {
1700                 ret = fruit_close_meta(handle, fsp);
1701         } else if (is_afpresource_stream(fsp->fsp_name->stream_name)) {
1702                 ret = fruit_close_rsrc(handle, fsp);
1703         } else {
1704                 ret = SMB_VFS_NEXT_CLOSE(handle, fsp);
1705         }
1706
1707         return ret;
1708 }
1709
1710 static int fruit_renameat(struct vfs_handle_struct *handle,
1711                         files_struct *srcfsp,
1712                         const struct smb_filename *smb_fname_src,
1713                         files_struct *dstfsp,
1714                         const struct smb_filename *smb_fname_dst)
1715 {
1716         int rc = -1;
1717         struct fruit_config_data *config = NULL;
1718         struct smb_filename *src_adp_smb_fname = NULL;
1719         struct smb_filename *dst_adp_smb_fname = NULL;
1720
1721         SMB_VFS_HANDLE_GET_DATA(handle, config,
1722                                 struct fruit_config_data, return -1);
1723
1724         if (!VALID_STAT(smb_fname_src->st)) {
1725                 DBG_ERR("Need valid stat for [%s]\n",
1726                         smb_fname_str_dbg(smb_fname_src));
1727                 return -1;
1728         }
1729
1730         rc = SMB_VFS_NEXT_RENAMEAT(handle,
1731                                 srcfsp,
1732                                 smb_fname_src,
1733                                 dstfsp,
1734                                 smb_fname_dst);
1735         if (rc != 0) {
1736                 return -1;
1737         }
1738
1739         if ((config->rsrc != FRUIT_RSRC_ADFILE) ||
1740             (!S_ISREG(smb_fname_src->st.st_ex_mode)))
1741         {
1742                 return 0;
1743         }
1744
1745         rc = adouble_path(talloc_tos(), smb_fname_src, &src_adp_smb_fname);
1746         if (rc != 0) {
1747                 goto done;
1748         }
1749
1750         rc = adouble_path(talloc_tos(), smb_fname_dst, &dst_adp_smb_fname);
1751         if (rc != 0) {
1752                 goto done;
1753         }
1754
1755         DBG_DEBUG("%s -> %s\n",
1756                   smb_fname_str_dbg(src_adp_smb_fname),
1757                   smb_fname_str_dbg(dst_adp_smb_fname));
1758
1759         rc = SMB_VFS_NEXT_RENAMEAT(handle,
1760                         srcfsp,
1761                         src_adp_smb_fname,
1762                         dstfsp,
1763                         dst_adp_smb_fname);
1764         if (errno == ENOENT) {
1765                 rc = 0;
1766         }
1767
1768 done:
1769         TALLOC_FREE(src_adp_smb_fname);
1770         TALLOC_FREE(dst_adp_smb_fname);
1771         return rc;
1772 }
1773
1774 static int fruit_unlink_meta_stream(vfs_handle_struct *handle,
1775                                 struct files_struct *dirfsp,
1776                                 const struct smb_filename *smb_fname)
1777 {
1778         return SMB_VFS_NEXT_UNLINKAT(handle,
1779                                 dirfsp,
1780                                 smb_fname,
1781                                 0);
1782 }
1783
1784 static int fruit_unlink_meta_netatalk(vfs_handle_struct *handle,
1785                                       const struct smb_filename *smb_fname)
1786 {
1787         return SMB_VFS_REMOVEXATTR(handle->conn,
1788                                    smb_fname,
1789                                    AFPINFO_EA_NETATALK);
1790 }
1791
1792 static int fruit_unlink_meta(vfs_handle_struct *handle,
1793                         struct files_struct *dirfsp,
1794                         const struct smb_filename *smb_fname)
1795 {
1796         struct fruit_config_data *config = NULL;
1797         int rc;
1798
1799         SMB_VFS_HANDLE_GET_DATA(handle, config,
1800                                 struct fruit_config_data, return -1);
1801
1802         switch (config->meta) {
1803         case FRUIT_META_STREAM:
1804                 rc = fruit_unlink_meta_stream(handle,
1805                                 dirfsp,
1806                                 smb_fname);
1807                 break;
1808
1809         case FRUIT_META_NETATALK:
1810                 rc = fruit_unlink_meta_netatalk(handle, smb_fname);
1811                 break;
1812
1813         default:
1814                 DBG_ERR("Unsupported meta config [%d]\n", config->meta);
1815                 return -1;
1816         }
1817
1818         return rc;
1819 }
1820
1821 static int fruit_unlink_rsrc_stream(vfs_handle_struct *handle,
1822                                 struct files_struct *dirfsp,
1823                                 const struct smb_filename *smb_fname,
1824                                 bool force_unlink)
1825 {
1826         int ret;
1827
1828         if (!force_unlink) {
1829                 struct smb_filename *smb_fname_cp = NULL;
1830                 off_t size;
1831
1832                 smb_fname_cp = cp_smb_filename(talloc_tos(), smb_fname);
1833                 if (smb_fname_cp == NULL) {
1834                         return -1;
1835                 }
1836
1837                 /*
1838                  * 0 byte resource fork streams are not listed by
1839                  * vfs_streaminfo, as a result stream cleanup/deletion of file
1840                  * deletion doesn't remove the resourcefork stream.
1841                  */
1842
1843                 ret = SMB_VFS_NEXT_STAT(handle, smb_fname_cp);
1844                 if (ret != 0) {
1845                         TALLOC_FREE(smb_fname_cp);
1846                         DBG_ERR("stat [%s] failed [%s]\n",
1847                                 smb_fname_str_dbg(smb_fname_cp), strerror(errno));
1848                         return -1;
1849                 }
1850
1851                 size = smb_fname_cp->st.st_ex_size;
1852                 TALLOC_FREE(smb_fname_cp);
1853
1854                 if (size > 0) {
1855                         /* OS X ignores resource fork stream delete requests */
1856                         return 0;
1857                 }
1858         }
1859
1860         ret = SMB_VFS_NEXT_UNLINKAT(handle,
1861                         dirfsp,
1862                         smb_fname,
1863                         0);
1864         if ((ret != 0) && (errno == ENOENT) && force_unlink) {
1865                 ret = 0;
1866         }
1867
1868         return ret;
1869 }
1870
1871 static int fruit_unlink_rsrc_adouble(vfs_handle_struct *handle,
1872                                 struct files_struct *dirfsp,
1873                                 const struct smb_filename *smb_fname,
1874                                 bool force_unlink)
1875 {
1876         int rc;
1877         struct adouble *ad = NULL;
1878         struct smb_filename *adp_smb_fname = NULL;
1879
1880         if (!force_unlink) {
1881                 ad = ad_get(talloc_tos(), handle, smb_fname,
1882                             ADOUBLE_RSRC);
1883                 if (ad == NULL) {
1884                         errno = ENOENT;
1885                         return -1;
1886                 }
1887
1888
1889                 /*
1890                  * 0 byte resource fork streams are not listed by
1891                  * vfs_streaminfo, as a result stream cleanup/deletion of file
1892                  * deletion doesn't remove the resourcefork stream.
1893                  */
1894
1895                 if (ad_getentrylen(ad, ADEID_RFORK) > 0) {
1896                         /* OS X ignores resource fork stream delete requests */
1897                         TALLOC_FREE(ad);
1898                         return 0;
1899                 }
1900
1901                 TALLOC_FREE(ad);
1902         }
1903
1904         rc = adouble_path(talloc_tos(), smb_fname, &adp_smb_fname);
1905         if (rc != 0) {
1906                 return -1;
1907         }
1908
1909         rc = SMB_VFS_NEXT_UNLINKAT(handle,
1910                         dirfsp,
1911                         adp_smb_fname,
1912                         0);
1913         TALLOC_FREE(adp_smb_fname);
1914         if ((rc != 0) && (errno == ENOENT) && force_unlink) {
1915                 rc = 0;
1916         }
1917
1918         return rc;
1919 }
1920
1921 static int fruit_unlink_rsrc_xattr(vfs_handle_struct *handle,
1922                                    const struct smb_filename *smb_fname,
1923                                    bool force_unlink)
1924 {
1925         /*
1926          * OS X ignores resource fork stream delete requests, so nothing to do
1927          * here. Removing the file will remove the xattr anyway, so we don't
1928          * have to take care of removing 0 byte resource forks that could be
1929          * left behind.
1930          */
1931         return 0;
1932 }
1933
1934 static int fruit_unlink_rsrc(vfs_handle_struct *handle,
1935                         struct files_struct *dirfsp,
1936                         const struct smb_filename *smb_fname,
1937                         bool force_unlink)
1938 {
1939         struct fruit_config_data *config = NULL;
1940         int rc;
1941
1942         SMB_VFS_HANDLE_GET_DATA(handle, config,
1943                                 struct fruit_config_data, return -1);
1944
1945         switch (config->rsrc) {
1946         case FRUIT_RSRC_STREAM:
1947                 rc = fruit_unlink_rsrc_stream(handle,
1948                                 dirfsp,
1949                                 smb_fname,
1950                                 force_unlink);
1951                 break;
1952
1953         case FRUIT_RSRC_ADFILE:
1954                 rc = fruit_unlink_rsrc_adouble(handle,
1955                                 dirfsp,
1956                                 smb_fname,
1957                                 force_unlink);
1958                 break;
1959
1960         case FRUIT_RSRC_XATTR:
1961                 rc = fruit_unlink_rsrc_xattr(handle, smb_fname, force_unlink);
1962                 break;
1963
1964         default:
1965                 DBG_ERR("Unsupported rsrc config [%d]\n", config->rsrc);
1966                 return -1;
1967         }
1968
1969         return rc;
1970 }
1971
1972 static int fruit_chmod(vfs_handle_struct *handle,
1973                        const struct smb_filename *smb_fname,
1974                        mode_t mode)
1975 {
1976         int rc = -1;
1977         struct fruit_config_data *config = NULL;
1978         struct smb_filename *smb_fname_adp = NULL;
1979
1980         rc = SMB_VFS_NEXT_CHMOD(handle, smb_fname, mode);
1981         if (rc != 0) {
1982                 return rc;
1983         }
1984
1985         SMB_VFS_HANDLE_GET_DATA(handle, config,
1986                                 struct fruit_config_data, return -1);
1987
1988         if (config->rsrc != FRUIT_RSRC_ADFILE) {
1989                 return 0;
1990         }
1991
1992         if (!VALID_STAT(smb_fname->st)) {
1993                 return 0;
1994         }
1995
1996         if (!S_ISREG(smb_fname->st.st_ex_mode)) {
1997                 return 0;
1998         }
1999
2000         rc = adouble_path(talloc_tos(), smb_fname, &smb_fname_adp);
2001         if (rc != 0) {
2002                 return -1;
2003         }
2004
2005         DEBUG(10, ("fruit_chmod: %s\n", smb_fname_adp->base_name));
2006
2007         rc = SMB_VFS_NEXT_CHMOD(handle, smb_fname_adp, mode);
2008         if (errno == ENOENT) {
2009                 rc = 0;
2010         }
2011
2012         TALLOC_FREE(smb_fname_adp);
2013         return rc;
2014 }
2015
2016 static int fruit_unlinkat(vfs_handle_struct *handle,
2017                         struct files_struct *dirfsp,
2018                         const struct smb_filename *smb_fname,
2019                         int flags)
2020 {
2021         struct fruit_config_data *config = NULL;
2022         struct smb_filename *rsrc_smb_fname = NULL;
2023         int ret;
2024
2025         SMB_ASSERT(dirfsp == dirfsp->conn->cwd_fsp);
2026
2027         if (flags & AT_REMOVEDIR) {
2028                 return SMB_VFS_NEXT_UNLINKAT(handle,
2029                                              dirfsp,
2030                                              smb_fname,
2031                                              AT_REMOVEDIR);
2032         }
2033
2034         SMB_VFS_HANDLE_GET_DATA(handle, config,
2035                                 struct fruit_config_data, return -1);
2036
2037         if (is_afpinfo_stream(smb_fname->stream_name)) {
2038                 return fruit_unlink_meta(handle,
2039                                 dirfsp,
2040                                 smb_fname);
2041         } else if (is_afpresource_stream(smb_fname->stream_name)) {
2042                 return fruit_unlink_rsrc(handle,
2043                                 dirfsp,
2044                                 smb_fname,
2045                                 false);
2046         } else if (is_named_stream(smb_fname)) {
2047                 return SMB_VFS_NEXT_UNLINKAT(handle,
2048                                 dirfsp,
2049                                 smb_fname,
2050                                 0);
2051         } else if (is_adouble_file(smb_fname->base_name)) {
2052                 return SMB_VFS_NEXT_UNLINKAT(handle,
2053                                 dirfsp,
2054                                 smb_fname,
2055                                 0);
2056         }
2057
2058         /*
2059          * A request to delete the base file. Because 0 byte resource
2060          * fork streams are not listed by fruit_streaminfo,
2061          * delete_all_streams() can't remove 0 byte resource fork
2062          * streams, so we have to cleanup this here.
2063          */
2064         rsrc_smb_fname = synthetic_smb_fname(talloc_tos(),
2065                                              smb_fname->base_name,
2066                                              AFPRESOURCE_STREAM_NAME,
2067                                              NULL,
2068                                              smb_fname->flags);
2069         if (rsrc_smb_fname == NULL) {
2070                 return -1;
2071         }
2072
2073         ret = fruit_unlink_rsrc(handle, dirfsp, rsrc_smb_fname, true);
2074         if ((ret != 0) && (errno != ENOENT)) {
2075                 DBG_ERR("Forced unlink of [%s] failed [%s]\n",
2076                         smb_fname_str_dbg(rsrc_smb_fname), strerror(errno));
2077                 TALLOC_FREE(rsrc_smb_fname);
2078                 return -1;
2079         }
2080         TALLOC_FREE(rsrc_smb_fname);
2081
2082         return SMB_VFS_NEXT_UNLINKAT(handle,
2083                         dirfsp,
2084                         smb_fname,
2085                         0);
2086 }
2087
2088 static ssize_t fruit_pread_meta_stream(vfs_handle_struct *handle,
2089                                        files_struct *fsp, void *data,
2090                                        size_t n, off_t offset)
2091 {
2092         ssize_t nread;
2093         int ret;
2094
2095         nread = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
2096         if (nread == -1 || nread == n) {
2097                 return nread;
2098         }
2099
2100         DBG_ERR("Removing [%s] after short read [%zd]\n",
2101                 fsp_str_dbg(fsp), nread);
2102
2103         ret = SMB_VFS_NEXT_UNLINKAT(handle,
2104                         fsp->conn->cwd_fsp,
2105                         fsp->fsp_name,
2106                         0);
2107         if (ret != 0) {
2108                 DBG_ERR("Removing [%s] failed\n", fsp_str_dbg(fsp));
2109                 return -1;
2110         }
2111
2112         errno = EINVAL;
2113         return -1;
2114 }
2115
2116 static ssize_t fruit_pread_meta_adouble(vfs_handle_struct *handle,
2117                                         files_struct *fsp, void *data,
2118                                         size_t n, off_t offset)
2119 {
2120         AfpInfo *ai = NULL;
2121         struct adouble *ad = NULL;
2122         char afpinfo_buf[AFP_INFO_SIZE];
2123         char *p = NULL;
2124         ssize_t nread;
2125
2126         ai = afpinfo_new(talloc_tos());
2127         if (ai == NULL) {
2128                 return -1;
2129         }
2130
2131         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_META);
2132         if (ad == NULL) {
2133                 nread = -1;
2134                 goto fail;
2135         }
2136
2137         p = ad_get_entry(ad, ADEID_FINDERI);
2138         if (p == NULL) {
2139                 DBG_ERR("No ADEID_FINDERI for [%s]\n", fsp_str_dbg(fsp));
2140                 nread = -1;
2141                 goto fail;
2142         }
2143
2144         memcpy(&ai->afpi_FinderInfo[0], p, ADEDLEN_FINDERI);
2145
2146         nread = afpinfo_pack(ai, afpinfo_buf);
2147         if (nread != AFP_INFO_SIZE) {
2148                 nread = -1;
2149                 goto fail;
2150         }
2151
2152         memcpy(data, afpinfo_buf, n);
2153         nread = n;
2154
2155 fail:
2156         TALLOC_FREE(ai);
2157         return nread;
2158 }
2159
2160 static ssize_t fruit_pread_meta(vfs_handle_struct *handle,
2161                                 files_struct *fsp, void *data,
2162                                 size_t n, off_t offset)
2163 {
2164         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
2165         ssize_t nread;
2166         ssize_t to_return;
2167
2168         /*
2169          * OS X has a off-by-1 error in the offset calculation, so we're
2170          * bug compatible here. It won't hurt, as any relevant real
2171          * world read requests from the AFP_AfpInfo stream will be
2172          * offset=0 n=60. offset is ignored anyway, see below.
2173          */
2174         if ((offset < 0) || (offset >= AFP_INFO_SIZE + 1)) {
2175                 return 0;
2176         }
2177
2178         if (fio == NULL) {
2179                 DBG_ERR("Failed to fetch fsp extension");
2180                 return -1;
2181         }
2182
2183         /* Yes, macOS always reads from offset 0 */
2184         offset = 0;
2185         to_return = MIN(n, AFP_INFO_SIZE);
2186
2187         switch (fio->config->meta) {
2188         case FRUIT_META_STREAM:
2189                 nread = fruit_pread_meta_stream(handle, fsp, data,
2190                                                 to_return, offset);
2191                 break;
2192
2193         case FRUIT_META_NETATALK:
2194                 nread = fruit_pread_meta_adouble(handle, fsp, data,
2195                                                  to_return, offset);
2196                 break;
2197
2198         default:
2199                 DBG_ERR("Unexpected meta config [%d]\n", fio->config->meta);
2200                 return -1;
2201         }
2202
2203         if (nread == -1 && fio->created) {
2204                 AfpInfo *ai = NULL;
2205                 char afpinfo_buf[AFP_INFO_SIZE];
2206
2207                 ai = afpinfo_new(talloc_tos());
2208                 if (ai == NULL) {
2209                         return -1;
2210                 }
2211
2212                 nread = afpinfo_pack(ai, afpinfo_buf);
2213                 TALLOC_FREE(ai);
2214                 if (nread != AFP_INFO_SIZE) {
2215                         return -1;
2216                 }
2217
2218                 memcpy(data, afpinfo_buf, to_return);
2219                 return to_return;
2220         }
2221
2222         return nread;
2223 }
2224
2225 static ssize_t fruit_pread_rsrc_stream(vfs_handle_struct *handle,
2226                                        files_struct *fsp, void *data,
2227                                        size_t n, off_t offset)
2228 {
2229         return SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
2230 }
2231
2232 static ssize_t fruit_pread_rsrc_xattr(vfs_handle_struct *handle,
2233                                       files_struct *fsp, void *data,
2234                                       size_t n, off_t offset)
2235 {
2236         return SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
2237 }
2238
2239 static ssize_t fruit_pread_rsrc_adouble(vfs_handle_struct *handle,
2240                                         files_struct *fsp, void *data,
2241                                         size_t n, off_t offset)
2242 {
2243         struct adouble *ad = NULL;
2244         ssize_t nread;
2245
2246         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_RSRC);
2247         if (ad == NULL) {
2248                 return -1;
2249         }
2250
2251         nread = SMB_VFS_NEXT_PREAD(handle, fsp, data, n,
2252                                    offset + ad_getentryoff(ad, ADEID_RFORK));
2253
2254         TALLOC_FREE(ad);
2255         return nread;
2256 }
2257
2258 static ssize_t fruit_pread_rsrc(vfs_handle_struct *handle,
2259                                 files_struct *fsp, void *data,
2260                                 size_t n, off_t offset)
2261 {
2262         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
2263         ssize_t nread;
2264
2265         if (fio == NULL) {
2266                 errno = EINVAL;
2267                 return -1;
2268         }
2269
2270         switch (fio->config->rsrc) {
2271         case FRUIT_RSRC_STREAM:
2272                 nread = fruit_pread_rsrc_stream(handle, fsp, data, n, offset);
2273                 break;
2274
2275         case FRUIT_RSRC_ADFILE:
2276                 nread = fruit_pread_rsrc_adouble(handle, fsp, data, n, offset);
2277                 break;
2278
2279         case FRUIT_RSRC_XATTR:
2280                 nread = fruit_pread_rsrc_xattr(handle, fsp, data, n, offset);
2281                 break;
2282
2283         default:
2284                 DBG_ERR("Unexpected rsrc config [%d]\n", fio->config->rsrc);
2285                 return -1;
2286         }
2287
2288         return nread;
2289 }
2290
2291 static ssize_t fruit_pread(vfs_handle_struct *handle,
2292                            files_struct *fsp, void *data,
2293                            size_t n, off_t offset)
2294 {
2295         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
2296         ssize_t nread;
2297
2298         DBG_DEBUG("Path [%s] offset=%"PRIdMAX", size=%zd\n",
2299                   fsp_str_dbg(fsp), (intmax_t)offset, n);
2300
2301         if (fio == NULL) {
2302                 return SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
2303         }
2304
2305         if (fio->type == ADOUBLE_META) {
2306                 nread = fruit_pread_meta(handle, fsp, data, n, offset);
2307         } else {
2308                 nread = fruit_pread_rsrc(handle, fsp, data, n, offset);
2309         }
2310
2311         DBG_DEBUG("Path [%s] nread [%zd]\n", fsp_str_dbg(fsp), nread);
2312         return nread;
2313 }
2314
2315 static bool fruit_must_handle_aio_stream(struct fio *fio)
2316 {
2317         if (fio == NULL) {
2318                 return false;
2319         };
2320
2321         if (fio->type == ADOUBLE_META) {
2322                 return true;
2323         }
2324
2325         if ((fio->type == ADOUBLE_RSRC) &&
2326             (fio->config->rsrc == FRUIT_RSRC_ADFILE))
2327         {
2328                 return true;
2329         }
2330
2331         return false;
2332 }
2333
2334 struct fruit_pread_state {
2335         ssize_t nread;
2336         struct vfs_aio_state vfs_aio_state;
2337 };
2338
2339 static void fruit_pread_done(struct tevent_req *subreq);
2340
2341 static struct tevent_req *fruit_pread_send(
2342         struct vfs_handle_struct *handle,
2343         TALLOC_CTX *mem_ctx,
2344         struct tevent_context *ev,
2345         struct files_struct *fsp,
2346         void *data,
2347         size_t n, off_t offset)
2348 {
2349         struct tevent_req *req = NULL;
2350         struct tevent_req *subreq = NULL;
2351         struct fruit_pread_state *state = NULL;
2352         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
2353
2354         req = tevent_req_create(mem_ctx, &state,
2355                                 struct fruit_pread_state);
2356         if (req == NULL) {
2357                 return NULL;
2358         }
2359
2360         if (fruit_must_handle_aio_stream(fio)) {
2361                 state->nread = SMB_VFS_PREAD(fsp, data, n, offset);
2362                 if (state->nread != n) {
2363                         if (state->nread != -1) {
2364                                 errno = EIO;
2365                         }
2366                         tevent_req_error(req, errno);
2367                         return tevent_req_post(req, ev);
2368                 }
2369                 tevent_req_done(req);
2370                 return tevent_req_post(req, ev);
2371         }
2372
2373         subreq = SMB_VFS_NEXT_PREAD_SEND(state, ev, handle, fsp,
2374                                          data, n, offset);
2375         if (tevent_req_nomem(req, subreq)) {
2376                 return tevent_req_post(req, ev);
2377         }
2378         tevent_req_set_callback(subreq, fruit_pread_done, req);
2379         return req;
2380 }
2381
2382 static void fruit_pread_done(struct tevent_req *subreq)
2383 {
2384         struct tevent_req *req = tevent_req_callback_data(
2385                 subreq, struct tevent_req);
2386         struct fruit_pread_state *state = tevent_req_data(
2387                 req, struct fruit_pread_state);
2388
2389         state->nread = SMB_VFS_PREAD_RECV(subreq, &state->vfs_aio_state);
2390         TALLOC_FREE(subreq);
2391
2392         if (tevent_req_error(req, state->vfs_aio_state.error)) {
2393                 return;
2394         }
2395         tevent_req_done(req);
2396 }
2397
2398 static ssize_t fruit_pread_recv(struct tevent_req *req,
2399                                         struct vfs_aio_state *vfs_aio_state)
2400 {
2401         struct fruit_pread_state *state = tevent_req_data(
2402                 req, struct fruit_pread_state);
2403
2404         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
2405                 return -1;
2406         }
2407
2408         *vfs_aio_state = state->vfs_aio_state;
2409         return state->nread;
2410 }
2411
2412 static ssize_t fruit_pwrite_meta_stream(vfs_handle_struct *handle,
2413                                         files_struct *fsp, const void *data,
2414                                         size_t n, off_t offset)
2415 {
2416         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
2417         AfpInfo *ai = NULL;
2418         size_t nwritten;
2419         int ret;
2420         bool ok;
2421
2422         DBG_DEBUG("Path [%s] offset=%"PRIdMAX", size=%zd\n",
2423                   fsp_str_dbg(fsp), (intmax_t)offset, n);
2424
2425         if (fio == NULL) {
2426                 return -1;
2427         }
2428
2429         if (fio->fake_fd) {
2430                 int fd;
2431
2432                 ret = SMB_VFS_NEXT_CLOSE(handle, fsp);
2433                 if (ret != 0) {
2434                         DBG_ERR("Close [%s] failed: %s\n",
2435                                 fsp_str_dbg(fsp), strerror(errno));
2436                         fsp->fh->fd = -1;
2437                         return -1;
2438                 }
2439
2440                 fd = SMB_VFS_NEXT_OPEN(handle,
2441                                        fsp->fsp_name,
2442                                        fsp,
2443                                        fio->flags,
2444                                        fio->mode);
2445                 if (fd == -1) {
2446                         DBG_ERR("On-demand create [%s] in write failed: %s\n",
2447                                 fsp_str_dbg(fsp), strerror(errno));
2448                         return -1;
2449                 }
2450                 fsp->fh->fd = fd;
2451                 fio->fake_fd = false;
2452         }
2453
2454         ai = afpinfo_unpack(talloc_tos(), data);
2455         if (ai == NULL) {
2456                 return -1;
2457         }
2458
2459         if (ai_empty_finderinfo(ai)) {
2460                 /*
2461                  * Writing an all 0 blob to the metadata stream results in the
2462                  * stream being removed on a macOS server. This ensures we
2463                  * behave the same and it verified by the "delete AFP_AfpInfo by
2464                  * writing all 0" test.
2465                  */
2466                 ret = SMB_VFS_NEXT_FTRUNCATE(handle, fsp, 0);
2467                 if (ret != 0) {
2468                         DBG_ERR("SMB_VFS_NEXT_FTRUNCATE on [%s] failed\n",
2469                                 fsp_str_dbg(fsp));
2470                         return -1;
2471                 }
2472
2473                 ok = set_delete_on_close(
2474                         fsp,
2475                         true,
2476                         handle->conn->session_info->security_token,
2477                         handle->conn->session_info->unix_token);
2478                 if (!ok) {
2479                         DBG_ERR("set_delete_on_close on [%s] failed\n",
2480                                 fsp_str_dbg(fsp));
2481                         return -1;
2482                 }
2483                 return n;
2484         }
2485
2486         nwritten = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2487         if (nwritten != n) {
2488                 return -1;
2489         }
2490
2491         return n;
2492 }
2493
2494 static ssize_t fruit_pwrite_meta_netatalk(vfs_handle_struct *handle,
2495                                           files_struct *fsp, const void *data,
2496                                           size_t n, off_t offset)
2497 {
2498         struct adouble *ad = NULL;
2499         AfpInfo *ai = NULL;
2500         char *p = NULL;
2501         int ret;
2502         bool ok;
2503
2504         ai = afpinfo_unpack(talloc_tos(), data);
2505         if (ai == NULL) {
2506                 return -1;
2507         }
2508
2509         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_META);
2510         if (ad == NULL) {
2511                 ad = ad_init(talloc_tos(), ADOUBLE_META);
2512                 if (ad == NULL) {
2513                         return -1;
2514                 }
2515         }
2516         p = ad_get_entry(ad, ADEID_FINDERI);
2517         if (p == NULL) {
2518                 DBG_ERR("No ADEID_FINDERI for [%s]\n", fsp_str_dbg(fsp));
2519                 TALLOC_FREE(ad);
2520                 return -1;
2521         }
2522
2523         memcpy(p, &ai->afpi_FinderInfo[0], ADEDLEN_FINDERI);
2524
2525         ret = ad_fset(handle, ad, fsp);
2526         if (ret != 0) {
2527                 DBG_ERR("ad_pwrite [%s] failed\n", fsp_str_dbg(fsp));
2528                 TALLOC_FREE(ad);
2529                 return -1;
2530         }
2531
2532         TALLOC_FREE(ad);
2533
2534         if (!ai_empty_finderinfo(ai)) {
2535                 return n;
2536         }
2537
2538         /*
2539          * Writing an all 0 blob to the metadata stream results in the stream
2540          * being removed on a macOS server. This ensures we behave the same and
2541          * it verified by the "delete AFP_AfpInfo by writing all 0" test.
2542          */
2543
2544         ok = set_delete_on_close(
2545                 fsp,
2546                 true,
2547                 handle->conn->session_info->security_token,
2548                 handle->conn->session_info->unix_token);
2549         if (!ok) {
2550                 DBG_ERR("set_delete_on_close on [%s] failed\n",
2551                         fsp_str_dbg(fsp));
2552                 return -1;
2553         }
2554
2555         return n;
2556 }
2557
2558 static ssize_t fruit_pwrite_meta(vfs_handle_struct *handle,
2559                                  files_struct *fsp, const void *data,
2560                                  size_t n, off_t offset)
2561 {
2562         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
2563         ssize_t nwritten;
2564         uint8_t buf[AFP_INFO_SIZE];
2565         size_t to_write;
2566         size_t to_copy;
2567         int cmp;
2568
2569         if (fio == NULL) {
2570                 DBG_ERR("Failed to fetch fsp extension");
2571                 return -1;
2572         }
2573
2574         if (n < 3) {
2575                 errno = EINVAL;
2576                 return -1;
2577         }
2578
2579         if (offset != 0 && n < 60) {
2580                 errno = EINVAL;
2581                 return -1;
2582         }
2583
2584         cmp = memcmp(data, "AFP", 3);
2585         if (cmp != 0) {
2586                 errno = EINVAL;
2587                 return -1;
2588         }
2589
2590         if (n <= AFP_OFF_FinderInfo) {
2591                 /*
2592                  * Nothing to do here really, just return
2593                  */
2594                 return n;
2595         }
2596
2597         offset = 0;
2598
2599         to_copy = n;
2600         if (to_copy > AFP_INFO_SIZE) {
2601                 to_copy = AFP_INFO_SIZE;
2602         }
2603         memcpy(buf, data, to_copy);
2604
2605         to_write = n;
2606         if (to_write != AFP_INFO_SIZE) {
2607                 to_write = AFP_INFO_SIZE;
2608         }
2609
2610         switch (fio->config->meta) {
2611         case FRUIT_META_STREAM:
2612                 nwritten = fruit_pwrite_meta_stream(handle,
2613                                                     fsp,
2614                                                     buf,
2615                                                     to_write,
2616                                                     offset);
2617                 break;
2618
2619         case FRUIT_META_NETATALK:
2620                 nwritten = fruit_pwrite_meta_netatalk(handle,
2621                                                       fsp,
2622                                                       buf,
2623                                                       to_write,
2624                                                       offset);
2625                 break;
2626
2627         default:
2628                 DBG_ERR("Unexpected meta config [%d]\n", fio->config->meta);
2629                 return -1;
2630         }
2631
2632         if (nwritten != to_write) {
2633                 return -1;
2634         }
2635
2636         /*
2637          * Return the requested amount, verified against macOS SMB server
2638          */
2639         return n;
2640 }
2641
2642 static ssize_t fruit_pwrite_rsrc_stream(vfs_handle_struct *handle,
2643                                         files_struct *fsp, const void *data,
2644                                         size_t n, off_t offset)
2645 {
2646         return SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2647 }
2648
2649 static ssize_t fruit_pwrite_rsrc_xattr(vfs_handle_struct *handle,
2650                                        files_struct *fsp, const void *data,
2651                                        size_t n, off_t offset)
2652 {
2653         return SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2654 }
2655
2656 static ssize_t fruit_pwrite_rsrc_adouble(vfs_handle_struct *handle,
2657                                          files_struct *fsp, const void *data,
2658                                          size_t n, off_t offset)
2659 {
2660         struct adouble *ad = NULL;
2661         ssize_t nwritten;
2662         int ret;
2663
2664         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_RSRC);
2665         if (ad == NULL) {
2666                 DBG_ERR("ad_get [%s] failed\n", fsp_str_dbg(fsp));
2667                 return -1;
2668         }
2669
2670         nwritten = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n,
2671                                        offset + ad_getentryoff(ad, ADEID_RFORK));
2672         if (nwritten != n) {
2673                 DBG_ERR("Short write on [%s] [%zd/%zd]\n",
2674                         fsp_str_dbg(fsp), nwritten, n);
2675                 TALLOC_FREE(ad);
2676                 return -1;
2677         }
2678
2679         if ((n + offset) > ad_getentrylen(ad, ADEID_RFORK)) {
2680                 ad_setentrylen(ad, ADEID_RFORK, n + offset);
2681                 ret = ad_fset(handle, ad, fsp);
2682                 if (ret != 0) {
2683                         DBG_ERR("ad_pwrite [%s] failed\n", fsp_str_dbg(fsp));
2684                         TALLOC_FREE(ad);
2685                         return -1;
2686                 }
2687         }
2688
2689         TALLOC_FREE(ad);
2690         return n;
2691 }
2692
2693 static ssize_t fruit_pwrite_rsrc(vfs_handle_struct *handle,
2694                                  files_struct *fsp, const void *data,
2695                                  size_t n, off_t offset)
2696 {
2697         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
2698         ssize_t nwritten;
2699
2700         if (fio == NULL) {
2701                 DBG_ERR("Failed to fetch fsp extension");
2702                 return -1;
2703         }
2704
2705         switch (fio->config->rsrc) {
2706         case FRUIT_RSRC_STREAM:
2707                 nwritten = fruit_pwrite_rsrc_stream(handle, fsp, data, n, offset);
2708                 break;
2709
2710         case FRUIT_RSRC_ADFILE:
2711                 nwritten = fruit_pwrite_rsrc_adouble(handle, fsp, data, n, offset);
2712                 break;
2713
2714         case FRUIT_RSRC_XATTR:
2715                 nwritten = fruit_pwrite_rsrc_xattr(handle, fsp, data, n, offset);
2716                 break;
2717
2718         default:
2719                 DBG_ERR("Unexpected rsrc config [%d]\n", fio->config->rsrc);
2720                 return -1;
2721         }
2722
2723         return nwritten;
2724 }
2725
2726 static ssize_t fruit_pwrite(vfs_handle_struct *handle,
2727                             files_struct *fsp, const void *data,
2728                             size_t n, off_t offset)
2729 {
2730         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
2731         ssize_t nwritten;
2732
2733         DBG_DEBUG("Path [%s] offset=%"PRIdMAX", size=%zd\n",
2734                   fsp_str_dbg(fsp), (intmax_t)offset, n);
2735
2736         if (fio == NULL) {
2737                 return SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2738         }
2739
2740         if (fio->type == ADOUBLE_META) {
2741                 nwritten = fruit_pwrite_meta(handle, fsp, data, n, offset);
2742         } else {
2743                 nwritten = fruit_pwrite_rsrc(handle, fsp, data, n, offset);
2744         }
2745
2746         DBG_DEBUG("Path [%s] nwritten=%zd\n", fsp_str_dbg(fsp), nwritten);
2747         return nwritten;
2748 }
2749
2750 struct fruit_pwrite_state {
2751         ssize_t nwritten;
2752         struct vfs_aio_state vfs_aio_state;
2753 };
2754
2755 static void fruit_pwrite_done(struct tevent_req *subreq);
2756
2757 static struct tevent_req *fruit_pwrite_send(
2758         struct vfs_handle_struct *handle,
2759         TALLOC_CTX *mem_ctx,
2760         struct tevent_context *ev,
2761         struct files_struct *fsp,
2762         const void *data,
2763         size_t n, off_t offset)
2764 {
2765         struct tevent_req *req = NULL;
2766         struct tevent_req *subreq = NULL;
2767         struct fruit_pwrite_state *state = NULL;
2768         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
2769
2770         req = tevent_req_create(mem_ctx, &state,
2771                                 struct fruit_pwrite_state);
2772         if (req == NULL) {
2773                 return NULL;
2774         }
2775
2776         if (fruit_must_handle_aio_stream(fio)) {
2777                 state->nwritten = SMB_VFS_PWRITE(fsp, data, n, offset);
2778                 if (state->nwritten != n) {
2779                         if (state->nwritten != -1) {
2780                                 errno = EIO;
2781                         }
2782                         tevent_req_error(req, errno);
2783                         return tevent_req_post(req, ev);
2784                 }
2785                 tevent_req_done(req);
2786                 return tevent_req_post(req, ev);
2787         }
2788
2789         subreq = SMB_VFS_NEXT_PWRITE_SEND(state, ev, handle, fsp,
2790                                           data, n, offset);
2791         if (tevent_req_nomem(req, subreq)) {
2792                 return tevent_req_post(req, ev);
2793         }
2794         tevent_req_set_callback(subreq, fruit_pwrite_done, req);
2795         return req;
2796 }
2797
2798 static void fruit_pwrite_done(struct tevent_req *subreq)
2799 {
2800         struct tevent_req *req = tevent_req_callback_data(
2801                 subreq, struct tevent_req);
2802         struct fruit_pwrite_state *state = tevent_req_data(
2803                 req, struct fruit_pwrite_state);
2804
2805         state->nwritten = SMB_VFS_PWRITE_RECV(subreq, &state->vfs_aio_state);
2806         TALLOC_FREE(subreq);
2807
2808         if (tevent_req_error(req, state->vfs_aio_state.error)) {
2809                 return;
2810         }
2811         tevent_req_done(req);
2812 }
2813
2814 static ssize_t fruit_pwrite_recv(struct tevent_req *req,
2815                                          struct vfs_aio_state *vfs_aio_state)
2816 {
2817         struct fruit_pwrite_state *state = tevent_req_data(
2818                 req, struct fruit_pwrite_state);
2819
2820         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
2821                 return -1;
2822         }
2823
2824         *vfs_aio_state = state->vfs_aio_state;
2825         return state->nwritten;
2826 }
2827
2828 /**
2829  * Helper to stat/lstat the base file of an smb_fname.
2830  */
2831 static int fruit_stat_base(vfs_handle_struct *handle,
2832                            struct smb_filename *smb_fname,
2833                            bool follow_links)
2834 {
2835         char *tmp_stream_name;
2836         int rc;
2837
2838         tmp_stream_name = smb_fname->stream_name;
2839         smb_fname->stream_name = NULL;
2840         if (follow_links) {
2841                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
2842         } else {
2843                 rc = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
2844         }
2845         smb_fname->stream_name = tmp_stream_name;
2846
2847         DBG_DEBUG("fruit_stat_base [%s] dev [%ju] ino [%ju]\n",
2848                   smb_fname->base_name,
2849                   (uintmax_t)smb_fname->st.st_ex_dev,
2850                   (uintmax_t)smb_fname->st.st_ex_ino);
2851         return rc;
2852 }
2853
2854 static int fruit_stat_meta_stream(vfs_handle_struct *handle,
2855                                   struct smb_filename *smb_fname,
2856                                   bool follow_links)
2857 {
2858         int ret;
2859         ino_t ino;
2860
2861         ret = fruit_stat_base(handle, smb_fname, false);
2862         if (ret != 0) {
2863                 return -1;
2864         }
2865
2866         ino = hash_inode(&smb_fname->st, smb_fname->stream_name);
2867
2868         if (follow_links) {
2869                 ret = SMB_VFS_NEXT_STAT(handle, smb_fname);
2870         } else {
2871                 ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
2872         }
2873
2874         smb_fname->st.st_ex_ino = ino;
2875
2876         return ret;
2877 }
2878
2879 static int fruit_stat_meta_netatalk(vfs_handle_struct *handle,
2880                                     struct smb_filename *smb_fname,
2881                                     bool follow_links)
2882 {
2883         struct adouble *ad = NULL;
2884
2885         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
2886         if (ad == NULL) {
2887                 DBG_INFO("fruit_stat_meta %s: %s\n",
2888                          smb_fname_str_dbg(smb_fname), strerror(errno));
2889                 errno = ENOENT;
2890                 return -1;
2891         }
2892         TALLOC_FREE(ad);
2893
2894         /* Populate the stat struct with info from the base file. */
2895         if (fruit_stat_base(handle, smb_fname, follow_links) == -1) {
2896                 return -1;
2897         }
2898         smb_fname->st.st_ex_size = AFP_INFO_SIZE;
2899         smb_fname->st.st_ex_ino = hash_inode(&smb_fname->st,
2900                                               smb_fname->stream_name);
2901         return 0;
2902 }
2903
2904 static int fruit_stat_meta(vfs_handle_struct *handle,
2905                            struct smb_filename *smb_fname,
2906                            bool follow_links)
2907 {
2908         struct fruit_config_data *config = NULL;
2909         int ret;
2910
2911         SMB_VFS_HANDLE_GET_DATA(handle, config,
2912                                 struct fruit_config_data, return -1);
2913
2914         switch (config->meta) {
2915         case FRUIT_META_STREAM:
2916                 ret = fruit_stat_meta_stream(handle, smb_fname, follow_links);
2917                 break;
2918
2919         case FRUIT_META_NETATALK:
2920                 ret = fruit_stat_meta_netatalk(handle, smb_fname, follow_links);
2921                 break;
2922
2923         default:
2924                 DBG_ERR("Unexpected meta config [%d]\n", config->meta);
2925                 return -1;
2926         }
2927
2928         return ret;
2929 }
2930
2931 static int fruit_stat_rsrc_netatalk(vfs_handle_struct *handle,
2932                                     struct smb_filename *smb_fname,
2933                                     bool follow_links)
2934 {
2935         struct adouble *ad = NULL;
2936         int ret;
2937
2938         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_RSRC);
2939         if (ad == NULL) {
2940                 errno = ENOENT;
2941                 return -1;
2942         }
2943
2944         /* Populate the stat struct with info from the base file. */
2945         ret = fruit_stat_base(handle, smb_fname, follow_links);
2946         if (ret != 0) {
2947                 TALLOC_FREE(ad);
2948                 return -1;
2949         }
2950
2951         smb_fname->st.st_ex_size = ad_getentrylen(ad, ADEID_RFORK);
2952         smb_fname->st.st_ex_ino = hash_inode(&smb_fname->st,
2953                                               smb_fname->stream_name);
2954         TALLOC_FREE(ad);
2955         return 0;
2956 }
2957
2958 static int fruit_stat_rsrc_stream(vfs_handle_struct *handle,
2959                                   struct smb_filename *smb_fname,
2960                                   bool follow_links)
2961 {
2962         int ret;
2963
2964         if (follow_links) {
2965                 ret = SMB_VFS_NEXT_STAT(handle, smb_fname);
2966         } else {
2967                 ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
2968         }
2969
2970         return ret;
2971 }
2972
2973 static int fruit_stat_rsrc_xattr(vfs_handle_struct *handle,
2974                                  struct smb_filename *smb_fname,
2975                                  bool follow_links)
2976 {
2977 #ifdef HAVE_ATTROPEN
2978         int ret;
2979         int fd = -1;
2980
2981         /* Populate the stat struct with info from the base file. */
2982         ret = fruit_stat_base(handle, smb_fname, follow_links);
2983         if (ret != 0) {
2984                 return -1;
2985         }
2986
2987         fd = attropen(smb_fname->base_name,
2988                       AFPRESOURCE_EA_NETATALK,
2989                       O_RDONLY);
2990         if (fd == -1) {
2991                 return 0;
2992         }
2993
2994         ret = sys_fstat(fd, &smb_fname->st, false);
2995         if (ret != 0) {
2996                 close(fd);
2997                 DBG_ERR("fstat [%s:%s] failed\n", smb_fname->base_name,
2998                         AFPRESOURCE_EA_NETATALK);
2999                 return -1;
3000         }
3001         close(fd);
3002         fd = -1;
3003
3004         smb_fname->st.st_ex_ino = hash_inode(&smb_fname->st,
3005                                              smb_fname->stream_name);
3006
3007         return ret;
3008
3009 #else
3010         errno = ENOSYS;
3011         return -1;
3012 #endif
3013 }
3014
3015 static int fruit_stat_rsrc(vfs_handle_struct *handle,
3016                            struct smb_filename *smb_fname,
3017                            bool follow_links)
3018 {
3019         struct fruit_config_data *config = NULL;
3020         int ret;
3021
3022         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
3023
3024         SMB_VFS_HANDLE_GET_DATA(handle, config,
3025                                 struct fruit_config_data, return -1);
3026
3027         switch (config->rsrc) {
3028         case FRUIT_RSRC_STREAM:
3029                 ret = fruit_stat_rsrc_stream(handle, smb_fname, follow_links);
3030                 break;
3031
3032         case FRUIT_RSRC_XATTR:
3033                 ret = fruit_stat_rsrc_xattr(handle, smb_fname, follow_links);
3034                 break;
3035
3036         case FRUIT_RSRC_ADFILE:
3037                 ret = fruit_stat_rsrc_netatalk(handle, smb_fname, follow_links);
3038                 break;
3039
3040         default:
3041                 DBG_ERR("Unexpected rsrc config [%d]\n", config->rsrc);
3042                 return -1;
3043         }
3044
3045         return ret;
3046 }
3047
3048 static int fruit_stat(vfs_handle_struct *handle,
3049                       struct smb_filename *smb_fname)
3050 {
3051         int rc = -1;
3052
3053         DEBUG(10, ("fruit_stat called for %s\n",
3054                    smb_fname_str_dbg(smb_fname)));
3055
3056         if (!is_named_stream(smb_fname)) {
3057                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
3058                 if (rc == 0) {
3059                         update_btime(handle, smb_fname);
3060                 }
3061                 return rc;
3062         }
3063
3064         /*
3065          * Note if lp_posix_paths() is true, we can never
3066          * get here as is_ntfs_stream_smb_fname() is
3067          * always false. So we never need worry about
3068          * not following links here.
3069          */
3070
3071         if (is_afpinfo_stream(smb_fname->stream_name)) {
3072                 rc = fruit_stat_meta(handle, smb_fname, true);
3073         } else if (is_afpresource_stream(smb_fname->stream_name)) {
3074                 rc = fruit_stat_rsrc(handle, smb_fname, true);
3075         } else {
3076                 return SMB_VFS_NEXT_STAT(handle, smb_fname);
3077         }
3078
3079         if (rc == 0) {
3080                 update_btime(handle, smb_fname);
3081                 smb_fname->st.st_ex_mode &= ~S_IFMT;
3082                 smb_fname->st.st_ex_mode |= S_IFREG;
3083                 smb_fname->st.st_ex_blocks =
3084                         smb_fname->st.st_ex_size / STAT_ST_BLOCKSIZE + 1;
3085         }
3086         return rc;
3087 }
3088
3089 static int fruit_lstat(vfs_handle_struct *handle,
3090                        struct smb_filename *smb_fname)
3091 {
3092         int rc = -1;
3093
3094         DEBUG(10, ("fruit_lstat called for %s\n",
3095                    smb_fname_str_dbg(smb_fname)));
3096
3097         if (!is_named_stream(smb_fname)) {
3098                 rc = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
3099                 if (rc == 0) {
3100                         update_btime(handle, smb_fname);
3101                 }
3102                 return rc;
3103         }
3104
3105         if (is_afpinfo_stream(smb_fname->stream_name)) {
3106                 rc = fruit_stat_meta(handle, smb_fname, false);
3107         } else if (is_afpresource_stream(smb_fname->stream_name)) {
3108                 rc = fruit_stat_rsrc(handle, smb_fname, false);
3109         } else {
3110                 return SMB_VFS_NEXT_LSTAT(handle, smb_fname);
3111         }
3112
3113         if (rc == 0) {
3114                 update_btime(handle, smb_fname);
3115                 smb_fname->st.st_ex_mode &= ~S_IFMT;
3116                 smb_fname->st.st_ex_mode |= S_IFREG;
3117                 smb_fname->st.st_ex_blocks =
3118                         smb_fname->st.st_ex_size / STAT_ST_BLOCKSIZE + 1;
3119         }
3120         return rc;
3121 }
3122
3123 static int fruit_fstat_meta_stream(vfs_handle_struct *handle,
3124                                    files_struct *fsp,
3125                                    SMB_STRUCT_STAT *sbuf)
3126 {
3127         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3128         struct smb_filename smb_fname;
3129         ino_t ino;
3130         int ret;
3131
3132         if (fio == NULL) {
3133                 return -1;
3134         }
3135
3136         if (fio->fake_fd) {
3137                 ret = fruit_stat_base(handle, fsp->base_fsp->fsp_name, false);
3138                 if (ret != 0) {
3139                         return -1;
3140                 }
3141
3142                 *sbuf = fsp->base_fsp->fsp_name->st;
3143                 sbuf->st_ex_size = AFP_INFO_SIZE;
3144                 sbuf->st_ex_ino = hash_inode(sbuf, fsp->fsp_name->stream_name);
3145                 return 0;
3146         }
3147
3148         smb_fname = (struct smb_filename) {
3149                 .base_name = fsp->fsp_name->base_name,
3150         };
3151
3152         ret = fruit_stat_base(handle, &smb_fname, false);
3153         if (ret != 0) {
3154                 return -1;
3155         }
3156         *sbuf = smb_fname.st;
3157
3158         ino = hash_inode(sbuf, fsp->fsp_name->stream_name);
3159
3160         ret = SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
3161         if (ret != 0) {
3162                 return -1;
3163         }
3164
3165         sbuf->st_ex_ino = ino;
3166         return 0;
3167 }
3168
3169 static int fruit_fstat_meta_netatalk(vfs_handle_struct *handle,
3170                                      files_struct *fsp,
3171                                      SMB_STRUCT_STAT *sbuf)
3172 {
3173         int ret;
3174
3175         ret = fruit_stat_base(handle, fsp->base_fsp->fsp_name, false);
3176         if (ret != 0) {
3177                 return -1;
3178         }
3179
3180         *sbuf = fsp->base_fsp->fsp_name->st;
3181         sbuf->st_ex_size = AFP_INFO_SIZE;
3182         sbuf->st_ex_ino = hash_inode(sbuf, fsp->fsp_name->stream_name);
3183
3184         return 0;
3185 }
3186
3187 static int fruit_fstat_meta(vfs_handle_struct *handle,
3188                             files_struct *fsp,
3189                             SMB_STRUCT_STAT *sbuf,
3190                             struct fio *fio)
3191 {
3192         int ret;
3193
3194         DBG_DEBUG("Path [%s]\n", fsp_str_dbg(fsp));
3195
3196         switch (fio->config->meta) {
3197         case FRUIT_META_STREAM:
3198                 ret = fruit_fstat_meta_stream(handle, fsp, sbuf);
3199                 break;
3200
3201         case FRUIT_META_NETATALK:
3202                 ret = fruit_fstat_meta_netatalk(handle, fsp, sbuf);
3203                 break;
3204
3205         default:
3206                 DBG_ERR("Unexpected meta config [%d]\n", fio->config->meta);
3207                 return -1;
3208         }
3209
3210         DBG_DEBUG("Path [%s] ret [%d]\n", fsp_str_dbg(fsp), ret);
3211         return ret;
3212 }
3213
3214 static int fruit_fstat_rsrc_xattr(vfs_handle_struct *handle,
3215                                   files_struct *fsp,
3216                                   SMB_STRUCT_STAT *sbuf)
3217 {
3218         return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
3219 }
3220
3221 static int fruit_fstat_rsrc_stream(vfs_handle_struct *handle,
3222                                    files_struct *fsp,
3223                                    SMB_STRUCT_STAT *sbuf)
3224 {
3225         return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
3226 }
3227
3228 static int fruit_fstat_rsrc_adouble(vfs_handle_struct *handle,
3229                                     files_struct *fsp,
3230                                     SMB_STRUCT_STAT *sbuf)
3231 {
3232         struct adouble *ad = NULL;
3233         int ret;
3234
3235         /* Populate the stat struct with info from the base file. */
3236         ret = fruit_stat_base(handle, fsp->base_fsp->fsp_name, false);
3237         if (ret == -1) {
3238                 return -1;
3239         }
3240
3241         ad = ad_get(talloc_tos(), handle,
3242                     fsp->base_fsp->fsp_name,
3243                     ADOUBLE_RSRC);
3244         if (ad == NULL) {
3245                 DBG_ERR("ad_get [%s] failed [%s]\n",
3246                         fsp_str_dbg(fsp), strerror(errno));
3247                 return -1;
3248         }
3249
3250         *sbuf = fsp->base_fsp->fsp_name->st;
3251         sbuf->st_ex_size = ad_getentrylen(ad, ADEID_RFORK);
3252         sbuf->st_ex_ino = hash_inode(sbuf, fsp->fsp_name->stream_name);
3253
3254         TALLOC_FREE(ad);
3255         return 0;
3256 }
3257
3258 static int fruit_fstat_rsrc(vfs_handle_struct *handle, files_struct *fsp,
3259                             SMB_STRUCT_STAT *sbuf, struct fio *fio)
3260 {
3261         int ret;
3262
3263         switch (fio->config->rsrc) {
3264         case FRUIT_RSRC_STREAM:
3265                 ret = fruit_fstat_rsrc_stream(handle, fsp, sbuf);
3266                 break;
3267
3268         case FRUIT_RSRC_ADFILE:
3269                 ret = fruit_fstat_rsrc_adouble(handle, fsp, sbuf);
3270                 break;
3271
3272         case FRUIT_RSRC_XATTR:
3273                 ret = fruit_fstat_rsrc_xattr(handle, fsp, sbuf);
3274                 break;
3275
3276         default:
3277                 DBG_ERR("Unexpected rsrc config [%d]\n", fio->config->rsrc);
3278                 return -1;
3279         }
3280
3281         return ret;
3282 }
3283
3284 static int fruit_fstat(vfs_handle_struct *handle, files_struct *fsp,
3285                        SMB_STRUCT_STAT *sbuf)
3286 {
3287         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3288         int rc;
3289
3290         if (fio == NULL) {
3291                 return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
3292         }
3293
3294         DBG_DEBUG("Path [%s]\n", fsp_str_dbg(fsp));
3295
3296         if (fio->type == ADOUBLE_META) {
3297                 rc = fruit_fstat_meta(handle, fsp, sbuf, fio);
3298         } else {
3299                 rc = fruit_fstat_rsrc(handle, fsp, sbuf, fio);
3300         }
3301
3302         if (rc == 0) {
3303                 sbuf->st_ex_mode &= ~S_IFMT;
3304                 sbuf->st_ex_mode |= S_IFREG;
3305                 sbuf->st_ex_blocks = sbuf->st_ex_size / STAT_ST_BLOCKSIZE + 1;
3306         }
3307
3308         DBG_DEBUG("Path [%s] rc [%d] size [%"PRIdMAX"]\n",
3309                   fsp_str_dbg(fsp), rc, (intmax_t)sbuf->st_ex_size);
3310         return rc;
3311 }
3312
3313 static NTSTATUS delete_invalid_meta_stream(
3314         vfs_handle_struct *handle,
3315         const struct smb_filename *smb_fname,
3316         TALLOC_CTX *mem_ctx,
3317         unsigned int *pnum_streams,
3318         struct stream_struct **pstreams,
3319         off_t size)
3320 {
3321         struct smb_filename *sname = NULL;
3322         int ret;
3323         bool ok;
3324
3325         ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams, AFPINFO_STREAM);
3326         if (!ok) {
3327                 return NT_STATUS_INTERNAL_ERROR;
3328         }
3329
3330         if (size == 0) {
3331                 return NT_STATUS_OK;
3332         }
3333
3334         sname = synthetic_smb_fname(talloc_tos(),
3335                                     smb_fname->base_name,
3336                                     AFPINFO_STREAM_NAME,
3337                                     NULL,
3338                                     0);
3339         if (sname == NULL) {
3340                 return NT_STATUS_NO_MEMORY;
3341         }
3342
3343         ret = SMB_VFS_NEXT_UNLINKAT(handle,
3344                         handle->conn->cwd_fsp,
3345                         sname,
3346                         0);
3347         TALLOC_FREE(sname);
3348         if (ret != 0) {
3349                 DBG_ERR("Removing [%s] failed\n", smb_fname_str_dbg(sname));
3350                 return map_nt_error_from_unix(errno);
3351         }
3352
3353         return NT_STATUS_OK;
3354 }
3355
3356 static NTSTATUS fruit_streaminfo_meta_stream(
3357         vfs_handle_struct *handle,
3358         struct files_struct *fsp,
3359         const struct smb_filename *smb_fname,
3360         TALLOC_CTX *mem_ctx,
3361         unsigned int *pnum_streams,
3362         struct stream_struct **pstreams)
3363 {
3364         struct stream_struct *stream = *pstreams;
3365         unsigned int num_streams = *pnum_streams;
3366         int i;
3367
3368         for (i = 0; i < num_streams; i++) {
3369                 if (strequal_m(stream[i].name, AFPINFO_STREAM)) {
3370                         break;
3371                 }
3372         }
3373
3374         if (i == num_streams) {
3375                 return NT_STATUS_OK;
3376         }
3377
3378         if (stream[i].size != AFP_INFO_SIZE) {
3379                 DBG_ERR("Removing invalid AFPINFO_STREAM size [%jd] from [%s]\n",
3380                         (intmax_t)stream[i].size, smb_fname_str_dbg(smb_fname));
3381
3382                 return delete_invalid_meta_stream(handle,
3383                                                   smb_fname,
3384                                                   mem_ctx,
3385                                                   pnum_streams,
3386                                                   pstreams,
3387                                                   stream[i].size);
3388         }
3389
3390
3391         return NT_STATUS_OK;
3392 }
3393
3394 static NTSTATUS fruit_streaminfo_meta_netatalk(
3395         vfs_handle_struct *handle,
3396         struct files_struct *fsp,
3397         const struct smb_filename *smb_fname,
3398         TALLOC_CTX *mem_ctx,
3399         unsigned int *pnum_streams,
3400         struct stream_struct **pstreams)
3401 {
3402         struct stream_struct *stream = *pstreams;
3403         unsigned int num_streams = *pnum_streams;
3404         struct adouble *ad = NULL;
3405         bool is_fi_empty;
3406         int i;
3407         bool ok;
3408
3409         /* Remove the Netatalk xattr from the list */
3410         ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams,
3411                               ":" NETATALK_META_XATTR ":$DATA");
3412         if (!ok) {
3413                 return NT_STATUS_NO_MEMORY;
3414         }
3415
3416         /*
3417          * Check if there's a AFPINFO_STREAM from the VFS streams
3418          * backend and if yes, remove it from the list
3419          */
3420         for (i = 0; i < num_streams; i++) {
3421                 if (strequal_m(stream[i].name, AFPINFO_STREAM)) {
3422                         break;
3423                 }
3424         }
3425
3426         if (i < num_streams) {
3427                 DBG_WARNING("Unexpected AFPINFO_STREAM on [%s]\n",
3428                             smb_fname_str_dbg(smb_fname));
3429
3430                 ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams,
3431                                       AFPINFO_STREAM);
3432                 if (!ok) {
3433                         return NT_STATUS_INTERNAL_ERROR;
3434                 }
3435         }
3436
3437         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
3438         if (ad == NULL) {
3439                 return NT_STATUS_OK;
3440         }
3441
3442         is_fi_empty = ad_empty_finderinfo(ad);
3443         TALLOC_FREE(ad);
3444
3445         if (is_fi_empty) {
3446                 return NT_STATUS_OK;
3447         }
3448
3449         ok = add_fruit_stream(mem_ctx, pnum_streams, pstreams,
3450                               AFPINFO_STREAM_NAME, AFP_INFO_SIZE,
3451                               smb_roundup(handle->conn, AFP_INFO_SIZE));
3452         if (!ok) {
3453                 return NT_STATUS_NO_MEMORY;
3454         }
3455
3456         return NT_STATUS_OK;
3457 }
3458
3459 static NTSTATUS fruit_streaminfo_meta(vfs_handle_struct *handle,
3460                                       struct files_struct *fsp,
3461                                       const struct smb_filename *smb_fname,
3462                                       TALLOC_CTX *mem_ctx,
3463                                       unsigned int *pnum_streams,
3464                                       struct stream_struct **pstreams)
3465 {
3466         struct fruit_config_data *config = NULL;
3467         NTSTATUS status;
3468
3469         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
3470                                 return NT_STATUS_INTERNAL_ERROR);
3471
3472         switch (config->meta) {
3473         case FRUIT_META_NETATALK:
3474                 status = fruit_streaminfo_meta_netatalk(handle, fsp, smb_fname,
3475                                                         mem_ctx, pnum_streams,
3476                                                         pstreams);
3477                 break;
3478
3479         case FRUIT_META_STREAM:
3480                 status = fruit_streaminfo_meta_stream(handle, fsp, smb_fname,
3481                                                       mem_ctx, pnum_streams,
3482                                                       pstreams);
3483                 break;
3484
3485         default:
3486                 return NT_STATUS_INTERNAL_ERROR;
3487         }
3488
3489         return status;
3490 }
3491
3492 static NTSTATUS fruit_streaminfo_rsrc_stream(
3493         vfs_handle_struct *handle,
3494         struct files_struct *fsp,
3495         const struct smb_filename *smb_fname,
3496         TALLOC_CTX *mem_ctx,
3497         unsigned int *pnum_streams,
3498         struct stream_struct **pstreams)
3499 {
3500         bool ok;
3501
3502         ok = filter_empty_rsrc_stream(pnum_streams, pstreams);
3503         if (!ok) {
3504                 DBG_ERR("Filtering resource stream failed\n");
3505                 return NT_STATUS_INTERNAL_ERROR;
3506         }
3507         return NT_STATUS_OK;
3508 }
3509
3510 static NTSTATUS fruit_streaminfo_rsrc_xattr(
3511         vfs_handle_struct *handle,
3512         struct files_struct *fsp,
3513         const struct smb_filename *smb_fname,
3514         TALLOC_CTX *mem_ctx,
3515         unsigned int *pnum_streams,
3516         struct stream_struct **pstreams)
3517 {
3518         bool ok;
3519
3520         ok = filter_empty_rsrc_stream(pnum_streams, pstreams);
3521         if (!ok) {
3522                 DBG_ERR("Filtering resource stream failed\n");
3523                 return NT_STATUS_INTERNAL_ERROR;
3524         }
3525         return NT_STATUS_OK;
3526 }
3527
3528 static NTSTATUS fruit_streaminfo_rsrc_adouble(
3529         vfs_handle_struct *handle,
3530         struct files_struct *fsp,
3531         const struct smb_filename *smb_fname,
3532         TALLOC_CTX *mem_ctx,
3533         unsigned int *pnum_streams,
3534         struct stream_struct **pstreams)
3535 {
3536         struct stream_struct *stream = *pstreams;
3537         unsigned int num_streams = *pnum_streams;
3538         struct adouble *ad = NULL;
3539         bool ok;
3540         size_t rlen;
3541         int i;
3542
3543         /*
3544          * Check if there's a AFPRESOURCE_STREAM from the VFS streams backend
3545          * and if yes, remove it from the list
3546          */
3547         for (i = 0; i < num_streams; i++) {
3548                 if (strequal_m(stream[i].name, AFPRESOURCE_STREAM)) {
3549                         break;
3550                 }
3551         }
3552
3553         if (i < num_streams) {
3554                 DBG_WARNING("Unexpected AFPRESOURCE_STREAM on [%s]\n",
3555                             smb_fname_str_dbg(smb_fname));
3556
3557                 ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams,
3558                                       AFPRESOURCE_STREAM);
3559                 if (!ok) {
3560                         return NT_STATUS_INTERNAL_ERROR;
3561                 }
3562         }
3563
3564         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_RSRC);
3565         if (ad == NULL) {
3566                 return NT_STATUS_OK;
3567         }
3568
3569         rlen = ad_getentrylen(ad, ADEID_RFORK);
3570         TALLOC_FREE(ad);
3571
3572         if (rlen == 0) {
3573                 return NT_STATUS_OK;
3574         }
3575
3576         ok = add_fruit_stream(mem_ctx, pnum_streams, pstreams,
3577                               AFPRESOURCE_STREAM_NAME, rlen,
3578                               smb_roundup(handle->conn, rlen));
3579         if (!ok) {
3580                 return NT_STATUS_NO_MEMORY;
3581         }
3582
3583         return NT_STATUS_OK;
3584 }
3585
3586 static NTSTATUS fruit_streaminfo_rsrc(vfs_handle_struct *handle,
3587                                       struct files_struct *fsp,
3588                                       const struct smb_filename *smb_fname,
3589                                       TALLOC_CTX *mem_ctx,
3590                                       unsigned int *pnum_streams,
3591                                       struct stream_struct **pstreams)
3592 {
3593         struct fruit_config_data *config = NULL;
3594         NTSTATUS status;
3595
3596         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
3597                                 return NT_STATUS_INTERNAL_ERROR);
3598
3599         switch (config->rsrc) {
3600         case FRUIT_RSRC_STREAM:
3601                 status = fruit_streaminfo_rsrc_stream(handle, fsp, smb_fname,
3602                                                       mem_ctx, pnum_streams,
3603                                                       pstreams);
3604                 break;
3605
3606         case FRUIT_RSRC_XATTR:
3607                 status = fruit_streaminfo_rsrc_xattr(handle, fsp, smb_fname,
3608                                                      mem_ctx, pnum_streams,
3609                                                      pstreams);
3610                 break;
3611
3612         case FRUIT_RSRC_ADFILE:
3613                 status = fruit_streaminfo_rsrc_adouble(handle, fsp, smb_fname,
3614                                                        mem_ctx, pnum_streams,
3615                                                        pstreams);
3616                 break;
3617
3618         default:
3619                 return NT_STATUS_INTERNAL_ERROR;
3620         }
3621
3622         return status;
3623 }
3624
3625 static void fruit_filter_empty_streams(unsigned int *pnum_streams,
3626                                        struct stream_struct **pstreams)
3627 {
3628         unsigned num_streams = *pnum_streams;
3629         struct stream_struct *streams = *pstreams;
3630         unsigned i = 0;
3631
3632         if (!global_fruit_config.nego_aapl) {
3633                 return;
3634         }
3635
3636         while (i < num_streams) {
3637                 struct smb_filename smb_fname = (struct smb_filename) {
3638                         .stream_name = streams[i].name,
3639                 };
3640
3641                 if (is_ntfs_default_stream_smb_fname(&smb_fname)
3642                     || streams[i].size > 0)
3643                 {
3644                         i++;
3645                         continue;
3646                 }
3647
3648                 streams[i] = streams[num_streams - 1];
3649                 num_streams--;
3650         }
3651
3652         *pnum_streams = num_streams;
3653 }
3654
3655 static NTSTATUS fruit_streaminfo(vfs_handle_struct *handle,
3656                                  struct files_struct *fsp,
3657                                  const struct smb_filename *smb_fname,
3658                                  TALLOC_CTX *mem_ctx,
3659                                  unsigned int *pnum_streams,
3660                                  struct stream_struct **pstreams)
3661 {
3662         struct fruit_config_data *config = NULL;
3663         NTSTATUS status;
3664
3665         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
3666                                 return NT_STATUS_UNSUCCESSFUL);
3667
3668         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
3669
3670         status = SMB_VFS_NEXT_STREAMINFO(handle, fsp, smb_fname, mem_ctx,
3671                                          pnum_streams, pstreams);
3672         if (!NT_STATUS_IS_OK(status)) {
3673                 return status;
3674         }
3675
3676         fruit_filter_empty_streams(pnum_streams, pstreams);
3677
3678         status = fruit_streaminfo_meta(handle, fsp, smb_fname,
3679                                        mem_ctx, pnum_streams, pstreams);
3680         if (!NT_STATUS_IS_OK(status)) {
3681                 return status;
3682         }
3683
3684         status = fruit_streaminfo_rsrc(handle, fsp, smb_fname,
3685                                        mem_ctx, pnum_streams, pstreams);
3686         if (!NT_STATUS_IS_OK(status)) {
3687                 return status;
3688         }
3689
3690         return NT_STATUS_OK;
3691 }
3692
3693 static int fruit_ntimes(vfs_handle_struct *handle,
3694                         const struct smb_filename *smb_fname,
3695                         struct smb_file_time *ft)
3696 {
3697         int rc = 0;
3698         struct adouble *ad = NULL;
3699         struct fruit_config_data *config = NULL;
3700
3701         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
3702                                 return -1);
3703
3704         if ((config->meta != FRUIT_META_NETATALK) ||
3705             is_omit_timespec(&ft->create_time))
3706         {
3707                 return SMB_VFS_NEXT_NTIMES(handle, smb_fname, ft);
3708         }
3709
3710         DEBUG(10,("set btime for %s to %s\n", smb_fname_str_dbg(smb_fname),
3711                  time_to_asc(convert_timespec_to_time_t(ft->create_time))));
3712
3713         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
3714         if (ad == NULL) {
3715                 goto exit;
3716         }
3717
3718         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX,
3719                    convert_time_t_to_uint32_t(ft->create_time.tv_sec));
3720
3721         rc = ad_set(handle, ad, smb_fname);
3722
3723 exit:
3724
3725         TALLOC_FREE(ad);
3726         if (rc != 0) {
3727                 DEBUG(1, ("fruit_ntimes: %s\n", smb_fname_str_dbg(smb_fname)));
3728                 return -1;
3729         }
3730         return SMB_VFS_NEXT_NTIMES(handle, smb_fname, ft);
3731 }
3732
3733 static int fruit_fallocate(struct vfs_handle_struct *handle,
3734                            struct files_struct *fsp,
3735                            uint32_t mode,
3736                            off_t offset,
3737                            off_t len)
3738 {
3739         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3740
3741         if (fio == NULL) {
3742                 return SMB_VFS_NEXT_FALLOCATE(handle, fsp, mode, offset, len);
3743         }
3744
3745         /* Let the pwrite code path handle it. */
3746         errno = ENOSYS;
3747         return -1;
3748 }
3749
3750 static int fruit_ftruncate_rsrc_xattr(struct vfs_handle_struct *handle,
3751                                       struct files_struct *fsp,
3752                                       off_t offset)
3753 {
3754 #ifdef HAVE_ATTROPEN
3755         return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
3756 #endif
3757         return 0;
3758 }
3759
3760 static int fruit_ftruncate_rsrc_adouble(struct vfs_handle_struct *handle,
3761                                         struct files_struct *fsp,
3762                                         off_t offset)
3763 {
3764         int rc;
3765         struct adouble *ad = NULL;
3766         off_t ad_off;
3767
3768         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_RSRC);
3769         if (ad == NULL) {
3770                 DBG_DEBUG("ad_get [%s] failed [%s]\n",
3771                           fsp_str_dbg(fsp), strerror(errno));
3772                 return -1;
3773         }
3774
3775         ad_off = ad_getentryoff(ad, ADEID_RFORK);
3776
3777         rc = ftruncate(fsp->fh->fd, offset + ad_off);
3778         if (rc != 0) {
3779                 TALLOC_FREE(ad);
3780                 return -1;
3781         }
3782
3783         ad_setentrylen(ad, ADEID_RFORK, offset);
3784
3785         rc = ad_fset(handle, ad, fsp);
3786         if (rc != 0) {
3787                 DBG_ERR("ad_fset [%s] failed [%s]\n",
3788                         fsp_str_dbg(fsp), strerror(errno));
3789                 TALLOC_FREE(ad);
3790                 return -1;
3791         }
3792
3793         TALLOC_FREE(ad);
3794         return 0;
3795 }
3796
3797 static int fruit_ftruncate_rsrc_stream(struct vfs_handle_struct *handle,
3798                                        struct files_struct *fsp,
3799                                        off_t offset)
3800 {
3801         return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
3802 }
3803
3804 static int fruit_ftruncate_rsrc(struct vfs_handle_struct *handle,
3805                                 struct files_struct *fsp,
3806                                 off_t offset)
3807 {
3808         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3809         int ret;
3810
3811         if (fio == NULL) {
3812                 DBG_ERR("Failed to fetch fsp extension");
3813                 return -1;
3814         }
3815
3816         switch (fio->config->rsrc) {
3817         case FRUIT_RSRC_XATTR:
3818                 ret = fruit_ftruncate_rsrc_xattr(handle, fsp, offset);
3819                 break;
3820
3821         case FRUIT_RSRC_ADFILE:
3822                 ret = fruit_ftruncate_rsrc_adouble(handle, fsp, offset);
3823                 break;
3824
3825         case FRUIT_RSRC_STREAM:
3826                 ret = fruit_ftruncate_rsrc_stream(handle, fsp, offset);
3827                 break;
3828
3829         default:
3830                 DBG_ERR("Unexpected rsrc config [%d]\n", fio->config->rsrc);
3831                 return -1;
3832         }
3833
3834
3835         return ret;
3836 }
3837
3838 static int fruit_ftruncate_meta(struct vfs_handle_struct *handle,
3839                                 struct files_struct *fsp,
3840                                 off_t offset)
3841 {
3842         if (offset > 60) {
3843                 DBG_WARNING("ftruncate %s to %jd",
3844                             fsp_str_dbg(fsp), (intmax_t)offset);
3845                 /* OS X returns NT_STATUS_ALLOTTED_SPACE_EXCEEDED  */
3846                 errno = EOVERFLOW;
3847                 return -1;
3848         }
3849
3850         /* OS X returns success but does nothing  */
3851         DBG_INFO("ignoring ftruncate %s to %jd\n",
3852                  fsp_str_dbg(fsp), (intmax_t)offset);
3853         return 0;
3854 }
3855
3856 static int fruit_ftruncate(struct vfs_handle_struct *handle,
3857                            struct files_struct *fsp,
3858                            off_t offset)
3859 {
3860         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3861         int ret;
3862
3863         DBG_DEBUG("Path [%s] offset [%"PRIdMAX"]\n", fsp_str_dbg(fsp),
3864                   (intmax_t)offset);
3865
3866         if (fio == NULL) {
3867                 return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
3868         }
3869
3870         if (fio->type == ADOUBLE_META) {
3871                 ret = fruit_ftruncate_meta(handle, fsp, offset);
3872         } else {
3873                 ret = fruit_ftruncate_rsrc(handle, fsp, offset);
3874         }
3875
3876         DBG_DEBUG("Path [%s] result [%d]\n", fsp_str_dbg(fsp), ret);
3877         return ret;
3878 }
3879
3880 static NTSTATUS fruit_create_file(vfs_handle_struct *handle,
3881                                   struct smb_request *req,
3882                                   uint16_t root_dir_fid,
3883                                   struct smb_filename *smb_fname,
3884                                   uint32_t access_mask,
3885                                   uint32_t share_access,
3886                                   uint32_t create_disposition,
3887                                   uint32_t create_options,
3888                                   uint32_t file_attributes,
3889                                   uint32_t oplock_request,
3890                                   const struct smb2_lease *lease,
3891                                   uint64_t allocation_size,
3892                                   uint32_t private_flags,
3893                                   struct security_descriptor *sd,
3894                                   struct ea_list *ea_list,
3895                                   files_struct **result,
3896                                   int *pinfo,
3897                                   const struct smb2_create_blobs *in_context_blobs,
3898                                   struct smb2_create_blobs *out_context_blobs)
3899 {
3900         NTSTATUS status;
3901         struct fruit_config_data *config = NULL;
3902         files_struct *fsp = NULL;
3903         struct fio *fio = NULL;
3904         bool internal_open = (oplock_request & INTERNAL_OPEN_ONLY);
3905         int ret;
3906
3907         status = check_aapl(handle, req, in_context_blobs, out_context_blobs);
3908         if (!NT_STATUS_IS_OK(status)) {
3909                 goto fail;
3910         }
3911
3912         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
3913                                 return NT_STATUS_UNSUCCESSFUL);
3914
3915         if (is_apple_stream(smb_fname->stream_name) && !internal_open) {
3916                 uint32_t conv_flags  = 0;
3917
3918                 if (config->wipe_intentionally_left_blank_rfork) {
3919                         conv_flags |= AD_CONV_WIPE_BLANK;
3920                 }
3921                 if (config->delete_empty_adfiles) {
3922                         conv_flags |= AD_CONV_DELETE;
3923                 }
3924
3925                 ret = ad_convert(handle,
3926                                  handle->conn->cwd_fsp,
3927                                  smb_fname,
3928                                  macos_string_replace_map,
3929                                  conv_flags);
3930                 if (ret != 0) {
3931                         DBG_ERR("ad_convert() failed\n");
3932                         return NT_STATUS_UNSUCCESSFUL;
3933                 }
3934         }
3935
3936         status = SMB_VFS_NEXT_CREATE_FILE(
3937                 handle, req, root_dir_fid, smb_fname,
3938                 access_mask, share_access,
3939                 create_disposition, create_options,
3940                 file_attributes, oplock_request,
3941                 lease,
3942                 allocation_size, private_flags,
3943                 sd, ea_list, result,
3944                 pinfo, in_context_blobs, out_context_blobs);
3945         if (!NT_STATUS_IS_OK(status)) {
3946                 return status;
3947         }
3948
3949         fsp = *result;
3950
3951         if (global_fruit_config.nego_aapl) {
3952                 if (config->posix_rename && fsp->fsp_flags.is_directory) {
3953                         /*
3954                          * Enable POSIX directory rename behaviour
3955                          */
3956                         fsp->posix_flags |= FSP_POSIX_FLAGS_RENAME;
3957                 }
3958         }
3959
3960         /*
3961          * If this is a plain open for existing files, opening an 0
3962          * byte size resource fork MUST fail with
3963          * NT_STATUS_OBJECT_NAME_NOT_FOUND.
3964          *
3965          * Cf the vfs_fruit torture tests in test_rfork_create().
3966          */
3967         if (global_fruit_config.nego_aapl &&
3968             create_disposition == FILE_OPEN &&
3969             smb_fname->st.st_ex_size == 0 &&
3970             is_named_stream(smb_fname))
3971         {
3972                 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
3973                 goto fail;
3974         }
3975
3976         fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3977         if (fio != NULL && pinfo != NULL && *pinfo == FILE_WAS_CREATED) {
3978                 fio->created = true;
3979         }
3980
3981         if (is_named_stream(smb_fname) || fsp->fsp_flags.is_directory) {
3982                 return status;
3983         }
3984
3985         if ((config->locking == FRUIT_LOCKING_NETATALK) &&
3986             (fsp->op != NULL))
3987         {
3988                 status = fruit_check_access(
3989                         handle, *result,
3990                         access_mask,
3991                         share_access);
3992                 if (!NT_STATUS_IS_OK(status)) {
3993                         goto fail;
3994                 }
3995         }
3996
3997         return status;
3998
3999 fail:
4000         DEBUG(10, ("fruit_create_file: %s\n", nt_errstr(status)));
4001
4002         if (fsp) {
4003                 close_file(req, fsp, ERROR_CLOSE);
4004                 *result = fsp = NULL;
4005         }
4006
4007         return status;
4008 }
4009
4010 static NTSTATUS fruit_readdir_attr(struct vfs_handle_struct *handle,
4011                                    const struct smb_filename *fname,
4012                                    TALLOC_CTX *mem_ctx,
4013                                    struct readdir_attr_data **pattr_data)
4014 {
4015         struct fruit_config_data *config = NULL;
4016         struct readdir_attr_data *attr_data;
4017         uint32_t conv_flags  = 0;
4018         NTSTATUS status;
4019         int ret;
4020
4021         SMB_VFS_HANDLE_GET_DATA(handle, config,
4022                                 struct fruit_config_data,
4023                                 return NT_STATUS_UNSUCCESSFUL);
4024
4025         if (!global_fruit_config.nego_aapl) {
4026                 return SMB_VFS_NEXT_READDIR_ATTR(handle, fname, mem_ctx, pattr_data);
4027         }
4028
4029         DEBUG(10, ("fruit_readdir_attr %s\n", fname->base_name));
4030
4031         if (config->wipe_intentionally_left_blank_rfork) {
4032                 conv_flags |= AD_CONV_WIPE_BLANK;
4033         }
4034         if (config->delete_empty_adfiles) {
4035                 conv_flags |= AD_CONV_DELETE;
4036         }
4037
4038         ret = ad_convert(handle,
4039                         handle->conn->cwd_fsp,
4040                         fname,
4041                         macos_string_replace_map,
4042                         conv_flags);
4043         if (ret != 0) {
4044                 DBG_ERR("ad_convert() failed\n");
4045                 return NT_STATUS_UNSUCCESSFUL;
4046         }
4047
4048         *pattr_data = talloc_zero(mem_ctx, struct readdir_attr_data);
4049         if (*pattr_data == NULL) {
4050                 return NT_STATUS_UNSUCCESSFUL;
4051         }
4052         attr_data = *pattr_data;
4053         attr_data->type = RDATTR_AAPL;
4054
4055         /*
4056          * Mac metadata: compressed FinderInfo, resource fork length
4057          * and creation date
4058          */
4059         status = readdir_attr_macmeta(handle, fname, attr_data);
4060         if (!NT_STATUS_IS_OK(status)) {
4061                 /*
4062                  * Error handling is tricky: if we return failure from
4063                  * this function, the corresponding directory entry
4064                  * will to be passed to the client, so we really just
4065                  * want to error out on fatal errors.
4066                  */
4067                 if  (!NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
4068                         goto fail;
4069                 }
4070         }
4071
4072         /*
4073          * UNIX mode
4074          */
4075         if (config->unix_info_enabled) {
4076                 attr_data->attr_data.aapl.unix_mode = fname->st.st_ex_mode;
4077         }
4078
4079         /*
4080          * max_access
4081          */
4082         if (!config->readdir_attr_max_access) {
4083                 attr_data->attr_data.aapl.max_access = FILE_GENERIC_ALL;
4084         } else {
4085                 status = smbd_calculate_access_mask(
4086                         handle->conn,
4087                         handle->conn->cwd_fsp,
4088                         fname,
4089                         false,
4090                         SEC_FLAG_MAXIMUM_ALLOWED,
4091                         &attr_data->attr_data.aapl.max_access);
4092                 if (!NT_STATUS_IS_OK(status)) {
4093                         goto fail;
4094                 }
4095         }
4096
4097         return NT_STATUS_OK;
4098
4099 fail:
4100         DEBUG(1, ("fruit_readdir_attr %s, error: %s\n",
4101                   fname->base_name, nt_errstr(status)));
4102         TALLOC_FREE(*pattr_data);
4103         return status;
4104 }
4105
4106 static NTSTATUS fruit_fget_nt_acl(vfs_handle_struct *handle,
4107                                   files_struct *fsp,
4108                                   uint32_t security_info,
4109                                   TALLOC_CTX *mem_ctx,
4110                                   struct security_descriptor **ppdesc)
4111 {
4112         NTSTATUS status;
4113         struct security_ace ace;
4114         struct dom_sid sid;
4115         struct fruit_config_data *config;
4116
4117         SMB_VFS_HANDLE_GET_DATA(handle, config,
4118                                 struct fruit_config_data,
4119                                 return NT_STATUS_UNSUCCESSFUL);
4120
4121         status = SMB_VFS_NEXT_FGET_NT_ACL(handle, fsp, security_info,
4122                                           mem_ctx, ppdesc);
4123         if (!NT_STATUS_IS_OK(status)) {
4124                 return status;
4125         }
4126
4127         /*
4128          * Add MS NFS style ACEs with uid, gid and mode
4129          */
4130         if (!global_fruit_config.nego_aapl) {
4131                 return NT_STATUS_OK;
4132         }
4133         if (!config->unix_info_enabled) {
4134                 return NT_STATUS_OK;
4135         }
4136
4137         /* First remove any existing ACE's with NFS style mode/uid/gid SIDs. */
4138         status = remove_virtual_nfs_aces(*ppdesc);
4139         if (!NT_STATUS_IS_OK(status)) {
4140                 DBG_WARNING("failed to remove MS NFS style ACEs\n");
4141                 return status;
4142         }
4143
4144         /* MS NFS style mode */
4145         sid_compose(&sid, &global_sid_Unix_NFS_Mode, fsp->fsp_name->st.st_ex_mode);
4146         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
4147         status = security_descriptor_dacl_add(*ppdesc, &ace);
4148         if (!NT_STATUS_IS_OK(status)) {
4149                 DEBUG(1,("failed to add MS NFS style ACE\n"));
4150                 return status;
4151         }
4152
4153         /* MS NFS style uid */
4154         sid_compose(&sid, &global_sid_Unix_NFS_Users, fsp->fsp_name->st.st_ex_uid);
4155         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
4156         status = security_descriptor_dacl_add(*ppdesc, &ace);
4157         if (!NT_STATUS_IS_OK(status)) {
4158                 DEBUG(1,("failed to add MS NFS style ACE\n"));
4159                 return status;
4160         }
4161
4162         /* MS NFS style gid */
4163         sid_compose(&sid, &global_sid_Unix_NFS_Groups, fsp->fsp_name->st.st_ex_gid);
4164         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
4165         status = security_descriptor_dacl_add(*ppdesc, &ace);
4166         if (!NT_STATUS_IS_OK(status)) {
4167                 DEBUG(1,("failed to add MS NFS style ACE\n"));
4168                 return status;
4169         }
4170
4171         return NT_STATUS_OK;
4172 }
4173
4174 static NTSTATUS fruit_fset_nt_acl(vfs_handle_struct *handle,
4175                                   files_struct *fsp,
4176                                   uint32_t security_info_sent,
4177                                   const struct security_descriptor *orig_psd)
4178 {
4179         NTSTATUS status;
4180         bool do_chmod;
4181         mode_t ms_nfs_mode = 0;
4182         int result;
4183         struct security_descriptor *psd = NULL;
4184         uint32_t orig_num_aces = 0;
4185
4186         if (orig_psd->dacl != NULL) {
4187                 orig_num_aces = orig_psd->dacl->num_aces;
4188         }
4189
4190         psd = security_descriptor_copy(talloc_tos(), orig_psd);
4191         if (psd == NULL) {
4192                 return NT_STATUS_NO_MEMORY;
4193         }
4194
4195         DBG_DEBUG("fruit_fset_nt_acl: %s\n", fsp_str_dbg(fsp));
4196
4197         status = check_ms_nfs(handle, fsp, psd, &ms_nfs_mode, &do_chmod);
4198         if (!NT_STATUS_IS_OK(status)) {
4199                 DEBUG(1, ("fruit_fset_nt_acl: check_ms_nfs failed%s\n", fsp_str_dbg(fsp)));
4200                 TALLOC_FREE(psd);
4201                 return status;
4202         }
4203
4204         /*
4205          * If only ms_nfs ACE entries were sent, ensure we set the DACL
4206          * sent/present flags correctly now we've removed them.
4207          */
4208
4209         if (orig_num_aces != 0) {
4210                 /*
4211                  * Are there any ACE's left ?
4212                  */
4213                 if (psd->dacl->num_aces == 0) {
4214                         /* No - clear the DACL sent/present flags. */
4215                         security_info_sent &= ~SECINFO_DACL;
4216                         psd->type &= ~SEC_DESC_DACL_PRESENT;
4217                 }
4218         }
4219
4220         status = SMB_VFS_NEXT_FSET_NT_ACL(handle, fsp, security_info_sent, psd);
4221         if (!NT_STATUS_IS_OK(status)) {
4222                 DEBUG(1, ("fruit_fset_nt_acl: SMB_VFS_NEXT_FSET_NT_ACL failed%s\n", fsp_str_dbg(fsp)));
4223                 TALLOC_FREE(psd);
4224                 return status;
4225         }
4226
4227         if (do_chmod) {
4228                 result = SMB_VFS_FCHMOD(fsp, ms_nfs_mode);
4229                 if (result != 0) {
4230                         DBG_WARNING("%s, result: %d, %04o error %s\n",
4231                                 fsp_str_dbg(fsp),
4232                                 result,
4233                                 (unsigned)ms_nfs_mode,
4234                                 strerror(errno));
4235                         status = map_nt_error_from_unix(errno);
4236                         TALLOC_FREE(psd);
4237                         return status;
4238                 }
4239         }
4240
4241         TALLOC_FREE(psd);
4242         return NT_STATUS_OK;
4243 }
4244
4245 static struct vfs_offload_ctx *fruit_offload_ctx;
4246
4247 struct fruit_offload_read_state {
4248         struct vfs_handle_struct *handle;
4249         struct tevent_context *ev;
4250         files_struct *fsp;
4251         uint32_t fsctl;
4252         DATA_BLOB token;
4253 };
4254
4255 static void fruit_offload_read_done(struct tevent_req *subreq);
4256
4257 static struct tevent_req *fruit_offload_read_send(
4258         TALLOC_CTX *mem_ctx,
4259         struct tevent_context *ev,
4260         struct vfs_handle_struct *handle,
4261         files_struct *fsp,
4262         uint32_t fsctl,
4263         uint32_t ttl,
4264         off_t offset,
4265         size_t to_copy)
4266 {
4267         struct tevent_req *req = NULL;
4268         struct tevent_req *subreq = NULL;
4269         struct fruit_offload_read_state *state = NULL;
4270
4271         req = tevent_req_create(mem_ctx, &state,
4272                                 struct fruit_offload_read_state);
4273         if (req == NULL) {
4274                 return NULL;
4275         }
4276         *state = (struct fruit_offload_read_state) {
4277                 .handle = handle,
4278                 .ev = ev,
4279                 .fsp = fsp,
4280                 .fsctl = fsctl,
4281         };
4282
4283         subreq = SMB_VFS_NEXT_OFFLOAD_READ_SEND(mem_ctx, ev, handle, fsp,
4284                                                 fsctl, ttl, offset, to_copy);
4285         if (tevent_req_nomem(subreq, req)) {
4286                 return tevent_req_post(req, ev);
4287         }
4288         tevent_req_set_callback(subreq, fruit_offload_read_done, req);
4289         return req;
4290 }
4291
4292 static void fruit_offload_read_done(struct tevent_req *subreq)
4293 {
4294         struct tevent_req *req = tevent_req_callback_data(
4295                 subreq, struct tevent_req);
4296         struct fruit_offload_read_state *state = tevent_req_data(
4297                 req, struct fruit_offload_read_state);
4298         NTSTATUS status;
4299
4300         status = SMB_VFS_NEXT_OFFLOAD_READ_RECV(subreq,
4301                                                 state->handle,
4302                                                 state,
4303                                                 &state->token);
4304         TALLOC_FREE(subreq);
4305         if (tevent_req_nterror(req, status)) {
4306                 return;
4307         }
4308
4309         if (state->fsctl != FSCTL_SRV_REQUEST_RESUME_KEY) {
4310                 tevent_req_done(req);
4311                 return;
4312         }
4313
4314         status = vfs_offload_token_ctx_init(state->fsp->conn->sconn->client,
4315                                             &fruit_offload_ctx);
4316         if (tevent_req_nterror(req, status)) {
4317                 return;
4318         }
4319
4320         status = vfs_offload_token_db_store_fsp(fruit_offload_ctx,
4321                                                 state->fsp,
4322                                                 &state->token);
4323         if (tevent_req_nterror(req, status)) {
4324                 return;
4325         }
4326
4327         tevent_req_done(req);
4328         return;
4329 }
4330
4331 static NTSTATUS fruit_offload_read_recv(struct tevent_req *req,
4332                                         struct vfs_handle_struct *handle,
4333                                         TALLOC_CTX *mem_ctx,
4334                                         DATA_BLOB *token)
4335 {
4336         struct fruit_offload_read_state *state = tevent_req_data(
4337                 req, struct fruit_offload_read_state);
4338         NTSTATUS status;
4339
4340         if (tevent_req_is_nterror(req, &status)) {
4341                 tevent_req_received(req);
4342                 return status;
4343         }
4344
4345         token->length = state->token.length;
4346         token->data = talloc_move(mem_ctx, &state->token.data);
4347
4348         tevent_req_received(req);
4349         return NT_STATUS_OK;
4350 }
4351
4352 struct fruit_offload_write_state {
4353         struct vfs_handle_struct *handle;
4354         off_t copied;
4355         struct files_struct *src_fsp;
4356         struct files_struct *dst_fsp;
4357         bool is_copyfile;
4358 };
4359
4360 static void fruit_offload_write_done(struct tevent_req *subreq);
4361 static struct tevent_req *fruit_offload_write_send(struct vfs_handle_struct *handle,
4362                                                 TALLOC_CTX *mem_ctx,
4363                                                 struct tevent_context *ev,
4364                                                 uint32_t fsctl,
4365                                                 DATA_BLOB *token,
4366                                                 off_t transfer_offset,
4367                                                 struct files_struct *dest_fsp,
4368                                                 off_t dest_off,
4369                                                 off_t num)
4370 {
4371         struct tevent_req *req, *subreq;
4372         struct fruit_offload_write_state *state;
4373         NTSTATUS status;
4374         struct fruit_config_data *config;
4375         off_t src_off = transfer_offset;
4376         files_struct *src_fsp = NULL;
4377         off_t to_copy = num;
4378         bool copyfile_enabled = false;
4379
4380         DEBUG(10,("soff: %ju, doff: %ju, len: %ju\n",
4381                   (uintmax_t)src_off, (uintmax_t)dest_off, (uintmax_t)num));
4382
4383         SMB_VFS_HANDLE_GET_DATA(handle, config,
4384                                 struct fruit_config_data,
4385                                 return NULL);
4386
4387         req = tevent_req_create(mem_ctx, &state,
4388                                 struct fruit_offload_write_state);
4389         if (req == NULL) {
4390                 return NULL;
4391         }
4392         state->handle = handle;
4393         state->dst_fsp = dest_fsp;
4394
4395         switch (fsctl) {
4396         case FSCTL_SRV_COPYCHUNK:
4397         case FSCTL_SRV_COPYCHUNK_WRITE:
4398                 copyfile_enabled = config->copyfile_enabled;
4399                 break;
4400         default:
4401                 break;
4402         }
4403
4404         /*
4405          * Check if this a OS X copyfile style copychunk request with
4406          * a requested chunk count of 0 that was translated to a
4407          * offload_write_send VFS call overloading the parameters src_off
4408          * = dest_off = num = 0.
4409          */
4410         if (copyfile_enabled && num == 0 && src_off == 0 && dest_off == 0) {
4411                 status = vfs_offload_token_db_fetch_fsp(
4412                         fruit_offload_ctx, token, &src_fsp);
4413                 if (tevent_req_nterror(req, status)) {
4414                         return tevent_req_post(req, ev);
4415                 }
4416                 state->src_fsp = src_fsp;
4417
4418                 status = vfs_stat_fsp(src_fsp);
4419                 if (tevent_req_nterror(req, status)) {
4420                         return tevent_req_post(req, ev);
4421                 }
4422
4423                 to_copy = src_fsp->fsp_name->st.st_ex_size;
4424                 state->is_copyfile = true;
4425         }
4426
4427         subreq = SMB_VFS_NEXT_OFFLOAD_WRITE_SEND(handle,
4428                                               mem_ctx,
4429                                               ev,
4430                                               fsctl,
4431                                               token,
4432                                               transfer_offset,
4433                                               dest_fsp,
4434                                               dest_off,
4435                                               to_copy);
4436         if (tevent_req_nomem(subreq, req)) {
4437                 return tevent_req_post(req, ev);
4438         }
4439
4440         tevent_req_set_callback(subreq, fruit_offload_write_done, req);
4441         return req;
4442 }
4443
4444 static void fruit_offload_write_done(struct tevent_req *subreq)
4445 {
4446         struct tevent_req *req = tevent_req_callback_data(
4447                 subreq, struct tevent_req);
4448         struct fruit_offload_write_state *state = tevent_req_data(
4449                 req, struct fruit_offload_write_state);
4450         NTSTATUS status;
4451         unsigned int num_streams = 0;
4452         struct stream_struct *streams = NULL;
4453         unsigned int i;
4454         struct smb_filename *src_fname_tmp = NULL;
4455         struct smb_filename *dst_fname_tmp = NULL;
4456
4457         status = SMB_VFS_NEXT_OFFLOAD_WRITE_RECV(state->handle,
4458                                               subreq,
4459                                               &state->copied);
4460         TALLOC_FREE(subreq);
4461         if (tevent_req_nterror(req, status)) {
4462                 return;
4463         }
4464
4465         if (!state->is_copyfile) {
4466                 tevent_req_done(req);
4467                 return;
4468         }
4469
4470         /*
4471          * Now copy all remaining streams. We know the share supports
4472          * streams, because we're in vfs_fruit. We don't do this async
4473          * because streams are few and small.
4474          */
4475         status = vfs_streaminfo(state->handle->conn, state->src_fsp,
4476                                 state->src_fsp->fsp_name,
4477                                 req, &num_streams, &streams);
4478         if (tevent_req_nterror(req, status)) {
4479                 return;
4480         }
4481
4482         if (num_streams == 1) {
4483                 /* There is always one stream, ::$DATA. */
4484                 tevent_req_done(req);
4485                 return;
4486         }
4487
4488         for (i = 0; i < num_streams; i++) {
4489                 DEBUG(10, ("%s: stream: '%s'/%zu\n",
4490                           __func__, streams[i].name, (size_t)streams[i].size));
4491
4492                 src_fname_tmp = synthetic_smb_fname(
4493                         req,
4494                         state->src_fsp->fsp_name->base_name,
4495                         streams[i].name,
4496                         NULL,
4497                         state->src_fsp->fsp_name->flags);
4498                 if (tevent_req_nomem(src_fname_tmp, req)) {
4499                         return;
4500                 }
4501
4502                 if (is_ntfs_default_stream_smb_fname(src_fname_tmp)) {
4503                         TALLOC_FREE(src_fname_tmp);
4504                         continue;
4505                 }
4506
4507                 dst_fname_tmp = synthetic_smb_fname(
4508                         req,
4509                         state->dst_fsp->fsp_name->base_name,
4510                         streams[i].name,
4511                         NULL,
4512                         state->dst_fsp->fsp_name->flags);
4513                 if (tevent_req_nomem(dst_fname_tmp, req)) {
4514                         TALLOC_FREE(src_fname_tmp);
4515                         return;
4516                 }
4517
4518                 status = copy_file(req,
4519                                    state->handle->conn,
4520                                    src_fname_tmp,
4521                                    dst_fname_tmp,
4522                                    OPENX_FILE_CREATE_IF_NOT_EXIST,
4523                                    0, false);
4524                 if (!NT_STATUS_IS_OK(status)) {
4525                         DEBUG(1, ("%s: copy %s to %s failed: %s\n", __func__,
4526                                   smb_fname_str_dbg(src_fname_tmp),
4527                                   smb_fname_str_dbg(dst_fname_tmp),
4528                                   nt_errstr(status)));
4529                         TALLOC_FREE(src_fname_tmp);
4530                         TALLOC_FREE(dst_fname_tmp);
4531                         tevent_req_nterror(req, status);
4532                         return;
4533                 }
4534
4535                 TALLOC_FREE(src_fname_tmp);
4536                 TALLOC_FREE(dst_fname_tmp);
4537         }
4538
4539         TALLOC_FREE(streams);
4540         TALLOC_FREE(src_fname_tmp);
4541         TALLOC_FREE(dst_fname_tmp);
4542         tevent_req_done(req);
4543 }
4544
4545 static NTSTATUS fruit_offload_write_recv(struct vfs_handle_struct *handle,
4546                                       struct tevent_req *req,
4547                                       off_t *copied)
4548 {
4549         struct fruit_offload_write_state *state = tevent_req_data(
4550                 req, struct fruit_offload_write_state);
4551         NTSTATUS status;
4552
4553         if (tevent_req_is_nterror(req, &status)) {
4554                 DEBUG(1, ("server side copy chunk failed: %s\n",
4555                           nt_errstr(status)));
4556                 *copied = 0;
4557                 tevent_req_received(req);
4558                 return status;
4559         }
4560
4561         *copied = state->copied;
4562         tevent_req_received(req);
4563
4564         return NT_STATUS_OK;
4565 }
4566
4567 static char *fruit_get_bandsize_line(char **lines, int numlines)
4568 {
4569         static regex_t re;
4570         static bool re_initialized = false;
4571         int i;
4572         int ret;
4573
4574         if (!re_initialized) {
4575                 ret = regcomp(&re, "^[[:blank:]]*<key>band-size</key>$", 0);
4576                 if (ret != 0) {
4577                         return NULL;
4578                 }
4579                 re_initialized = true;
4580         }
4581
4582         for (i = 0; i < numlines; i++) {
4583                 regmatch_t matches[1];
4584
4585                 ret = regexec(&re, lines[i], 1, matches, 0);
4586                 if (ret == 0) {
4587                         /*
4588                          * Check if the match was on the last line, sa we want
4589                          * the subsequent line.
4590                          */
4591                         if (i + 1 == numlines) {
4592                                 return NULL;
4593                         }
4594                         return lines[i + 1];
4595                 }
4596                 if (ret != REG_NOMATCH) {
4597                         return NULL;
4598                 }
4599         }
4600
4601         return NULL;
4602 }
4603
4604 static bool fruit_get_bandsize_from_line(char *line, size_t *_band_size)
4605 {
4606         static regex_t re;
4607         static bool re_initialized = false;
4608         regmatch_t matches[2];
4609         uint64_t band_size;
4610         int ret;
4611         bool ok;
4612
4613         if (!re_initialized) {
4614                 ret = regcomp(&re,
4615                               "^[[:blank:]]*"
4616                               "<integer>\\([[:digit:]]*\\)</integer>$",
4617                               0);
4618                 if (ret != 0) {
4619                         return false;
4620                 }
4621                 re_initialized = true;
4622         }
4623
4624         ret = regexec(&re, line, 2, matches, 0);
4625         if (ret != 0) {
4626                 DBG_ERR("regex failed [%s]\n", line);
4627                 return false;
4628         }
4629
4630         line[matches[1].rm_eo] = '\0';
4631
4632         ok = conv_str_u64(&line[matches[1].rm_so], &band_size);
4633         if (!ok) {
4634                 return false;
4635         }
4636         *_band_size = (size_t)band_size;
4637         return true;
4638 }
4639
4640 /*
4641  * This reads and parses an Info.plist from a TM sparsebundle looking for the
4642  * "band-size" key and value.
4643  */
4644 static bool fruit_get_bandsize(vfs_handle_struct *handle,
4645                                const char *dir,
4646                                size_t *band_size)
4647 {
4648 #define INFO_PLIST_MAX_SIZE 64*1024
4649         char *plist = NULL;
4650         struct smb_filename *smb_fname = NULL;
4651         files_struct *fsp = NULL;
4652         uint8_t *file_data = NULL;
4653         char **lines = NULL;
4654         char *band_size_line = NULL;
4655         size_t plist_file_size;
4656         ssize_t nread;
4657         int numlines;
4658         int ret;
4659         bool ok = false;
4660         NTSTATUS status;
4661
4662         plist = talloc_asprintf(talloc_tos(),
4663                                 "%s/%s/Info.plist",
4664                                 handle->conn->connectpath,
4665                                 dir);
4666         if (plist == NULL) {
4667                 ok = false;
4668                 goto out;
4669         }
4670
4671         smb_fname = synthetic_smb_fname(talloc_tos(),
4672                                         plist,
4673                                         NULL,
4674                                         NULL,
4675                                         0);
4676         if (smb_fname == NULL) {
4677                 ok = false;
4678                 goto out;
4679         }
4680
4681         ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
4682         if (ret != 0) {
4683                 DBG_INFO("Ignoring Sparsebundle without Info.plist [%s]\n", dir);
4684                 ok = true;
4685                 goto out;
4686         }
4687
4688         plist_file_size = smb_fname->st.st_ex_size;
4689
4690         if (plist_file_size > INFO_PLIST_MAX_SIZE) {
4691                 DBG_INFO("%s is too large, ignoring\n", plist);
4692                 ok = true;
4693                 goto out;
4694         }
4695
4696         status = SMB_VFS_NEXT_CREATE_FILE(
4697                 handle,                         /* conn */
4698                 NULL,                           /* req */
4699                 0,                              /* root_dir_fid */
4700                 smb_fname,                      /* fname */
4701                 FILE_GENERIC_READ,              /* access_mask */
4702                 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share_access */
4703                 FILE_OPEN,                      /* create_disposition */
4704                 0,                              /* create_options */
4705                 0,                              /* file_attributes */
4706                 INTERNAL_OPEN_ONLY,             /* oplock_request */
4707                 NULL,                           /* lease */
4708                 0,                              /* allocation_size */
4709                 0,                              /* private_flags */
4710                 NULL,                           /* sd */
4711                 NULL,                           /* ea_list */
4712                 &fsp,                           /* result */
4713                 NULL,                           /* psbuf */
4714                 NULL, NULL);                    /* create context */
4715         if (!NT_STATUS_IS_OK(status)) {
4716                 DBG_INFO("Opening [%s] failed [%s]\n",
4717                          smb_fname_str_dbg(smb_fname), nt_errstr(status));
4718                 ok = false;
4719                 goto out;
4720         }
4721
4722         file_data = talloc_array(talloc_tos(), uint8_t, plist_file_size);
4723         if (file_data == NULL) {
4724                 ok = false;
4725                 goto out;
4726         }
4727
4728         nread = SMB_VFS_NEXT_PREAD(handle, fsp, file_data, plist_file_size, 0);
4729         if (nread != plist_file_size) {
4730                 DBG_ERR("Short read on [%s]: %zu/%zd\n",
4731                         fsp_str_dbg(fsp), nread, plist_file_size);
4732                 ok = false;
4733                 goto out;
4734
4735         }
4736
4737         status = close_file(NULL, fsp, NORMAL_CLOSE);
4738         fsp = NULL;
4739         if (!NT_STATUS_IS_OK(status)) {
4740                 DBG_ERR("close_file failed: %s\n", nt_errstr(status));
4741                 ok = false;
4742                 goto out;
4743         }
4744
4745         lines = file_lines_parse((char *)file_data,
4746                                  plist_file_size,
4747                                  &numlines,
4748                                  talloc_tos());
4749         if (lines == NULL) {
4750                 ok = false;
4751                 goto out;
4752         }
4753
4754         band_size_line = fruit_get_bandsize_line(lines, numlines);
4755         if (band_size_line == NULL) {
4756                 DBG_ERR("Didn't find band-size key in [%s]\n",
4757                         smb_fname_str_dbg(smb_fname));
4758                 ok = false;
4759                 goto out;
4760         }
4761
4762         ok = fruit_get_bandsize_from_line(band_size_line, band_size);
4763         if (!ok) {
4764                 DBG_ERR("fruit_get_bandsize_from_line failed\n");
4765                 goto out;
4766         }
4767
4768         DBG_DEBUG("Parsed band-size [%zu] for [%s]\n", *band_size, plist);
4769
4770 out:
4771         if (fsp != NULL) {
4772                 status = close_file(NULL, fsp, NORMAL_CLOSE);
4773                 if (!NT_STATUS_IS_OK(status)) {
4774                         DBG_ERR("close_file failed: %s\n", nt_errstr(status));
4775                 }
4776                 fsp = NULL;
4777         }
4778         TALLOC_FREE(plist);
4779         TALLOC_FREE(smb_fname);
4780         TALLOC_FREE(file_data);
4781         TALLOC_FREE(lines);
4782         return ok;
4783 }
4784
4785 struct fruit_disk_free_state {
4786         off_t total_size;
4787 };
4788
4789 static bool fruit_get_num_bands(vfs_handle_struct *handle,
4790                                 const char *bundle,
4791                                 size_t *_nbands)
4792 {
4793         char *path = NULL;
4794         struct smb_filename *bands_dir = NULL;
4795         struct smb_Dir *dir_hnd = NULL;
4796         const char *dname = NULL;
4797         char *talloced = NULL;
4798         long offset = 0;
4799         size_t nbands;
4800
4801         path = talloc_asprintf(talloc_tos(),
4802                                "%s/%s/bands",
4803                                handle->conn->connectpath,
4804                                bundle);
4805         if (path == NULL) {
4806                 return false;
4807         }
4808
4809         bands_dir = synthetic_smb_fname(talloc_tos(),
4810                                         path,
4811                                         NULL,
4812                                         NULL,
4813                                         0);
4814         TALLOC_FREE(path);
4815         if (bands_dir == NULL) {
4816                 return false;
4817         }
4818
4819         dir_hnd = OpenDir(talloc_tos(), handle->conn, bands_dir, NULL, 0);
4820         if (dir_hnd == NULL) {
4821                 TALLOC_FREE(bands_dir);
4822                 return false;
4823         }
4824
4825         nbands = 0;
4826
4827         while ((dname = ReadDirName(dir_hnd, &offset, NULL, &talloced))
4828                != NULL)
4829         {
4830                 if (ISDOT(dname) || ISDOTDOT(dname)) {
4831                         continue;
4832                 }
4833                 nbands++;
4834         }
4835         TALLOC_FREE(dir_hnd);
4836
4837         DBG_DEBUG("%zu bands in [%s]\n", nbands, smb_fname_str_dbg(bands_dir));
4838
4839         TALLOC_FREE(bands_dir);
4840
4841         *_nbands = nbands;
4842         return true;
4843 }
4844
4845 static bool fruit_tmsize_do_dirent(vfs_handle_struct *handle,
4846                                    struct fruit_disk_free_state *state,
4847                                    const char *name)
4848 {
4849         bool ok;
4850         char *p = NULL;
4851         size_t sparsebundle_strlen = strlen("sparsebundle");
4852         size_t bandsize = 0;
4853         size_t nbands;
4854         off_t tm_size;
4855
4856         p = strstr(name, "sparsebundle");
4857         if (p == NULL) {
4858                 return true;
4859         }
4860
4861         if (p[sparsebundle_strlen] != '\0') {
4862                 return true;
4863         }
4864
4865         DBG_DEBUG("Processing sparsebundle [%s]\n", name);
4866
4867         ok = fruit_get_bandsize(handle, name, &bandsize);
4868         if (!ok) {
4869                 /*
4870                  * Beware of race conditions: this may be an uninitialized
4871                  * Info.plist that a client is just creating. We don't want let
4872                  * this to trigger complete failure.
4873                  */
4874                 DBG_ERR("Processing sparsebundle [%s] failed\n", name);
4875                 return true;
4876         }
4877
4878         ok = fruit_get_num_bands(handle, name, &nbands);
4879         if (!ok) {
4880                 /*
4881                  * Beware of race conditions: this may be a backup sparsebundle
4882                  * in an early stage lacking a bands subdirectory. We don't want
4883                  * let this to trigger complete failure.
4884                  */
4885                 DBG_ERR("Processing sparsebundle [%s] failed\n", name);
4886                 return true;
4887         }
4888
4889         /*
4890          * Arithmetic on 32-bit systems may cause overflow, depending on
4891          * size_t precision. First we check its unlikely, then we
4892          * force the precision into target off_t, then we check that
4893          * the total did not overflow either.
4894          */
4895         if (bandsize > SIZE_MAX/nbands) {
4896                 DBG_ERR("tmsize potential overflow: bandsize [%zu] nbands [%zu]\n",
4897                         bandsize, nbands);
4898                 return false;
4899         }
4900         tm_size = (off_t)bandsize * (off_t)nbands;
4901
4902         if (state->total_size + tm_size < state->total_size) {
4903                 DBG_ERR("tm total size overflow: bandsize [%zu] nbands [%zu]\n",
4904                         bandsize, nbands);
4905                 return false;
4906         }
4907
4908         state->total_size += tm_size;
4909
4910         DBG_DEBUG("[%s] tm_size [%jd] total_size [%jd]\n",
4911                   name, (intmax_t)tm_size, (intmax_t)state->total_size);
4912
4913         return true;
4914 }
4915
4916 /**
4917  * Calculate used size of a TimeMachine volume
4918  *
4919  * This assumes that the volume is used only for TimeMachine.
4920  *
4921  * - readdir(basedir of share), then
4922  * - for every element that matches regex "^\(.*\)\.sparsebundle$" :
4923  * - parse "\1.sparsebundle/Info.plist" and read the band-size XML key
4924  * - count band files in "\1.sparsebundle/bands/"
4925  * - calculate used size of all bands: band_count * band_size
4926  **/
4927 static uint64_t fruit_disk_free(vfs_handle_struct *handle,
4928                                 const struct smb_filename *smb_fname,
4929                                 uint64_t *_bsize,
4930                                 uint64_t *_dfree,
4931                                 uint64_t *_dsize)
4932 {
4933         struct fruit_config_data *config = NULL;
4934         struct fruit_disk_free_state state = {0};
4935         struct smb_Dir *dir_hnd = NULL;
4936         const char *dname = NULL;
4937         char *talloced = NULL;
4938         long offset = 0;
4939         uint64_t dfree;
4940         uint64_t dsize;
4941         bool ok;
4942
4943         SMB_VFS_HANDLE_GET_DATA(handle, config,
4944                                 struct fruit_config_data,
4945                                 return UINT64_MAX);
4946
4947         if (!config->time_machine ||
4948             config->time_machine_max_size == 0)
4949         {
4950                 return SMB_VFS_NEXT_DISK_FREE(handle,
4951                                               smb_fname,
4952                                               _bsize,
4953                                               _dfree,
4954                                               _dsize);
4955         }
4956
4957         dir_hnd = OpenDir(talloc_tos(), handle->conn, smb_fname, NULL, 0);
4958         if (dir_hnd == NULL) {
4959                 return UINT64_MAX;
4960         }
4961
4962         while ((dname = ReadDirName(dir_hnd, &offset, NULL, &talloced))
4963                != NULL)
4964         {
4965                 ok = fruit_tmsize_do_dirent(handle, &state, dname);
4966                 if (!ok) {
4967                         TALLOC_FREE(talloced);
4968                         TALLOC_FREE(dir_hnd);
4969                         return UINT64_MAX;
4970                 }
4971                 TALLOC_FREE(talloced);
4972         }
4973
4974         TALLOC_FREE(dir_hnd);
4975
4976         dsize = config->time_machine_max_size / 512;
4977         dfree = dsize - (state.total_size / 512);
4978         if (dfree > dsize) {
4979                 dfree = 0;
4980         }
4981
4982         *_bsize = 512;
4983         *_dsize = dsize;
4984         *_dfree = dfree;
4985         return dfree / 2;
4986 }
4987
4988 static uint64_t fruit_fs_file_id(struct vfs_handle_struct *handle,
4989                                  const SMB_STRUCT_STAT *psbuf)
4990 {
4991         struct fruit_config_data *config = NULL;
4992
4993         SMB_VFS_HANDLE_GET_DATA(handle, config,
4994                                 struct fruit_config_data,
4995                                 return 0);
4996
4997         if (global_fruit_config.nego_aapl &&
4998             config->aapl_zero_file_id)
4999         {
5000                 return 0;
5001         }
5002
5003         return SMB_VFS_NEXT_FS_FILE_ID(handle, psbuf);
5004 }
5005
5006 static struct vfs_fn_pointers vfs_fruit_fns = {
5007         .connect_fn = fruit_connect,
5008         .disk_free_fn = fruit_disk_free,
5009
5010         /* File operations */
5011         .chmod_fn = fruit_chmod,
5012         .unlinkat_fn = fruit_unlinkat,
5013         .renameat_fn = fruit_renameat,
5014         .open_fn = fruit_open,
5015         .close_fn = fruit_close,
5016         .pread_fn = fruit_pread,
5017         .pwrite_fn = fruit_pwrite,
5018         .pread_send_fn = fruit_pread_send,
5019         .pread_recv_fn = fruit_pread_recv,
5020         .pwrite_send_fn = fruit_pwrite_send,
5021         .pwrite_recv_fn = fruit_pwrite_recv,
5022         .stat_fn = fruit_stat,
5023         .lstat_fn = fruit_lstat,
5024         .fstat_fn = fruit_fstat,
5025         .streaminfo_fn = fruit_streaminfo,
5026         .ntimes_fn = fruit_ntimes,
5027         .ftruncate_fn = fruit_ftruncate,
5028         .fallocate_fn = fruit_fallocate,
5029         .create_file_fn = fruit_create_file,
5030         .readdir_attr_fn = fruit_readdir_attr,
5031         .offload_read_send_fn = fruit_offload_read_send,
5032         .offload_read_recv_fn = fruit_offload_read_recv,
5033         .offload_write_send_fn = fruit_offload_write_send,
5034         .offload_write_recv_fn = fruit_offload_write_recv,
5035         .fs_file_id_fn = fruit_fs_file_id,
5036
5037         /* NT ACL operations */
5038         .fget_nt_acl_fn = fruit_fget_nt_acl,
5039         .fset_nt_acl_fn = fruit_fset_nt_acl,
5040 };
5041
5042 static_decl_vfs;
5043 NTSTATUS vfs_fruit_init(TALLOC_CTX *ctx)
5044 {
5045         NTSTATUS ret = smb_register_vfs(SMB_VFS_INTERFACE_VERSION, "fruit",
5046                                         &vfs_fruit_fns);
5047         if (!NT_STATUS_IS_OK(ret)) {
5048                 return ret;
5049         }
5050
5051         vfs_fruit_debug_level = debug_add_class("fruit");
5052         if (vfs_fruit_debug_level == -1) {
5053                 vfs_fruit_debug_level = DBGC_VFS;
5054                 DEBUG(0, ("%s: Couldn't register custom debugging class!\n",
5055                           "vfs_fruit_init"));
5056         } else {
5057                 DEBUG(10, ("%s: Debug class number of '%s': %d\n",
5058                            "vfs_fruit_init","fruit",vfs_fruit_debug_level));
5059         }
5060
5061         return ret;
5062 }