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