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