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