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