s3: smbd: vfs_fruit: Replace code in check_ms_nfs() with remove_virtual_nfs_aces().
[metze/samba/wip.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         off_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 = conv_str_size(tm_size_str);
1993         }
1994
1995         SMB_VFS_HANDLE_SET_DATA(handle, config,
1996                                 NULL, struct fruit_config_data,
1997                                 return -1);
1998
1999         return 0;
2000 }
2001
2002 /**
2003  * Prepend "._" to a basename
2004  * Return a new struct smb_filename with stream_name == NULL.
2005  **/
2006 static int adouble_path(TALLOC_CTX *ctx,
2007                         const struct smb_filename *smb_fname_in,
2008                         struct smb_filename **pp_smb_fname_out)
2009 {
2010         char *parent;
2011         const char *base;
2012         struct smb_filename *smb_fname = cp_smb_filename(ctx,
2013                                                 smb_fname_in);
2014
2015         if (smb_fname == NULL) {
2016                 return -1;
2017         }
2018
2019         /* We need streamname to be NULL */
2020         TALLOC_FREE(smb_fname->stream_name);
2021
2022         /* And we're replacing base_name. */
2023         TALLOC_FREE(smb_fname->base_name);
2024
2025         if (!parent_dirname(smb_fname, smb_fname_in->base_name,
2026                                 &parent, &base)) {
2027                 TALLOC_FREE(smb_fname);
2028                 return -1;
2029         }
2030
2031         smb_fname->base_name = talloc_asprintf(smb_fname,
2032                                         "%s/._%s", parent, base);
2033         if (smb_fname->base_name == NULL) {
2034                 TALLOC_FREE(smb_fname);
2035                 return -1;
2036         }
2037
2038         *pp_smb_fname_out = smb_fname;
2039
2040         return 0;
2041 }
2042
2043 /**
2044  * Allocate and initialize an AfpInfo struct
2045  **/
2046 static AfpInfo *afpinfo_new(TALLOC_CTX *ctx)
2047 {
2048         AfpInfo *ai = talloc_zero(ctx, AfpInfo);
2049         if (ai == NULL) {
2050                 return NULL;
2051         }
2052         ai->afpi_Signature = AFP_Signature;
2053         ai->afpi_Version = AFP_Version;
2054         ai->afpi_BackupTime = AD_DATE_START;
2055         return ai;
2056 }
2057
2058 /**
2059  * Pack an AfpInfo struct into a buffer
2060  *
2061  * Buffer size must be at least AFP_INFO_SIZE
2062  * Returns size of packed buffer
2063  **/
2064 static ssize_t afpinfo_pack(const AfpInfo *ai, char *buf)
2065 {
2066         memset(buf, 0, AFP_INFO_SIZE);
2067
2068         RSIVAL(buf, 0, ai->afpi_Signature);
2069         RSIVAL(buf, 4, ai->afpi_Version);
2070         RSIVAL(buf, 12, ai->afpi_BackupTime);
2071         memcpy(buf + 16, ai->afpi_FinderInfo, sizeof(ai->afpi_FinderInfo));
2072
2073         return AFP_INFO_SIZE;
2074 }
2075
2076 /**
2077  * Unpack a buffer into a AfpInfo structure
2078  *
2079  * Buffer size must be at least AFP_INFO_SIZE
2080  * Returns allocated AfpInfo struct
2081  **/
2082 static AfpInfo *afpinfo_unpack(TALLOC_CTX *ctx, const void *data)
2083 {
2084         AfpInfo *ai = talloc_zero(ctx, AfpInfo);
2085         if (ai == NULL) {
2086                 return NULL;
2087         }
2088
2089         ai->afpi_Signature = RIVAL(data, 0);
2090         ai->afpi_Version = RIVAL(data, 4);
2091         ai->afpi_BackupTime = RIVAL(data, 12);
2092         memcpy(ai->afpi_FinderInfo, (const char *)data + 16,
2093                sizeof(ai->afpi_FinderInfo));
2094
2095         if (ai->afpi_Signature != AFP_Signature
2096             || ai->afpi_Version != AFP_Version) {
2097                 DEBUG(1, ("Bad AfpInfo signature or version\n"));
2098                 TALLOC_FREE(ai);
2099         }
2100
2101         return ai;
2102 }
2103
2104 /**
2105  * Fake an inode number from the md5 hash of the (xattr) name
2106  **/
2107 static SMB_INO_T fruit_inode(const SMB_STRUCT_STAT *sbuf, const char *sname)
2108 {
2109         MD5_CTX ctx;
2110         unsigned char hash[16];
2111         SMB_INO_T result;
2112         char *upper_sname;
2113
2114         upper_sname = talloc_strdup_upper(talloc_tos(), sname);
2115         SMB_ASSERT(upper_sname != NULL);
2116
2117         MD5Init(&ctx);
2118         MD5Update(&ctx, (const unsigned char *)&(sbuf->st_ex_dev),
2119                   sizeof(sbuf->st_ex_dev));
2120         MD5Update(&ctx, (const unsigned char *)&(sbuf->st_ex_ino),
2121                   sizeof(sbuf->st_ex_ino));
2122         MD5Update(&ctx, (unsigned char *)upper_sname,
2123                   talloc_get_size(upper_sname)-1);
2124         MD5Final(hash, &ctx);
2125
2126         TALLOC_FREE(upper_sname);
2127
2128         /* Hopefully all the variation is in the lower 4 (or 8) bytes! */
2129         memcpy(&result, hash, sizeof(result));
2130
2131         DEBUG(10, ("fruit_inode \"%s\": ino=0x%llu\n",
2132                    sname, (unsigned long long)result));
2133
2134         return result;
2135 }
2136
2137 static bool add_fruit_stream(TALLOC_CTX *mem_ctx, unsigned int *num_streams,
2138                              struct stream_struct **streams,
2139                              const char *name, off_t size,
2140                              off_t alloc_size)
2141 {
2142         struct stream_struct *tmp;
2143
2144         tmp = talloc_realloc(mem_ctx, *streams, struct stream_struct,
2145                              (*num_streams)+1);
2146         if (tmp == NULL) {
2147                 return false;
2148         }
2149
2150         tmp[*num_streams].name = talloc_asprintf(tmp, "%s:$DATA", name);
2151         if (tmp[*num_streams].name == NULL) {
2152                 return false;
2153         }
2154
2155         tmp[*num_streams].size = size;
2156         tmp[*num_streams].alloc_size = alloc_size;
2157
2158         *streams = tmp;
2159         *num_streams += 1;
2160         return true;
2161 }
2162
2163 static bool filter_empty_rsrc_stream(unsigned int *num_streams,
2164                                      struct stream_struct **streams)
2165 {
2166         struct stream_struct *tmp = *streams;
2167         unsigned int i;
2168
2169         if (*num_streams == 0) {
2170                 return true;
2171         }
2172
2173         for (i = 0; i < *num_streams; i++) {
2174                 if (strequal_m(tmp[i].name, AFPRESOURCE_STREAM)) {
2175                         break;
2176                 }
2177         }
2178
2179         if (i == *num_streams) {
2180                 return true;
2181         }
2182
2183         if (tmp[i].size > 0) {
2184                 return true;
2185         }
2186
2187         TALLOC_FREE(tmp[i].name);
2188         if (*num_streams - 1 > i) {
2189                 memmove(&tmp[i], &tmp[i+1],
2190                         (*num_streams - i - 1) * sizeof(struct stream_struct));
2191         }
2192
2193         *num_streams -= 1;
2194         return true;
2195 }
2196
2197 static bool del_fruit_stream(TALLOC_CTX *mem_ctx, unsigned int *num_streams,
2198                              struct stream_struct **streams,
2199                              const char *name)
2200 {
2201         struct stream_struct *tmp = *streams;
2202         unsigned int i;
2203
2204         if (*num_streams == 0) {
2205                 return true;
2206         }
2207
2208         for (i = 0; i < *num_streams; i++) {
2209                 if (strequal_m(tmp[i].name, name)) {
2210                         break;
2211                 }
2212         }
2213
2214         if (i == *num_streams) {
2215                 return true;
2216         }
2217
2218         TALLOC_FREE(tmp[i].name);
2219         if (*num_streams - 1 > i) {
2220                 memmove(&tmp[i], &tmp[i+1],
2221                         (*num_streams - i - 1) * sizeof(struct stream_struct));
2222         }
2223
2224         *num_streams -= 1;
2225         return true;
2226 }
2227
2228 static bool ad_empty_finderinfo(const struct adouble *ad)
2229 {
2230         int cmp;
2231         char emptybuf[ADEDLEN_FINDERI] = {0};
2232         char *fi = NULL;
2233
2234         fi = ad_get_entry(ad, ADEID_FINDERI);
2235         if (fi == NULL) {
2236                 DBG_ERR("Missing FinderInfo in struct adouble [%p]\n", ad);
2237                 return false;
2238         }
2239
2240         cmp = memcmp(emptybuf, fi, ADEDLEN_FINDERI);
2241         return (cmp == 0);
2242 }
2243
2244 static bool ai_empty_finderinfo(const AfpInfo *ai)
2245 {
2246         int cmp;
2247         char emptybuf[ADEDLEN_FINDERI] = {0};
2248
2249         cmp = memcmp(emptybuf, &ai->afpi_FinderInfo[0], ADEDLEN_FINDERI);
2250         return (cmp == 0);
2251 }
2252
2253 /**
2254  * Update btime with btime from Netatalk
2255  **/
2256 static void update_btime(vfs_handle_struct *handle,
2257                          struct smb_filename *smb_fname)
2258 {
2259         uint32_t t;
2260         struct timespec creation_time = {0};
2261         struct adouble *ad;
2262         struct fruit_config_data *config = NULL;
2263
2264         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
2265                                 return);
2266
2267         switch (config->meta) {
2268         case FRUIT_META_STREAM:
2269                 return;
2270         case FRUIT_META_NETATALK:
2271                 /* Handled below */
2272                 break;
2273         default:
2274                 DBG_ERR("Unexpected meta config [%d]\n", config->meta);
2275                 return;
2276         }
2277
2278         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
2279         if (ad == NULL) {
2280                 return;
2281         }
2282         if (ad_getdate(ad, AD_DATE_UNIX | AD_DATE_CREATE, &t) != 0) {
2283                 TALLOC_FREE(ad);
2284                 return;
2285         }
2286         TALLOC_FREE(ad);
2287
2288         creation_time.tv_sec = convert_uint32_t_to_time_t(t);
2289         update_stat_ex_create_time(&smb_fname->st, creation_time);
2290
2291         return;
2292 }
2293
2294 /**
2295  * Map an access mask to a Netatalk single byte byte range lock
2296  **/
2297 static off_t access_to_netatalk_brl(enum apple_fork fork_type,
2298                                     uint32_t access_mask)
2299 {
2300         off_t offset;
2301
2302         switch (access_mask) {
2303         case FILE_READ_DATA:
2304                 offset = AD_FILELOCK_OPEN_RD;
2305                 break;
2306
2307         case FILE_WRITE_DATA:
2308         case FILE_APPEND_DATA:
2309                 offset = AD_FILELOCK_OPEN_WR;
2310                 break;
2311
2312         default:
2313                 offset = AD_FILELOCK_OPEN_NONE;
2314                 break;
2315         }
2316
2317         if (fork_type == APPLE_FORK_RSRC) {
2318                 if (offset == AD_FILELOCK_OPEN_NONE) {
2319                         offset = AD_FILELOCK_RSRC_OPEN_NONE;
2320                 } else {
2321                         offset += 2;
2322                 }
2323         }
2324
2325         return offset;
2326 }
2327
2328 /**
2329  * Map a deny mode to a Netatalk brl
2330  **/
2331 static off_t denymode_to_netatalk_brl(enum apple_fork fork_type,
2332                                       uint32_t deny_mode)
2333 {
2334         off_t offset;
2335
2336         switch (deny_mode) {
2337         case DENY_READ:
2338                 offset = AD_FILELOCK_DENY_RD;
2339                 break;
2340
2341         case DENY_WRITE:
2342                 offset = AD_FILELOCK_DENY_WR;
2343                 break;
2344
2345         default:
2346                 smb_panic("denymode_to_netatalk_brl: bad deny mode\n");
2347         }
2348
2349         if (fork_type == APPLE_FORK_RSRC) {
2350                 offset += 2;
2351         }
2352
2353         return offset;
2354 }
2355
2356 /**
2357  * Call fcntl() with an exclusive F_GETLK request in order to
2358  * determine if there's an exisiting shared lock
2359  *
2360  * @return true if the requested lock was found or any error occurred
2361  *         false if the lock was not found
2362  **/
2363 static bool test_netatalk_lock(files_struct *fsp, off_t in_offset)
2364 {
2365         bool result;
2366         off_t offset = in_offset;
2367         off_t len = 1;
2368         int type = F_WRLCK;
2369         pid_t pid;
2370
2371         result = SMB_VFS_GETLOCK(fsp, &offset, &len, &type, &pid);
2372         if (result == false) {
2373                 return true;
2374         }
2375
2376         if (type != F_UNLCK) {
2377                 return true;
2378         }
2379
2380         return false;
2381 }
2382
2383 static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
2384                                    files_struct *fsp,
2385                                    uint32_t access_mask,
2386                                    uint32_t deny_mode)
2387 {
2388         NTSTATUS status = NT_STATUS_OK;
2389         struct byte_range_lock *br_lck = NULL;
2390         bool open_for_reading, open_for_writing, deny_read, deny_write;
2391         off_t off;
2392         bool have_read = false;
2393         int flags;
2394
2395         /* FIXME: hardcoded data fork, add resource fork */
2396         enum apple_fork fork_type = APPLE_FORK_DATA;
2397
2398         DEBUG(10, ("fruit_check_access: %s, am: %s/%s, dm: %s/%s\n",
2399                   fsp_str_dbg(fsp),
2400                   access_mask & FILE_READ_DATA ? "READ" :"-",
2401                   access_mask & FILE_WRITE_DATA ? "WRITE" : "-",
2402                   deny_mode & DENY_READ ? "DENY_READ" : "-",
2403                   deny_mode & DENY_WRITE ? "DENY_WRITE" : "-"));
2404
2405         if (fsp->fh->fd == -1) {
2406                 return NT_STATUS_OK;
2407         }
2408
2409         flags = fcntl(fsp->fh->fd, F_GETFL);
2410         if (flags == -1) {
2411                 DBG_ERR("fcntl get flags [%s] fd [%d] failed [%s]\n",
2412                         fsp_str_dbg(fsp), fsp->fh->fd, strerror(errno));
2413                 return map_nt_error_from_unix(errno);
2414         }
2415
2416         if (flags & (O_RDONLY|O_RDWR)) {
2417                 /*
2418                  * Applying fcntl read locks requires an fd opened for
2419                  * reading. This means we won't be applying locks for
2420                  * files openend write-only, but what can we do...
2421                  */
2422                 have_read = true;
2423         }
2424
2425         /*
2426          * Check read access and deny read mode
2427          */
2428         if ((access_mask & FILE_READ_DATA) || (deny_mode & DENY_READ)) {
2429                 /* Check access */
2430                 open_for_reading = test_netatalk_lock(
2431                         fsp, access_to_netatalk_brl(fork_type, FILE_READ_DATA));
2432
2433                 deny_read = test_netatalk_lock(
2434                         fsp, denymode_to_netatalk_brl(fork_type, DENY_READ));
2435
2436                 DEBUG(10, ("read: %s, deny_write: %s\n",
2437                           open_for_reading == true ? "yes" : "no",
2438                           deny_read == true ? "yes" : "no"));
2439
2440                 if (((access_mask & FILE_READ_DATA) && deny_read)
2441                     || ((deny_mode & DENY_READ) && open_for_reading)) {
2442                         return NT_STATUS_SHARING_VIOLATION;
2443                 }
2444
2445                 /* Set locks */
2446                 if ((access_mask & FILE_READ_DATA) && have_read) {
2447                         off = access_to_netatalk_brl(fork_type, FILE_READ_DATA);
2448                         br_lck = do_lock(
2449                                 handle->conn->sconn->msg_ctx, fsp,
2450                                 fsp->op->global->open_persistent_id, 1, off,
2451                                 READ_LOCK, POSIX_LOCK, false,
2452                                 &status, NULL);
2453
2454                         if (!NT_STATUS_IS_OK(status))  {
2455                                 return status;
2456                         }
2457                         TALLOC_FREE(br_lck);
2458                 }
2459
2460                 if ((deny_mode & DENY_READ) && have_read) {
2461                         off = denymode_to_netatalk_brl(fork_type, DENY_READ);
2462                         br_lck = do_lock(
2463                                 handle->conn->sconn->msg_ctx, fsp,
2464                                 fsp->op->global->open_persistent_id, 1, off,
2465                                 READ_LOCK, POSIX_LOCK, false,
2466                                 &status, NULL);
2467
2468                         if (!NT_STATUS_IS_OK(status)) {
2469                                 return status;
2470                         }
2471                         TALLOC_FREE(br_lck);
2472                 }
2473         }
2474
2475         /*
2476          * Check write access and deny write mode
2477          */
2478         if ((access_mask & FILE_WRITE_DATA) || (deny_mode & DENY_WRITE)) {
2479                 /* Check access */
2480                 open_for_writing = test_netatalk_lock(
2481                         fsp, access_to_netatalk_brl(fork_type, FILE_WRITE_DATA));
2482
2483                 deny_write = test_netatalk_lock(
2484                         fsp, denymode_to_netatalk_brl(fork_type, DENY_WRITE));
2485
2486                 DEBUG(10, ("write: %s, deny_write: %s\n",
2487                           open_for_writing == true ? "yes" : "no",
2488                           deny_write == true ? "yes" : "no"));
2489
2490                 if (((access_mask & FILE_WRITE_DATA) && deny_write)
2491                     || ((deny_mode & DENY_WRITE) && open_for_writing)) {
2492                         return NT_STATUS_SHARING_VIOLATION;
2493                 }
2494
2495                 /* Set locks */
2496                 if ((access_mask & FILE_WRITE_DATA) && have_read) {
2497                         off = access_to_netatalk_brl(fork_type, FILE_WRITE_DATA);
2498                         br_lck = do_lock(
2499                                 handle->conn->sconn->msg_ctx, fsp,
2500                                 fsp->op->global->open_persistent_id, 1, off,
2501                                 READ_LOCK, POSIX_LOCK, false,
2502                                 &status, NULL);
2503
2504                         if (!NT_STATUS_IS_OK(status)) {
2505                                 return status;
2506                         }
2507                         TALLOC_FREE(br_lck);
2508
2509                 }
2510                 if ((deny_mode & DENY_WRITE) && have_read) {
2511                         off = denymode_to_netatalk_brl(fork_type, DENY_WRITE);
2512                         br_lck = do_lock(
2513                                 handle->conn->sconn->msg_ctx, fsp,
2514                                 fsp->op->global->open_persistent_id, 1, off,
2515                                 READ_LOCK, POSIX_LOCK, false,
2516                                 &status, NULL);
2517
2518                         if (!NT_STATUS_IS_OK(status)) {
2519                                 return status;
2520                         }
2521                         TALLOC_FREE(br_lck);
2522                 }
2523         }
2524
2525         TALLOC_FREE(br_lck);
2526
2527         return status;
2528 }
2529
2530 static NTSTATUS check_aapl(vfs_handle_struct *handle,
2531                            struct smb_request *req,
2532                            const struct smb2_create_blobs *in_context_blobs,
2533                            struct smb2_create_blobs *out_context_blobs)
2534 {
2535         struct fruit_config_data *config;
2536         NTSTATUS status;
2537         struct smb2_create_blob *aapl = NULL;
2538         uint32_t cmd;
2539         bool ok;
2540         uint8_t p[16];
2541         DATA_BLOB blob = data_blob_talloc(req, NULL, 0);
2542         uint64_t req_bitmap, client_caps;
2543         uint64_t server_caps = SMB2_CRTCTX_AAPL_UNIX_BASED;
2544         smb_ucs2_t *model;
2545         size_t modellen;
2546
2547         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
2548                                 return NT_STATUS_UNSUCCESSFUL);
2549
2550         if (!config->use_aapl
2551             || in_context_blobs == NULL
2552             || out_context_blobs == NULL) {
2553                 return NT_STATUS_OK;
2554         }
2555
2556         aapl = smb2_create_blob_find(in_context_blobs,
2557                                      SMB2_CREATE_TAG_AAPL);
2558         if (aapl == NULL) {
2559                 return NT_STATUS_OK;
2560         }
2561
2562         if (aapl->data.length != 24) {
2563                 DEBUG(1, ("unexpected AAPL ctxt length: %ju\n",
2564                           (uintmax_t)aapl->data.length));
2565                 return NT_STATUS_INVALID_PARAMETER;
2566         }
2567
2568         cmd = IVAL(aapl->data.data, 0);
2569         if (cmd != SMB2_CRTCTX_AAPL_SERVER_QUERY) {
2570                 DEBUG(1, ("unsupported AAPL cmd: %d\n", cmd));
2571                 return NT_STATUS_INVALID_PARAMETER;
2572         }
2573
2574         req_bitmap = BVAL(aapl->data.data, 8);
2575         client_caps = BVAL(aapl->data.data, 16);
2576
2577         SIVAL(p, 0, SMB2_CRTCTX_AAPL_SERVER_QUERY);
2578         SIVAL(p, 4, 0);
2579         SBVAL(p, 8, req_bitmap);
2580         ok = data_blob_append(req, &blob, p, 16);
2581         if (!ok) {
2582                 return NT_STATUS_UNSUCCESSFUL;
2583         }
2584
2585         if (req_bitmap & SMB2_CRTCTX_AAPL_SERVER_CAPS) {
2586                 if ((client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR) &&
2587                     (handle->conn->tcon->compat->fs_capabilities & FILE_NAMED_STREAMS)) {
2588                         server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR;
2589                         config->readdir_attr_enabled = true;
2590                 }
2591
2592                 if (config->use_copyfile) {
2593                         server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_OSX_COPYFILE;
2594                         config->copyfile_enabled = true;
2595                 }
2596
2597                 /*
2598                  * The client doesn't set the flag, so we can't check
2599                  * for it and just set it unconditionally
2600                  */
2601                 if (config->unix_info_enabled) {
2602                         server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_NFS_ACE;
2603                 }
2604
2605                 SBVAL(p, 0, server_caps);
2606                 ok = data_blob_append(req, &blob, p, 8);
2607                 if (!ok) {
2608                         return NT_STATUS_UNSUCCESSFUL;
2609                 }
2610         }
2611
2612         if (req_bitmap & SMB2_CRTCTX_AAPL_VOLUME_CAPS) {
2613                 int val = lp_case_sensitive(SNUM(handle->conn->tcon->compat));
2614                 uint64_t caps = 0;
2615
2616                 switch (val) {
2617                 case Auto:
2618                         break;
2619
2620                 case True:
2621                         caps |= SMB2_CRTCTX_AAPL_CASE_SENSITIVE;
2622                         break;
2623
2624                 default:
2625                         break;
2626                 }
2627
2628                 if (config->time_machine) {
2629                         caps |= SMB2_CRTCTX_AAPL_FULL_SYNC;
2630                 }
2631
2632                 SBVAL(p, 0, caps);
2633
2634                 ok = data_blob_append(req, &blob, p, 8);
2635                 if (!ok) {
2636                         return NT_STATUS_UNSUCCESSFUL;
2637                 }
2638         }
2639
2640         if (req_bitmap & SMB2_CRTCTX_AAPL_MODEL_INFO) {
2641                 ok = convert_string_talloc(req,
2642                                            CH_UNIX, CH_UTF16LE,
2643                                            config->model, strlen(config->model),
2644                                            &model, &modellen);
2645                 if (!ok) {
2646                         return NT_STATUS_UNSUCCESSFUL;
2647                 }
2648
2649                 SIVAL(p, 0, 0);
2650                 SIVAL(p + 4, 0, modellen);
2651                 ok = data_blob_append(req, &blob, p, 8);
2652                 if (!ok) {
2653                         talloc_free(model);
2654                         return NT_STATUS_UNSUCCESSFUL;
2655                 }
2656
2657                 ok = data_blob_append(req, &blob, model, modellen);
2658                 talloc_free(model);
2659                 if (!ok) {
2660                         return NT_STATUS_UNSUCCESSFUL;
2661                 }
2662         }
2663
2664         status = smb2_create_blob_add(out_context_blobs,
2665                                       out_context_blobs,
2666                                       SMB2_CREATE_TAG_AAPL,
2667                                       blob);
2668         if (NT_STATUS_IS_OK(status)) {
2669                 global_fruit_config.nego_aapl = true;
2670                 if (config->aapl_zero_file_id) {
2671                         aapl_force_zero_file_id(handle->conn->sconn);
2672                 }
2673         }
2674
2675         return status;
2676 }
2677
2678 static bool readdir_attr_meta_finderi_stream(
2679         struct vfs_handle_struct *handle,
2680         const struct smb_filename *smb_fname,
2681         AfpInfo *ai)
2682 {
2683         struct smb_filename *stream_name = NULL;
2684         files_struct *fsp = NULL;
2685         ssize_t nread;
2686         NTSTATUS status;
2687         int ret;
2688         bool ok;
2689         uint8_t buf[AFP_INFO_SIZE];
2690
2691         stream_name = synthetic_smb_fname(talloc_tos(),
2692                                           smb_fname->base_name,
2693                                           AFPINFO_STREAM_NAME,
2694                                           NULL, smb_fname->flags);
2695         if (stream_name == NULL) {
2696                 return false;
2697         }
2698
2699         ret = SMB_VFS_STAT(handle->conn, stream_name);
2700         if (ret != 0) {
2701                 return false;
2702         }
2703
2704         status = SMB_VFS_CREATE_FILE(
2705                 handle->conn,                           /* conn */
2706                 NULL,                                   /* req */
2707                 0,                                      /* root_dir_fid */
2708                 stream_name,                            /* fname */
2709                 FILE_READ_DATA,                         /* access_mask */
2710                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
2711                         FILE_SHARE_DELETE),
2712                 FILE_OPEN,                              /* create_disposition*/
2713                 0,                                      /* create_options */
2714                 0,                                      /* file_attributes */
2715                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
2716                 NULL,                                   /* lease */
2717                 0,                                      /* allocation_size */
2718                 0,                                      /* private_flags */
2719                 NULL,                                   /* sd */
2720                 NULL,                                   /* ea_list */
2721                 &fsp,                                   /* result */
2722                 NULL,                                   /* pinfo */
2723                 NULL, NULL);                            /* create context */
2724
2725         TALLOC_FREE(stream_name);
2726
2727         if (!NT_STATUS_IS_OK(status)) {
2728                 return false;
2729         }
2730
2731         nread = SMB_VFS_PREAD(fsp, &buf[0], AFP_INFO_SIZE, 0);
2732         if (nread != AFP_INFO_SIZE) {
2733                 DBG_ERR("short read [%s] [%zd/%d]\n",
2734                         smb_fname_str_dbg(stream_name), nread, AFP_INFO_SIZE);
2735                 ok = false;
2736                 goto fail;
2737         }
2738
2739         memcpy(&ai->afpi_FinderInfo[0], &buf[AFP_OFF_FinderInfo],
2740                AFP_FinderSize);
2741
2742         ok = true;
2743
2744 fail:
2745         if (fsp != NULL) {
2746                 close_file(NULL, fsp, NORMAL_CLOSE);
2747         }
2748
2749         return ok;
2750 }
2751
2752 static bool readdir_attr_meta_finderi_netatalk(
2753         struct vfs_handle_struct *handle,
2754         const struct smb_filename *smb_fname,
2755         AfpInfo *ai)
2756 {
2757         struct adouble *ad = NULL;
2758         char *p = NULL;
2759
2760         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
2761         if (ad == NULL) {
2762                 return false;
2763         }
2764
2765         p = ad_get_entry(ad, ADEID_FINDERI);
2766         if (p == NULL) {
2767                 DBG_ERR("No ADEID_FINDERI for [%s]\n", smb_fname->base_name);
2768                 TALLOC_FREE(ad);
2769                 return false;
2770         }
2771
2772         memcpy(&ai->afpi_FinderInfo[0], p, AFP_FinderSize);
2773         TALLOC_FREE(ad);
2774         return true;
2775 }
2776
2777 static bool readdir_attr_meta_finderi(struct vfs_handle_struct *handle,
2778                                       const struct smb_filename *smb_fname,
2779                                       struct readdir_attr_data *attr_data)
2780 {
2781         struct fruit_config_data *config = NULL;
2782         uint32_t date_added;
2783         AfpInfo ai = {0};
2784         bool ok;
2785
2786         SMB_VFS_HANDLE_GET_DATA(handle, config,
2787                                 struct fruit_config_data,
2788                                 return false);
2789
2790         switch (config->meta) {
2791         case FRUIT_META_NETATALK:
2792                 ok = readdir_attr_meta_finderi_netatalk(
2793                         handle, smb_fname, &ai);
2794                 break;
2795
2796         case FRUIT_META_STREAM:
2797                 ok = readdir_attr_meta_finderi_stream(
2798                         handle, smb_fname, &ai);
2799                 break;
2800
2801         default:
2802                 DBG_ERR("Unexpected meta config [%d]\n", config->meta);
2803                 return false;
2804         }
2805
2806         if (!ok) {
2807                 /* Don't bother with errors, it's likely ENOENT */
2808                 return true;
2809         }
2810
2811         if (S_ISREG(smb_fname->st.st_ex_mode)) {
2812                 /* finder_type */
2813                 memcpy(&attr_data->attr_data.aapl.finder_info[0],
2814                        &ai.afpi_FinderInfo[0], 4);
2815
2816                 /* finder_creator */
2817                 memcpy(&attr_data->attr_data.aapl.finder_info[0] + 4,
2818                        &ai.afpi_FinderInfo[4], 4);
2819         }
2820
2821         /* finder_flags */
2822         memcpy(&attr_data->attr_data.aapl.finder_info[0] + 8,
2823                &ai.afpi_FinderInfo[8], 2);
2824
2825         /* finder_ext_flags */
2826         memcpy(&attr_data->attr_data.aapl.finder_info[0] + 10,
2827                &ai.afpi_FinderInfo[24], 2);
2828
2829         /* creation date */
2830         date_added = convert_time_t_to_uint32_t(
2831                 smb_fname->st.st_ex_btime.tv_sec - AD_DATE_DELTA);
2832
2833         RSIVAL(&attr_data->attr_data.aapl.finder_info[0], 12, date_added);
2834
2835         return true;
2836 }
2837
2838 static uint64_t readdir_attr_rfork_size_adouble(
2839         struct vfs_handle_struct *handle,
2840         const struct smb_filename *smb_fname)
2841 {
2842         struct adouble *ad = NULL;
2843         uint64_t rfork_size;
2844
2845         ad = ad_get(talloc_tos(), handle, smb_fname,
2846                     ADOUBLE_RSRC);
2847         if (ad == NULL) {
2848                 return 0;
2849         }
2850
2851         rfork_size = ad_getentrylen(ad, ADEID_RFORK);
2852         TALLOC_FREE(ad);
2853
2854         return rfork_size;
2855 }
2856
2857 static uint64_t readdir_attr_rfork_size_stream(
2858         struct vfs_handle_struct *handle,
2859         const struct smb_filename *smb_fname)
2860 {
2861         struct smb_filename *stream_name = NULL;
2862         int ret;
2863         uint64_t rfork_size;
2864
2865         stream_name = synthetic_smb_fname(talloc_tos(),
2866                                           smb_fname->base_name,
2867                                           AFPRESOURCE_STREAM_NAME,
2868                                           NULL, 0);
2869         if (stream_name == NULL) {
2870                 return 0;
2871         }
2872
2873         ret = SMB_VFS_STAT(handle->conn, stream_name);
2874         if (ret != 0) {
2875                 TALLOC_FREE(stream_name);
2876                 return 0;
2877         }
2878
2879         rfork_size = stream_name->st.st_ex_size;
2880         TALLOC_FREE(stream_name);
2881
2882         return rfork_size;
2883 }
2884
2885 static uint64_t readdir_attr_rfork_size(struct vfs_handle_struct *handle,
2886                                         const struct smb_filename *smb_fname)
2887 {
2888         struct fruit_config_data *config = NULL;
2889         uint64_t rfork_size;
2890
2891         SMB_VFS_HANDLE_GET_DATA(handle, config,
2892                                 struct fruit_config_data,
2893                                 return 0);
2894
2895         switch (config->rsrc) {
2896         case FRUIT_RSRC_ADFILE:
2897         case FRUIT_RSRC_XATTR:
2898                 rfork_size = readdir_attr_rfork_size_adouble(handle,
2899                                                              smb_fname);
2900                 break;
2901
2902         case FRUIT_META_STREAM:
2903                 rfork_size = readdir_attr_rfork_size_stream(handle,
2904                                                             smb_fname);
2905                 break;
2906
2907         default:
2908                 DBG_ERR("Unexpected rsrc config [%d]\n", config->rsrc);
2909                 rfork_size = 0;
2910                 break;
2911         }
2912
2913         return rfork_size;
2914 }
2915
2916 static NTSTATUS readdir_attr_macmeta(struct vfs_handle_struct *handle,
2917                                      const struct smb_filename *smb_fname,
2918                                      struct readdir_attr_data *attr_data)
2919 {
2920         NTSTATUS status = NT_STATUS_OK;
2921         struct fruit_config_data *config = NULL;
2922         bool ok;
2923
2924         SMB_VFS_HANDLE_GET_DATA(handle, config,
2925                                 struct fruit_config_data,
2926                                 return NT_STATUS_UNSUCCESSFUL);
2927
2928
2929         /* Ensure we return a default value in the creation_date field */
2930         RSIVAL(&attr_data->attr_data.aapl.finder_info, 12, AD_DATE_START);
2931
2932         /*
2933          * Resource fork length
2934          */
2935
2936         if (config->readdir_attr_rsize) {
2937                 uint64_t rfork_size;
2938
2939                 rfork_size = readdir_attr_rfork_size(handle, smb_fname);
2940                 attr_data->attr_data.aapl.rfork_size = rfork_size;
2941         }
2942
2943         /*
2944          * FinderInfo
2945          */
2946
2947         if (config->readdir_attr_finder_info) {
2948                 ok = readdir_attr_meta_finderi(handle, smb_fname, attr_data);
2949                 if (!ok) {
2950                         status = NT_STATUS_INTERNAL_ERROR;
2951                 }
2952         }
2953
2954         return status;
2955 }
2956
2957 static NTSTATUS remove_virtual_nfs_aces(struct security_descriptor *psd)
2958 {
2959         NTSTATUS status;
2960         uint32_t i;
2961
2962         if (psd->dacl == NULL) {
2963                 return NT_STATUS_OK;
2964         }
2965
2966         for (i = 0; i < psd->dacl->num_aces; i++) {
2967                 /* MS NFS style mode/uid/gid */
2968                 if (!dom_sid_compare_domain(
2969                                 &global_sid_Unix_NFS,
2970                                 &psd->dacl->aces[i].trustee) == 0) {
2971                         /* Normal ACE entry. */
2972                         continue;
2973                 }
2974
2975                 /*
2976                  * security_descriptor_dacl_del()
2977                  * *must* return NT_STATUS_OK as we know
2978                  * we have something to remove.
2979                  */
2980
2981                 status = security_descriptor_dacl_del(psd,
2982                                 &psd->dacl->aces[i].trustee);
2983                 if (!NT_STATUS_IS_OK(status)) {
2984                         DBG_WARNING("failed to remove MS NFS style ACE: %s\n",
2985                                 nt_errstr(status));
2986                         return status;
2987                 }
2988
2989                 /*
2990                  * security_descriptor_dacl_del() may delete more
2991                  * then one entry subsequent to this one if the
2992                  * SID matches, but we only need to ensure that
2993                  * we stay looking at the same element in the array.
2994                  */
2995                 i--;
2996         }
2997         return NT_STATUS_OK;
2998 }
2999
3000 /* Search MS NFS style ACE with UNIX mode */
3001 static NTSTATUS check_ms_nfs(vfs_handle_struct *handle,
3002                              files_struct *fsp,
3003                              struct security_descriptor *psd,
3004                              mode_t *pmode,
3005                              bool *pdo_chmod)
3006 {
3007         uint32_t i;
3008         struct fruit_config_data *config = NULL;
3009
3010         *pdo_chmod = false;
3011
3012         SMB_VFS_HANDLE_GET_DATA(handle, config,
3013                                 struct fruit_config_data,
3014                                 return NT_STATUS_UNSUCCESSFUL);
3015
3016         if (!global_fruit_config.nego_aapl) {
3017                 return NT_STATUS_OK;
3018         }
3019         if (psd->dacl == NULL || !config->unix_info_enabled) {
3020                 return NT_STATUS_OK;
3021         }
3022
3023         for (i = 0; i < psd->dacl->num_aces; i++) {
3024                 if (dom_sid_compare_domain(
3025                             &global_sid_Unix_NFS_Mode,
3026                             &psd->dacl->aces[i].trustee) == 0) {
3027                         *pmode = (mode_t)psd->dacl->aces[i].trustee.sub_auths[2];
3028                         *pmode &= (S_IRWXU | S_IRWXG | S_IRWXO);
3029                         *pdo_chmod = true;
3030
3031                         DEBUG(10, ("MS NFS chmod request %s, %04o\n",
3032                                    fsp_str_dbg(fsp), (unsigned)(*pmode)));
3033                         break;
3034                 }
3035         }
3036
3037         /*
3038          * Remove any incoming virtual ACE entries generated by
3039          * fruit_fget_nt_acl().
3040          */
3041
3042         return remove_virtual_nfs_aces(psd);
3043 }
3044
3045 /****************************************************************************
3046  * VFS ops
3047  ****************************************************************************/
3048
3049 static int fruit_connect(vfs_handle_struct *handle,
3050                          const char *service,
3051                          const char *user)
3052 {
3053         int rc;
3054         char *list = NULL, *newlist = NULL;
3055         struct fruit_config_data *config;
3056
3057         DEBUG(10, ("fruit_connect\n"));
3058
3059         rc = SMB_VFS_NEXT_CONNECT(handle, service, user);
3060         if (rc < 0) {
3061                 return rc;
3062         }
3063
3064         rc = init_fruit_config(handle);
3065         if (rc != 0) {
3066                 return rc;
3067         }
3068
3069         SMB_VFS_HANDLE_GET_DATA(handle, config,
3070                                 struct fruit_config_data, return -1);
3071
3072         if (config->veto_appledouble) {
3073                 list = lp_veto_files(talloc_tos(), SNUM(handle->conn));
3074
3075                 if (list) {
3076                         if (strstr(list, "/" ADOUBLE_NAME_PREFIX "*/") == NULL) {
3077                                 newlist = talloc_asprintf(
3078                                         list,
3079                                         "%s/" ADOUBLE_NAME_PREFIX "*/",
3080                                         list);
3081                                 lp_do_parameter(SNUM(handle->conn),
3082                                                 "veto files",
3083                                                 newlist);
3084                         }
3085                 } else {
3086                         lp_do_parameter(SNUM(handle->conn),
3087                                         "veto files",
3088                                         "/" ADOUBLE_NAME_PREFIX "*/");
3089                 }
3090
3091                 TALLOC_FREE(list);
3092         }
3093
3094         if (config->encoding == FRUIT_ENC_NATIVE) {
3095                 lp_do_parameter(SNUM(handle->conn),
3096                                 "catia:mappings",
3097                                 fruit_catia_maps);
3098         }
3099
3100         if (config->time_machine) {
3101                 DBG_NOTICE("Enabling durable handles for Time Machine "
3102                            "support on [%s]\n", service);
3103                 lp_do_parameter(SNUM(handle->conn), "durable handles", "yes");
3104                 lp_do_parameter(SNUM(handle->conn), "kernel oplocks", "no");
3105                 lp_do_parameter(SNUM(handle->conn), "kernel share modes", "no");
3106                 if (!lp_strict_sync(SNUM(handle->conn))) {
3107                         DBG_WARNING("Time Machine without strict sync is not "
3108                                     "recommended!\n");
3109                 }
3110                 lp_do_parameter(SNUM(handle->conn), "posix locking", "no");
3111         }
3112
3113         return rc;
3114 }
3115
3116 static int fruit_open_meta_stream(vfs_handle_struct *handle,
3117                                   struct smb_filename *smb_fname,
3118                                   files_struct *fsp,
3119                                   int flags,
3120                                   mode_t mode)
3121 {
3122         AfpInfo *ai = NULL;
3123         char afpinfo_buf[AFP_INFO_SIZE];
3124         ssize_t len, written;
3125         int hostfd = -1;
3126         int rc = -1;
3127
3128         hostfd = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
3129         if (hostfd == -1) {
3130                 return -1;
3131         }
3132
3133         if (!(flags & (O_CREAT | O_TRUNC))) {
3134                 return hostfd;
3135         }
3136
3137         ai = afpinfo_new(talloc_tos());
3138         if (ai == NULL) {
3139                 rc = -1;
3140                 goto fail;
3141         }
3142
3143         len = afpinfo_pack(ai, afpinfo_buf);
3144         if (len != AFP_INFO_SIZE) {
3145                 rc = -1;
3146                 goto fail;
3147         }
3148
3149         /* Set fd, needed in SMB_VFS_NEXT_PWRITE() */
3150         fsp->fh->fd = hostfd;
3151
3152         written = SMB_VFS_NEXT_PWRITE(handle, fsp, afpinfo_buf,
3153                                       AFP_INFO_SIZE, 0);
3154         fsp->fh->fd = -1;
3155         if (written != AFP_INFO_SIZE) {
3156                 DBG_ERR("bad write [%zd/%d]\n", written, AFP_INFO_SIZE);
3157                 rc = -1;
3158                 goto fail;
3159         }
3160
3161         rc = 0;
3162
3163 fail:
3164         DBG_DEBUG("rc=%d, fd=%d\n", rc, hostfd);
3165
3166         if (rc != 0) {
3167                 int saved_errno = errno;
3168                 if (hostfd >= 0) {
3169                         fsp->fh->fd = hostfd;
3170                         SMB_VFS_NEXT_CLOSE(handle, fsp);
3171                 }
3172                 hostfd = -1;
3173                 errno = saved_errno;
3174         }
3175         return hostfd;
3176 }
3177
3178 static int fruit_open_meta_netatalk(vfs_handle_struct *handle,
3179                                     struct smb_filename *smb_fname,
3180                                     files_struct *fsp,
3181                                     int flags,
3182                                     mode_t mode)
3183 {
3184         int rc;
3185         int fakefd = -1;
3186         struct adouble *ad = NULL;
3187         int fds[2];
3188
3189         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
3190
3191         /*
3192          * Return a valid fd, but ensure any attempt to use it returns an error
3193          * (EPIPE). All operations on the smb_fname or the fsp will use path
3194          * based syscalls.
3195          */
3196         rc = pipe(fds);
3197         if (rc != 0) {
3198                 goto exit;
3199         }
3200         fakefd = fds[0];
3201         close(fds[1]);
3202
3203         if (flags & (O_CREAT | O_TRUNC)) {
3204                 /*
3205                  * The attribute does not exist or needs to be truncated,
3206                  * create an AppleDouble EA
3207                  */
3208                 ad = ad_init(fsp, handle, ADOUBLE_META);
3209                 if (ad == NULL) {
3210                         rc = -1;
3211                         goto exit;
3212                 }
3213
3214                 rc = ad_set(ad, fsp->fsp_name);
3215                 if (rc != 0) {
3216                         rc = -1;
3217                         goto exit;
3218                 }
3219
3220                 TALLOC_FREE(ad);
3221         }
3222
3223 exit:
3224         DEBUG(10, ("fruit_open meta rc=%d, fd=%d\n", rc, fakefd));
3225         if (rc != 0) {
3226                 int saved_errno = errno;
3227                 if (fakefd >= 0) {
3228                         close(fakefd);
3229                 }
3230                 fakefd = -1;
3231                 errno = saved_errno;
3232         }
3233         return fakefd;
3234 }
3235
3236 static int fruit_open_meta(vfs_handle_struct *handle,
3237                            struct smb_filename *smb_fname,
3238                            files_struct *fsp, int flags, mode_t mode)
3239 {
3240         int fd;
3241         struct fruit_config_data *config = NULL;
3242         struct fio *fio = NULL;
3243
3244         DBG_DEBUG("path [%s]\n", smb_fname_str_dbg(smb_fname));
3245
3246         SMB_VFS_HANDLE_GET_DATA(handle, config,
3247                                 struct fruit_config_data, return -1);
3248
3249         switch (config->meta) {
3250         case FRUIT_META_STREAM:
3251                 fd = fruit_open_meta_stream(handle, smb_fname,
3252                                             fsp, flags, mode);
3253                 break;
3254
3255         case FRUIT_META_NETATALK:
3256                 fd = fruit_open_meta_netatalk(handle, smb_fname,
3257                                               fsp, flags, mode);
3258                 break;
3259
3260         default:
3261                 DBG_ERR("Unexpected meta config [%d]\n", config->meta);
3262                 return -1;
3263         }
3264
3265         DBG_DEBUG("path [%s] fd [%d]\n", smb_fname_str_dbg(smb_fname), fd);
3266
3267         if (fd == -1) {
3268                 return -1;
3269         }
3270
3271         fio = VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
3272         fio->type = ADOUBLE_META;
3273         fio->config = config;
3274
3275         return fd;
3276 }
3277
3278 static int fruit_open_rsrc_adouble(vfs_handle_struct *handle,
3279                                    struct smb_filename *smb_fname,
3280                                    files_struct *fsp,
3281                                    int flags,
3282                                    mode_t mode)
3283 {
3284         int rc = 0;
3285         struct adouble *ad = NULL;
3286         struct smb_filename *smb_fname_base = NULL;
3287         struct fruit_config_data *config = NULL;
3288         int hostfd = -1;
3289
3290         SMB_VFS_HANDLE_GET_DATA(handle, config,
3291                                 struct fruit_config_data, return -1);
3292
3293         if ((!(flags & O_CREAT)) &&
3294             S_ISDIR(fsp->base_fsp->fsp_name->st.st_ex_mode))
3295         {
3296                 /* sorry, but directories don't habe a resource fork */
3297                 rc = -1;
3298                 goto exit;
3299         }
3300
3301         rc = adouble_path(talloc_tos(), smb_fname, &smb_fname_base);
3302         if (rc != 0) {
3303                 goto exit;
3304         }
3305
3306         /* Sanitize flags */
3307         if (flags & O_WRONLY) {
3308                 /* We always need read access for the metadata header too */
3309                 flags &= ~O_WRONLY;
3310                 flags |= O_RDWR;
3311         }
3312
3313         hostfd = SMB_VFS_NEXT_OPEN(handle, smb_fname_base, fsp,
3314                                    flags, mode);
3315         if (hostfd == -1) {
3316                 rc = -1;
3317                 goto exit;
3318         }
3319
3320         if (flags & (O_CREAT | O_TRUNC)) {
3321                 ad = ad_init(fsp, handle, ADOUBLE_RSRC);
3322                 if (ad == NULL) {
3323                         rc = -1;
3324                         goto exit;
3325                 }
3326
3327                 fsp->fh->fd = hostfd;
3328
3329                 rc = ad_fset(ad, fsp);
3330                 fsp->fh->fd = -1;
3331                 if (rc != 0) {
3332                         rc = -1;
3333                         goto exit;
3334                 }
3335                 TALLOC_FREE(ad);
3336         }
3337
3338 exit:
3339
3340         TALLOC_FREE(smb_fname_base);
3341
3342         DEBUG(10, ("fruit_open resource fork: rc=%d, fd=%d\n", rc, hostfd));
3343         if (rc != 0) {
3344                 int saved_errno = errno;
3345                 if (hostfd >= 0) {
3346                         /*
3347                          * BUGBUGBUG -- we would need to call
3348                          * fd_close_posix here, but we don't have a
3349                          * full fsp yet
3350                          */
3351                         fsp->fh->fd = hostfd;
3352                         SMB_VFS_CLOSE(fsp);
3353                 }
3354                 hostfd = -1;
3355                 errno = saved_errno;
3356         }
3357         return hostfd;
3358 }
3359
3360 static int fruit_open_rsrc_xattr(vfs_handle_struct *handle,
3361                                  struct smb_filename *smb_fname,
3362                                  files_struct *fsp,
3363                                  int flags,
3364                                  mode_t mode)
3365 {
3366 #ifdef HAVE_ATTROPEN
3367         int fd = -1;
3368
3369         fd = attropen(smb_fname->base_name,
3370                       AFPRESOURCE_EA_NETATALK,
3371                       flags,
3372                       mode);
3373         if (fd == -1) {
3374                 return -1;
3375         }
3376
3377         return fd;
3378
3379 #else
3380         errno = ENOSYS;
3381         return -1;
3382 #endif
3383 }
3384
3385 static int fruit_open_rsrc(vfs_handle_struct *handle,
3386                            struct smb_filename *smb_fname,
3387                            files_struct *fsp, int flags, mode_t mode)
3388 {
3389         int fd;
3390         struct fruit_config_data *config = NULL;
3391         struct fio *fio = NULL;
3392
3393         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
3394
3395         SMB_VFS_HANDLE_GET_DATA(handle, config,
3396                                 struct fruit_config_data, return -1);
3397
3398         if (((flags & O_ACCMODE) == O_RDONLY)
3399             && (flags & O_CREAT)
3400             && !VALID_STAT(fsp->fsp_name->st))
3401         {
3402                 /*
3403                  * This means the stream doesn't exist. macOS SMB server fails
3404                  * this with NT_STATUS_OBJECT_NAME_NOT_FOUND, so must we. Cf bug
3405                  * 12565 and the test for this combination in
3406                  * test_rfork_create().
3407                  */
3408                 errno = ENOENT;
3409                 return -1;
3410         }
3411
3412         switch (config->rsrc) {
3413         case FRUIT_RSRC_STREAM:
3414                 fd = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
3415                 break;
3416
3417         case FRUIT_RSRC_ADFILE:
3418                 fd = fruit_open_rsrc_adouble(handle, smb_fname,
3419                                              fsp, flags, mode);
3420                 break;
3421
3422         case FRUIT_RSRC_XATTR:
3423                 fd = fruit_open_rsrc_xattr(handle, smb_fname,
3424                                            fsp, flags, mode);
3425                 break;
3426
3427         default:
3428                 DBG_ERR("Unexpected rsrc config [%d]\n", config->rsrc);
3429                 return -1;
3430         }
3431
3432         DBG_DEBUG("Path [%s] fd [%d]\n", smb_fname_str_dbg(smb_fname), fd);
3433
3434         if (fd == -1) {
3435                 return -1;
3436         }
3437
3438         fio = VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
3439         fio->type = ADOUBLE_RSRC;
3440         fio->config = config;
3441
3442         return fd;
3443 }
3444
3445 static int fruit_open(vfs_handle_struct *handle,
3446                       struct smb_filename *smb_fname,
3447                       files_struct *fsp, int flags, mode_t mode)
3448 {
3449         int fd;
3450
3451         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
3452
3453         if (!is_ntfs_stream_smb_fname(smb_fname)) {
3454                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
3455         }
3456
3457         if (is_afpinfo_stream(smb_fname)) {
3458                 fd = fruit_open_meta(handle, smb_fname, fsp, flags, mode);
3459         } else if (is_afpresource_stream(smb_fname)) {
3460                 fd = fruit_open_rsrc(handle, smb_fname, fsp, flags, mode);
3461         } else {
3462                 fd = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
3463         }
3464
3465         DBG_DEBUG("Path [%s] fd [%d]\n", smb_fname_str_dbg(smb_fname), fd);
3466
3467         return fd;
3468 }
3469
3470 static int fruit_rename(struct vfs_handle_struct *handle,
3471                         const struct smb_filename *smb_fname_src,
3472                         const struct smb_filename *smb_fname_dst)
3473 {
3474         int rc = -1;
3475         struct fruit_config_data *config = NULL;
3476         struct smb_filename *src_adp_smb_fname = NULL;
3477         struct smb_filename *dst_adp_smb_fname = NULL;
3478
3479         SMB_VFS_HANDLE_GET_DATA(handle, config,
3480                                 struct fruit_config_data, return -1);
3481
3482         if (!VALID_STAT(smb_fname_src->st)) {
3483                 DBG_ERR("Need valid stat for [%s]\n",
3484                         smb_fname_str_dbg(smb_fname_src));
3485                 return -1;
3486         }
3487
3488         rc = SMB_VFS_NEXT_RENAME(handle, smb_fname_src, smb_fname_dst);
3489         if (rc != 0) {
3490                 return -1;
3491         }
3492
3493         if ((config->rsrc != FRUIT_RSRC_ADFILE) ||
3494             (!S_ISREG(smb_fname_src->st.st_ex_mode)))
3495         {
3496                 return 0;
3497         }
3498
3499         rc = adouble_path(talloc_tos(), smb_fname_src, &src_adp_smb_fname);
3500         if (rc != 0) {
3501                 goto done;
3502         }
3503
3504         rc = adouble_path(talloc_tos(), smb_fname_dst, &dst_adp_smb_fname);
3505         if (rc != 0) {
3506                 goto done;
3507         }
3508
3509         DBG_DEBUG("%s -> %s\n",
3510                   smb_fname_str_dbg(src_adp_smb_fname),
3511                   smb_fname_str_dbg(dst_adp_smb_fname));
3512
3513         rc = SMB_VFS_NEXT_RENAME(handle, src_adp_smb_fname, dst_adp_smb_fname);
3514         if (errno == ENOENT) {
3515                 rc = 0;
3516         }
3517
3518 done:
3519         TALLOC_FREE(src_adp_smb_fname);
3520         TALLOC_FREE(dst_adp_smb_fname);
3521         return rc;
3522 }
3523
3524 static int fruit_unlink_meta_stream(vfs_handle_struct *handle,
3525                                     const struct smb_filename *smb_fname)
3526 {
3527         return SMB_VFS_NEXT_UNLINK(handle, smb_fname);
3528 }
3529
3530 static int fruit_unlink_meta_netatalk(vfs_handle_struct *handle,
3531                                       const struct smb_filename *smb_fname)
3532 {
3533         return SMB_VFS_REMOVEXATTR(handle->conn,
3534                                    smb_fname,
3535                                    AFPINFO_EA_NETATALK);
3536 }
3537
3538 static int fruit_unlink_meta(vfs_handle_struct *handle,
3539                              const struct smb_filename *smb_fname)
3540 {
3541         struct fruit_config_data *config = NULL;
3542         int rc;
3543
3544         SMB_VFS_HANDLE_GET_DATA(handle, config,
3545                                 struct fruit_config_data, return -1);
3546
3547         switch (config->meta) {
3548         case FRUIT_META_STREAM:
3549                 rc = fruit_unlink_meta_stream(handle, smb_fname);
3550                 break;
3551
3552         case FRUIT_META_NETATALK:
3553                 rc = fruit_unlink_meta_netatalk(handle, smb_fname);
3554                 break;
3555
3556         default:
3557                 DBG_ERR("Unsupported meta config [%d]\n", config->meta);
3558                 return -1;
3559         }
3560
3561         return rc;
3562 }
3563
3564 static int fruit_unlink_rsrc_stream(vfs_handle_struct *handle,
3565                                     const struct smb_filename *smb_fname,
3566                                     bool force_unlink)
3567 {
3568         int ret;
3569
3570         if (!force_unlink) {
3571                 struct smb_filename *smb_fname_cp = NULL;
3572                 off_t size;
3573
3574                 smb_fname_cp = cp_smb_filename(talloc_tos(), smb_fname);
3575                 if (smb_fname_cp == NULL) {
3576                         return -1;
3577                 }
3578
3579                 /*
3580                  * 0 byte resource fork streams are not listed by
3581                  * vfs_streaminfo, as a result stream cleanup/deletion of file
3582                  * deletion doesn't remove the resourcefork stream.
3583                  */
3584
3585                 ret = SMB_VFS_NEXT_STAT(handle, smb_fname_cp);
3586                 if (ret != 0) {
3587                         TALLOC_FREE(smb_fname_cp);
3588                         DBG_ERR("stat [%s] failed [%s]\n",
3589                                 smb_fname_str_dbg(smb_fname_cp), strerror(errno));
3590                         return -1;
3591                 }
3592
3593                 size = smb_fname_cp->st.st_ex_size;
3594                 TALLOC_FREE(smb_fname_cp);
3595
3596                 if (size > 0) {
3597                         /* OS X ignores resource fork stream delete requests */
3598                         return 0;
3599                 }
3600         }
3601
3602         ret = SMB_VFS_NEXT_UNLINK(handle, smb_fname);
3603         if ((ret != 0) && (errno == ENOENT) && force_unlink) {
3604                 ret = 0;
3605         }
3606
3607         return ret;
3608 }
3609
3610 static int fruit_unlink_rsrc_adouble(vfs_handle_struct *handle,
3611                                      const struct smb_filename *smb_fname,
3612                                      bool force_unlink)
3613 {
3614         int rc;
3615         struct adouble *ad = NULL;
3616         struct smb_filename *adp_smb_fname = NULL;
3617
3618         if (!force_unlink) {
3619                 ad = ad_get(talloc_tos(), handle, smb_fname,
3620                             ADOUBLE_RSRC);
3621                 if (ad == NULL) {
3622                         errno = ENOENT;
3623                         return -1;
3624                 }
3625
3626
3627                 /*
3628                  * 0 byte resource fork streams are not listed by
3629                  * vfs_streaminfo, as a result stream cleanup/deletion of file
3630                  * deletion doesn't remove the resourcefork stream.
3631                  */
3632
3633                 if (ad_getentrylen(ad, ADEID_RFORK) > 0) {
3634                         /* OS X ignores resource fork stream delete requests */
3635                         TALLOC_FREE(ad);
3636                         return 0;
3637                 }
3638
3639                 TALLOC_FREE(ad);
3640         }
3641
3642         rc = adouble_path(talloc_tos(), smb_fname, &adp_smb_fname);
3643         if (rc != 0) {
3644                 return -1;
3645         }
3646
3647         rc = SMB_VFS_NEXT_UNLINK(handle, adp_smb_fname);
3648         TALLOC_FREE(adp_smb_fname);
3649         if ((rc != 0) && (errno == ENOENT) && force_unlink) {
3650                 rc = 0;
3651         }
3652
3653         return rc;
3654 }
3655
3656 static int fruit_unlink_rsrc_xattr(vfs_handle_struct *handle,
3657                                    const struct smb_filename *smb_fname,
3658                                    bool force_unlink)
3659 {
3660         /*
3661          * OS X ignores resource fork stream delete requests, so nothing to do
3662          * here. Removing the file will remove the xattr anyway, so we don't
3663          * have to take care of removing 0 byte resource forks that could be
3664          * left behind.
3665          */
3666         return 0;
3667 }
3668
3669 static int fruit_unlink_rsrc(vfs_handle_struct *handle,
3670                              const struct smb_filename *smb_fname,
3671                              bool force_unlink)
3672 {
3673         struct fruit_config_data *config = NULL;
3674         int rc;
3675
3676         SMB_VFS_HANDLE_GET_DATA(handle, config,
3677                                 struct fruit_config_data, return -1);
3678
3679         switch (config->rsrc) {
3680         case FRUIT_RSRC_STREAM:
3681                 rc = fruit_unlink_rsrc_stream(handle, smb_fname, force_unlink);
3682                 break;
3683
3684         case FRUIT_RSRC_ADFILE:
3685                 rc = fruit_unlink_rsrc_adouble(handle, smb_fname, force_unlink);
3686                 break;
3687
3688         case FRUIT_RSRC_XATTR:
3689                 rc = fruit_unlink_rsrc_xattr(handle, smb_fname, force_unlink);
3690                 break;
3691
3692         default:
3693                 DBG_ERR("Unsupported rsrc config [%d]\n", config->rsrc);
3694                 return -1;
3695         }
3696
3697         return rc;
3698 }
3699
3700 static int fruit_unlink(vfs_handle_struct *handle,
3701                         const struct smb_filename *smb_fname)
3702 {
3703         int rc;
3704         struct fruit_config_data *config = NULL;
3705         struct smb_filename *rsrc_smb_fname = NULL;
3706
3707         SMB_VFS_HANDLE_GET_DATA(handle, config,
3708                                 struct fruit_config_data, return -1);
3709
3710         if (is_afpinfo_stream(smb_fname)) {
3711                 return fruit_unlink_meta(handle, smb_fname);
3712         } else if (is_afpresource_stream(smb_fname)) {
3713                 return fruit_unlink_rsrc(handle, smb_fname, false);
3714         } if (is_ntfs_stream_smb_fname(smb_fname)) {
3715                 return SMB_VFS_NEXT_UNLINK(handle, smb_fname);
3716         }
3717
3718         /*
3719          * A request to delete the base file. Because 0 byte resource
3720          * fork streams are not listed by fruit_streaminfo,
3721          * delete_all_streams() can't remove 0 byte resource fork
3722          * streams, so we have to cleanup this here.
3723          */
3724         rsrc_smb_fname = synthetic_smb_fname(talloc_tos(),
3725                                              smb_fname->base_name,
3726                                              AFPRESOURCE_STREAM_NAME,
3727                                              NULL,
3728                                              smb_fname->flags);
3729         if (rsrc_smb_fname == NULL) {
3730                 return -1;
3731         }
3732
3733         rc = fruit_unlink_rsrc(handle, rsrc_smb_fname, true);
3734         if ((rc != 0) && (errno != ENOENT)) {
3735                 DBG_ERR("Forced unlink of [%s] failed [%s]\n",
3736                         smb_fname_str_dbg(rsrc_smb_fname), strerror(errno));
3737                 TALLOC_FREE(rsrc_smb_fname);
3738                 return -1;
3739         }
3740         TALLOC_FREE(rsrc_smb_fname);
3741
3742         return SMB_VFS_NEXT_UNLINK(handle, smb_fname);
3743 }
3744
3745 static int fruit_chmod(vfs_handle_struct *handle,
3746                        const struct smb_filename *smb_fname,
3747                        mode_t mode)
3748 {
3749         int rc = -1;
3750         struct fruit_config_data *config = NULL;
3751         struct smb_filename *smb_fname_adp = NULL;
3752
3753         rc = SMB_VFS_NEXT_CHMOD(handle, smb_fname, mode);
3754         if (rc != 0) {
3755                 return rc;
3756         }
3757
3758         SMB_VFS_HANDLE_GET_DATA(handle, config,
3759                                 struct fruit_config_data, return -1);
3760
3761         if (config->rsrc != FRUIT_RSRC_ADFILE) {
3762                 return 0;
3763         }
3764
3765         if (!VALID_STAT(smb_fname->st)) {
3766                 return 0;
3767         }
3768
3769         if (!S_ISREG(smb_fname->st.st_ex_mode)) {
3770                 return 0;
3771         }
3772
3773         rc = adouble_path(talloc_tos(), smb_fname, &smb_fname_adp);
3774         if (rc != 0) {
3775                 return -1;
3776         }
3777
3778         DEBUG(10, ("fruit_chmod: %s\n", smb_fname_adp->base_name));
3779
3780         rc = SMB_VFS_NEXT_CHMOD(handle, smb_fname_adp, mode);
3781         if (errno == ENOENT) {
3782                 rc = 0;
3783         }
3784
3785         TALLOC_FREE(smb_fname_adp);
3786         return rc;
3787 }
3788
3789 static int fruit_chown(vfs_handle_struct *handle,
3790                        const struct smb_filename *smb_fname,
3791                        uid_t uid,
3792                        gid_t gid)
3793 {
3794         int rc = -1;
3795         struct fruit_config_data *config = NULL;
3796         struct smb_filename *adp_smb_fname = NULL;
3797
3798         rc = SMB_VFS_NEXT_CHOWN(handle, smb_fname, uid, gid);
3799         if (rc != 0) {
3800                 return rc;
3801         }
3802
3803         SMB_VFS_HANDLE_GET_DATA(handle, config,
3804                                 struct fruit_config_data, return -1);
3805
3806         if (config->rsrc != FRUIT_RSRC_ADFILE) {
3807                 return 0;
3808         }
3809
3810         if (!VALID_STAT(smb_fname->st)) {
3811                 return 0;
3812         }
3813
3814         if (!S_ISREG(smb_fname->st.st_ex_mode)) {
3815                 return 0;
3816         }
3817
3818         rc = adouble_path(talloc_tos(), smb_fname, &adp_smb_fname);
3819         if (rc != 0) {
3820                 goto done;
3821         }
3822
3823         DEBUG(10, ("fruit_chown: %s\n", adp_smb_fname->base_name));
3824
3825         rc = SMB_VFS_NEXT_CHOWN(handle, adp_smb_fname, uid, gid);
3826         if (errno == ENOENT) {
3827                 rc = 0;
3828         }
3829
3830  done:
3831         TALLOC_FREE(adp_smb_fname);
3832         return rc;
3833 }
3834
3835 static int fruit_rmdir(struct vfs_handle_struct *handle,
3836                         const struct smb_filename *smb_fname)
3837 {
3838         DIR *dh = NULL;
3839         struct dirent *de;
3840         struct fruit_config_data *config;
3841
3842         SMB_VFS_HANDLE_GET_DATA(handle, config,
3843                                 struct fruit_config_data, return -1);
3844
3845         if (config->rsrc != FRUIT_RSRC_ADFILE) {
3846                 goto exit_rmdir;
3847         }
3848
3849         /*
3850          * Due to there is no way to change bDeleteVetoFiles variable
3851          * from this module, need to clean up ourselves
3852          */
3853
3854         dh = SMB_VFS_OPENDIR(handle->conn, smb_fname, NULL, 0);
3855         if (dh == NULL) {
3856                 goto exit_rmdir;
3857         }
3858
3859         while ((de = SMB_VFS_READDIR(handle->conn, dh, NULL)) != NULL) {
3860                 int match;
3861                 struct adouble *ad = NULL;
3862                 char *p = NULL;
3863                 struct smb_filename *ad_smb_fname = NULL;
3864                 int ret;
3865
3866                 match = strncmp(de->d_name,
3867                                 ADOUBLE_NAME_PREFIX,
3868                                 strlen(ADOUBLE_NAME_PREFIX));
3869                 if (match != 0) {
3870                         continue;
3871                 }
3872
3873                 p = talloc_asprintf(talloc_tos(), "%s/%s",
3874                                     smb_fname->base_name, de->d_name);
3875                 if (p == NULL) {
3876                         DBG_ERR("talloc_asprintf failed\n");
3877                         return -1;
3878                 }
3879
3880                 ad_smb_fname = synthetic_smb_fname(talloc_tos(), p,
3881                                                     NULL, NULL,
3882                                                     smb_fname->flags);
3883                 TALLOC_FREE(p);
3884                 if (ad_smb_fname == NULL) {
3885                         DBG_ERR("synthetic_smb_fname failed\n");
3886                         return -1;
3887                 }
3888
3889                 /*
3890                  * Check whether it's a valid AppleDouble file, if
3891                  * yes, delete it, ignore it otherwise.
3892                  */
3893                 ad = ad_get(talloc_tos(), handle, ad_smb_fname, ADOUBLE_RSRC);
3894                 if (ad == NULL) {
3895                         TALLOC_FREE(ad_smb_fname);
3896                         TALLOC_FREE(p);
3897                         continue;
3898                 }
3899                 TALLOC_FREE(ad);
3900
3901                 ret = SMB_VFS_NEXT_UNLINK(handle, ad_smb_fname);
3902                 if (ret != 0) {
3903                         DBG_ERR("Deleting [%s] failed\n",
3904                                 smb_fname_str_dbg(ad_smb_fname));
3905                 }
3906                 TALLOC_FREE(ad_smb_fname);
3907         }
3908
3909 exit_rmdir:
3910         if (dh) {
3911                 SMB_VFS_CLOSEDIR(handle->conn, dh);
3912         }
3913         return SMB_VFS_NEXT_RMDIR(handle, smb_fname);
3914 }
3915
3916 static ssize_t fruit_pread_meta_stream(vfs_handle_struct *handle,
3917                                        files_struct *fsp, void *data,
3918                                        size_t n, off_t offset)
3919 {
3920         ssize_t nread;
3921         int ret;
3922
3923         nread = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
3924
3925         if (nread == n) {
3926                 return nread;
3927         }
3928
3929         DBG_ERR("Removing [%s] after short read [%zd]\n",
3930                 fsp_str_dbg(fsp), nread);
3931
3932         ret = SMB_VFS_NEXT_UNLINK(handle, fsp->fsp_name);
3933         if (ret != 0) {
3934                 DBG_ERR("Removing [%s] failed\n", fsp_str_dbg(fsp));
3935                 return -1;
3936         }
3937
3938         errno = EINVAL;
3939         return -1;
3940 }
3941
3942 static ssize_t fruit_pread_meta_adouble(vfs_handle_struct *handle,
3943                                         files_struct *fsp, void *data,
3944                                         size_t n, off_t offset)
3945 {
3946         AfpInfo *ai = NULL;
3947         struct adouble *ad = NULL;
3948         char afpinfo_buf[AFP_INFO_SIZE];
3949         char *p = NULL;
3950         ssize_t nread;
3951
3952         ai = afpinfo_new(talloc_tos());
3953         if (ai == NULL) {
3954                 return -1;
3955         }
3956
3957         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_META);
3958         if (ad == NULL) {
3959                 nread = -1;
3960                 goto fail;
3961         }
3962
3963         p = ad_get_entry(ad, ADEID_FINDERI);
3964         if (p == NULL) {
3965                 DBG_ERR("No ADEID_FINDERI for [%s]\n", fsp_str_dbg(fsp));
3966                 nread = -1;
3967                 goto fail;
3968         }
3969
3970         memcpy(&ai->afpi_FinderInfo[0], p, ADEDLEN_FINDERI);
3971
3972         nread = afpinfo_pack(ai, afpinfo_buf);
3973         if (nread != AFP_INFO_SIZE) {
3974                 nread = -1;
3975                 goto fail;
3976         }
3977
3978         memcpy(data, afpinfo_buf, n);
3979         nread = n;
3980
3981 fail:
3982         TALLOC_FREE(ai);
3983         return nread;
3984 }
3985
3986 static ssize_t fruit_pread_meta(vfs_handle_struct *handle,
3987                                 files_struct *fsp, void *data,
3988                                 size_t n, off_t offset)
3989 {
3990         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3991         ssize_t nread;
3992         ssize_t to_return;
3993
3994         /*
3995          * OS X has a off-by-1 error in the offset calculation, so we're
3996          * bug compatible here. It won't hurt, as any relevant real
3997          * world read requests from the AFP_AfpInfo stream will be
3998          * offset=0 n=60. offset is ignored anyway, see below.
3999          */
4000         if ((offset < 0) || (offset >= AFP_INFO_SIZE + 1)) {
4001                 return 0;
4002         }
4003
4004         /* Yes, macOS always reads from offset 0 */
4005         offset = 0;
4006         to_return = MIN(n, AFP_INFO_SIZE);
4007
4008         switch (fio->config->meta) {
4009         case FRUIT_META_STREAM:
4010                 nread = fruit_pread_meta_stream(handle, fsp, data,
4011                                                 to_return, offset);
4012                 break;
4013
4014         case FRUIT_META_NETATALK:
4015                 nread = fruit_pread_meta_adouble(handle, fsp, data,
4016                                                  to_return, offset);
4017                 break;
4018
4019         default:
4020                 DBG_ERR("Unexpected meta config [%d]\n", fio->config->meta);
4021                 return -1;
4022         }
4023
4024         return nread;
4025 }
4026
4027 static ssize_t fruit_pread_rsrc_stream(vfs_handle_struct *handle,
4028                                        files_struct *fsp, void *data,
4029                                        size_t n, off_t offset)
4030 {
4031         return SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
4032 }
4033
4034 static ssize_t fruit_pread_rsrc_xattr(vfs_handle_struct *handle,
4035                                       files_struct *fsp, void *data,
4036                                       size_t n, off_t offset)
4037 {
4038         return SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
4039 }
4040
4041 static ssize_t fruit_pread_rsrc_adouble(vfs_handle_struct *handle,
4042                                         files_struct *fsp, void *data,
4043                                         size_t n, off_t offset)
4044 {
4045         struct adouble *ad = NULL;
4046         ssize_t nread;
4047
4048         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_RSRC);
4049         if (ad == NULL) {
4050                 return -1;
4051         }
4052
4053         nread = SMB_VFS_NEXT_PREAD(handle, fsp, data, n,
4054                                    offset + ad_getentryoff(ad, ADEID_RFORK));
4055
4056         TALLOC_FREE(ad);
4057         return nread;
4058 }
4059
4060 static ssize_t fruit_pread_rsrc(vfs_handle_struct *handle,
4061                                 files_struct *fsp, void *data,
4062                                 size_t n, off_t offset)
4063 {
4064         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
4065         ssize_t nread;
4066
4067         switch (fio->config->rsrc) {
4068         case FRUIT_RSRC_STREAM:
4069                 nread = fruit_pread_rsrc_stream(handle, fsp, data, n, offset);
4070                 break;
4071
4072         case FRUIT_RSRC_ADFILE:
4073                 nread = fruit_pread_rsrc_adouble(handle, fsp, data, n, offset);
4074                 break;
4075
4076         case FRUIT_RSRC_XATTR:
4077                 nread = fruit_pread_rsrc_xattr(handle, fsp, data, n, offset);
4078                 break;
4079
4080         default:
4081                 DBG_ERR("Unexpected rsrc config [%d]\n", fio->config->rsrc);
4082                 return -1;
4083         }
4084
4085         return nread;
4086 }
4087
4088 static ssize_t fruit_pread(vfs_handle_struct *handle,
4089                            files_struct *fsp, void *data,
4090                            size_t n, off_t offset)
4091 {
4092         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
4093         ssize_t nread;
4094
4095         DBG_DEBUG("Path [%s] offset=%"PRIdMAX", size=%zd\n",
4096                   fsp_str_dbg(fsp), (intmax_t)offset, n);
4097
4098         if (fio == NULL) {
4099                 return SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
4100         }
4101
4102         if (fio->type == ADOUBLE_META) {
4103                 nread = fruit_pread_meta(handle, fsp, data, n, offset);
4104         } else {
4105                 nread = fruit_pread_rsrc(handle, fsp, data, n, offset);
4106         }
4107
4108         DBG_DEBUG("Path [%s] nread [%zd]\n", fsp_str_dbg(fsp), nread);
4109         return nread;
4110 }
4111
4112 static bool fruit_must_handle_aio_stream(struct fio *fio)
4113 {
4114         if (fio == NULL) {
4115                 return false;
4116         };
4117
4118         if ((fio->type == ADOUBLE_META) &&
4119             (fio->config->meta == FRUIT_META_NETATALK))
4120         {
4121                 return true;
4122         }
4123
4124         if ((fio->type == ADOUBLE_RSRC) &&
4125             (fio->config->rsrc == FRUIT_RSRC_ADFILE))
4126         {
4127                 return true;
4128         }
4129
4130         return false;
4131 }
4132
4133 struct fruit_pread_state {
4134         ssize_t nread;
4135         struct vfs_aio_state vfs_aio_state;
4136 };
4137
4138 static void fruit_pread_done(struct tevent_req *subreq);
4139
4140 static struct tevent_req *fruit_pread_send(
4141         struct vfs_handle_struct *handle,
4142         TALLOC_CTX *mem_ctx,
4143         struct tevent_context *ev,
4144         struct files_struct *fsp,
4145         void *data,
4146         size_t n, off_t offset)
4147 {
4148         struct tevent_req *req = NULL;
4149         struct tevent_req *subreq = NULL;
4150         struct fruit_pread_state *state = NULL;
4151         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
4152
4153         req = tevent_req_create(mem_ctx, &state,
4154                                 struct fruit_pread_state);
4155         if (req == NULL) {
4156                 return NULL;
4157         }
4158
4159         if (fruit_must_handle_aio_stream(fio)) {
4160                 state->nread = SMB_VFS_PREAD(fsp, data, n, offset);
4161                 if (state->nread != n) {
4162                         if (state->nread != -1) {
4163                                 errno = EIO;
4164                         }
4165                         tevent_req_error(req, errno);
4166                         return tevent_req_post(req, ev);
4167                 }
4168                 tevent_req_done(req);
4169                 return tevent_req_post(req, ev);
4170         }
4171
4172         subreq = SMB_VFS_NEXT_PREAD_SEND(state, ev, handle, fsp,
4173                                          data, n, offset);
4174         if (tevent_req_nomem(req, subreq)) {
4175                 return tevent_req_post(req, ev);
4176         }
4177         tevent_req_set_callback(subreq, fruit_pread_done, req);
4178         return req;
4179 }
4180
4181 static void fruit_pread_done(struct tevent_req *subreq)
4182 {
4183         struct tevent_req *req = tevent_req_callback_data(
4184                 subreq, struct tevent_req);
4185         struct fruit_pread_state *state = tevent_req_data(
4186                 req, struct fruit_pread_state);
4187
4188         state->nread = SMB_VFS_PREAD_RECV(subreq, &state->vfs_aio_state);
4189         TALLOC_FREE(subreq);
4190
4191         if (tevent_req_error(req, state->vfs_aio_state.error)) {
4192                 return;
4193         }
4194         tevent_req_done(req);
4195 }
4196
4197 static ssize_t fruit_pread_recv(struct tevent_req *req,
4198                                         struct vfs_aio_state *vfs_aio_state)
4199 {
4200         struct fruit_pread_state *state = tevent_req_data(
4201                 req, struct fruit_pread_state);
4202
4203         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
4204                 return -1;
4205         }
4206
4207         *vfs_aio_state = state->vfs_aio_state;
4208         return state->nread;
4209 }
4210
4211 static ssize_t fruit_pwrite_meta_stream(vfs_handle_struct *handle,
4212                                         files_struct *fsp, const void *data,
4213                                         size_t n, off_t offset)
4214 {
4215         AfpInfo *ai = NULL;
4216         size_t nwritten;
4217         bool ok;
4218
4219         ai = afpinfo_unpack(talloc_tos(), data);
4220         if (ai == NULL) {
4221                 return -1;
4222         }
4223
4224         nwritten = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
4225         if (nwritten != n) {
4226                 return -1;
4227         }
4228
4229         if (!ai_empty_finderinfo(ai)) {
4230                 return n;
4231         }
4232
4233         ok = set_delete_on_close(
4234                         fsp,
4235                         true,
4236                         handle->conn->session_info->security_token,
4237                         handle->conn->session_info->unix_token);
4238         if (!ok) {
4239                 DBG_ERR("set_delete_on_close on [%s] failed\n",
4240                         fsp_str_dbg(fsp));
4241                 return -1;
4242         }
4243
4244         return n;
4245 }
4246
4247 static ssize_t fruit_pwrite_meta_netatalk(vfs_handle_struct *handle,
4248                                           files_struct *fsp, const void *data,
4249                                           size_t n, off_t offset)
4250 {
4251         struct adouble *ad = NULL;
4252         AfpInfo *ai = NULL;
4253         char *p = NULL;
4254         int ret;
4255         bool ok;
4256
4257         ai = afpinfo_unpack(talloc_tos(), data);
4258         if (ai == NULL) {
4259                 return -1;
4260         }
4261
4262         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_META);
4263         if (ad == NULL) {
4264                 ad = ad_init(talloc_tos(), handle, ADOUBLE_META);
4265                 if (ad == NULL) {
4266                         return -1;
4267                 }
4268         }
4269         p = ad_get_entry(ad, ADEID_FINDERI);
4270         if (p == NULL) {
4271                 DBG_ERR("No ADEID_FINDERI for [%s]\n", fsp_str_dbg(fsp));
4272                 TALLOC_FREE(ad);
4273                 return -1;
4274         }
4275
4276         memcpy(p, &ai->afpi_FinderInfo[0], ADEDLEN_FINDERI);
4277
4278         ret = ad_fset(ad, fsp);
4279         if (ret != 0) {
4280                 DBG_ERR("ad_pwrite [%s] failed\n", fsp_str_dbg(fsp));
4281                 TALLOC_FREE(ad);
4282                 return -1;
4283         }
4284
4285         TALLOC_FREE(ad);
4286
4287         if (!ai_empty_finderinfo(ai)) {
4288                 return n;
4289         }
4290
4291         ok = set_delete_on_close(
4292                 fsp,
4293                 true,
4294                 handle->conn->session_info->security_token,
4295                 handle->conn->session_info->unix_token);
4296         if (!ok) {
4297                 DBG_ERR("set_delete_on_close on [%s] failed\n",
4298                         fsp_str_dbg(fsp));
4299                 return -1;
4300         }
4301
4302         return n;
4303 }
4304
4305 static ssize_t fruit_pwrite_meta(vfs_handle_struct *handle,
4306                                  files_struct *fsp, const void *data,
4307                                  size_t n, off_t offset)
4308 {
4309         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
4310         ssize_t nwritten;
4311
4312         /*
4313          * Writing an all 0 blob to the metadata stream
4314          * results in the stream being removed on a macOS
4315          * server. This ensures we behave the same and it
4316          * verified by the "delete AFP_AfpInfo by writing all
4317          * 0" test.
4318          */
4319         if (n != AFP_INFO_SIZE || offset != 0) {
4320                 DBG_ERR("unexpected offset=%jd or size=%jd\n",
4321                         (intmax_t)offset, (intmax_t)n);
4322                 return -1;
4323         }
4324
4325         switch (fio->config->meta) {
4326         case FRUIT_META_STREAM:
4327                 nwritten = fruit_pwrite_meta_stream(handle, fsp, data,
4328                                                     n, offset);
4329                 break;
4330
4331         case FRUIT_META_NETATALK:
4332                 nwritten = fruit_pwrite_meta_netatalk(handle, fsp, data,
4333                                                       n, offset);
4334                 break;
4335
4336         default:
4337                 DBG_ERR("Unexpected meta config [%d]\n", fio->config->meta);
4338                 return -1;
4339         }
4340
4341         return nwritten;
4342 }
4343
4344 static ssize_t fruit_pwrite_rsrc_stream(vfs_handle_struct *handle,
4345                                         files_struct *fsp, const void *data,
4346                                         size_t n, off_t offset)
4347 {
4348         return SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
4349 }
4350
4351 static ssize_t fruit_pwrite_rsrc_xattr(vfs_handle_struct *handle,
4352                                        files_struct *fsp, const void *data,
4353                                        size_t n, off_t offset)
4354 {
4355         return SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
4356 }
4357
4358 static ssize_t fruit_pwrite_rsrc_adouble(vfs_handle_struct *handle,
4359                                          files_struct *fsp, const void *data,
4360                                          size_t n, off_t offset)
4361 {
4362         struct adouble *ad = NULL;
4363         ssize_t nwritten;
4364         int ret;
4365
4366         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_RSRC);
4367         if (ad == NULL) {
4368                 DBG_ERR("ad_get [%s] failed\n", fsp_str_dbg(fsp));
4369                 return -1;
4370         }
4371
4372         nwritten = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n,
4373                                        offset + ad_getentryoff(ad, ADEID_RFORK));
4374         if (nwritten != n) {
4375                 DBG_ERR("Short write on [%s] [%zd/%zd]\n",
4376                         fsp_str_dbg(fsp), nwritten, n);
4377                 TALLOC_FREE(ad);
4378                 return -1;
4379         }
4380
4381         if ((n + offset) > ad_getentrylen(ad, ADEID_RFORK)) {
4382                 ad_setentrylen(ad, ADEID_RFORK, n + offset);
4383                 ret = ad_fset(ad, fsp);
4384                 if (ret != 0) {
4385                         DBG_ERR("ad_pwrite [%s] failed\n", fsp_str_dbg(fsp));
4386                         TALLOC_FREE(ad);
4387                         return -1;
4388                 }
4389         }
4390
4391         TALLOC_FREE(ad);
4392         return n;
4393 }
4394
4395 static ssize_t fruit_pwrite_rsrc(vfs_handle_struct *handle,
4396                                  files_struct *fsp, const void *data,
4397                                  size_t n, off_t offset)
4398 {
4399         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
4400         ssize_t nwritten;
4401
4402         switch (fio->config->rsrc) {
4403         case FRUIT_RSRC_STREAM:
4404                 nwritten = fruit_pwrite_rsrc_stream(handle, fsp, data, n, offset);
4405                 break;
4406
4407         case FRUIT_RSRC_ADFILE:
4408                 nwritten = fruit_pwrite_rsrc_adouble(handle, fsp, data, n, offset);
4409                 break;
4410
4411         case FRUIT_RSRC_XATTR:
4412                 nwritten = fruit_pwrite_rsrc_xattr(handle, fsp, data, n, offset);
4413                 break;
4414
4415         default:
4416                 DBG_ERR("Unexpected rsrc config [%d]\n", fio->config->rsrc);
4417                 return -1;
4418         }
4419
4420         return nwritten;
4421 }
4422
4423 static ssize_t fruit_pwrite(vfs_handle_struct *handle,
4424                             files_struct *fsp, const void *data,
4425                             size_t n, off_t offset)
4426 {
4427         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
4428         ssize_t nwritten;
4429
4430         DBG_DEBUG("Path [%s] offset=%"PRIdMAX", size=%zd\n",
4431                   fsp_str_dbg(fsp), (intmax_t)offset, n);
4432
4433         if (fio == NULL) {
4434                 return SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
4435         }
4436
4437         if (fio->type == ADOUBLE_META) {
4438                 nwritten = fruit_pwrite_meta(handle, fsp, data, n, offset);
4439         } else {
4440                 nwritten = fruit_pwrite_rsrc(handle, fsp, data, n, offset);
4441         }
4442
4443         DBG_DEBUG("Path [%s] nwritten=%zd\n", fsp_str_dbg(fsp), nwritten);
4444         return nwritten;
4445 }
4446
4447 struct fruit_pwrite_state {
4448         ssize_t nwritten;
4449         struct vfs_aio_state vfs_aio_state;
4450 };
4451
4452 static void fruit_pwrite_done(struct tevent_req *subreq);
4453
4454 static struct tevent_req *fruit_pwrite_send(
4455         struct vfs_handle_struct *handle,
4456         TALLOC_CTX *mem_ctx,
4457         struct tevent_context *ev,
4458         struct files_struct *fsp,
4459         const void *data,
4460         size_t n, off_t offset)
4461 {
4462         struct tevent_req *req = NULL;
4463         struct tevent_req *subreq = NULL;
4464         struct fruit_pwrite_state *state = NULL;
4465         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
4466
4467         req = tevent_req_create(mem_ctx, &state,
4468                                 struct fruit_pwrite_state);
4469         if (req == NULL) {
4470                 return NULL;
4471         }
4472
4473         if (fruit_must_handle_aio_stream(fio)) {
4474                 state->nwritten = SMB_VFS_PWRITE(fsp, data, n, offset);
4475                 if (state->nwritten != n) {
4476                         if (state->nwritten != -1) {
4477                                 errno = EIO;
4478                         }
4479                         tevent_req_error(req, errno);
4480                         return tevent_req_post(req, ev);
4481                 }
4482                 tevent_req_done(req);
4483                 return tevent_req_post(req, ev);
4484         }
4485
4486         subreq = SMB_VFS_NEXT_PWRITE_SEND(state, ev, handle, fsp,
4487                                           data, n, offset);
4488         if (tevent_req_nomem(req, subreq)) {
4489                 return tevent_req_post(req, ev);
4490         }
4491         tevent_req_set_callback(subreq, fruit_pwrite_done, req);
4492         return req;
4493 }
4494
4495 static void fruit_pwrite_done(struct tevent_req *subreq)
4496 {
4497         struct tevent_req *req = tevent_req_callback_data(
4498                 subreq, struct tevent_req);
4499         struct fruit_pwrite_state *state = tevent_req_data(
4500                 req, struct fruit_pwrite_state);
4501
4502         state->nwritten = SMB_VFS_PWRITE_RECV(subreq, &state->vfs_aio_state);
4503         TALLOC_FREE(subreq);
4504
4505         if (tevent_req_error(req, state->vfs_aio_state.error)) {
4506                 return;
4507         }
4508         tevent_req_done(req);
4509 }
4510
4511 static ssize_t fruit_pwrite_recv(struct tevent_req *req,
4512                                          struct vfs_aio_state *vfs_aio_state)
4513 {
4514         struct fruit_pwrite_state *state = tevent_req_data(
4515                 req, struct fruit_pwrite_state);
4516
4517         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
4518                 return -1;
4519         }
4520
4521         *vfs_aio_state = state->vfs_aio_state;
4522         return state->nwritten;
4523 }
4524
4525 /**
4526  * Helper to stat/lstat the base file of an smb_fname.
4527  */
4528 static int fruit_stat_base(vfs_handle_struct *handle,
4529                            struct smb_filename *smb_fname,
4530                            bool follow_links)
4531 {
4532         char *tmp_stream_name;
4533         int rc;
4534
4535         tmp_stream_name = smb_fname->stream_name;
4536         smb_fname->stream_name = NULL;
4537         if (follow_links) {
4538                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
4539         } else {
4540                 rc = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
4541         }
4542         smb_fname->stream_name = tmp_stream_name;
4543         return rc;
4544 }
4545
4546 static int fruit_stat_meta_stream(vfs_handle_struct *handle,
4547                                   struct smb_filename *smb_fname,
4548                                   bool follow_links)
4549 {
4550         int ret;
4551
4552         if (follow_links) {
4553                 ret = SMB_VFS_NEXT_STAT(handle, smb_fname);
4554         } else {
4555                 ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
4556         }
4557
4558         return ret;
4559 }
4560
4561 static int fruit_stat_meta_netatalk(vfs_handle_struct *handle,
4562                                     struct smb_filename *smb_fname,
4563                                     bool follow_links)
4564 {
4565         struct adouble *ad = NULL;
4566
4567         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
4568         if (ad == NULL) {
4569                 DBG_INFO("fruit_stat_meta %s: %s\n",
4570                          smb_fname_str_dbg(smb_fname), strerror(errno));
4571                 errno = ENOENT;
4572                 return -1;
4573         }
4574         TALLOC_FREE(ad);
4575
4576         /* Populate the stat struct with info from the base file. */
4577         if (fruit_stat_base(handle, smb_fname, follow_links) == -1) {
4578                 return -1;
4579         }
4580         smb_fname->st.st_ex_size = AFP_INFO_SIZE;
4581         smb_fname->st.st_ex_ino = fruit_inode(&smb_fname->st,
4582                                               smb_fname->stream_name);
4583         return 0;
4584 }
4585
4586 static int fruit_stat_meta(vfs_handle_struct *handle,
4587                            struct smb_filename *smb_fname,
4588                            bool follow_links)
4589 {
4590         struct fruit_config_data *config = NULL;
4591         int ret;
4592
4593         SMB_VFS_HANDLE_GET_DATA(handle, config,
4594                                 struct fruit_config_data, return -1);
4595
4596         switch (config->meta) {
4597         case FRUIT_META_STREAM:
4598                 ret = fruit_stat_meta_stream(handle, smb_fname, follow_links);
4599                 break;
4600
4601         case FRUIT_META_NETATALK:
4602                 ret = fruit_stat_meta_netatalk(handle, smb_fname, follow_links);
4603                 break;
4604
4605         default:
4606                 DBG_ERR("Unexpected meta config [%d]\n", config->meta);
4607                 return -1;
4608         }
4609
4610         return ret;
4611 }
4612
4613 static int fruit_stat_rsrc_netatalk(vfs_handle_struct *handle,
4614                                     struct smb_filename *smb_fname,
4615                                     bool follow_links)
4616 {
4617         struct adouble *ad = NULL;
4618         int ret;
4619
4620         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_RSRC);
4621         if (ad == NULL) {
4622                 errno = ENOENT;
4623                 return -1;
4624         }
4625
4626         /* Populate the stat struct with info from the base file. */
4627         ret = fruit_stat_base(handle, smb_fname, follow_links);
4628         if (ret != 0) {
4629                 TALLOC_FREE(ad);
4630                 return -1;
4631         }
4632
4633         smb_fname->st.st_ex_size = ad_getentrylen(ad, ADEID_RFORK);
4634         smb_fname->st.st_ex_ino = fruit_inode(&smb_fname->st,
4635                                               smb_fname->stream_name);
4636         TALLOC_FREE(ad);
4637         return 0;
4638 }
4639
4640 static int fruit_stat_rsrc_stream(vfs_handle_struct *handle,
4641                                   struct smb_filename *smb_fname,
4642                                   bool follow_links)
4643 {
4644         int ret;
4645
4646         if (follow_links) {
4647                 ret = SMB_VFS_NEXT_STAT(handle, smb_fname);
4648         } else {
4649                 ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
4650         }
4651
4652         return ret;
4653 }
4654
4655 static int fruit_stat_rsrc_xattr(vfs_handle_struct *handle,
4656                                  struct smb_filename *smb_fname,
4657                                  bool follow_links)
4658 {
4659 #ifdef HAVE_ATTROPEN
4660         int ret;
4661         int fd = -1;
4662
4663         /* Populate the stat struct with info from the base file. */
4664         ret = fruit_stat_base(handle, smb_fname, follow_links);
4665         if (ret != 0) {
4666                 return -1;
4667         }
4668
4669         fd = attropen(smb_fname->base_name,
4670                       AFPRESOURCE_EA_NETATALK,
4671                       O_RDONLY);
4672         if (fd == -1) {
4673                 return 0;
4674         }
4675
4676         ret = sys_fstat(fd, &smb_fname->st, false);
4677         if (ret != 0) {
4678                 close(fd);
4679                 DBG_ERR("fstat [%s:%s] failed\n", smb_fname->base_name,
4680                         AFPRESOURCE_EA_NETATALK);
4681                 return -1;
4682         }
4683         close(fd);
4684         fd = -1;
4685
4686         smb_fname->st.st_ex_ino = fruit_inode(&smb_fname->st,
4687                                               smb_fname->stream_name);
4688
4689         return ret;
4690
4691 #else
4692         errno = ENOSYS;
4693         return -1;
4694 #endif
4695 }
4696
4697 static int fruit_stat_rsrc(vfs_handle_struct *handle,
4698                            struct smb_filename *smb_fname,
4699                            bool follow_links)
4700 {
4701         struct fruit_config_data *config = NULL;
4702         int ret;
4703
4704         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
4705
4706         SMB_VFS_HANDLE_GET_DATA(handle, config,
4707                                 struct fruit_config_data, return -1);
4708
4709         switch (config->rsrc) {
4710         case FRUIT_RSRC_STREAM:
4711                 ret = fruit_stat_rsrc_stream(handle, smb_fname, follow_links);
4712                 break;
4713
4714         case FRUIT_RSRC_XATTR:
4715                 ret = fruit_stat_rsrc_xattr(handle, smb_fname, follow_links);
4716                 break;
4717
4718         case FRUIT_RSRC_ADFILE:
4719                 ret = fruit_stat_rsrc_netatalk(handle, smb_fname, follow_links);
4720                 break;
4721
4722         default:
4723                 DBG_ERR("Unexpected rsrc config [%d]\n", config->rsrc);
4724                 return -1;
4725         }
4726
4727         return ret;
4728 }
4729
4730 static int fruit_stat(vfs_handle_struct *handle,
4731                       struct smb_filename *smb_fname)
4732 {
4733         int rc = -1;
4734
4735         DEBUG(10, ("fruit_stat called for %s\n",
4736                    smb_fname_str_dbg(smb_fname)));
4737
4738         if (!is_ntfs_stream_smb_fname(smb_fname)
4739             || is_ntfs_default_stream_smb_fname(smb_fname)) {
4740                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
4741                 if (rc == 0) {
4742                         update_btime(handle, smb_fname);
4743                 }
4744                 return rc;
4745         }
4746
4747         /*
4748          * Note if lp_posix_paths() is true, we can never
4749          * get here as is_ntfs_stream_smb_fname() is
4750          * always false. So we never need worry about
4751          * not following links here.
4752          */
4753
4754         if (is_afpinfo_stream(smb_fname)) {
4755                 rc = fruit_stat_meta(handle, smb_fname, true);
4756         } else if (is_afpresource_stream(smb_fname)) {
4757                 rc = fruit_stat_rsrc(handle, smb_fname, true);
4758         } else {
4759                 return SMB_VFS_NEXT_STAT(handle, smb_fname);
4760         }
4761
4762         if (rc == 0) {
4763                 update_btime(handle, smb_fname);
4764                 smb_fname->st.st_ex_mode &= ~S_IFMT;
4765                 smb_fname->st.st_ex_mode |= S_IFREG;
4766                 smb_fname->st.st_ex_blocks =
4767                         smb_fname->st.st_ex_size / STAT_ST_BLOCKSIZE + 1;
4768         }
4769         return rc;
4770 }
4771
4772 static int fruit_lstat(vfs_handle_struct *handle,
4773                        struct smb_filename *smb_fname)
4774 {
4775         int rc = -1;
4776
4777         DEBUG(10, ("fruit_lstat called for %s\n",
4778                    smb_fname_str_dbg(smb_fname)));
4779
4780         if (!is_ntfs_stream_smb_fname(smb_fname)
4781             || is_ntfs_default_stream_smb_fname(smb_fname)) {
4782                 rc = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
4783                 if (rc == 0) {
4784                         update_btime(handle, smb_fname);
4785                 }
4786                 return rc;
4787         }
4788
4789         if (is_afpinfo_stream(smb_fname)) {
4790                 rc = fruit_stat_meta(handle, smb_fname, false);
4791         } else if (is_afpresource_stream(smb_fname)) {
4792                 rc = fruit_stat_rsrc(handle, smb_fname, false);
4793         } else {
4794                 return SMB_VFS_NEXT_LSTAT(handle, smb_fname);
4795         }
4796
4797         if (rc == 0) {
4798                 update_btime(handle, smb_fname);
4799                 smb_fname->st.st_ex_mode &= ~S_IFMT;
4800                 smb_fname->st.st_ex_mode |= S_IFREG;
4801                 smb_fname->st.st_ex_blocks =
4802                         smb_fname->st.st_ex_size / STAT_ST_BLOCKSIZE + 1;
4803         }
4804         return rc;
4805 }
4806
4807 static int fruit_fstat_meta_stream(vfs_handle_struct *handle,
4808                                    files_struct *fsp,
4809                                    SMB_STRUCT_STAT *sbuf)
4810 {
4811         return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
4812 }
4813
4814 static int fruit_fstat_meta_netatalk(vfs_handle_struct *handle,
4815                                      files_struct *fsp,
4816                                      SMB_STRUCT_STAT *sbuf)
4817 {
4818         int ret;
4819
4820         ret = fruit_stat_base(handle, fsp->base_fsp->fsp_name, false);
4821         if (ret != 0) {
4822                 return -1;
4823         }
4824
4825         *sbuf = fsp->base_fsp->fsp_name->st;
4826         sbuf->st_ex_size = AFP_INFO_SIZE;
4827         sbuf->st_ex_ino = fruit_inode(sbuf, fsp->fsp_name->stream_name);
4828
4829         return 0;
4830 }
4831
4832 static int fruit_fstat_meta(vfs_handle_struct *handle,
4833                             files_struct *fsp,
4834                             SMB_STRUCT_STAT *sbuf,
4835                             struct fio *fio)
4836 {
4837         int ret;
4838
4839         DBG_DEBUG("Path [%s]\n", fsp_str_dbg(fsp));
4840
4841         switch (fio->config->meta) {
4842         case FRUIT_META_STREAM:
4843                 ret = fruit_fstat_meta_stream(handle, fsp, sbuf);
4844                 break;
4845
4846         case FRUIT_META_NETATALK:
4847                 ret = fruit_fstat_meta_netatalk(handle, fsp, sbuf);
4848                 break;
4849
4850         default:
4851                 DBG_ERR("Unexpected meta config [%d]\n", fio->config->meta);
4852                 return -1;
4853         }
4854
4855         DBG_DEBUG("Path [%s] ret [%d]\n", fsp_str_dbg(fsp), ret);
4856         return ret;
4857 }
4858
4859 static int fruit_fstat_rsrc_xattr(vfs_handle_struct *handle,
4860                                   files_struct *fsp,
4861                                   SMB_STRUCT_STAT *sbuf)
4862 {
4863         return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
4864 }
4865
4866 static int fruit_fstat_rsrc_stream(vfs_handle_struct *handle,
4867                                    files_struct *fsp,
4868                                    SMB_STRUCT_STAT *sbuf)
4869 {
4870         return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
4871 }
4872
4873 static int fruit_fstat_rsrc_adouble(vfs_handle_struct *handle,
4874                                     files_struct *fsp,
4875                                     SMB_STRUCT_STAT *sbuf)
4876 {
4877         struct adouble *ad = NULL;
4878         int ret;
4879
4880         /* Populate the stat struct with info from the base file. */
4881         ret = fruit_stat_base(handle, fsp->base_fsp->fsp_name, false);
4882         if (ret == -1) {
4883                 return -1;
4884         }
4885
4886         ad = ad_get(talloc_tos(), handle,
4887                     fsp->base_fsp->fsp_name,
4888                     ADOUBLE_RSRC);
4889         if (ad == NULL) {
4890                 DBG_ERR("ad_get [%s] failed [%s]\n",
4891                         fsp_str_dbg(fsp), strerror(errno));
4892                 return -1;
4893         }
4894
4895         *sbuf = fsp->base_fsp->fsp_name->st;
4896         sbuf->st_ex_size = ad_getentrylen(ad, ADEID_RFORK);
4897         sbuf->st_ex_ino = fruit_inode(sbuf, fsp->fsp_name->stream_name);
4898
4899         TALLOC_FREE(ad);
4900         return 0;
4901 }
4902
4903 static int fruit_fstat_rsrc(vfs_handle_struct *handle, files_struct *fsp,
4904                             SMB_STRUCT_STAT *sbuf, struct fio *fio)
4905 {
4906         int ret;
4907
4908         switch (fio->config->rsrc) {
4909         case FRUIT_RSRC_STREAM:
4910                 ret = fruit_fstat_rsrc_stream(handle, fsp, sbuf);
4911                 break;
4912
4913         case FRUIT_RSRC_ADFILE:
4914                 ret = fruit_fstat_rsrc_adouble(handle, fsp, sbuf);
4915                 break;
4916
4917         case FRUIT_RSRC_XATTR:
4918                 ret = fruit_fstat_rsrc_xattr(handle, fsp, sbuf);
4919                 break;
4920
4921         default:
4922                 DBG_ERR("Unexpected rsrc config [%d]\n", fio->config->rsrc);
4923                 return -1;
4924         }
4925
4926         return ret;
4927 }
4928
4929 static int fruit_fstat(vfs_handle_struct *handle, files_struct *fsp,
4930                        SMB_STRUCT_STAT *sbuf)
4931 {
4932         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
4933         int rc;
4934
4935         if (fio == NULL) {
4936                 return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
4937         }
4938
4939         DBG_DEBUG("Path [%s]\n", fsp_str_dbg(fsp));
4940
4941         if (fio->type == ADOUBLE_META) {
4942                 rc = fruit_fstat_meta(handle, fsp, sbuf, fio);
4943         } else {
4944                 rc = fruit_fstat_rsrc(handle, fsp, sbuf, fio);
4945         }
4946
4947         if (rc == 0) {
4948                 sbuf->st_ex_mode &= ~S_IFMT;
4949                 sbuf->st_ex_mode |= S_IFREG;
4950                 sbuf->st_ex_blocks = sbuf->st_ex_size / STAT_ST_BLOCKSIZE + 1;
4951         }
4952
4953         DBG_DEBUG("Path [%s] rc [%d] size [%"PRIdMAX"]\n",
4954                   fsp_str_dbg(fsp), rc, (intmax_t)sbuf->st_ex_size);
4955         return rc;
4956 }
4957
4958 static NTSTATUS delete_invalid_meta_stream(
4959         vfs_handle_struct *handle,
4960         const struct smb_filename *smb_fname,
4961         TALLOC_CTX *mem_ctx,
4962         unsigned int *pnum_streams,
4963         struct stream_struct **pstreams)
4964 {
4965         struct smb_filename *sname = NULL;
4966         int ret;
4967         bool ok;
4968
4969         ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams, AFPINFO_STREAM);
4970         if (!ok) {
4971                 return NT_STATUS_INTERNAL_ERROR;
4972         }
4973
4974         sname = synthetic_smb_fname(talloc_tos(),
4975                                     smb_fname->base_name,
4976                                     AFPINFO_STREAM_NAME,
4977                                     NULL, 0);
4978         if (sname == NULL) {
4979                 return NT_STATUS_NO_MEMORY;
4980         }
4981
4982         ret = SMB_VFS_NEXT_UNLINK(handle, sname);
4983         TALLOC_FREE(sname);
4984         if (ret != 0) {
4985                 DBG_ERR("Removing [%s] failed\n", smb_fname_str_dbg(sname));
4986                 return map_nt_error_from_unix(errno);
4987         }
4988
4989         return NT_STATUS_OK;
4990 }
4991
4992 static NTSTATUS fruit_streaminfo_meta_stream(
4993         vfs_handle_struct *handle,
4994         struct files_struct *fsp,
4995         const struct smb_filename *smb_fname,
4996         TALLOC_CTX *mem_ctx,
4997         unsigned int *pnum_streams,
4998         struct stream_struct **pstreams)
4999 {
5000         struct stream_struct *stream = *pstreams;
5001         unsigned int num_streams = *pnum_streams;
5002         struct smb_filename *sname = NULL;
5003         char *full_name = NULL;
5004         uint32_t name_hash;
5005         struct share_mode_lock *lck = NULL;
5006         struct file_id id = {0};
5007         bool delete_on_close_set;
5008         int i;
5009         int ret;
5010         NTSTATUS status;
5011         bool ok;
5012
5013         for (i = 0; i < num_streams; i++) {
5014                 if (strequal_m(stream[i].name, AFPINFO_STREAM)) {
5015                         break;
5016                 }
5017         }
5018
5019         if (i == num_streams) {
5020                 return NT_STATUS_OK;
5021         }
5022
5023         if (stream[i].size != AFP_INFO_SIZE) {
5024                 DBG_ERR("Removing invalid AFPINFO_STREAM size [%jd] from [%s]\n",
5025                         (intmax_t)stream[i].size, smb_fname_str_dbg(smb_fname));
5026
5027                 return delete_invalid_meta_stream(handle, smb_fname, mem_ctx,
5028                                                   pnum_streams, pstreams);
5029         }
5030
5031         /*
5032          * Now check if there's a delete-on-close pending on the stream. If so,
5033          * hide the stream. This behaviour was verified against a macOS 10.12
5034          * SMB server.
5035          */
5036
5037         sname = synthetic_smb_fname(talloc_tos(),
5038                                     smb_fname->base_name,
5039                                     AFPINFO_STREAM_NAME,
5040                                     NULL, 0);
5041         if (sname == NULL) {
5042                 status = NT_STATUS_NO_MEMORY;
5043                 goto out;
5044         }
5045
5046         ret = SMB_VFS_NEXT_STAT(handle, sname);
5047         if (ret != 0) {
5048                 status = map_nt_error_from_unix(errno);
5049                 goto out;
5050         }
5051
5052         id = SMB_VFS_NEXT_FILE_ID_CREATE(handle, &sname->st);
5053
5054         lck = get_existing_share_mode_lock(talloc_tos(), id);
5055         if (lck == NULL) {
5056                 status = NT_STATUS_OK;
5057                 goto out;
5058         }
5059
5060         full_name = talloc_asprintf(talloc_tos(),
5061                                     "%s%s",
5062                                     sname->base_name,
5063                                     AFPINFO_STREAM);
5064         if (full_name == NULL) {
5065                 status = NT_STATUS_NO_MEMORY;
5066                 goto out;
5067         }
5068
5069         status = file_name_hash(handle->conn, full_name, &name_hash);
5070         if (!NT_STATUS_IS_OK(status)) {
5071                 goto out;
5072         }
5073
5074         delete_on_close_set = is_delete_on_close_set(lck, name_hash);
5075         if (delete_on_close_set) {
5076                 ok = del_fruit_stream(mem_ctx,
5077                                       pnum_streams,
5078                                       pstreams,
5079                                       AFPINFO_STREAM);
5080                 if (!ok) {
5081                         status = NT_STATUS_INTERNAL_ERROR;
5082                         goto out;
5083                 }
5084         }
5085
5086         status  = NT_STATUS_OK;
5087
5088 out:
5089         TALLOC_FREE(sname);
5090         TALLOC_FREE(lck);
5091         TALLOC_FREE(full_name);
5092         return status;
5093 }
5094
5095 static NTSTATUS fruit_streaminfo_meta_netatalk(
5096         vfs_handle_struct *handle,
5097         struct files_struct *fsp,
5098         const struct smb_filename *smb_fname,
5099         TALLOC_CTX *mem_ctx,
5100         unsigned int *pnum_streams,
5101         struct stream_struct **pstreams)
5102 {
5103         struct stream_struct *stream = *pstreams;
5104         unsigned int num_streams = *pnum_streams;
5105         struct adouble *ad = NULL;
5106         bool is_fi_empty;
5107         int i;
5108         bool ok;
5109
5110         /* Remove the Netatalk xattr from the list */
5111         ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams,
5112                               ":" NETATALK_META_XATTR ":$DATA");
5113         if (!ok) {
5114                 return NT_STATUS_NO_MEMORY;
5115         }
5116
5117         /*
5118          * Check if there's a AFPINFO_STREAM from the VFS streams
5119          * backend and if yes, remove it from the list
5120          */
5121         for (i = 0; i < num_streams; i++) {
5122                 if (strequal_m(stream[i].name, AFPINFO_STREAM)) {
5123                         break;
5124                 }
5125         }
5126
5127         if (i < num_streams) {
5128                 DBG_WARNING("Unexpected AFPINFO_STREAM on [%s]\n",
5129                             smb_fname_str_dbg(smb_fname));
5130
5131                 ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams,
5132                                       AFPINFO_STREAM);
5133                 if (!ok) {
5134                         return NT_STATUS_INTERNAL_ERROR;
5135                 }
5136         }
5137
5138         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
5139         if (ad == NULL) {
5140                 return NT_STATUS_OK;
5141         }
5142
5143         is_fi_empty = ad_empty_finderinfo(ad);
5144         TALLOC_FREE(ad);
5145
5146         if (is_fi_empty) {
5147                 return NT_STATUS_OK;
5148         }
5149
5150         ok = add_fruit_stream(mem_ctx, pnum_streams, pstreams,
5151                               AFPINFO_STREAM_NAME, AFP_INFO_SIZE,
5152                               smb_roundup(handle->conn, AFP_INFO_SIZE));
5153         if (!ok) {
5154                 return NT_STATUS_NO_MEMORY;
5155         }
5156
5157         return NT_STATUS_OK;
5158 }
5159
5160 static NTSTATUS fruit_streaminfo_meta(vfs_handle_struct *handle,
5161                                       struct files_struct *fsp,
5162                                       const struct smb_filename *smb_fname,
5163                                       TALLOC_CTX *mem_ctx,
5164                                       unsigned int *pnum_streams,
5165                                       struct stream_struct **pstreams)
5166 {
5167         struct fruit_config_data *config = NULL;
5168         NTSTATUS status;
5169
5170         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
5171                                 return NT_STATUS_INTERNAL_ERROR);
5172
5173         switch (config->meta) {
5174         case FRUIT_META_NETATALK:
5175                 status = fruit_streaminfo_meta_netatalk(handle, fsp, smb_fname,
5176                                                         mem_ctx, pnum_streams,
5177                                                         pstreams);
5178                 break;
5179
5180         case FRUIT_META_STREAM:
5181                 status = fruit_streaminfo_meta_stream(handle, fsp, smb_fname,
5182                                                       mem_ctx, pnum_streams,
5183                                                       pstreams);
5184                 break;
5185
5186         default:
5187                 return NT_STATUS_INTERNAL_ERROR;
5188         }
5189
5190         return status;
5191 }
5192
5193 static NTSTATUS fruit_streaminfo_rsrc_stream(
5194         vfs_handle_struct *handle,
5195         struct files_struct *fsp,
5196         const struct smb_filename *smb_fname,
5197         TALLOC_CTX *mem_ctx,
5198         unsigned int *pnum_streams,
5199         struct stream_struct **pstreams)
5200 {
5201         bool ok;
5202
5203         ok = filter_empty_rsrc_stream(pnum_streams, pstreams);
5204         if (!ok) {
5205                 DBG_ERR("Filtering resource stream failed\n");
5206                 return NT_STATUS_INTERNAL_ERROR;
5207         }
5208         return NT_STATUS_OK;
5209 }
5210
5211 static NTSTATUS fruit_streaminfo_rsrc_xattr(
5212         vfs_handle_struct *handle,
5213         struct files_struct *fsp,
5214         const struct smb_filename *smb_fname,
5215         TALLOC_CTX *mem_ctx,
5216         unsigned int *pnum_streams,
5217         struct stream_struct **pstreams)
5218 {
5219         bool ok;
5220
5221         ok = filter_empty_rsrc_stream(pnum_streams, pstreams);
5222         if (!ok) {
5223                 DBG_ERR("Filtering resource stream failed\n");
5224                 return NT_STATUS_INTERNAL_ERROR;
5225         }
5226         return NT_STATUS_OK;
5227 }
5228
5229 static NTSTATUS fruit_streaminfo_rsrc_adouble(
5230         vfs_handle_struct *handle,
5231         struct files_struct *fsp,
5232         const struct smb_filename *smb_fname,
5233         TALLOC_CTX *mem_ctx,
5234         unsigned int *pnum_streams,
5235         struct stream_struct **pstreams)
5236 {
5237         struct stream_struct *stream = *pstreams;
5238         unsigned int num_streams = *pnum_streams;
5239         struct adouble *ad = NULL;
5240         bool ok;
5241         size_t rlen;
5242         int i;
5243
5244         /*
5245          * Check if there's a AFPRESOURCE_STREAM from the VFS streams backend
5246          * and if yes, remove it from the list
5247          */
5248         for (i = 0; i < num_streams; i++) {
5249                 if (strequal_m(stream[i].name, AFPRESOURCE_STREAM)) {
5250                         break;
5251                 }
5252         }
5253
5254         if (i < num_streams) {
5255                 DBG_WARNING("Unexpected AFPRESOURCE_STREAM on [%s]\n",
5256                             smb_fname_str_dbg(smb_fname));
5257
5258                 ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams,
5259                                       AFPRESOURCE_STREAM);
5260                 if (!ok) {
5261                         return NT_STATUS_INTERNAL_ERROR;
5262                 }
5263         }
5264
5265         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_RSRC);
5266         if (ad == NULL) {
5267                 return NT_STATUS_OK;
5268         }
5269
5270         rlen = ad_getentrylen(ad, ADEID_RFORK);
5271         TALLOC_FREE(ad);
5272
5273         if (rlen == 0) {
5274                 return NT_STATUS_OK;
5275         }
5276
5277         ok = add_fruit_stream(mem_ctx, pnum_streams, pstreams,
5278                               AFPRESOURCE_STREAM_NAME, rlen,
5279                               smb_roundup(handle->conn, rlen));
5280         if (!ok) {
5281                 return NT_STATUS_NO_MEMORY;
5282         }
5283
5284         return NT_STATUS_OK;
5285 }
5286
5287 static NTSTATUS fruit_streaminfo_rsrc(vfs_handle_struct *handle,
5288                                       struct files_struct *fsp,
5289                                       const struct smb_filename *smb_fname,
5290                                       TALLOC_CTX *mem_ctx,
5291                                       unsigned int *pnum_streams,
5292                                       struct stream_struct **pstreams)
5293 {
5294         struct fruit_config_data *config = NULL;
5295         NTSTATUS status;
5296
5297         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
5298                                 return NT_STATUS_INTERNAL_ERROR);
5299
5300         switch (config->rsrc) {
5301         case FRUIT_RSRC_STREAM:
5302                 status = fruit_streaminfo_rsrc_stream(handle, fsp, smb_fname,
5303                                                       mem_ctx, pnum_streams,
5304                                                       pstreams);
5305                 break;
5306
5307         case FRUIT_RSRC_XATTR:
5308                 status = fruit_streaminfo_rsrc_xattr(handle, fsp, smb_fname,
5309                                                      mem_ctx, pnum_streams,
5310                                                      pstreams);
5311                 break;
5312
5313         case FRUIT_RSRC_ADFILE:
5314                 status = fruit_streaminfo_rsrc_adouble(handle, fsp, smb_fname,
5315                                                        mem_ctx, pnum_streams,
5316                                                        pstreams);
5317                 break;
5318
5319         default:
5320                 return NT_STATUS_INTERNAL_ERROR;
5321         }
5322
5323         return status;
5324 }
5325
5326 static NTSTATUS fruit_streaminfo(vfs_handle_struct *handle,
5327                                  struct files_struct *fsp,
5328                                  const struct smb_filename *smb_fname,
5329                                  TALLOC_CTX *mem_ctx,
5330                                  unsigned int *pnum_streams,
5331                                  struct stream_struct **pstreams)
5332 {
5333         struct fruit_config_data *config = NULL;
5334         NTSTATUS status;
5335
5336         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
5337                                 return NT_STATUS_UNSUCCESSFUL);
5338
5339         DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
5340
5341         status = SMB_VFS_NEXT_STREAMINFO(handle, fsp, smb_fname, mem_ctx,
5342                                          pnum_streams, pstreams);
5343         if (!NT_STATUS_IS_OK(status)) {
5344                 return status;
5345         }
5346
5347         status = fruit_streaminfo_meta(handle, fsp, smb_fname,
5348                                        mem_ctx, pnum_streams, pstreams);
5349         if (!NT_STATUS_IS_OK(status)) {
5350                 return status;
5351         }
5352
5353         status = fruit_streaminfo_rsrc(handle, fsp, smb_fname,
5354                                        mem_ctx, pnum_streams, pstreams);
5355         if (!NT_STATUS_IS_OK(status)) {
5356                 return status;
5357         }
5358
5359         return NT_STATUS_OK;
5360 }
5361
5362 static int fruit_ntimes(vfs_handle_struct *handle,
5363                         const struct smb_filename *smb_fname,
5364                         struct smb_file_time *ft)
5365 {
5366         int rc = 0;
5367         struct adouble *ad = NULL;
5368         struct fruit_config_data *config = NULL;
5369
5370         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
5371                                 return -1);
5372
5373         if ((config->meta != FRUIT_META_NETATALK) ||
5374             null_timespec(ft->create_time))
5375         {
5376                 return SMB_VFS_NEXT_NTIMES(handle, smb_fname, ft);
5377         }
5378
5379         DEBUG(10,("set btime for %s to %s\n", smb_fname_str_dbg(smb_fname),
5380                  time_to_asc(convert_timespec_to_time_t(ft->create_time))));
5381
5382         ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
5383         if (ad == NULL) {
5384                 goto exit;
5385         }
5386
5387         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX,
5388                    convert_time_t_to_uint32_t(ft->create_time.tv_sec));
5389
5390         rc = ad_set(ad, smb_fname);
5391
5392 exit:
5393
5394         TALLOC_FREE(ad);
5395         if (rc != 0) {
5396                 DEBUG(1, ("fruit_ntimes: %s\n", smb_fname_str_dbg(smb_fname)));
5397                 return -1;
5398         }
5399         return SMB_VFS_NEXT_NTIMES(handle, smb_fname, ft);
5400 }
5401
5402 static int fruit_fallocate(struct vfs_handle_struct *handle,
5403                            struct files_struct *fsp,
5404                            uint32_t mode,
5405                            off_t offset,
5406                            off_t len)
5407 {
5408         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
5409
5410         if (fio == NULL) {
5411                 return SMB_VFS_NEXT_FALLOCATE(handle, fsp, mode, offset, len);
5412         }
5413
5414         /* Let the pwrite code path handle it. */
5415         errno = ENOSYS;
5416         return -1;
5417 }
5418
5419 static int fruit_ftruncate_rsrc_xattr(struct vfs_handle_struct *handle,
5420                                       struct files_struct *fsp,
5421                                       off_t offset)
5422 {
5423         if (offset == 0) {
5424                 return SMB_VFS_FREMOVEXATTR(fsp, AFPRESOURCE_EA_NETATALK);
5425         }
5426
5427 #ifdef HAVE_ATTROPEN
5428         return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
5429 #endif
5430         return 0;
5431 }
5432
5433 static int fruit_ftruncate_rsrc_adouble(struct vfs_handle_struct *handle,
5434                                         struct files_struct *fsp,
5435                                         off_t offset)
5436 {
5437         int rc;
5438         struct adouble *ad = NULL;
5439         off_t ad_off;
5440
5441         ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_RSRC);
5442         if (ad == NULL) {
5443                 DBG_DEBUG("ad_get [%s] failed [%s]\n",
5444                           fsp_str_dbg(fsp), strerror(errno));
5445                 return -1;
5446         }
5447
5448         ad_off = ad_getentryoff(ad, ADEID_RFORK);
5449
5450         rc = ftruncate(fsp->fh->fd, offset + ad_off);
5451         if (rc != 0) {
5452                 TALLOC_FREE(ad);
5453                 return -1;
5454         }
5455
5456         ad_setentrylen(ad, ADEID_RFORK, offset);
5457
5458         rc = ad_fset(ad, fsp);
5459         if (rc != 0) {
5460                 DBG_ERR("ad_fset [%s] failed [%s]\n",
5461                         fsp_str_dbg(fsp), strerror(errno));
5462                 TALLOC_FREE(ad);
5463                 return -1;
5464         }
5465
5466         TALLOC_FREE(ad);
5467         return 0;
5468 }
5469
5470 static int fruit_ftruncate_rsrc_stream(struct vfs_handle_struct *handle,
5471                                        struct files_struct *fsp,
5472                                        off_t offset)
5473 {
5474         if (offset == 0) {
5475                 return SMB_VFS_NEXT_UNLINK(handle, fsp->fsp_name);
5476         }
5477
5478         return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
5479 }
5480
5481 static int fruit_ftruncate_rsrc(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         switch (fio->config->rsrc) {
5489         case FRUIT_RSRC_XATTR:
5490                 ret = fruit_ftruncate_rsrc_xattr(handle, fsp, offset);
5491                 break;
5492
5493         case FRUIT_RSRC_ADFILE:
5494                 ret = fruit_ftruncate_rsrc_adouble(handle, fsp, offset);
5495                 break;
5496
5497         case FRUIT_RSRC_STREAM:
5498                 ret = fruit_ftruncate_rsrc_stream(handle, fsp, offset);
5499                 break;
5500
5501         default:
5502                 DBG_ERR("Unexpected rsrc config [%d]\n", fio->config->rsrc);
5503                 return -1;
5504         }
5505
5506
5507         return ret;
5508 }
5509
5510 static int fruit_ftruncate_meta(struct vfs_handle_struct *handle,
5511                                 struct files_struct *fsp,
5512                                 off_t offset)
5513 {
5514         if (offset > 60) {
5515                 DBG_WARNING("ftruncate %s to %jd",
5516                             fsp_str_dbg(fsp), (intmax_t)offset);
5517                 /* OS X returns NT_STATUS_ALLOTTED_SPACE_EXCEEDED  */
5518                 errno = EOVERFLOW;
5519                 return -1;
5520         }
5521
5522         /* OS X returns success but does nothing  */
5523         DBG_INFO("ignoring ftruncate %s to %jd\n",
5524                  fsp_str_dbg(fsp), (intmax_t)offset);
5525         return 0;
5526 }
5527
5528 static int fruit_ftruncate(struct vfs_handle_struct *handle,
5529                            struct files_struct *fsp,
5530                            off_t offset)
5531 {
5532         struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
5533         int ret;
5534
5535         DBG_DEBUG("Path [%s] offset [%"PRIdMAX"]\n", fsp_str_dbg(fsp),
5536                   (intmax_t)offset);
5537
5538         if (fio == NULL) {
5539                 return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
5540         }
5541
5542         if (fio->type == ADOUBLE_META) {
5543                 ret = fruit_ftruncate_meta(handle, fsp, offset);
5544         } else {
5545                 ret = fruit_ftruncate_rsrc(handle, fsp, offset);
5546         }
5547
5548         DBG_DEBUG("Path [%s] result [%d]\n", fsp_str_dbg(fsp), ret);
5549         return ret;
5550 }
5551
5552 static NTSTATUS fruit_create_file(vfs_handle_struct *handle,
5553                                   struct smb_request *req,
5554                                   uint16_t root_dir_fid,
5555                                   struct smb_filename *smb_fname,
5556                                   uint32_t access_mask,
5557                                   uint32_t share_access,
5558                                   uint32_t create_disposition,
5559                                   uint32_t create_options,
5560                                   uint32_t file_attributes,
5561                                   uint32_t oplock_request,
5562                                   struct smb2_lease *lease,
5563                                   uint64_t allocation_size,
5564                                   uint32_t private_flags,
5565                                   struct security_descriptor *sd,
5566                                   struct ea_list *ea_list,
5567                                   files_struct **result,
5568                                   int *pinfo,
5569                                   const struct smb2_create_blobs *in_context_blobs,
5570                                   struct smb2_create_blobs *out_context_blobs)
5571 {
5572         NTSTATUS status;
5573         struct fruit_config_data *config = NULL;
5574         files_struct *fsp = NULL;
5575
5576         status = check_aapl(handle, req, in_context_blobs, out_context_blobs);
5577         if (!NT_STATUS_IS_OK(status)) {
5578                 goto fail;
5579         }
5580
5581         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
5582                                 return NT_STATUS_UNSUCCESSFUL);
5583
5584         status = SMB_VFS_NEXT_CREATE_FILE(
5585                 handle, req, root_dir_fid, smb_fname,
5586                 access_mask, share_access,
5587                 create_disposition, create_options,
5588                 file_attributes, oplock_request,
5589                 lease,
5590                 allocation_size, private_flags,
5591                 sd, ea_list, result,
5592                 pinfo, in_context_blobs, out_context_blobs);
5593         if (!NT_STATUS_IS_OK(status)) {
5594                 return status;
5595         }
5596
5597         fsp = *result;
5598
5599         if (global_fruit_config.nego_aapl) {
5600                 if (config->posix_rename && fsp->is_directory) {
5601                         /*
5602                          * Enable POSIX directory rename behaviour
5603                          */
5604                         fsp->posix_flags |= FSP_POSIX_FLAGS_RENAME;
5605                 }
5606         }
5607
5608         /*
5609          * If this is a plain open for existing files, opening an 0
5610          * byte size resource fork MUST fail with
5611          * NT_STATUS_OBJECT_NAME_NOT_FOUND.
5612          *
5613          * Cf the vfs_fruit torture tests in test_rfork_create().
5614          */
5615         if (is_afpresource_stream(fsp->fsp_name) &&
5616             create_disposition == FILE_OPEN)
5617         {
5618                 if (fsp->fsp_name->st.st_ex_size == 0) {
5619                         status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5620                         goto fail;
5621                 }
5622         }
5623
5624         if (is_ntfs_stream_smb_fname(smb_fname)
5625             || fsp->is_directory) {
5626                 return status;
5627         }
5628
5629         if (config->locking == FRUIT_LOCKING_NETATALK) {
5630                 status = fruit_check_access(
5631                         handle, *result,
5632                         access_mask,
5633                         map_share_mode_to_deny_mode(share_access, 0));
5634                 if (!NT_STATUS_IS_OK(status)) {
5635                         goto fail;
5636                 }
5637         }
5638
5639         return status;
5640
5641 fail:
5642         DEBUG(10, ("fruit_create_file: %s\n", nt_errstr(status)));
5643
5644         if (fsp) {
5645                 close_file(req, fsp, ERROR_CLOSE);
5646                 *result = fsp = NULL;
5647         }
5648
5649         return status;
5650 }
5651
5652 static NTSTATUS fruit_readdir_attr(struct vfs_handle_struct *handle,
5653                                    const struct smb_filename *fname,
5654                                    TALLOC_CTX *mem_ctx,
5655                                    struct readdir_attr_data **pattr_data)
5656 {
5657         struct fruit_config_data *config = NULL;
5658         struct readdir_attr_data *attr_data;
5659         NTSTATUS status;
5660
5661         SMB_VFS_HANDLE_GET_DATA(handle, config,
5662                                 struct fruit_config_data,
5663                                 return NT_STATUS_UNSUCCESSFUL);
5664
5665         if (!global_fruit_config.nego_aapl) {
5666                 return SMB_VFS_NEXT_READDIR_ATTR(handle, fname, mem_ctx, pattr_data);
5667         }
5668
5669         DEBUG(10, ("fruit_readdir_attr %s\n", fname->base_name));
5670
5671         *pattr_data = talloc_zero(mem_ctx, struct readdir_attr_data);
5672         if (*pattr_data == NULL) {
5673                 return NT_STATUS_UNSUCCESSFUL;
5674         }
5675         attr_data = *pattr_data;
5676         attr_data->type = RDATTR_AAPL;
5677
5678         /*
5679          * Mac metadata: compressed FinderInfo, resource fork length
5680          * and creation date
5681          */
5682         status = readdir_attr_macmeta(handle, fname, attr_data);
5683         if (!NT_STATUS_IS_OK(status)) {
5684                 /*
5685                  * Error handling is tricky: if we return failure from
5686                  * this function, the corresponding directory entry
5687                  * will to be passed to the client, so we really just
5688                  * want to error out on fatal errors.
5689                  */
5690                 if  (!NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
5691                         goto fail;
5692                 }
5693         }
5694
5695         /*
5696          * UNIX mode
5697          */
5698         if (config->unix_info_enabled) {
5699                 attr_data->attr_data.aapl.unix_mode = fname->st.st_ex_mode;
5700         }
5701
5702         /*
5703          * max_access
5704          */
5705         if (!config->readdir_attr_max_access) {
5706                 attr_data->attr_data.aapl.max_access = FILE_GENERIC_ALL;
5707         } else {
5708                 status = smbd_calculate_access_mask(
5709                         handle->conn,
5710                         fname,
5711                         false,
5712                         SEC_FLAG_MAXIMUM_ALLOWED,
5713                         &attr_data->attr_data.aapl.max_access);
5714                 if (!NT_STATUS_IS_OK(status)) {
5715                         goto fail;
5716                 }
5717         }
5718
5719         return NT_STATUS_OK;
5720
5721 fail:
5722         DEBUG(1, ("fruit_readdir_attr %s, error: %s\n",
5723                   fname->base_name, nt_errstr(status)));
5724         TALLOC_FREE(*pattr_data);
5725         return status;
5726 }
5727
5728 static NTSTATUS fruit_fget_nt_acl(vfs_handle_struct *handle,
5729                                   files_struct *fsp,
5730                                   uint32_t security_info,
5731                                   TALLOC_CTX *mem_ctx,
5732                                   struct security_descriptor **ppdesc)
5733 {
5734         NTSTATUS status;
5735         struct security_ace ace;
5736         struct dom_sid sid;
5737         struct fruit_config_data *config;
5738         bool remove_ok = false;
5739
5740         SMB_VFS_HANDLE_GET_DATA(handle, config,
5741                                 struct fruit_config_data,
5742                                 return NT_STATUS_UNSUCCESSFUL);
5743
5744         status = SMB_VFS_NEXT_FGET_NT_ACL(handle, fsp, security_info,
5745                                           mem_ctx, ppdesc);
5746         if (!NT_STATUS_IS_OK(status)) {
5747                 return status;
5748         }
5749
5750         /*
5751          * Add MS NFS style ACEs with uid, gid and mode
5752          */
5753         if (!global_fruit_config.nego_aapl) {
5754                 return NT_STATUS_OK;
5755         }
5756         if (!config->unix_info_enabled) {
5757                 return NT_STATUS_OK;
5758         }
5759
5760         /* MS NFS style mode */
5761         sid_compose(&sid, &global_sid_Unix_NFS_Mode, fsp->fsp_name->st.st_ex_mode);
5762         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
5763
5764         /* First remove any existing ACE's with this SID. */
5765         status = security_descriptor_dacl_del(*ppdesc, &sid);
5766         remove_ok = (NT_STATUS_IS_OK(status) ||
5767                      NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND));
5768         if (!remove_ok) {
5769                 DBG_WARNING("failed to remove MS NFS_mode style ACE\n");
5770                 return status;
5771         }
5772         status = security_descriptor_dacl_add(*ppdesc, &ace);
5773         if (!NT_STATUS_IS_OK(status)) {
5774                 DEBUG(1,("failed to add MS NFS style ACE\n"));
5775                 return status;
5776         }
5777
5778         /* MS NFS style uid */
5779         sid_compose(&sid, &global_sid_Unix_NFS_Users, fsp->fsp_name->st.st_ex_uid);
5780         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
5781
5782         /* First remove any existing ACE's with this SID. */
5783         status = security_descriptor_dacl_del(*ppdesc, &sid);
5784         remove_ok = (NT_STATUS_IS_OK(status) ||
5785                      NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND));
5786         if (!remove_ok) {
5787                 DBG_WARNING("failed to remove MS NFS_users style ACE\n");
5788                 return status;
5789         }
5790         status = security_descriptor_dacl_add(*ppdesc, &ace);
5791         if (!NT_STATUS_IS_OK(status)) {
5792                 DEBUG(1,("failed to add MS NFS style ACE\n"));
5793                 return status;
5794         }
5795
5796         /* MS NFS style gid */
5797         sid_compose(&sid, &global_sid_Unix_NFS_Groups, fsp->fsp_name->st.st_ex_gid);
5798         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
5799
5800         /* First remove any existing ACE's with this SID. */
5801         status = security_descriptor_dacl_del(*ppdesc, &sid);
5802         remove_ok = (NT_STATUS_IS_OK(status) ||
5803                      NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND));
5804         if (!remove_ok) {
5805                 DBG_WARNING("failed to remove MS NFS_groups style ACE\n");
5806                 return status;
5807         }
5808         status = security_descriptor_dacl_add(*ppdesc, &ace);
5809         if (!NT_STATUS_IS_OK(status)) {
5810                 DEBUG(1,("failed to add MS NFS style ACE\n"));
5811                 return status;
5812         }
5813
5814         return NT_STATUS_OK;
5815 }
5816
5817 static NTSTATUS fruit_fset_nt_acl(vfs_handle_struct *handle,
5818                                   files_struct *fsp,
5819                                   uint32_t security_info_sent,
5820                                   const struct security_descriptor *orig_psd)
5821 {
5822         NTSTATUS status;
5823         bool do_chmod;
5824         mode_t ms_nfs_mode = 0;
5825         int result;
5826         struct security_descriptor *psd = NULL;
5827         uint32_t orig_num_aces = 0;
5828
5829         if (orig_psd->dacl != NULL) {
5830                 orig_num_aces = orig_psd->dacl->num_aces;
5831         }
5832
5833         psd = security_descriptor_copy(talloc_tos(), orig_psd);
5834         if (psd == NULL) {
5835                 return NT_STATUS_NO_MEMORY;
5836         }
5837
5838         DBG_DEBUG("fruit_fset_nt_acl: %s\n", fsp_str_dbg(fsp));
5839
5840         status = check_ms_nfs(handle, fsp, psd, &ms_nfs_mode, &do_chmod);
5841         if (!NT_STATUS_IS_OK(status)) {
5842                 DEBUG(1, ("fruit_fset_nt_acl: check_ms_nfs failed%s\n", fsp_str_dbg(fsp)));
5843                 TALLOC_FREE(psd);
5844                 return status;
5845         }
5846
5847         /*
5848          * If only ms_nfs ACE entries were sent, ensure we set the DACL
5849          * sent/present flags correctly now we've removed them.
5850          */
5851
5852         if (orig_num_aces != 0) {
5853                 /*
5854                  * Are there any ACE's left ?
5855                  */
5856                 if (psd->dacl->num_aces == 0) {
5857                         /* No - clear the DACL sent/present flags. */
5858                         security_info_sent &= ~SECINFO_DACL;
5859                         psd->type &= ~SEC_DESC_DACL_PRESENT;
5860                 }
5861         }
5862
5863         status = SMB_VFS_NEXT_FSET_NT_ACL(handle, fsp, security_info_sent, psd);
5864         if (!NT_STATUS_IS_OK(status)) {
5865                 DEBUG(1, ("fruit_fset_nt_acl: SMB_VFS_NEXT_FSET_NT_ACL failed%s\n", fsp_str_dbg(fsp)));
5866                 TALLOC_FREE(psd);
5867                 return status;
5868         }
5869
5870         if (do_chmod) {
5871                 if (fsp->fh->fd != -1) {
5872                         result = SMB_VFS_FCHMOD(fsp, ms_nfs_mode);
5873                 } else {
5874                         result = SMB_VFS_CHMOD(fsp->conn,
5875                                                fsp->fsp_name,
5876                                                ms_nfs_mode);
5877                 }
5878
5879                 if (result != 0) {
5880                         DEBUG(1, ("chmod: %s, result: %d, %04o error %s\n", fsp_str_dbg(fsp),
5881                                   result, (unsigned)ms_nfs_mode,
5882                                   strerror(errno)));
5883                         status = map_nt_error_from_unix(errno);
5884                         TALLOC_FREE(psd);
5885                         return status;
5886                 }
5887         }
5888
5889         TALLOC_FREE(psd);
5890         return NT_STATUS_OK;
5891 }
5892
5893 static struct vfs_offload_ctx *fruit_offload_ctx;
5894
5895 struct fruit_offload_read_state {
5896         struct vfs_handle_struct *handle;
5897         struct tevent_context *ev;
5898         files_struct *fsp;
5899         uint32_t fsctl;
5900         DATA_BLOB token;
5901 };
5902
5903 static void fruit_offload_read_done(struct tevent_req *subreq);
5904
5905 static struct tevent_req *fruit_offload_read_send(
5906         TALLOC_CTX *mem_ctx,
5907         struct tevent_context *ev,
5908         struct vfs_handle_struct *handle,
5909         files_struct *fsp,
5910         uint32_t fsctl,
5911         uint32_t ttl,
5912         off_t offset,
5913         size_t to_copy)
5914 {
5915         struct tevent_req *req = NULL;
5916         struct tevent_req *subreq = NULL;
5917         struct fruit_offload_read_state *state = NULL;
5918
5919         req = tevent_req_create(mem_ctx, &state,
5920                                 struct fruit_offload_read_state);
5921         if (req == NULL) {
5922                 return NULL;
5923         }
5924         *state = (struct fruit_offload_read_state) {
5925                 .handle = handle,
5926                 .ev = ev,
5927                 .fsp = fsp,
5928                 .fsctl = fsctl,
5929         };
5930
5931         subreq = SMB_VFS_NEXT_OFFLOAD_READ_SEND(mem_ctx, ev, handle, fsp,
5932                                                 fsctl, ttl, offset, to_copy);
5933         if (tevent_req_nomem(subreq, req)) {
5934                 return tevent_req_post(req, ev);
5935         }
5936         tevent_req_set_callback(subreq, fruit_offload_read_done, req);
5937         return req;
5938 }
5939
5940 static void fruit_offload_read_done(struct tevent_req *subreq)
5941 {
5942         struct tevent_req *req = tevent_req_callback_data(
5943                 subreq, struct tevent_req);
5944         struct fruit_offload_read_state *state = tevent_req_data(
5945                 req, struct fruit_offload_read_state);
5946         NTSTATUS status;
5947
5948         status = SMB_VFS_NEXT_OFFLOAD_READ_RECV(subreq,
5949                                                 state->handle,
5950                                                 state,
5951                                                 &state->token);
5952         TALLOC_FREE(subreq);
5953         if (tevent_req_nterror(req, status)) {
5954                 return;
5955         }
5956
5957         if (state->fsctl != FSCTL_SRV_REQUEST_RESUME_KEY) {
5958                 tevent_req_done(req);
5959                 return;
5960         }
5961
5962         status = vfs_offload_token_ctx_init(state->fsp->conn->sconn->client,
5963                                             &fruit_offload_ctx);
5964         if (tevent_req_nterror(req, status)) {
5965                 return;
5966         }
5967
5968         status = vfs_offload_token_db_store_fsp(fruit_offload_ctx,
5969                                                 state->fsp,
5970                                                 &state->token);
5971         if (tevent_req_nterror(req, status)) {
5972                 return;
5973         }
5974
5975         tevent_req_done(req);
5976         return;
5977 }
5978
5979 static NTSTATUS fruit_offload_read_recv(struct tevent_req *req,
5980                                         struct vfs_handle_struct *handle,
5981                                         TALLOC_CTX *mem_ctx,
5982                                         DATA_BLOB *token)
5983 {
5984         struct fruit_offload_read_state *state = tevent_req_data(
5985                 req, struct fruit_offload_read_state);
5986         NTSTATUS status;
5987
5988         if (tevent_req_is_nterror(req, &status)) {
5989                 tevent_req_received(req);
5990                 return status;
5991         }
5992
5993         token->length = state->token.length;
5994         token->data = talloc_move(mem_ctx, &state->token.data);
5995
5996         tevent_req_received(req);
5997         return NT_STATUS_OK;
5998 }
5999
6000 struct fruit_offload_write_state {
6001         struct vfs_handle_struct *handle;
6002         off_t copied;
6003         struct files_struct *src_fsp;
6004         struct files_struct *dst_fsp;
6005         bool is_copyfile;
6006 };
6007
6008 static void fruit_offload_write_done(struct tevent_req *subreq);
6009 static struct tevent_req *fruit_offload_write_send(struct vfs_handle_struct *handle,
6010                                                 TALLOC_CTX *mem_ctx,
6011                                                 struct tevent_context *ev,
6012                                                 uint32_t fsctl,
6013                                                 DATA_BLOB *token,
6014                                                 off_t transfer_offset,
6015                                                 struct files_struct *dest_fsp,
6016                                                 off_t dest_off,
6017                                                 off_t num)
6018 {
6019         struct tevent_req *req, *subreq;
6020         struct fruit_offload_write_state *state;
6021         NTSTATUS status;
6022         struct fruit_config_data *config;
6023         off_t src_off = transfer_offset;
6024         files_struct *src_fsp = NULL;
6025         off_t to_copy = num;
6026         bool copyfile_enabled = false;
6027
6028         DEBUG(10,("soff: %ju, doff: %ju, len: %ju\n",
6029                   (uintmax_t)src_off, (uintmax_t)dest_off, (uintmax_t)num));
6030
6031         SMB_VFS_HANDLE_GET_DATA(handle, config,
6032                                 struct fruit_config_data,
6033                                 return NULL);
6034
6035         req = tevent_req_create(mem_ctx, &state,
6036                                 struct fruit_offload_write_state);
6037         if (req == NULL) {
6038                 return NULL;
6039         }
6040         state->handle = handle;
6041         state->dst_fsp = dest_fsp;
6042
6043         switch (fsctl) {
6044         case FSCTL_SRV_COPYCHUNK:
6045         case FSCTL_SRV_COPYCHUNK_WRITE:
6046                 copyfile_enabled = config->copyfile_enabled;
6047                 break;
6048         default:
6049                 break;
6050         }
6051
6052         /*
6053          * Check if this a OS X copyfile style copychunk request with
6054          * a requested chunk count of 0 that was translated to a
6055          * offload_write_send VFS call overloading the parameters src_off
6056          * = dest_off = num = 0.
6057          */
6058         if (copyfile_enabled && num == 0 && src_off == 0 && dest_off == 0) {
6059                 status = vfs_offload_token_db_fetch_fsp(
6060                         fruit_offload_ctx, token, &src_fsp);
6061                 if (tevent_req_nterror(req, status)) {
6062                         return tevent_req_post(req, ev);
6063                 }
6064                 state->src_fsp = src_fsp;
6065
6066                 status = vfs_stat_fsp(src_fsp);
6067                 if (tevent_req_nterror(req, status)) {
6068                         return tevent_req_post(req, ev);
6069                 }
6070
6071                 to_copy = src_fsp->fsp_name->st.st_ex_size;
6072                 state->is_copyfile = true;
6073         }
6074
6075         subreq = SMB_VFS_NEXT_OFFLOAD_WRITE_SEND(handle,
6076                                               mem_ctx,
6077                                               ev,
6078                                               fsctl,
6079                                               token,
6080                                               transfer_offset,
6081                                               dest_fsp,
6082                                               dest_off,
6083                                               to_copy);
6084         if (tevent_req_nomem(subreq, req)) {
6085                 return tevent_req_post(req, ev);
6086         }
6087
6088         tevent_req_set_callback(subreq, fruit_offload_write_done, req);
6089         return req;
6090 }
6091
6092 static void fruit_offload_write_done(struct tevent_req *subreq)
6093 {
6094         struct tevent_req *req = tevent_req_callback_data(
6095                 subreq, struct tevent_req);
6096         struct fruit_offload_write_state *state = tevent_req_data(
6097                 req, struct fruit_offload_write_state);
6098         NTSTATUS status;
6099         unsigned int num_streams = 0;
6100         struct stream_struct *streams = NULL;
6101         unsigned int i;
6102         struct smb_filename *src_fname_tmp = NULL;
6103         struct smb_filename *dst_fname_tmp = NULL;
6104
6105         status = SMB_VFS_NEXT_OFFLOAD_WRITE_RECV(state->handle,
6106                                               subreq,
6107                                               &state->copied);
6108         TALLOC_FREE(subreq);
6109         if (tevent_req_nterror(req, status)) {
6110                 return;
6111         }
6112
6113         if (!state->is_copyfile) {
6114                 tevent_req_done(req);
6115                 return;
6116         }
6117
6118         /*
6119          * Now copy all remaining streams. We know the share supports
6120          * streams, because we're in vfs_fruit. We don't do this async
6121          * because streams are few and small.
6122          */
6123         status = vfs_streaminfo(state->handle->conn, state->src_fsp,
6124                                 state->src_fsp->fsp_name,
6125                                 req, &num_streams, &streams);
6126         if (tevent_req_nterror(req, status)) {
6127                 return;
6128         }
6129
6130         if (num_streams == 1) {
6131                 /* There is always one stream, ::$DATA. */
6132                 tevent_req_done(req);
6133                 return;
6134         }
6135
6136         for (i = 0; i < num_streams; i++) {
6137                 DEBUG(10, ("%s: stream: '%s'/%zu\n",
6138                           __func__, streams[i].name, (size_t)streams[i].size));
6139
6140                 src_fname_tmp = synthetic_smb_fname(
6141                         req,
6142                         state->src_fsp->fsp_name->base_name,
6143                         streams[i].name,
6144                         NULL,
6145                         state->src_fsp->fsp_name->flags);
6146                 if (tevent_req_nomem(src_fname_tmp, req)) {
6147                         return;
6148                 }
6149
6150                 if (is_ntfs_default_stream_smb_fname(src_fname_tmp)) {
6151                         TALLOC_FREE(src_fname_tmp);
6152                         continue;
6153                 }
6154
6155                 dst_fname_tmp = synthetic_smb_fname(
6156                         req,
6157                         state->dst_fsp->fsp_name->base_name,
6158                         streams[i].name,
6159                         NULL,
6160                         state->dst_fsp->fsp_name->flags);
6161                 if (tevent_req_nomem(dst_fname_tmp, req)) {
6162                         TALLOC_FREE(src_fname_tmp);
6163                         return;
6164                 }
6165
6166                 status = copy_file(req,
6167                                    state->handle->conn,
6168                                    src_fname_tmp,
6169                                    dst_fname_tmp,
6170                                    OPENX_FILE_CREATE_IF_NOT_EXIST,
6171                                    0, false);
6172                 if (!NT_STATUS_IS_OK(status)) {
6173                         DEBUG(1, ("%s: copy %s to %s failed: %s\n", __func__,
6174                                   smb_fname_str_dbg(src_fname_tmp),
6175                                   smb_fname_str_dbg(dst_fname_tmp),
6176                                   nt_errstr(status)));
6177                         TALLOC_FREE(src_fname_tmp);
6178                         TALLOC_FREE(dst_fname_tmp);
6179                         tevent_req_nterror(req, status);
6180                         return;
6181                 }
6182
6183                 TALLOC_FREE(src_fname_tmp);
6184                 TALLOC_FREE(dst_fname_tmp);
6185         }
6186
6187         TALLOC_FREE(streams);
6188         TALLOC_FREE(src_fname_tmp);
6189         TALLOC_FREE(dst_fname_tmp);
6190         tevent_req_done(req);
6191 }
6192
6193 static NTSTATUS fruit_offload_write_recv(struct vfs_handle_struct *handle,
6194                                       struct tevent_req *req,
6195                                       off_t *copied)
6196 {
6197         struct fruit_offload_write_state *state = tevent_req_data(
6198                 req, struct fruit_offload_write_state);
6199         NTSTATUS status;
6200
6201         if (tevent_req_is_nterror(req, &status)) {
6202                 DEBUG(1, ("server side copy chunk failed: %s\n",
6203                           nt_errstr(status)));
6204                 *copied = 0;
6205                 tevent_req_received(req);
6206                 return status;
6207         }
6208
6209         *copied = state->copied;
6210         tevent_req_received(req);
6211
6212         return NT_STATUS_OK;
6213 }
6214
6215 static char *fruit_get_bandsize_line(char **lines, int numlines)
6216 {
6217         static regex_t re;
6218         static bool re_initialized = false;
6219         int i;
6220         int ret;
6221
6222         if (!re_initialized) {
6223                 ret = regcomp(&re, "^[[:blank:]]*<key>band-size</key>$", 0);
6224                 if (ret != 0) {
6225                         return NULL;
6226                 }
6227                 re_initialized = true;
6228         }
6229
6230         for (i = 0; i < numlines; i++) {
6231                 regmatch_t matches[1];
6232
6233                 ret = regexec(&re, lines[i], 1, matches, 0);
6234                 if (ret == 0) {
6235                         /*
6236                          * Check if the match was on the last line, sa we want
6237                          * the subsequent line.
6238                          */
6239                         if (i + 1 == numlines) {
6240                                 return NULL;
6241                         }
6242                         return lines[i + 1];
6243                 }
6244                 if (ret != REG_NOMATCH) {
6245                         return NULL;
6246                 }
6247         }
6248
6249         return NULL;
6250 }
6251
6252 static bool fruit_get_bandsize_from_line(char *line, size_t *_band_size)
6253 {
6254         static regex_t re;
6255         static bool re_initialized = false;
6256         regmatch_t matches[2];
6257         uint64_t band_size;
6258         int ret;
6259         bool ok;
6260
6261         if (!re_initialized) {
6262                 ret = regcomp(&re,
6263                               "^[[:blank:]]*"
6264                               "<integer>\\([[:digit:]]*\\)</integer>$",
6265                               0);
6266                 if (ret != 0) {
6267                         return false;
6268                 }
6269                 re_initialized = true;
6270         }
6271
6272         ret = regexec(&re, line, 2, matches, 0);
6273         if (ret != 0) {
6274                 DBG_ERR("regex failed [%s]\n", line);
6275                 return false;
6276         }
6277
6278         line[matches[1].rm_eo] = '\0';
6279
6280         ok = conv_str_u64(&line[matches[1].rm_so], &band_size);
6281         if (!ok) {
6282                 return false;
6283         }
6284         *_band_size = (size_t)band_size;
6285         return true;
6286 }
6287
6288 /*
6289  * This reads and parses an Info.plist from a TM sparsebundle looking for the
6290  * "band-size" key and value.
6291  */
6292 static bool fruit_get_bandsize(vfs_handle_struct *handle,
6293                                const char *dir,
6294                                size_t *band_size)
6295 {
6296 #define INFO_PLIST_MAX_SIZE 64*1024
6297         char *plist = NULL;
6298         struct smb_filename *smb_fname = NULL;
6299         files_struct *fsp = NULL;
6300         uint8_t *file_data = NULL;
6301         char **lines = NULL;
6302         char *band_size_line = NULL;
6303         size_t plist_file_size;
6304         ssize_t nread;
6305         int numlines;
6306         int ret;
6307         bool ok = false;
6308         NTSTATUS status;
6309
6310         plist = talloc_asprintf(talloc_tos(),
6311                                 "%s/%s/Info.plist",
6312                                 handle->conn->connectpath,
6313                                 dir);
6314         if (plist == NULL) {
6315                 ok = false;
6316                 goto out;
6317         }
6318
6319         smb_fname = synthetic_smb_fname(talloc_tos(), plist, NULL, NULL, 0);
6320         if (smb_fname == NULL) {
6321                 ok = false;
6322                 goto out;
6323         }
6324
6325         ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
6326         if (ret != 0) {
6327                 DBG_INFO("Ignoring Sparsebundle without Info.plist [%s]\n", dir);
6328                 ok = true;
6329                 goto out;
6330         }
6331
6332         plist_file_size = smb_fname->st.st_ex_size;
6333
6334         if (plist_file_size > INFO_PLIST_MAX_SIZE) {
6335                 DBG_INFO("%s is too large, ignoring\n", plist);
6336                 ok = true;
6337                 goto out;
6338         }
6339
6340         status = SMB_VFS_NEXT_CREATE_FILE(
6341                 handle,                         /* conn */
6342                 NULL,                           /* req */
6343                 0,                              /* root_dir_fid */
6344                 smb_fname,                      /* fname */
6345                 FILE_GENERIC_READ,              /* access_mask */
6346                 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share_access */
6347                 FILE_OPEN,                      /* create_disposition */
6348                 0,                              /* create_options */
6349                 0,                              /* file_attributes */
6350                 INTERNAL_OPEN_ONLY,             /* oplock_request */
6351                 NULL,                           /* lease */
6352                 0,                              /* allocation_size */
6353                 0,                              /* private_flags */
6354                 NULL,                           /* sd */
6355                 NULL,                           /* ea_list */
6356                 &fsp,                           /* result */
6357                 NULL,                           /* psbuf */
6358                 NULL, NULL);                    /* create context */
6359         if (!NT_STATUS_IS_OK(status)) {
6360                 DBG_INFO("Opening [%s] failed [%s]\n",
6361                          smb_fname_str_dbg(smb_fname), nt_errstr(status));
6362                 ok = false;
6363                 goto out;
6364         }
6365
6366         file_data = talloc_array(talloc_tos(), uint8_t, plist_file_size);
6367         if (file_data == NULL) {
6368                 ok = false;
6369                 goto out;
6370         }
6371
6372         nread = SMB_VFS_NEXT_PREAD(handle, fsp, file_data, plist_file_size, 0);
6373         if (nread != plist_file_size) {
6374                 DBG_ERR("Short read on [%s]: %zu/%zd\n",
6375                         fsp_str_dbg(fsp), nread, plist_file_size);
6376                 ok = false;
6377                 goto out;
6378
6379         }
6380
6381         status = close_file(NULL, fsp, NORMAL_CLOSE);
6382         fsp = NULL;
6383         if (!NT_STATUS_IS_OK(status)) {
6384                 DBG_ERR("close_file failed: %s\n", nt_errstr(status));
6385                 ok = false;
6386                 goto out;
6387         }
6388
6389         lines = file_lines_parse((char *)file_data,
6390                                  plist_file_size,
6391                                  &numlines,
6392                                  talloc_tos());
6393         if (lines == NULL) {
6394                 ok = false;
6395                 goto out;
6396         }
6397
6398         band_size_line = fruit_get_bandsize_line(lines, numlines);
6399         if (band_size_line == NULL) {
6400                 DBG_ERR("Didn't find band-size key in [%s]\n",
6401                         smb_fname_str_dbg(smb_fname));
6402                 ok = false;
6403                 goto out;
6404         }
6405
6406         ok = fruit_get_bandsize_from_line(band_size_line, band_size);
6407         if (!ok) {
6408                 DBG_ERR("fruit_get_bandsize_from_line failed\n");
6409                 goto out;
6410         }
6411
6412         DBG_DEBUG("Parsed band-size [%zu] for [%s]\n", *band_size, plist);
6413
6414 out:
6415         if (fsp != NULL) {
6416                 status = close_file(NULL, fsp, NORMAL_CLOSE);
6417                 if (!NT_STATUS_IS_OK(status)) {
6418                         DBG_ERR("close_file failed: %s\n", nt_errstr(status));
6419                 }
6420                 fsp = NULL;
6421         }
6422         TALLOC_FREE(plist);
6423         TALLOC_FREE(smb_fname);
6424         TALLOC_FREE(file_data);
6425         TALLOC_FREE(lines);
6426         return ok;
6427 }
6428
6429 struct fruit_disk_free_state {
6430         off_t total_size;
6431 };
6432
6433 static bool fruit_get_num_bands(vfs_handle_struct *handle,
6434                                 char *bundle,
6435                                 size_t *_nbands)
6436 {
6437         char *path = NULL;
6438         struct smb_filename *bands_dir = NULL;
6439         DIR *d = NULL;
6440         struct dirent *e = NULL;
6441         size_t nbands;
6442         int ret;
6443
6444         path = talloc_asprintf(talloc_tos(),
6445                                "%s/%s/bands",
6446                                handle->conn->connectpath,
6447                                bundle);
6448         if (path == NULL) {
6449                 return false;
6450         }
6451
6452         bands_dir = synthetic_smb_fname(talloc_tos(),
6453                                         path,
6454                                         NULL,
6455                                         NULL,
6456                                         0);
6457         TALLOC_FREE(path);
6458         if (bands_dir == NULL) {
6459                 return false;
6460         }
6461
6462         d = SMB_VFS_NEXT_OPENDIR(handle, bands_dir, NULL, 0);
6463         if (d == NULL) {
6464                 TALLOC_FREE(bands_dir);
6465                 return false;
6466         }
6467
6468         nbands = 0;
6469
6470         for (e = SMB_VFS_NEXT_READDIR(handle, d, NULL);
6471              e != NULL;
6472              e = SMB_VFS_NEXT_READDIR(handle, d, NULL))
6473         {
6474                 if (ISDOT(e->d_name) || ISDOTDOT(e->d_name)) {
6475                         continue;
6476                 }
6477                 nbands++;
6478         }
6479
6480         ret = SMB_VFS_NEXT_CLOSEDIR(handle, d);
6481         if (ret != 0) {
6482                 TALLOC_FREE(bands_dir);
6483                 return false;
6484         }
6485
6486         DBG_DEBUG("%zu bands in [%s]\n", nbands, smb_fname_str_dbg(bands_dir));
6487
6488         TALLOC_FREE(bands_dir);
6489
6490         *_nbands = nbands;
6491         return true;
6492 }
6493
6494 static bool fruit_tmsize_do_dirent(vfs_handle_struct *handle,
6495                                    struct fruit_disk_free_state *state,
6496                                    struct dirent *e)
6497 {
6498         bool ok;
6499         char *p = NULL;
6500         size_t sparsebundle_strlen = strlen("sparsebundle");
6501         size_t bandsize = 0;
6502         size_t nbands;
6503         off_t tm_size;
6504
6505         p = strstr(e->d_name, "sparsebundle");
6506         if (p == NULL) {
6507                 return true;
6508         }
6509
6510         if (p[sparsebundle_strlen] != '\0') {
6511                 return true;
6512         }
6513
6514         DBG_DEBUG("Processing sparsebundle [%s]\n", e->d_name);
6515
6516         ok = fruit_get_bandsize(handle, e->d_name, &bandsize);
6517         if (!ok) {
6518                 /*
6519                  * Beware of race conditions: this may be an uninitialized
6520                  * Info.plist that a client is just creating. We don't want let
6521                  * this to trigger complete failure.
6522                  */
6523                 DBG_ERR("Processing sparsebundle [%s] failed\n", e->d_name);
6524                 return true;
6525         }
6526
6527         ok = fruit_get_num_bands(handle, e->d_name, &nbands);
6528         if (!ok) {
6529                 /*
6530                  * Beware of race conditions: this may be a backup sparsebundle
6531                  * in an early stage lacking a bands subdirectory. We don't want
6532                  * let this to trigger complete failure.
6533                  */
6534                 DBG_ERR("Processing sparsebundle [%s] failed\n", e->d_name);
6535                 return true;
6536         }
6537
6538         tm_size = bandsize * nbands;
6539         if (tm_size > UINT64_MAX) {
6540                 DBG_ERR("tmsize overflow: bandsize [%zu] nbands [%zu]\n",
6541                         bandsize, nbands);
6542                 return false;
6543         }
6544
6545         if (state->total_size + tm_size < state->total_size) {
6546                 DBG_ERR("tmsize overflow: bandsize [%zu] nbands [%zu]\n",
6547                         bandsize, nbands);
6548                 return false;
6549         }
6550
6551         state->total_size += tm_size;
6552
6553         DBG_DEBUG("[%s] tm_size [%jd] total_size [%jd]\n",
6554                   e->d_name, (intmax_t)tm_size, (intmax_t)state->total_size);
6555
6556         return true;
6557 }
6558
6559 /**
6560  * Calculate used size of a TimeMachine volume
6561  *
6562  * This assumes that the volume is used only for TimeMachine.
6563  *
6564  * - readdir(basedir of share), then
6565  * - for every element that matches regex "^\(.*\)\.sparsebundle$" :
6566  * - parse "\1.sparsebundle/Info.plist" and read the band-size XML key
6567  * - count band files in "\1.sparsebundle/bands/"
6568  * - calculate used size of all bands: band_count * band_size
6569  **/
6570 static uint64_t fruit_disk_free(vfs_handle_struct *handle,
6571                                 const struct smb_filename *smb_fname,
6572                                 uint64_t *_bsize,
6573                                 uint64_t *_dfree,
6574                                 uint64_t *_dsize)
6575 {
6576         struct fruit_config_data *config = NULL;
6577         struct fruit_disk_free_state state = {0};
6578         DIR *d = NULL;
6579         struct dirent *e = NULL;
6580         uint64_t dfree;
6581         uint64_t dsize;
6582         int ret;
6583         bool ok;
6584
6585         SMB_VFS_HANDLE_GET_DATA(handle, config,
6586                                 struct fruit_config_data,
6587                                 return UINT64_MAX);
6588
6589         if (!config->time_machine ||
6590             config->time_machine_max_size == 0)
6591         {
6592                 return SMB_VFS_NEXT_DISK_FREE(handle,
6593                                               smb_fname,
6594                                               _bsize,
6595                                               _dfree,
6596                                               _dsize);
6597         }
6598
6599         d = SMB_VFS_NEXT_OPENDIR(handle, smb_fname, NULL, 0);
6600         if (d == NULL) {
6601                 return UINT64_MAX;
6602         }
6603
6604         for (e = SMB_VFS_NEXT_READDIR(handle, d, NULL);
6605              e != NULL;
6606              e = SMB_VFS_NEXT_READDIR(handle, d, NULL))
6607         {
6608                 ok = fruit_tmsize_do_dirent(handle, &state, e);
6609                 if (!ok) {
6610                         SMB_VFS_NEXT_CLOSEDIR(handle, d);
6611                         return UINT64_MAX;
6612                 }
6613         }
6614
6615         ret = SMB_VFS_NEXT_CLOSEDIR(handle, d);
6616         if (ret != 0) {
6617                 return UINT64_MAX;
6618         }
6619
6620         dsize = config->time_machine_max_size / 512;
6621         dfree = dsize - (state.total_size / 512);
6622         if (dfree > dsize) {
6623                 dfree = 0;
6624         }
6625
6626         *_bsize = 512;
6627         *_dsize = dsize;
6628         *_dfree = dfree;
6629         return dfree / 2;
6630 }
6631
6632 static struct vfs_fn_pointers vfs_fruit_fns = {
6633         .connect_fn = fruit_connect,
6634         .disk_free_fn = fruit_disk_free,
6635
6636         /* File operations */
6637         .chmod_fn = fruit_chmod,
6638         .chown_fn = fruit_chown,
6639         .unlink_fn = fruit_unlink,
6640         .rename_fn = fruit_rename,
6641         .rmdir_fn = fruit_rmdir,
6642         .open_fn = fruit_open,
6643         .pread_fn = fruit_pread,
6644         .pwrite_fn = fruit_pwrite,
6645         .pread_send_fn = fruit_pread_send,
6646         .pread_recv_fn = fruit_pread_recv,
6647         .pwrite_send_fn = fruit_pwrite_send,
6648         .pwrite_recv_fn = fruit_pwrite_recv,
6649         .stat_fn = fruit_stat,
6650         .lstat_fn = fruit_lstat,
6651         .fstat_fn = fruit_fstat,
6652         .streaminfo_fn = fruit_streaminfo,
6653         .ntimes_fn = fruit_ntimes,
6654         .ftruncate_fn = fruit_ftruncate,
6655         .fallocate_fn = fruit_fallocate,
6656         .create_file_fn = fruit_create_file,
6657         .readdir_attr_fn = fruit_readdir_attr,
6658         .offload_read_send_fn = fruit_offload_read_send,
6659         .offload_read_recv_fn = fruit_offload_read_recv,
6660         .offload_write_send_fn = fruit_offload_write_send,
6661         .offload_write_recv_fn = fruit_offload_write_recv,
6662
6663         /* NT ACL operations */
6664         .fget_nt_acl_fn = fruit_fget_nt_acl,
6665         .fset_nt_acl_fn = fruit_fset_nt_acl,
6666 };
6667
6668 static_decl_vfs;
6669 NTSTATUS vfs_fruit_init(TALLOC_CTX *ctx)
6670 {
6671         NTSTATUS ret = smb_register_vfs(SMB_VFS_INTERFACE_VERSION, "fruit",
6672                                         &vfs_fruit_fns);
6673         if (!NT_STATUS_IS_OK(ret)) {
6674                 return ret;
6675         }
6676
6677         vfs_fruit_debug_level = debug_add_class("fruit");
6678         if (vfs_fruit_debug_level == -1) {
6679                 vfs_fruit_debug_level = DBGC_VFS;
6680                 DEBUG(0, ("%s: Couldn't register custom debugging class!\n",
6681                           "vfs_fruit_init"));
6682         } else {
6683                 DEBUG(10, ("%s: Debug class number of '%s': %d\n",
6684                            "vfs_fruit_init","fruit",vfs_fruit_debug_level));
6685         }
6686
6687         return ret;
6688 }