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