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