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