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