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