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