vfs_fruit: comment fix: the options are documented
[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/sys_rw.h"
33
34 /*
35  * Enhanced OS X and Netatalk compatibility
36  * ========================================
37  *
38  * This modules takes advantage of vfs_streams_xattr and
39  * vfs_catia. VFS modules vfs_fruit and vfs_streams_xattr must be
40  * loaded in the correct order:
41  *
42  *   vfs modules = catia fruit streams_xattr
43  *
44  * The module intercepts the OS X special streams "AFP_AfpInfo" and
45  * "AFP_Resource" and handles them in a special way. All other named
46  * streams are deferred to vfs_streams_xattr.
47  *
48  * The OS X client maps all NTFS illegal characters to the Unicode
49  * private range. This module optionally stores the charcters using
50  * their native ASCII encoding using vfs_catia. If you're not enabling
51  * this feature, you can skip catia from vfs modules.
52  *
53  * Finally, open modes are optionally checked against Netatalk AFP
54  * share modes.
55  *
56  * The "AFP_AfpInfo" named stream is a binary blob containing OS X
57  * extended metadata for files and directories. This module optionally
58  * reads and stores this metadata in a way compatible with Netatalk 3
59  * which stores the metadata in an EA "org.netatalk.metadata". Cf
60  * source3/include/MacExtensions.h for a description of the binary
61  * blobs content.
62  *
63  * The "AFP_Resource" named stream may be arbitrarily large, thus it
64  * can't be stored in an xattr on most filesystem. ZFS on Solaris is
65  * the only available filesystem where xattrs can be of any size and
66  * the OS supports using the file APIs for xattrs.
67  *
68  * The AFP_Resource stream is stored in an AppleDouble file prepending
69  * "._" to the filename. On Solaris with ZFS the stream is optionally
70  * stored in an EA "org.netatalk.ressource".
71  *
72  *
73  * Extended Attributes
74  * ===================
75  *
76  * The OS X SMB client sends xattrs as ADS too. For xattr interop with
77  * other protocols you may want to adjust the xattr names the VFS
78  * module vfs_streams_xattr uses for storing ADS's. This defaults to
79  * user.DosStream.ADS_NAME:$DATA and can be changed by specifying
80  * these module parameters:
81  *
82  *   streams_xattr:prefix = user.
83  *   streams_xattr:store_stream_type = false
84  *
85  *
86  * TODO
87  * ====
88  *
89  * - log diagnostic if any needed VFS module is not loaded
90  *   (eg with lp_vfs_objects())
91  * - add tests
92  */
93
94 static int vfs_fruit_debug_level = DBGC_VFS;
95
96 #undef DBGC_CLASS
97 #define DBGC_CLASS vfs_fruit_debug_level
98
99 #define FRUIT_PARAM_TYPE_NAME "fruit"
100 #define ADOUBLE_NAME_PREFIX "._"
101
102 /*
103  * REVIEW:
104  * This is hokey, but what else can we do?
105  */
106 #if defined(HAVE_ATTROPEN) || defined(FREEBSD)
107 #define AFPINFO_EA_NETATALK "org.netatalk.Metadata"
108 #define AFPRESOURCE_EA_NETATALK "org.netatalk.ResourceFork"
109 #else
110 #define AFPINFO_EA_NETATALK "user.org.netatalk.Metadata"
111 #define AFPRESOURCE_EA_NETATALK "user.org.netatalk.ResourceFork"
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;
127         bool readdir_attr_enabled;
128         bool unix_info_enabled;
129
130         /*
131          * Additional options, all enabled by default,
132          * possibly useful for analyzing performance. The associated
133          * operations with each of them may be expensive, so having
134          * the chance to disable them individually gives a chance
135          * tweaking the setup for the particular usecase.
136          */
137         bool readdir_attr_rsize;
138         bool readdir_attr_finder_info;
139         bool readdir_attr_max_access;
140 };
141
142 static const struct enum_list fruit_rsrc[] = {
143         {FRUIT_RSRC_STREAM, "stream"}, /* pass on to vfs_streams_xattr */
144         {FRUIT_RSRC_ADFILE, "file"}, /* ._ AppleDouble file */
145         {FRUIT_RSRC_XATTR, "xattr"}, /* Netatalk compatible xattr (ZFS only) */
146         { -1, NULL}
147 };
148
149 static const struct enum_list fruit_meta[] = {
150         {FRUIT_META_STREAM, "stream"}, /* pass on to vfs_streams_xattr */
151         {FRUIT_META_NETATALK, "netatalk"}, /* Netatalk compatible xattr */
152         { -1, NULL}
153 };
154
155 static const struct enum_list fruit_locking[] = {
156         {FRUIT_LOCKING_NETATALK, "netatalk"}, /* synchronize locks with Netatalk */
157         {FRUIT_LOCKING_NONE, "none"},
158         { -1, NULL}
159 };
160
161 static const struct enum_list fruit_encoding[] = {
162         {FRUIT_ENC_NATIVE, "native"}, /* map unicode private chars to ASCII */
163         {FRUIT_ENC_PRIVATE, "private"}, /* keep unicode private chars */
164         { -1, NULL}
165 };
166
167 /*****************************************************************************
168  * Defines, functions and data structures that deal with AppleDouble
169  *****************************************************************************/
170
171 /*
172  * There are two AppleDouble blobs we deal with:
173  *
174  * - ADOUBLE_META - AppleDouble blob used by Netatalk for storing
175  *   metadata in an xattr
176  *
177  * - ADOUBLE_RSRC - AppleDouble blob used by OS X and Netatalk in
178  *   ._ files
179  */
180 typedef enum {ADOUBLE_META, ADOUBLE_RSRC} adouble_type_t;
181
182 /* Version info */
183 #define AD_VERSION2     0x00020000
184 #define AD_VERSION      AD_VERSION2
185
186 /*
187  * AppleDouble entry IDs.
188  */
189 #define ADEID_DFORK         1
190 #define ADEID_RFORK         2
191 #define ADEID_NAME          3
192 #define ADEID_COMMENT       4
193 #define ADEID_ICONBW        5
194 #define ADEID_ICONCOL       6
195 #define ADEID_FILEI         7
196 #define ADEID_FILEDATESI    8
197 #define ADEID_FINDERI       9
198 #define ADEID_MACFILEI      10
199 #define ADEID_PRODOSFILEI   11
200 #define ADEID_MSDOSFILEI    12
201 #define ADEID_SHORTNAME     13
202 #define ADEID_AFPFILEI      14
203 #define ADEID_DID           15
204
205 /* Private Netatalk entries */
206 #define ADEID_PRIVDEV       16
207 #define ADEID_PRIVINO       17
208 #define ADEID_PRIVSYN       18
209 #define ADEID_PRIVID        19
210 #define ADEID_MAX           (ADEID_PRIVID + 1)
211
212 /*
213  * These are the real ids for the private entries,
214  * as stored in the adouble file
215  */
216 #define AD_DEV              0x80444556
217 #define AD_INO              0x80494E4F
218 #define AD_SYN              0x8053594E
219 #define AD_ID               0x8053567E
220
221 /* Number of actually used entries */
222 #define ADEID_NUM_XATTR      8
223 #define ADEID_NUM_DOT_UND    2
224 #define ADEID_NUM_RSRC_XATTR 1
225
226 /* AppleDouble magic */
227 #define AD_APPLESINGLE_MAGIC 0x00051600
228 #define AD_APPLEDOUBLE_MAGIC 0x00051607
229 #define AD_MAGIC             AD_APPLEDOUBLE_MAGIC
230
231 /* Sizes of relevant entry bits */
232 #define ADEDLEN_MAGIC       4
233 #define ADEDLEN_VERSION     4
234 #define ADEDLEN_FILLER      16
235 #define AD_FILLER_TAG       "Netatalk        " /* should be 16 bytes */
236 #define ADEDLEN_NENTRIES    2
237 #define AD_HEADER_LEN       (ADEDLEN_MAGIC + ADEDLEN_VERSION + \
238                              ADEDLEN_FILLER + ADEDLEN_NENTRIES) /* 26 */
239 #define AD_ENTRY_LEN_EID    4
240 #define AD_ENTRY_LEN_OFF    4
241 #define AD_ENTRY_LEN_LEN    4
242 #define AD_ENTRY_LEN (AD_ENTRY_LEN_EID + AD_ENTRY_LEN_OFF + AD_ENTRY_LEN_LEN)
243
244 /* Field widths */
245 #define ADEDLEN_NAME            255
246 #define ADEDLEN_COMMENT         200
247 #define ADEDLEN_FILEI           16
248 #define ADEDLEN_FINDERI         32
249 #define ADEDLEN_FILEDATESI      16
250 #define ADEDLEN_SHORTNAME       12 /* length up to 8.3 */
251 #define ADEDLEN_AFPFILEI        4
252 #define ADEDLEN_MACFILEI        4
253 #define ADEDLEN_PRODOSFILEI     8
254 #define ADEDLEN_MSDOSFILEI      2
255 #define ADEDLEN_DID             4
256 #define ADEDLEN_PRIVDEV         8
257 #define ADEDLEN_PRIVINO         8
258 #define ADEDLEN_PRIVSYN         8
259 #define ADEDLEN_PRIVID          4
260
261 /* Offsets */
262 #define ADEDOFF_MAGIC         0
263 #define ADEDOFF_VERSION       (ADEDOFF_MAGIC + ADEDLEN_MAGIC)
264 #define ADEDOFF_FILLER        (ADEDOFF_VERSION + ADEDLEN_VERSION)
265 #define ADEDOFF_NENTRIES      (ADEDOFF_FILLER + ADEDLEN_FILLER)
266
267 #define ADEDOFF_FINDERI_XATTR    (AD_HEADER_LEN + \
268                                   (ADEID_NUM_XATTR * AD_ENTRY_LEN))
269 #define ADEDOFF_COMMENT_XATTR    (ADEDOFF_FINDERI_XATTR    + ADEDLEN_FINDERI)
270 #define ADEDOFF_FILEDATESI_XATTR (ADEDOFF_COMMENT_XATTR    + ADEDLEN_COMMENT)
271 #define ADEDOFF_AFPFILEI_XATTR   (ADEDOFF_FILEDATESI_XATTR + \
272                                   ADEDLEN_FILEDATESI)
273 #define ADEDOFF_PRIVDEV_XATTR    (ADEDOFF_AFPFILEI_XATTR   + ADEDLEN_AFPFILEI)
274 #define ADEDOFF_PRIVINO_XATTR    (ADEDOFF_PRIVDEV_XATTR    + ADEDLEN_PRIVDEV)
275 #define ADEDOFF_PRIVSYN_XATTR    (ADEDOFF_PRIVINO_XATTR    + ADEDLEN_PRIVINO)
276 #define ADEDOFF_PRIVID_XATTR     (ADEDOFF_PRIVSYN_XATTR    + ADEDLEN_PRIVSYN)
277
278 #define ADEDOFF_FINDERI_DOT_UND  (AD_HEADER_LEN + \
279                                   (ADEID_NUM_DOT_UND * AD_ENTRY_LEN))
280 #define ADEDOFF_RFORK_DOT_UND    (ADEDOFF_FINDERI_DOT_UND + ADEDLEN_FINDERI)
281
282 #define AD_DATASZ_XATTR (AD_HEADER_LEN + \
283                          (ADEID_NUM_XATTR * AD_ENTRY_LEN) + \
284                          ADEDLEN_FINDERI + ADEDLEN_COMMENT + \
285                          ADEDLEN_FILEDATESI + ADEDLEN_AFPFILEI + \
286                          ADEDLEN_PRIVDEV + ADEDLEN_PRIVINO + \
287                          ADEDLEN_PRIVSYN + ADEDLEN_PRIVID)
288
289 #if AD_DATASZ_XATTR != 402
290 #error bad size for AD_DATASZ_XATTR
291 #endif
292
293 #define AD_DATASZ_DOT_UND (AD_HEADER_LEN + \
294                            (ADEID_NUM_DOT_UND * AD_ENTRY_LEN) + \
295                            ADEDLEN_FINDERI)
296 #if AD_DATASZ_DOT_UND != 82
297 #error bad size for AD_DATASZ_DOT_UND
298 #endif
299
300 /*
301  * Sharemode locks fcntl() offsets
302  */
303 #if _FILE_OFFSET_BITS == 64 || defined(HAVE_LARGEFILE)
304 #define AD_FILELOCK_BASE (UINT64_C(0x7FFFFFFFFFFFFFFF) - 9)
305 #else
306 #define AD_FILELOCK_BASE (UINT32_C(0x7FFFFFFF) - 9)
307 #endif
308 #define BYTELOCK_MAX (AD_FILELOCK_BASE - 1)
309
310 #define AD_FILELOCK_OPEN_WR        (AD_FILELOCK_BASE + 0)
311 #define AD_FILELOCK_OPEN_RD        (AD_FILELOCK_BASE + 1)
312 #define AD_FILELOCK_RSRC_OPEN_WR   (AD_FILELOCK_BASE + 2)
313 #define AD_FILELOCK_RSRC_OPEN_RD   (AD_FILELOCK_BASE + 3)
314 #define AD_FILELOCK_DENY_WR        (AD_FILELOCK_BASE + 4)
315 #define AD_FILELOCK_DENY_RD        (AD_FILELOCK_BASE + 5)
316 #define AD_FILELOCK_RSRC_DENY_WR   (AD_FILELOCK_BASE + 6)
317 #define AD_FILELOCK_RSRC_DENY_RD   (AD_FILELOCK_BASE + 7)
318 #define AD_FILELOCK_OPEN_NONE      (AD_FILELOCK_BASE + 8)
319 #define AD_FILELOCK_RSRC_OPEN_NONE (AD_FILELOCK_BASE + 9)
320
321 /* Time stuff we overload the bits a little */
322 #define AD_DATE_CREATE         0
323 #define AD_DATE_MODIFY         4
324 #define AD_DATE_BACKUP         8
325 #define AD_DATE_ACCESS        12
326 #define AD_DATE_MASK          (AD_DATE_CREATE | AD_DATE_MODIFY | \
327                                AD_DATE_BACKUP | AD_DATE_ACCESS)
328 #define AD_DATE_UNIX          (1 << 10)
329 #define AD_DATE_START         0x80000000
330 #define AD_DATE_DELTA         946684800
331 #define AD_DATE_FROM_UNIX(x)  (htonl((x) - AD_DATE_DELTA))
332 #define AD_DATE_TO_UNIX(x)    (ntohl(x) + AD_DATE_DELTA)
333
334 /* Accessor macros */
335 #define ad_getentrylen(ad,eid)     ((ad)->ad_eid[(eid)].ade_len)
336 #define ad_getentryoff(ad,eid)     ((ad)->ad_eid[(eid)].ade_off)
337 #define ad_setentrylen(ad,eid,len) ((ad)->ad_eid[(eid)].ade_len = (len))
338 #define ad_setentryoff(ad,eid,off) ((ad)->ad_eid[(eid)].ade_off = (off))
339 #define ad_entry(ad,eid)           ((ad)->ad_data + ad_getentryoff((ad),(eid)))
340
341 struct ad_entry {
342         size_t ade_off;
343         size_t ade_len;
344 };
345
346 struct adouble {
347         vfs_handle_struct        *ad_handle;
348         files_struct             *ad_fsp;
349         adouble_type_t            ad_type;
350         uint32_t                  ad_magic;
351         uint32_t                  ad_version;
352         struct ad_entry           ad_eid[ADEID_MAX];
353         char                     *ad_data;
354 };
355
356 struct ad_entry_order {
357         uint32_t id, offset, len;
358 };
359
360 /* Netatalk AppleDouble metadata xattr */
361 static const
362 struct ad_entry_order entry_order_meta_xattr[ADEID_NUM_XATTR + 1] = {
363         {ADEID_FINDERI,    ADEDOFF_FINDERI_XATTR,    ADEDLEN_FINDERI},
364         {ADEID_COMMENT,    ADEDOFF_COMMENT_XATTR,    0},
365         {ADEID_FILEDATESI, ADEDOFF_FILEDATESI_XATTR, ADEDLEN_FILEDATESI},
366         {ADEID_AFPFILEI,   ADEDOFF_AFPFILEI_XATTR,   ADEDLEN_AFPFILEI},
367         {ADEID_PRIVDEV,    ADEDOFF_PRIVDEV_XATTR,    0},
368         {ADEID_PRIVINO,    ADEDOFF_PRIVINO_XATTR,    0},
369         {ADEID_PRIVSYN,    ADEDOFF_PRIVSYN_XATTR,    0},
370         {ADEID_PRIVID,     ADEDOFF_PRIVID_XATTR,     0},
371         {0, 0, 0}
372 };
373
374 /* AppleDouble ressource fork file (the ones prefixed by "._") */
375 static const
376 struct ad_entry_order entry_order_dot_und[ADEID_NUM_DOT_UND + 1] = {
377         {ADEID_FINDERI,    ADEDOFF_FINDERI_DOT_UND,  ADEDLEN_FINDERI},
378         {ADEID_RFORK,      ADEDOFF_RFORK_DOT_UND,    0},
379         {0, 0, 0}
380 };
381
382 /*
383  * Fake AppleDouble entry oder for ressource fork xattr.  The xattr
384  * isn't an AppleDouble file, it simply contains the ressource data,
385  * but in order to be able to use some API calls like ad_getentryoff()
386  * we build a fake/helper struct adouble with this entry order struct.
387  */
388 static const
389 struct ad_entry_order entry_order_rsrc_xattr[ADEID_NUM_RSRC_XATTR + 1] = {
390         {ADEID_RFORK, 0, 0},
391         {0, 0, 0}
392 };
393
394 /* Conversion from enumerated id to on-disk AppleDouble id */
395 #define AD_EID_DISK(a) (set_eid[a])
396 static const uint32_t set_eid[] = {
397         0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
398         AD_DEV, AD_INO, AD_SYN, AD_ID
399 };
400
401 /*
402  * Forward declarations
403  */
404 static struct adouble *ad_init(TALLOC_CTX *ctx, vfs_handle_struct *handle,
405                                adouble_type_t type, files_struct *fsp);
406 static int ad_write(struct adouble *ad, const char *path);
407 static int adouble_path(TALLOC_CTX *ctx, const char *path_in, char **path_out);
408
409 /**
410  * Get a date
411  **/
412 static int ad_getdate(const struct adouble *ad,
413                       unsigned int dateoff,
414                       uint32_t *date)
415 {
416         bool xlate = (dateoff & AD_DATE_UNIX);
417
418         dateoff &= AD_DATE_MASK;
419         if (!ad_getentryoff(ad, ADEID_FILEDATESI)) {
420                 return -1;
421         }
422
423         if (dateoff > AD_DATE_ACCESS) {
424             return -1;
425         }
426         memcpy(date,
427                ad_entry(ad, ADEID_FILEDATESI) + dateoff,
428                sizeof(uint32_t));
429
430         if (xlate) {
431                 *date = AD_DATE_TO_UNIX(*date);
432         }
433         return 0;
434 }
435
436 /**
437  * Set a date
438  **/
439 static int ad_setdate(struct adouble *ad, unsigned int dateoff, uint32_t date)
440 {
441         bool xlate = (dateoff & AD_DATE_UNIX);
442
443         if (!ad_getentryoff(ad, ADEID_FILEDATESI)) {
444                 return 0;
445         }
446
447         dateoff &= AD_DATE_MASK;
448         if (xlate) {
449                 date = AD_DATE_FROM_UNIX(date);
450         }
451
452         if (dateoff > AD_DATE_ACCESS) {
453                 return -1;
454         }
455
456         memcpy(ad_entry(ad, ADEID_FILEDATESI) + dateoff, &date, sizeof(date));
457
458         return 0;
459 }
460
461
462 /**
463  * Map on-disk AppleDouble id to enumerated id
464  **/
465 static uint32_t get_eid(uint32_t eid)
466 {
467         if (eid <= 15) {
468                 return eid;
469         }
470
471         switch (eid) {
472         case AD_DEV:
473                 return ADEID_PRIVDEV;
474         case AD_INO:
475                 return ADEID_PRIVINO;
476         case AD_SYN:
477                 return ADEID_PRIVSYN;
478         case AD_ID:
479                 return ADEID_PRIVID;
480         default:
481                 break;
482         }
483
484         return 0;
485 }
486
487 /**
488  * Pack AppleDouble structure into data buffer
489  **/
490 static bool ad_pack(struct adouble *ad)
491 {
492         uint32_t       eid;
493         uint16_t       nent;
494         uint32_t       bufsize;
495         uint32_t       offset = 0;
496
497         bufsize = talloc_get_size(ad->ad_data);
498
499         if (offset + ADEDLEN_MAGIC < offset ||
500                         offset + ADEDLEN_MAGIC >= bufsize) {
501                 return false;
502         }
503         RSIVAL(ad->ad_data, offset, ad->ad_magic);
504         offset += ADEDLEN_MAGIC;
505
506         if (offset + ADEDLEN_VERSION < offset ||
507                         offset + ADEDLEN_VERSION >= bufsize) {
508                 return false;
509         }
510         RSIVAL(ad->ad_data, offset, ad->ad_version);
511         offset += ADEDLEN_VERSION;
512
513         if (offset + ADEDLEN_FILLER < offset ||
514                         offset + ADEDLEN_FILLER >= bufsize) {
515                 return false;
516         }
517         if (ad->ad_type == ADOUBLE_RSRC) {
518                 memcpy(ad->ad_data + offset, AD_FILLER_TAG, ADEDLEN_FILLER);
519         }
520         offset += ADEDLEN_FILLER;
521
522         if (offset + ADEDLEN_NENTRIES < offset ||
523                         offset + ADEDLEN_NENTRIES >= bufsize) {
524                 return false;
525         }
526         offset += ADEDLEN_NENTRIES;
527
528         for (eid = 0, nent = 0; eid < ADEID_MAX; eid++) {
529                 if (ad->ad_eid[eid].ade_off == 0) {
530                         /*
531                          * ade_off is also used as indicator whether a
532                          * specific entry is used or not
533                          */
534                         continue;
535                 }
536
537                 if (offset + AD_ENTRY_LEN_EID < offset ||
538                                 offset + AD_ENTRY_LEN_EID >= bufsize) {
539                         return false;
540                 }
541                 RSIVAL(ad->ad_data, offset, AD_EID_DISK(eid));
542                 offset += AD_ENTRY_LEN_EID;
543
544                 if (offset + AD_ENTRY_LEN_OFF < offset ||
545                                 offset + AD_ENTRY_LEN_OFF >= bufsize) {
546                         return false;
547                 }
548                 RSIVAL(ad->ad_data, offset, ad->ad_eid[eid].ade_off);
549                 offset += AD_ENTRY_LEN_OFF;
550
551                 if (offset + AD_ENTRY_LEN_LEN < offset ||
552                                 offset + AD_ENTRY_LEN_LEN >= bufsize) {
553                         return false;
554                 }
555                 RSIVAL(ad->ad_data, offset, ad->ad_eid[eid].ade_len);
556                 offset += AD_ENTRY_LEN_LEN;
557
558                 nent++;
559         }
560
561         if (ADEDOFF_NENTRIES + 2 >= bufsize) {
562                 return false;
563         }
564         RSSVAL(ad->ad_data, ADEDOFF_NENTRIES, nent);
565
566         return 0;
567 }
568
569 /**
570  * Unpack an AppleDouble blob into a struct adoble
571  **/
572 static bool ad_unpack(struct adouble *ad, const int nentries, size_t filesize)
573 {
574         size_t bufsize = talloc_get_size(ad->ad_data);
575         int adentries, i;
576         uint32_t eid, len, off;
577
578         /*
579          * The size of the buffer ad->ad_data is checked when read, so
580          * we wouldn't have to check our own offsets, a few extra
581          * checks won't hurt though. We have to check the offsets we
582          * read from the buffer anyway.
583          */
584
585         if (bufsize < (AD_HEADER_LEN + (AD_ENTRY_LEN * nentries))) {
586                 DEBUG(1, ("bad size\n"));
587                 return false;
588         }
589
590         ad->ad_magic = RIVAL(ad->ad_data, 0);
591         ad->ad_version = RIVAL(ad->ad_data, ADEDOFF_VERSION);
592         if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION)) {
593                 DEBUG(1, ("wrong magic or version\n"));
594                 return false;
595         }
596
597         adentries = RSVAL(ad->ad_data, ADEDOFF_NENTRIES);
598         if (adentries != nentries) {
599                 DEBUG(1, ("invalid number of entries: %d\n", adentries));
600                 return false;
601         }
602
603         /* now, read in the entry bits */
604         for (i = 0; i < adentries; i++) {
605                 eid = RIVAL(ad->ad_data, AD_HEADER_LEN + (i * AD_ENTRY_LEN));
606                 eid = get_eid(eid);
607                 off = RIVAL(ad->ad_data, AD_HEADER_LEN + (i * AD_ENTRY_LEN) + 4);
608                 len = RIVAL(ad->ad_data, AD_HEADER_LEN + (i * AD_ENTRY_LEN) + 8);
609
610                 if (!eid || eid > ADEID_MAX) {
611                         DEBUG(1, ("bogus eid %d\n", eid));
612                         return false;
613                 }
614
615                 /*
616                  * All entries other than the resource fork are
617                  * expected to be read into the ad_data buffer, so
618                  * ensure the specified offset is within that bound
619                  */
620                 if ((off > bufsize) && (eid != ADEID_RFORK)) {
621                         DEBUG(1, ("bogus eid %d: off: %" PRIu32 ", len: %" PRIu32 "\n",
622                                   eid, off, len));
623                         return false;
624                 }
625
626                 /*
627                  * All entries besides FinderInfo and resource fork
628                  * must fit into the buffer. FinderInfo is special as
629                  * it may be larger then the default 32 bytes (if it
630                  * contains marshalled xattrs), but we will fixup that
631                  * in ad_convert(). And the resource fork is never
632                  * accessed directly by the ad_data buf (also see
633                  * comment above) anyway.
634                  */
635                 if ((eid != ADEID_RFORK) &&
636                     (eid != ADEID_FINDERI) &&
637                     ((off + len) > bufsize)) {
638                         DEBUG(1, ("bogus eid %d: off: %" PRIu32 ", len: %" PRIu32 "\n",
639                                   eid, off, len));
640                         return false;
641                 }
642
643                 /*
644                  * That would be obviously broken
645                  */
646                 if (off > filesize) {
647                         DEBUG(1, ("bogus eid %d: off: %" PRIu32 ", len: %" PRIu32 "\n",
648                                   eid, off, len));
649                         return false;
650                 }
651
652                 /*
653                  * Check for any entry that has its end beyond the
654                  * filesize.
655                  */
656                 if (off + len < off) {
657                         DEBUG(1, ("offset wrap in eid %d: off: %" PRIu32
658                                   ", len: %" PRIu32 "\n",
659                                   eid, off, len));
660                         return false;
661
662                 }
663                 if (off + len > filesize) {
664                         /*
665                          * If this is the resource fork entry, we fix
666                          * up the length, for any other entry we bail
667                          * out.
668                          */
669                         if (eid != ADEID_RFORK) {
670                                 DEBUG(1, ("bogus eid %d: off: %" PRIu32
671                                           ", len: %" PRIu32 "\n",
672                                           eid, off, len));
673                                 return false;
674                         }
675
676                         /*
677                          * Fixup the resource fork entry by limiting
678                          * the size to entryoffset - filesize.
679                          */
680                         len = filesize - off;
681                         DEBUG(1, ("Limiting ADEID_RFORK: off: %" PRIu32
682                                   ", len: %" PRIu32 "\n", off, len));
683                 }
684
685                 ad->ad_eid[eid].ade_off = off;
686                 ad->ad_eid[eid].ade_len = len;
687         }
688
689         return true;
690 }
691
692 /**
693  * Convert from Apple's ._ file to Netatalk
694  *
695  * Apple's AppleDouble may contain a FinderInfo entry longer then 32
696  * bytes containing packed xattrs. Netatalk can't deal with that, so
697  * we simply discard the packed xattrs.
698  *
699  * @return -1 in case an error occured, 0 if no conversion was done, 1
700  * otherwise
701  **/
702 static int ad_convert(struct adouble *ad, int fd)
703 {
704         int rc = 0;
705         char *map = MAP_FAILED;
706         size_t origlen;
707
708         origlen = ad_getentryoff(ad, ADEID_RFORK) +
709                 ad_getentrylen(ad, ADEID_RFORK);
710
711         /* FIXME: direct use of mmap(), vfs_aio_fork does it too */
712         map = mmap(NULL, origlen, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
713         if (map == MAP_FAILED) {
714                 DEBUG(2, ("mmap AppleDouble: %s\n", strerror(errno)));
715                 rc = -1;
716                 goto exit;
717         }
718
719         if (ad_getentrylen(ad, ADEID_RFORK) > 0) {
720                 memmove(map + ad_getentryoff(ad, ADEID_FINDERI) + ADEDLEN_FINDERI,
721                         map + ad_getentryoff(ad, ADEID_RFORK),
722                         ad_getentrylen(ad, ADEID_RFORK));
723         }
724
725         ad_setentrylen(ad, ADEID_FINDERI, ADEDLEN_FINDERI);
726         ad_setentryoff(ad, ADEID_RFORK,
727                        ad_getentryoff(ad, ADEID_FINDERI) + ADEDLEN_FINDERI);
728
729         /*
730          * FIXME: direct ftruncate(), but we don't have a fsp for the
731          * VFS call
732          */
733         rc = ftruncate(fd, ad_getentryoff(ad, ADEID_RFORK)
734                        + ad_getentrylen(ad, ADEID_RFORK));
735
736 exit:
737         if (map != MAP_FAILED) {
738                 munmap(map, origlen);
739         }
740         return rc;
741 }
742
743 /**
744  * Read and parse Netatalk AppleDouble metadata xattr
745  **/
746 static ssize_t ad_header_read_meta(struct adouble *ad, const char *path)
747 {
748         int      rc = 0;
749         ssize_t  ealen;
750         bool     ok;
751
752         DEBUG(10, ("reading meta xattr for %s\n", path));
753
754         ealen = SMB_VFS_GETXATTR(ad->ad_handle->conn, path,
755                                  AFPINFO_EA_NETATALK, ad->ad_data,
756                                  AD_DATASZ_XATTR);
757         if (ealen == -1) {
758                 switch (errno) {
759                 case ENOATTR:
760                 case ENOENT:
761                         if (errno == ENOATTR) {
762                                 errno = ENOENT;
763                         }
764                         rc = -1;
765                         goto exit;
766                 default:
767                         DEBUG(2, ("error reading meta xattr: %s\n",
768                                   strerror(errno)));
769                         rc = -1;
770                         goto exit;
771                 }
772         }
773         if (ealen != AD_DATASZ_XATTR) {
774                 DEBUG(2, ("bad size %zd\n", ealen));
775                 errno = EINVAL;
776                 rc = -1;
777                 goto exit;
778         }
779
780         /* Now parse entries */
781         ok = ad_unpack(ad, ADEID_NUM_XATTR, AD_DATASZ_XATTR);
782         if (!ok) {
783                 DEBUG(2, ("invalid AppleDouble metadata xattr\n"));
784                 errno = EINVAL;
785                 rc = -1;
786                 goto exit;
787         }
788
789         if (!ad_getentryoff(ad, ADEID_FINDERI)
790             || !ad_getentryoff(ad, ADEID_COMMENT)
791             || !ad_getentryoff(ad, ADEID_FILEDATESI)
792             || !ad_getentryoff(ad, ADEID_AFPFILEI)
793             || !ad_getentryoff(ad, ADEID_PRIVDEV)
794             || !ad_getentryoff(ad, ADEID_PRIVINO)
795             || !ad_getentryoff(ad, ADEID_PRIVSYN)
796             || !ad_getentryoff(ad, ADEID_PRIVID)) {
797                 DEBUG(2, ("invalid AppleDouble metadata xattr\n"));
798                 errno = EINVAL;
799                 rc = -1;
800                 goto exit;
801         }
802
803 exit:
804         DEBUG(10, ("reading meta xattr for %s, rc: %d\n", path, rc));
805
806         if (rc != 0) {
807                 ealen = -1;
808                 if (errno == EINVAL) {
809                         become_root();
810                         removexattr(path, AFPINFO_EA_NETATALK);
811                         unbecome_root();
812                         errno = ENOENT;
813                 }
814         }
815         return ealen;
816 }
817
818 /**
819  * Read and parse resource fork, either ._ AppleDouble file or xattr
820  **/
821 static ssize_t ad_header_read_rsrc(struct adouble *ad, const char *path)
822 {
823         struct fruit_config_data *config = NULL;
824         int fd = -1;
825         int rc = 0;
826         ssize_t len;
827         char *adpath = NULL;
828         bool opened = false;
829         int mode;
830         struct adouble *meta_ad = NULL;
831         SMB_STRUCT_STAT sbuf;
832         bool ok;
833         int saved_errno = 0;
834
835         SMB_VFS_HANDLE_GET_DATA(ad->ad_handle, config,
836                                 struct fruit_config_data, return -1);
837
838         /* Try rw first so we can use the fd in ad_convert() */
839         mode = O_RDWR;
840
841         if (ad->ad_fsp && ad->ad_fsp->fh && (ad->ad_fsp->fh->fd != -1)) {
842                 fd = ad->ad_fsp->fh->fd;
843         } else {
844                 if (config->rsrc == FRUIT_RSRC_XATTR) {
845                         adpath = talloc_strdup(talloc_tos(), path);
846                 } else {
847                         rc = adouble_path(talloc_tos(), path, &adpath);
848                         if (rc != 0) {
849                                 goto exit;
850                         }
851                 }
852
853         retry:
854                 if (config->rsrc == FRUIT_RSRC_XATTR) {
855 #ifndef HAVE_ATTROPEN
856                         errno = ENOSYS;
857                         rc = -1;
858                         goto exit;
859 #else
860                         /* FIXME: direct Solaris xattr syscall */
861                         fd = attropen(adpath, AFPRESOURCE_EA_NETATALK,
862                                       mode, 0);
863 #endif
864                 } else {
865                         /* FIXME: direct open(), don't have an fsp */
866                         fd = open(adpath, mode);
867                 }
868
869                 if (fd == -1) {
870                         switch (errno) {
871                         case EROFS:
872                         case EACCES:
873                                 if (mode == O_RDWR) {
874                                         mode = O_RDONLY;
875                                         goto retry;
876                                 }
877                                 /* fall through ... */
878                         default:
879                                 DEBUG(2, ("open AppleDouble: %s, %s\n",
880                                           adpath, strerror(errno)));
881                                 rc = -1;
882                                 goto exit;
883                         }
884                 }
885                 opened = true;
886         }
887
888         if (config->rsrc == FRUIT_RSRC_XATTR) {
889                 /* FIXME: direct sys_fstat(), don't have an fsp */
890                 rc = sys_fstat(
891                         fd, &sbuf,
892                         lp_fake_directory_create_times(
893                                 SNUM(ad->ad_handle->conn)));
894                 if (rc != 0) {
895                         goto exit;
896                 }
897                 len = sbuf.st_ex_size;
898                 ad_setentrylen(ad, ADEID_RFORK, len);
899         } else {
900                 /* FIXME: direct sys_pread(), don't have an fsp */
901                 len = sys_pread(fd, ad->ad_data, AD_DATASZ_DOT_UND, 0);
902                 if (len != AD_DATASZ_DOT_UND) {
903                         DEBUG(2, ("%s: bad size: %zd\n",
904                                   strerror(errno), len));
905                         rc = -1;
906                         goto exit;
907                 }
908
909                 /* FIXME: direct sys_fstat(), we don't have an fsp */
910                 rc = sys_fstat(fd, &sbuf,
911                                lp_fake_directory_create_times(
912                                        SNUM(ad->ad_handle->conn)));
913                 if (rc != 0) {
914                         goto exit;
915                 }
916
917                 /* Now parse entries */
918                 ok = ad_unpack(ad, ADEID_NUM_DOT_UND, sbuf.st_ex_size);
919                 if (!ok) {
920                         DEBUG(1, ("invalid AppleDouble ressource %s\n", path));
921                         errno = EINVAL;
922                         rc = -1;
923                         goto exit;
924                 }
925
926                 if ((ad_getentryoff(ad, ADEID_FINDERI)
927                      != ADEDOFF_FINDERI_DOT_UND)
928                     || (ad_getentrylen(ad, ADEID_FINDERI)
929                         < ADEDLEN_FINDERI)
930                     || (ad_getentryoff(ad, ADEID_RFORK)
931                         < ADEDOFF_RFORK_DOT_UND)) {
932                         DEBUG(2, ("invalid AppleDouble ressource %s\n", path));
933                         errno = EINVAL;
934                         rc = -1;
935                         goto exit;
936                 }
937
938                 if ((mode == O_RDWR)
939                     && (ad_getentrylen(ad, ADEID_FINDERI) > ADEDLEN_FINDERI)) {
940                         rc = ad_convert(ad, fd);
941                         if (rc != 0) {
942                                 rc = -1;
943                                 goto exit;
944                         }
945                         /*
946                          * Can't use ad_write() because we might not have a fsp
947                          */
948                         rc = ad_pack(ad);
949                         if (rc != 0) {
950                                 goto exit;
951                         }
952                         /* FIXME: direct sys_pwrite(), don't have an fsp */
953                         len = sys_pwrite(fd, ad->ad_data,
954                                          AD_DATASZ_DOT_UND, 0);
955                         if (len != AD_DATASZ_DOT_UND) {
956                                 DEBUG(2, ("%s: bad size: %zd\n", adpath, len));
957                                 rc = -1;
958                                 goto exit;
959                         }
960
961                         meta_ad = ad_init(talloc_tos(), ad->ad_handle,
962                                           ADOUBLE_META, NULL);
963                         if (meta_ad == NULL) {
964                                 rc = -1;
965                                 goto exit;
966                         }
967
968                         memcpy(ad_entry(meta_ad, ADEID_FINDERI),
969                                ad_entry(ad, ADEID_FINDERI),
970                                ADEDLEN_FINDERI);
971
972                         rc = ad_write(meta_ad, path);
973                         if (rc != 0) {
974                                 rc = -1;
975                                 goto exit;
976                         }
977                 }
978         }
979
980         DEBUG(10, ("opened AppleDouble: %s\n", path));
981
982 exit:
983         if (rc != 0) {
984                 saved_errno = errno;
985                 len = -1;
986         }
987         if (opened && fd != -1) {
988                 close(fd);
989         }
990         TALLOC_FREE(adpath);
991         TALLOC_FREE(meta_ad);
992         if (rc != 0) {
993                 errno = saved_errno;
994         }
995         return len;
996 }
997
998 /**
999  * Read and unpack an AppleDouble metadata xattr or resource
1000  **/
1001 static ssize_t ad_read(struct adouble *ad, const char *path)
1002 {
1003         switch (ad->ad_type) {
1004         case ADOUBLE_META:
1005                 return ad_header_read_meta(ad, path);
1006         case ADOUBLE_RSRC:
1007                 return ad_header_read_rsrc(ad, path);
1008         default:
1009                 return -1;
1010         }
1011 }
1012
1013 /**
1014  * Allocate a struct adouble without initialiing it
1015  *
1016  * The struct is either hang of the fsp extension context or if fsp is
1017  * NULL from ctx.
1018  *
1019  * @param[in] ctx        talloc context
1020  * @param[in] handle     vfs handle
1021  * @param[in] type       type of AppleDouble, ADOUBLE_META or ADOUBLE_RSRC
1022
1023  * @param[in] fsp        if not NULL (for stream IO), the adouble handle is
1024  *                       added as an fsp extension
1025  *
1026  * @return               adouble handle
1027  **/
1028 static struct adouble *ad_alloc(TALLOC_CTX *ctx, vfs_handle_struct *handle,
1029                                 adouble_type_t type, files_struct *fsp)
1030 {
1031         int rc = 0;
1032         size_t adsize = 0;
1033         struct adouble *ad;
1034         struct fruit_config_data *config;
1035
1036         SMB_VFS_HANDLE_GET_DATA(handle, config,
1037                                 struct fruit_config_data, return NULL);
1038
1039         switch (type) {
1040         case ADOUBLE_META:
1041                 adsize = AD_DATASZ_XATTR;
1042                 break;
1043         case ADOUBLE_RSRC:
1044                 if (config->rsrc == FRUIT_RSRC_ADFILE) {
1045                         adsize = AD_DATASZ_DOT_UND;
1046                 }
1047                 break;
1048         default:
1049                 return NULL;
1050         }
1051
1052         if (!fsp) {
1053                 ad = talloc_zero(ctx, struct adouble);
1054                 if (ad == NULL) {
1055                         rc = -1;
1056                         goto exit;
1057                 }
1058                 if (adsize) {
1059                         ad->ad_data = talloc_zero_array(ad, char, adsize);
1060                 }
1061         } else {
1062                 ad = (struct adouble *)VFS_ADD_FSP_EXTENSION(handle, fsp,
1063                                                              struct adouble,
1064                                                              NULL);
1065                 if (ad == NULL) {
1066                         rc = -1;
1067                         goto exit;
1068                 }
1069                 if (adsize) {
1070                         ad->ad_data = talloc_zero_array(
1071                                 VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
1072                                 char, adsize);
1073                 }
1074                 ad->ad_fsp = fsp;
1075         }
1076
1077         if (adsize && ad->ad_data == NULL) {
1078                 rc = -1;
1079                 goto exit;
1080         }
1081         ad->ad_handle = handle;
1082         ad->ad_type = type;
1083         ad->ad_magic = AD_MAGIC;
1084         ad->ad_version = AD_VERSION;
1085
1086 exit:
1087         if (rc != 0) {
1088                 TALLOC_FREE(ad);
1089         }
1090         return ad;
1091 }
1092
1093 /**
1094  * Allocate and initialize a new struct adouble
1095  *
1096  * @param[in] ctx        talloc context
1097  * @param[in] handle     vfs handle
1098  * @param[in] type       type of AppleDouble, ADOUBLE_META or ADOUBLE_RSRC
1099  * @param[in] fsp        file handle, may be NULL for a type of e_ad_meta
1100  *
1101  * @return               adouble handle, initialized
1102  **/
1103 static struct adouble *ad_init(TALLOC_CTX *ctx, vfs_handle_struct *handle,
1104                                adouble_type_t type, files_struct *fsp)
1105 {
1106         int rc = 0;
1107         const struct ad_entry_order  *eid;
1108         struct adouble *ad = NULL;
1109         struct fruit_config_data *config;
1110         time_t t = time(NULL);
1111
1112         SMB_VFS_HANDLE_GET_DATA(handle, config,
1113                                 struct fruit_config_data, return NULL);
1114
1115         switch (type) {
1116         case ADOUBLE_META:
1117                 eid = entry_order_meta_xattr;
1118                 break;
1119         case ADOUBLE_RSRC:
1120                 if (config->rsrc == FRUIT_RSRC_ADFILE) {
1121                         eid = entry_order_dot_und;
1122                 } else {
1123                         eid = entry_order_rsrc_xattr;
1124                 }
1125                 break;
1126         default:
1127                 return NULL;
1128         }
1129
1130         ad = ad_alloc(ctx, handle, type, fsp);
1131         if (ad == NULL) {
1132                 return NULL;
1133         }
1134
1135         while (eid->id) {
1136                 ad->ad_eid[eid->id].ade_off = eid->offset;
1137                 ad->ad_eid[eid->id].ade_len = eid->len;
1138                 eid++;
1139         }
1140
1141         /* put something sane in the date fields */
1142         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, t);
1143         ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, t);
1144         ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, t);
1145         ad_setdate(ad, AD_DATE_BACKUP, htonl(AD_DATE_START));
1146
1147         if (rc != 0) {
1148                 TALLOC_FREE(ad);
1149         }
1150         return ad;
1151 }
1152
1153 /**
1154  * Return AppleDouble data for a file
1155  *
1156  * @param[in] ctx      talloc context
1157  * @param[in] handle   vfs handle
1158  * @param[in] path     pathname to file or directory
1159  * @param[in] type     type of AppleDouble, ADOUBLE_META or ADOUBLE_RSRC
1160  *
1161  * @return             talloced struct adouble or NULL on error
1162  **/
1163 static struct adouble *ad_get(TALLOC_CTX *ctx, vfs_handle_struct *handle,
1164                               const char *path, adouble_type_t type)
1165 {
1166         int rc = 0;
1167         ssize_t len;
1168         struct adouble *ad = NULL;
1169
1170         DEBUG(10, ("ad_get(%s) called for %s\n",
1171                    type == ADOUBLE_META ? "meta" : "rsrc", path));
1172
1173         ad = ad_alloc(ctx, handle, type, NULL);
1174         if (ad == NULL) {
1175                 rc = -1;
1176                 goto exit;
1177         }
1178
1179         len = ad_read(ad, path);
1180         if (len == -1) {
1181                 DEBUG(10, ("error reading AppleDouble for %s\n", path));
1182                 rc = -1;
1183                 goto exit;
1184         }
1185
1186 exit:
1187         DEBUG(10, ("ad_get(%s) for %s returning %d\n",
1188                   type == ADOUBLE_META ? "meta" : "rsrc", path, rc));
1189
1190         if (rc != 0) {
1191                 TALLOC_FREE(ad);
1192         }
1193         return ad;
1194 }
1195
1196 /**
1197  * Set AppleDouble metadata on a file or directory
1198  *
1199  * @param[in] ad      adouble handle
1200
1201  * @param[in] path    pathname to file or directory, may be NULL for a
1202  *                    resource fork
1203  *
1204  * @return            status code, 0 means success
1205  **/
1206 static int ad_write(struct adouble *ad, const char *path)
1207 {
1208         int rc = 0;
1209         ssize_t len;
1210
1211         rc = ad_pack(ad);
1212         if (rc != 0) {
1213                 goto exit;
1214         }
1215
1216         switch (ad->ad_type) {
1217         case ADOUBLE_META:
1218                 rc = SMB_VFS_SETXATTR(ad->ad_handle->conn, path,
1219                                       AFPINFO_EA_NETATALK, ad->ad_data,
1220                                       AD_DATASZ_XATTR, 0);
1221                 break;
1222         case ADOUBLE_RSRC:
1223                 if ((ad->ad_fsp == NULL)
1224                     || (ad->ad_fsp->fh == NULL)
1225                     || (ad->ad_fsp->fh->fd == -1)) {
1226                         rc = -1;
1227                         goto exit;
1228                 }
1229                 /* FIXME: direct sys_pwrite(), don't have an fsp */
1230                 len = sys_pwrite(ad->ad_fsp->fh->fd, ad->ad_data,
1231                                  talloc_get_size(ad->ad_data), 0);
1232                 if (len != talloc_get_size(ad->ad_data)) {
1233                         DEBUG(1, ("short write on %s: %zd",
1234                                   fsp_str_dbg(ad->ad_fsp), len));
1235                         rc = -1;
1236                         goto exit;
1237                 }
1238                 break;
1239         default:
1240                 return -1;
1241         }
1242 exit:
1243         return rc;
1244 }
1245
1246 /*****************************************************************************
1247  * Helper functions
1248  *****************************************************************************/
1249
1250 static bool is_afpinfo_stream(const struct smb_filename *smb_fname)
1251 {
1252         if (strncasecmp_m(smb_fname->stream_name,
1253                           AFPINFO_STREAM_NAME,
1254                           strlen(AFPINFO_STREAM_NAME)) == 0) {
1255                 return true;
1256         }
1257         return false;
1258 }
1259
1260 static bool is_afpresource_stream(const struct smb_filename *smb_fname)
1261 {
1262         if (strncasecmp_m(smb_fname->stream_name,
1263                           AFPRESOURCE_STREAM_NAME,
1264                           strlen(AFPRESOURCE_STREAM_NAME)) == 0) {
1265                 return true;
1266         }
1267         return false;
1268 }
1269
1270 /**
1271  * Test whether stream is an Apple stream, not used atm
1272  **/
1273 #if 0
1274 static bool is_apple_stream(const struct smb_filename *smb_fname)
1275 {
1276         if (is_afpinfo_stream(smb_fname)) {
1277                 return true;
1278         }
1279         if (is_afpresource_stream(smb_fname)) {
1280                 return true;
1281         }
1282         return false;
1283 }
1284 #endif
1285
1286 /**
1287  * Initialize config struct from our smb.conf config parameters
1288  **/
1289 static int init_fruit_config(vfs_handle_struct *handle)
1290 {
1291         struct fruit_config_data *config;
1292         int enumval;
1293
1294         config = talloc_zero(handle->conn, struct fruit_config_data);
1295         if (!config) {
1296                 DEBUG(1, ("talloc_zero() failed\n"));
1297                 errno = ENOMEM;
1298                 return -1;
1299         }
1300
1301         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
1302                                "ressource", fruit_rsrc, FRUIT_RSRC_ADFILE);
1303         if (enumval == -1) {
1304                 DEBUG(1, ("value for %s: ressource type unknown\n",
1305                           FRUIT_PARAM_TYPE_NAME));
1306                 return -1;
1307         }
1308         config->rsrc = (enum fruit_rsrc)enumval;
1309
1310         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
1311                                "metadata", fruit_meta, FRUIT_META_NETATALK);
1312         if (enumval == -1) {
1313                 DEBUG(1, ("value for %s: metadata type unknown\n",
1314                           FRUIT_PARAM_TYPE_NAME));
1315                 return -1;
1316         }
1317         config->meta = (enum fruit_meta)enumval;
1318
1319         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
1320                                "locking", fruit_locking, FRUIT_LOCKING_NONE);
1321         if (enumval == -1) {
1322                 DEBUG(1, ("value for %s: locking type unknown\n",
1323                           FRUIT_PARAM_TYPE_NAME));
1324                 return -1;
1325         }
1326         config->locking = (enum fruit_locking)enumval;
1327
1328         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
1329                                "encoding", fruit_encoding, FRUIT_ENC_PRIVATE);
1330         if (enumval == -1) {
1331                 DEBUG(1, ("value for %s: encoding type unknown\n",
1332                           FRUIT_PARAM_TYPE_NAME));
1333                 return -1;
1334         }
1335         config->encoding = (enum fruit_encoding)enumval;
1336
1337         if (lp_parm_bool(-1, FRUIT_PARAM_TYPE_NAME, "aapl", true)) {
1338                 config->use_aapl = true;
1339         }
1340
1341         if (lp_parm_bool(-1, FRUIT_PARAM_TYPE_NAME, "nfs_aces", true)) {
1342                 config->unix_info_enabled = true;
1343         }
1344
1345         if (lp_parm_bool(SNUM(handle->conn),
1346                          "readdir_attr", "aapl_rsize", true)) {
1347                 config->readdir_attr_rsize = true;
1348         }
1349
1350         if (lp_parm_bool(SNUM(handle->conn),
1351                          "readdir_attr", "aapl_finder_info", true)) {
1352                 config->readdir_attr_finder_info = true;
1353         }
1354
1355         if (lp_parm_bool(SNUM(handle->conn),
1356                          "readdir_attr", "aapl_max_access", true)) {
1357                 config->readdir_attr_max_access = true;
1358         }
1359
1360         SMB_VFS_HANDLE_SET_DATA(handle, config,
1361                                 NULL, struct fruit_config_data,
1362                                 return -1);
1363
1364         return 0;
1365 }
1366
1367 /**
1368  * Prepend "._" to a basename
1369  **/
1370 static int adouble_path(TALLOC_CTX *ctx, const char *path_in, char **path_out)
1371 {
1372         char *parent;
1373         const char *base;
1374
1375         if (!parent_dirname(ctx, path_in, &parent, &base)) {
1376                 return -1;
1377         }
1378
1379         *path_out = talloc_asprintf(ctx, "%s/._%s", parent, base);
1380         if (*path_out == NULL) {
1381                 return -1;
1382         }
1383
1384         return 0;
1385 }
1386
1387 /**
1388  * Allocate and initialize an AfpInfo struct
1389  **/
1390 static AfpInfo *afpinfo_new(TALLOC_CTX *ctx)
1391 {
1392         AfpInfo *ai = talloc_zero(ctx, AfpInfo);
1393         if (ai == NULL) {
1394                 return NULL;
1395         }
1396         ai->afpi_Signature = AFP_Signature;
1397         ai->afpi_Version = AFP_Version;
1398         ai->afpi_BackupTime = AD_DATE_START;
1399         return ai;
1400 }
1401
1402 /**
1403  * Pack an AfpInfo struct into a buffer
1404  *
1405  * Buffer size must be at least AFP_INFO_SIZE
1406  * Returns size of packed buffer
1407  **/
1408 static ssize_t afpinfo_pack(const AfpInfo *ai, char *buf)
1409 {
1410         memset(buf, 0, AFP_INFO_SIZE);
1411
1412         RSIVAL(buf, 0, ai->afpi_Signature);
1413         RSIVAL(buf, 4, ai->afpi_Version);
1414         RSIVAL(buf, 12, ai->afpi_BackupTime);
1415         memcpy(buf + 16, ai->afpi_FinderInfo, sizeof(ai->afpi_FinderInfo));
1416
1417         return AFP_INFO_SIZE;
1418 }
1419
1420 /**
1421  * Unpack a buffer into a AfpInfo structure
1422  *
1423  * Buffer size must be at least AFP_INFO_SIZE
1424  * Returns allocated AfpInfo struct
1425  **/
1426 static AfpInfo *afpinfo_unpack(TALLOC_CTX *ctx, const void *data)
1427 {
1428         AfpInfo *ai = talloc_zero(ctx, AfpInfo);
1429         if (ai == NULL) {
1430                 return NULL;
1431         }
1432
1433         ai->afpi_Signature = RIVAL(data, 0);
1434         ai->afpi_Version = RIVAL(data, 4);
1435         ai->afpi_BackupTime = RIVAL(data, 12);
1436         memcpy(ai->afpi_FinderInfo, (const char *)data + 16,
1437                sizeof(ai->afpi_FinderInfo));
1438
1439         if (ai->afpi_Signature != AFP_Signature
1440             || ai->afpi_Version != AFP_Version) {
1441                 DEBUG(1, ("Bad AfpInfo signature or version\n"));
1442                 TALLOC_FREE(ai);
1443         }
1444
1445         return ai;
1446 }
1447
1448 /**
1449  * Fake an inode number from the md5 hash of the (xattr) name
1450  **/
1451 static SMB_INO_T fruit_inode(const SMB_STRUCT_STAT *sbuf, const char *sname)
1452 {
1453         MD5_CTX ctx;
1454         unsigned char hash[16];
1455         SMB_INO_T result;
1456         char *upper_sname;
1457
1458         upper_sname = talloc_strdup_upper(talloc_tos(), sname);
1459         SMB_ASSERT(upper_sname != NULL);
1460
1461         MD5Init(&ctx);
1462         MD5Update(&ctx, (const unsigned char *)&(sbuf->st_ex_dev),
1463                   sizeof(sbuf->st_ex_dev));
1464         MD5Update(&ctx, (const unsigned char *)&(sbuf->st_ex_ino),
1465                   sizeof(sbuf->st_ex_ino));
1466         MD5Update(&ctx, (unsigned char *)upper_sname,
1467                   talloc_get_size(upper_sname)-1);
1468         MD5Final(hash, &ctx);
1469
1470         TALLOC_FREE(upper_sname);
1471
1472         /* Hopefully all the variation is in the lower 4 (or 8) bytes! */
1473         memcpy(&result, hash, sizeof(result));
1474
1475         DEBUG(10, ("fruit_inode \"%s\": ino=0x%llu\n",
1476                    sname, (unsigned long long)result));
1477
1478         return result;
1479 }
1480
1481 /**
1482  * Ensure ad_fsp is still valid
1483  **/
1484 static bool fruit_fsp_recheck(struct adouble *ad, files_struct *fsp)
1485 {
1486         if (ad->ad_fsp == fsp) {
1487                 return true;
1488         }
1489         ad->ad_fsp = fsp;
1490
1491         return true;
1492 }
1493
1494 static bool add_fruit_stream(TALLOC_CTX *mem_ctx, unsigned int *num_streams,
1495                              struct stream_struct **streams,
1496                              const char *name, off_t size,
1497                              off_t alloc_size)
1498 {
1499         struct stream_struct *tmp;
1500
1501         tmp = talloc_realloc(mem_ctx, *streams, struct stream_struct,
1502                              (*num_streams)+1);
1503         if (tmp == NULL) {
1504                 return false;
1505         }
1506
1507         tmp[*num_streams].name = talloc_asprintf(tmp, "%s:$DATA", name);
1508         if (tmp[*num_streams].name == NULL) {
1509                 return false;
1510         }
1511
1512         tmp[*num_streams].size = size;
1513         tmp[*num_streams].alloc_size = alloc_size;
1514
1515         *streams = tmp;
1516         *num_streams += 1;
1517         return true;
1518 }
1519
1520 static bool empty_finderinfo(const struct adouble *ad)
1521 {
1522
1523         char emptybuf[ADEDLEN_FINDERI] = {0};
1524         if (memcmp(emptybuf,
1525                    ad_entry(ad, ADEID_FINDERI),
1526                    ADEDLEN_FINDERI) == 0) {
1527                 return true;
1528         }
1529         return false;
1530 }
1531
1532 /**
1533  * Update btime with btime from Netatalk
1534  **/
1535 static void update_btime(vfs_handle_struct *handle,
1536                          struct smb_filename *smb_fname)
1537 {
1538         uint32_t t;
1539         struct timespec creation_time = {0};
1540         struct adouble *ad;
1541
1542         ad = ad_get(talloc_tos(), handle, smb_fname->base_name, ADOUBLE_META);
1543         if (ad == NULL) {
1544                 return;
1545         }
1546         if (ad_getdate(ad, AD_DATE_UNIX | AD_DATE_CREATE, &t) != 0) {
1547                 TALLOC_FREE(ad);
1548                 return;
1549         }
1550         TALLOC_FREE(ad);
1551
1552         creation_time.tv_sec = convert_uint32_t_to_time_t(t);
1553         update_stat_ex_create_time(&smb_fname->st, creation_time);
1554
1555         return;
1556 }
1557
1558 /**
1559  * Map an access mask to a Netatalk single byte byte range lock
1560  **/
1561 static off_t access_to_netatalk_brl(enum apple_fork fork_type,
1562                                     uint32_t access_mask)
1563 {
1564         off_t offset;
1565
1566         switch (access_mask) {
1567         case FILE_READ_DATA:
1568                 offset = AD_FILELOCK_OPEN_RD;
1569                 break;
1570
1571         case FILE_WRITE_DATA:
1572         case FILE_APPEND_DATA:
1573                 offset = AD_FILELOCK_OPEN_WR;
1574                 break;
1575
1576         default:
1577                 offset = AD_FILELOCK_OPEN_NONE;
1578                 break;
1579         }
1580
1581         if (fork_type == APPLE_FORK_RSRC) {
1582                 if (offset == AD_FILELOCK_OPEN_NONE) {
1583                         offset = AD_FILELOCK_RSRC_OPEN_NONE;
1584                 } else {
1585                         offset += 2;
1586                 }
1587         }
1588
1589         return offset;
1590 }
1591
1592 /**
1593  * Map a deny mode to a Netatalk brl
1594  **/
1595 static off_t denymode_to_netatalk_brl(enum apple_fork fork_type,
1596                                       uint32_t deny_mode)
1597 {
1598         off_t offset;
1599
1600         switch (deny_mode) {
1601         case DENY_READ:
1602                 offset = AD_FILELOCK_DENY_RD;
1603                 break;
1604
1605         case DENY_WRITE:
1606                 offset = AD_FILELOCK_DENY_WR;
1607                 break;
1608
1609         default:
1610                 smb_panic("denymode_to_netatalk_brl: bad deny mode\n");
1611         }
1612
1613         if (fork_type == APPLE_FORK_RSRC) {
1614                 offset += 2;
1615         }
1616
1617         return offset;
1618 }
1619
1620 /**
1621  * Call fcntl() with an exclusive F_GETLK request in order to
1622  * determine if there's an exisiting shared lock
1623  *
1624  * @return true if the requested lock was found or any error occured
1625  *         false if the lock was not found
1626  **/
1627 static bool test_netatalk_lock(files_struct *fsp, off_t in_offset)
1628 {
1629         bool result;
1630         off_t offset = in_offset;
1631         off_t len = 1;
1632         int type = F_WRLCK;
1633         pid_t pid;
1634
1635         result = SMB_VFS_GETLOCK(fsp, &offset, &len, &type, &pid);
1636         if (result == false) {
1637                 return true;
1638         }
1639
1640         if (type != F_UNLCK) {
1641                 return true;
1642         }
1643
1644         return false;
1645 }
1646
1647 static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
1648                                    files_struct *fsp,
1649                                    uint32_t access_mask,
1650                                    uint32_t deny_mode)
1651 {
1652         NTSTATUS status = NT_STATUS_OK;
1653         struct byte_range_lock *br_lck = NULL;
1654         bool open_for_reading, open_for_writing, deny_read, deny_write;
1655         off_t off;
1656
1657         /* FIXME: hardcoded data fork, add resource fork */
1658         enum apple_fork fork_type = APPLE_FORK_DATA;
1659
1660         DEBUG(10, ("fruit_check_access: %s, am: %s/%s, dm: %s/%s\n",
1661                   fsp_str_dbg(fsp),
1662                   access_mask & FILE_READ_DATA ? "READ" :"-",
1663                   access_mask & FILE_WRITE_DATA ? "WRITE" : "-",
1664                   deny_mode & DENY_READ ? "DENY_READ" : "-",
1665                   deny_mode & DENY_WRITE ? "DENY_WRITE" : "-"));
1666
1667         /*
1668          * Check read access and deny read mode
1669          */
1670         if ((access_mask & FILE_READ_DATA) || (deny_mode & DENY_READ)) {
1671                 /* Check access */
1672                 open_for_reading = test_netatalk_lock(
1673                         fsp, access_to_netatalk_brl(fork_type, FILE_READ_DATA));
1674
1675                 deny_read = test_netatalk_lock(
1676                         fsp, denymode_to_netatalk_brl(fork_type, DENY_READ));
1677
1678                 DEBUG(10, ("read: %s, deny_write: %s\n",
1679                           open_for_reading == true ? "yes" : "no",
1680                           deny_read == true ? "yes" : "no"));
1681
1682                 if (((access_mask & FILE_READ_DATA) && deny_read)
1683                     || ((deny_mode & DENY_READ) && open_for_reading)) {
1684                         return NT_STATUS_SHARING_VIOLATION;
1685                 }
1686
1687                 /* Set locks */
1688                 if (access_mask & FILE_READ_DATA) {
1689                         off = access_to_netatalk_brl(fork_type, FILE_READ_DATA);
1690                         br_lck = do_lock(
1691                                 handle->conn->sconn->msg_ctx, fsp,
1692                                 fsp->op->global->open_persistent_id, 1, off,
1693                                 READ_LOCK, POSIX_LOCK, false,
1694                                 &status, NULL);
1695
1696                         if (!NT_STATUS_IS_OK(status))  {
1697                                 return status;
1698                         }
1699                         TALLOC_FREE(br_lck);
1700                 }
1701
1702                 if (deny_mode & DENY_READ) {
1703                         off = denymode_to_netatalk_brl(fork_type, DENY_READ);
1704                         br_lck = do_lock(
1705                                 handle->conn->sconn->msg_ctx, fsp,
1706                                 fsp->op->global->open_persistent_id, 1, off,
1707                                 READ_LOCK, POSIX_LOCK, false,
1708                                 &status, NULL);
1709
1710                         if (!NT_STATUS_IS_OK(status)) {
1711                                 return status;
1712                         }
1713                         TALLOC_FREE(br_lck);
1714                 }
1715         }
1716
1717         /*
1718          * Check write access and deny write mode
1719          */
1720         if ((access_mask & FILE_WRITE_DATA) || (deny_mode & DENY_WRITE)) {
1721                 /* Check access */
1722                 open_for_writing = test_netatalk_lock(
1723                         fsp, access_to_netatalk_brl(fork_type, FILE_WRITE_DATA));
1724
1725                 deny_write = test_netatalk_lock(
1726                         fsp, denymode_to_netatalk_brl(fork_type, DENY_WRITE));
1727
1728                 DEBUG(10, ("write: %s, deny_write: %s\n",
1729                           open_for_writing == true ? "yes" : "no",
1730                           deny_write == true ? "yes" : "no"));
1731
1732                 if (((access_mask & FILE_WRITE_DATA) && deny_write)
1733                     || ((deny_mode & DENY_WRITE) && open_for_writing)) {
1734                         return NT_STATUS_SHARING_VIOLATION;
1735                 }
1736
1737                 /* Set locks */
1738                 if (access_mask & FILE_WRITE_DATA) {
1739                         off = access_to_netatalk_brl(fork_type, FILE_WRITE_DATA);
1740                         br_lck = do_lock(
1741                                 handle->conn->sconn->msg_ctx, fsp,
1742                                 fsp->op->global->open_persistent_id, 1, off,
1743                                 READ_LOCK, POSIX_LOCK, false,
1744                                 &status, NULL);
1745
1746                         if (!NT_STATUS_IS_OK(status)) {
1747                                 return status;
1748                         }
1749                         TALLOC_FREE(br_lck);
1750
1751                 }
1752                 if (deny_mode & DENY_WRITE) {
1753                         off = denymode_to_netatalk_brl(fork_type, DENY_WRITE);
1754                         br_lck = do_lock(
1755                                 handle->conn->sconn->msg_ctx, fsp,
1756                                 fsp->op->global->open_persistent_id, 1, off,
1757                                 READ_LOCK, POSIX_LOCK, false,
1758                                 &status, NULL);
1759
1760                         if (!NT_STATUS_IS_OK(status)) {
1761                                 return status;
1762                         }
1763                         TALLOC_FREE(br_lck);
1764                 }
1765         }
1766
1767         TALLOC_FREE(br_lck);
1768
1769         return status;
1770 }
1771
1772 static NTSTATUS check_aapl(vfs_handle_struct *handle,
1773                            struct smb_request *req,
1774                            const struct smb2_create_blobs *in_context_blobs,
1775                            struct smb2_create_blobs *out_context_blobs)
1776 {
1777         struct fruit_config_data *config;
1778         NTSTATUS status;
1779         struct smb2_create_blob *aapl = NULL;
1780         uint32_t cmd;
1781         bool ok;
1782         uint8_t p[16];
1783         DATA_BLOB blob = data_blob_talloc(req, NULL, 0);
1784         uint64_t req_bitmap, client_caps;
1785         uint64_t server_caps = SMB2_CRTCTX_AAPL_UNIX_BASED;
1786         smb_ucs2_t *model;
1787         size_t modellen;
1788
1789         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
1790                                 return NT_STATUS_UNSUCCESSFUL);
1791
1792         if (!config->use_aapl
1793             || in_context_blobs == NULL
1794             || out_context_blobs == NULL) {
1795                 return NT_STATUS_OK;
1796         }
1797
1798         aapl = smb2_create_blob_find(in_context_blobs,
1799                                      SMB2_CREATE_TAG_AAPL);
1800         if (aapl == NULL) {
1801                 return NT_STATUS_OK;
1802         }
1803
1804         if (aapl->data.length != 24) {
1805                 DEBUG(1, ("unexpected AAPL ctxt legnth: %ju\n",
1806                           (uintmax_t)aapl->data.length));
1807                 return NT_STATUS_INVALID_PARAMETER;
1808         }
1809
1810         cmd = IVAL(aapl->data.data, 0);
1811         if (cmd != SMB2_CRTCTX_AAPL_SERVER_QUERY) {
1812                 DEBUG(1, ("unsupported AAPL cmd: %d\n", cmd));
1813                 return NT_STATUS_INVALID_PARAMETER;
1814         }
1815
1816         req_bitmap = BVAL(aapl->data.data, 8);
1817         client_caps = BVAL(aapl->data.data, 16);
1818
1819         SIVAL(p, 0, SMB2_CRTCTX_AAPL_SERVER_QUERY);
1820         SIVAL(p, 4, 0);
1821         SBVAL(p, 8, req_bitmap);
1822         ok = data_blob_append(req, &blob, p, 16);
1823         if (!ok) {
1824                 return NT_STATUS_UNSUCCESSFUL;
1825         }
1826
1827         if (req_bitmap & SMB2_CRTCTX_AAPL_SERVER_CAPS) {
1828                 if ((client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR) &&
1829                     (handle->conn->tcon->compat->fs_capabilities & FILE_NAMED_STREAMS)) {
1830                         server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR;
1831                         config->readdir_attr_enabled = true;
1832                 }
1833
1834                 /*
1835                  * The client doesn't set the flag, so we can't check
1836                  * for it and just set it unconditionally
1837                  */
1838                 if (config->unix_info_enabled) {
1839                         server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_NFS_ACE;
1840                 }
1841
1842                 SBVAL(p, 0, server_caps);
1843                 ok = data_blob_append(req, &blob, p, 8);
1844                 if (!ok) {
1845                         return NT_STATUS_UNSUCCESSFUL;
1846                 }
1847         }
1848
1849         if (req_bitmap & SMB2_CRTCTX_AAPL_VOLUME_CAPS) {
1850                 SBVAL(p, 0,
1851                       lp_case_sensitive(SNUM(handle->conn->tcon->compat)) ?
1852                       SMB2_CRTCTX_AAPL_CASE_SENSITIVE : 0);
1853                 ok = data_blob_append(req, &blob, p, 8);
1854                 if (!ok) {
1855                         return NT_STATUS_UNSUCCESSFUL;
1856                 }
1857         }
1858
1859         if (req_bitmap & SMB2_CRTCTX_AAPL_MODEL_INFO) {
1860                 ok = convert_string_talloc(req,
1861                                            CH_UNIX, CH_UTF16LE,
1862                                            "Samba", strlen("Samba"),
1863                                            &model, &modellen);
1864                 if (!ok) {
1865                         return NT_STATUS_UNSUCCESSFUL;
1866                 }
1867
1868                 SIVAL(p, 0, 0);
1869                 SIVAL(p + 4, 0, modellen);
1870                 ok = data_blob_append(req, &blob, p, 8);
1871                 if (!ok) {
1872                         talloc_free(model);
1873                         return NT_STATUS_UNSUCCESSFUL;
1874                 }
1875
1876                 ok = data_blob_append(req, &blob, model, modellen);
1877                 talloc_free(model);
1878                 if (!ok) {
1879                         return NT_STATUS_UNSUCCESSFUL;
1880                 }
1881         }
1882
1883         status = smb2_create_blob_add(out_context_blobs,
1884                                       out_context_blobs,
1885                                       SMB2_CREATE_TAG_AAPL,
1886                                       blob);
1887
1888         return status;
1889 }
1890
1891 static NTSTATUS readdir_attr_macmeta(struct vfs_handle_struct *handle,
1892                                      const struct smb_filename *smb_fname,
1893                                      struct readdir_attr_data *attr_data)
1894 {
1895         NTSTATUS status = NT_STATUS_OK;
1896         uint32_t date_added;
1897         struct adouble *ad = NULL;
1898         struct fruit_config_data *config = NULL;
1899
1900         SMB_VFS_HANDLE_GET_DATA(handle, config,
1901                                 struct fruit_config_data,
1902                                 return NT_STATUS_UNSUCCESSFUL);
1903
1904
1905         /* Ensure we return a default value in the creation_date field */
1906         RSIVAL(&attr_data->attr_data.aapl.finder_info, 12, AD_DATE_START);
1907
1908         /*
1909          * Resource fork length
1910          */
1911
1912         if (config->readdir_attr_rsize) {
1913                 ad = ad_get(talloc_tos(), handle, smb_fname->base_name,
1914                             ADOUBLE_RSRC);
1915                 if (ad) {
1916                         attr_data->attr_data.aapl.rfork_size = ad_getentrylen(
1917                                 ad, ADEID_RFORK);
1918                         TALLOC_FREE(ad);
1919                 }
1920         }
1921
1922         /*
1923          * FinderInfo
1924          */
1925
1926         if (config->readdir_attr_finder_info) {
1927                 ad = ad_get(talloc_tos(), handle, smb_fname->base_name,
1928                             ADOUBLE_META);
1929                 if (ad) {
1930                         if (S_ISREG(smb_fname->st.st_ex_mode)) {
1931                                 /* finder_type */
1932                                 memcpy(&attr_data->attr_data.aapl.finder_info[0],
1933                                        ad_entry(ad, ADEID_FINDERI), 4);
1934
1935                                 /* finder_creator */
1936                                 memcpy(&attr_data->attr_data.aapl.finder_info[0] + 4,
1937                                        ad_entry(ad, ADEID_FINDERI) + 4, 4);
1938                         }
1939
1940                         /* finder_flags */
1941                         memcpy(&attr_data->attr_data.aapl.finder_info[0] + 8,
1942                                ad_entry(ad, ADEID_FINDERI) + 8, 2);
1943
1944                         /* finder_ext_flags */
1945                         memcpy(&attr_data->attr_data.aapl.finder_info[0] + 10,
1946                                ad_entry(ad, ADEID_FINDERI) + 24, 2);
1947
1948                         /* creation date */
1949                         date_added = convert_time_t_to_uint32_t(
1950                                 smb_fname->st.st_ex_btime.tv_sec - AD_DATE_DELTA);
1951                         RSIVAL(&attr_data->attr_data.aapl.finder_info[0], 12, date_added);
1952
1953                         TALLOC_FREE(ad);
1954                 }
1955         }
1956
1957         TALLOC_FREE(ad);
1958         return status;
1959 }
1960
1961 /* Search MS NFS style ACE with UNIX mode */
1962 static NTSTATUS check_ms_nfs(vfs_handle_struct *handle,
1963                              files_struct *fsp,
1964                              const struct security_descriptor *psd,
1965                              mode_t *pmode,
1966                              bool *pdo_chmod)
1967 {
1968         int i;
1969         struct fruit_config_data *config = NULL;
1970
1971         *pdo_chmod = false;
1972
1973         SMB_VFS_HANDLE_GET_DATA(handle, config,
1974                                 struct fruit_config_data,
1975                                 return NT_STATUS_UNSUCCESSFUL);
1976
1977         if (psd->dacl == NULL || !config->unix_info_enabled) {
1978                 return NT_STATUS_OK;
1979         }
1980
1981         for (i = 0; i < psd->dacl->num_aces; i++) {
1982                 if (dom_sid_compare_domain(
1983                             &global_sid_Unix_NFS_Mode,
1984                             &psd->dacl->aces[i].trustee) == 0) {
1985                         *pmode = (mode_t)psd->dacl->aces[i].trustee.sub_auths[2];
1986                         *pmode &= (S_IRWXU | S_IRWXG | S_IRWXO);
1987                         *pdo_chmod = true;
1988
1989                         DEBUG(10, ("MS NFS chmod request %s, %04o\n",
1990                                    fsp_str_dbg(fsp), (unsigned)(*pmode)));
1991                         break;
1992                 }
1993         }
1994
1995         return NT_STATUS_OK;
1996 }
1997
1998 /****************************************************************************
1999  * VFS ops
2000  ****************************************************************************/
2001
2002 static int fruit_connect(vfs_handle_struct *handle,
2003                          const char *service,
2004                          const char *user)
2005 {
2006         int rc;
2007         char *list = NULL, *newlist = NULL;
2008         struct fruit_config_data *config;
2009
2010         DEBUG(10, ("fruit_connect\n"));
2011
2012         rc = SMB_VFS_NEXT_CONNECT(handle, service, user);
2013         if (rc < 0) {
2014                 return rc;
2015         }
2016
2017         list = lp_veto_files(talloc_tos(), SNUM(handle->conn));
2018
2019         if (list) {
2020                 if (strstr(list, "/" ADOUBLE_NAME_PREFIX "*/") == NULL) {
2021                         newlist = talloc_asprintf(
2022                                 list,
2023                                 "%s/" ADOUBLE_NAME_PREFIX "*/",
2024                                 list);
2025                         lp_do_parameter(SNUM(handle->conn),
2026                                         "veto files",
2027                                         newlist);
2028                 }
2029         } else {
2030                 lp_do_parameter(SNUM(handle->conn),
2031                                 "veto files",
2032                                 "/" ADOUBLE_NAME_PREFIX "*/");
2033         }
2034
2035         TALLOC_FREE(list);
2036
2037         rc = init_fruit_config(handle);
2038         if (rc != 0) {
2039                 return rc;
2040         }
2041
2042         SMB_VFS_HANDLE_GET_DATA(handle, config,
2043                                 struct fruit_config_data, return -1);
2044
2045         if (config->encoding == FRUIT_ENC_NATIVE) {
2046                 lp_do_parameter(
2047                         SNUM(handle->conn),
2048                         "catia:mappings",
2049                         "0x01:0xf001,0x02:0xf002,0x03:0xf003,0x04:0xf004,"
2050                         "0x05:0xf005,0x06:0xf006,0x07:0xf007,0x08:0xf008,"
2051                         "0x09:0xf009,0x0a:0xf00a,0x0b:0xf00b,0x0c:0xf00c,"
2052                         "0x0d:0xf00d,0x0e:0xf00e,0x0f:0xf00f,0x10:0xf010,"
2053                         "0x11:0xf011,0x12:0xf012,0x13:0xf013,0x14:0xf014,"
2054                         "0x15:0xf015,0x16:0xf016,0x17:0xf017,0x18:0xf018,"
2055                         "0x19:0xf019,0x1a:0xf01a,0x1b:0xf01b,0x1c:0xf01c,"
2056                         "0x1d:0xf01d,0x1e:0xf01e,0x1f:0xf01f,"
2057                         "0x22:0xf020,0x2a:0xf021,0x3a:0xf022,0x3c:0xf023,"
2058                         "0x3e:0xf024,0x3f:0xf025,0x5c:0xf026,0x7c:0xf027,"
2059                         "0x0d:0xf00d");
2060         }
2061
2062         return rc;
2063 }
2064
2065 static int fruit_open_meta(vfs_handle_struct *handle,
2066                            struct smb_filename *smb_fname,
2067                            files_struct *fsp, int flags, mode_t mode)
2068 {
2069         int rc = 0;
2070         struct fruit_config_data *config = NULL;
2071         struct smb_filename *smb_fname_base = NULL;
2072         int baseflags;
2073         int hostfd = -1;
2074         struct adouble *ad = NULL;
2075
2076         DEBUG(10, ("fruit_open_meta for %s\n", smb_fname_str_dbg(smb_fname)));
2077
2078         SMB_VFS_HANDLE_GET_DATA(handle, config,
2079                                 struct fruit_config_data, return -1);
2080
2081         if (config->meta == FRUIT_META_STREAM) {
2082                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
2083         }
2084
2085         /* Create an smb_filename with stream_name == NULL. */
2086         smb_fname_base = synthetic_smb_fname(talloc_tos(),
2087                                              smb_fname->base_name, NULL, NULL);
2088
2089         if (smb_fname_base == NULL) {
2090                 errno = ENOMEM;
2091                 rc = -1;
2092                 goto exit;
2093         }
2094
2095         /*
2096          * We use baseflags to turn off nasty side-effects when opening the
2097          * underlying file.
2098          */
2099         baseflags = flags;
2100         baseflags &= ~O_TRUNC;
2101         baseflags &= ~O_EXCL;
2102         baseflags &= ~O_CREAT;
2103
2104         hostfd = SMB_VFS_OPEN(handle->conn, smb_fname_base, fsp,
2105                               baseflags, mode);
2106
2107         /*
2108          * It is legit to open a stream on a directory, but the base
2109          * fd has to be read-only.
2110          */
2111         if ((hostfd == -1) && (errno == EISDIR)) {
2112                 baseflags &= ~O_ACCMODE;
2113                 baseflags |= O_RDONLY;
2114                 hostfd = SMB_VFS_OPEN(handle->conn, smb_fname_base, fsp,
2115                                       baseflags, mode);
2116         }
2117
2118         TALLOC_FREE(smb_fname_base);
2119
2120         if (hostfd == -1) {
2121                 rc = -1;
2122                 goto exit;
2123         }
2124
2125         if (flags & (O_CREAT | O_TRUNC)) {
2126                 /*
2127                  * The attribute does not exist or needs to be truncated,
2128                  * create an AppleDouble EA
2129                  */
2130                 ad = ad_init(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2131                              handle, ADOUBLE_META, fsp);
2132                 if (ad == NULL) {
2133                         rc = -1;
2134                         goto exit;
2135                 }
2136
2137                 rc = ad_write(ad, smb_fname->base_name);
2138                 if (rc != 0) {
2139                         rc = -1;
2140                         goto exit;
2141                 }
2142         } else {
2143                 ad = ad_alloc(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2144                               handle, ADOUBLE_META, fsp);
2145                 if (ad == NULL) {
2146                         rc = -1;
2147                         goto exit;
2148                 }
2149                 if (ad_read(ad, smb_fname->base_name) == -1) {
2150                         rc = -1;
2151                         goto exit;
2152                 }
2153         }
2154
2155 exit:
2156         DEBUG(10, ("fruit_open meta rc=%d, fd=%d\n", rc, hostfd));
2157         if (rc != 0) {
2158                 int saved_errno = errno;
2159                 if (hostfd >= 0) {
2160                         /*
2161                          * BUGBUGBUG -- we would need to call
2162                          * fd_close_posix here, but we don't have a
2163                          * full fsp yet
2164                          */
2165                         fsp->fh->fd = hostfd;
2166                         SMB_VFS_CLOSE(fsp);
2167                 }
2168                 hostfd = -1;
2169                 errno = saved_errno;
2170         }
2171         return hostfd;
2172 }
2173
2174 static int fruit_open_rsrc(vfs_handle_struct *handle,
2175                            struct smb_filename *smb_fname,
2176                            files_struct *fsp, int flags, mode_t mode)
2177 {
2178         int rc = 0;
2179         struct fruit_config_data *config = NULL;
2180         struct adouble *ad = NULL;
2181         struct smb_filename *smb_fname_base = NULL;
2182         char *adpath = NULL;
2183         int hostfd = -1;
2184
2185         DEBUG(10, ("fruit_open_rsrc for %s\n", smb_fname_str_dbg(smb_fname)));
2186
2187         SMB_VFS_HANDLE_GET_DATA(handle, config,
2188                                 struct fruit_config_data, return -1);
2189
2190         switch (config->rsrc) {
2191         case FRUIT_RSRC_STREAM:
2192                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
2193         case FRUIT_RSRC_XATTR:
2194 #ifdef HAVE_ATTROPEN
2195                 hostfd = attropen(smb_fname->base_name,
2196                                   AFPRESOURCE_EA_NETATALK, flags, mode);
2197                 if (hostfd == -1) {
2198                         return -1;
2199                 }
2200                 ad = ad_init(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2201                              handle, ADOUBLE_RSRC, fsp);
2202                 if (ad == NULL) {
2203                         rc = -1;
2204                         goto exit;
2205                 }
2206                 goto exit;
2207 #else
2208                 errno = ENOTSUP;
2209                 return -1;
2210 #endif
2211         default:
2212                 break;
2213         }
2214
2215         if (!(flags & O_CREAT) && !VALID_STAT(smb_fname->st)) {
2216                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
2217                 if (rc != 0) {
2218                         rc = -1;
2219                         goto exit;
2220                 }
2221         }
2222
2223         if (VALID_STAT(smb_fname->st) && S_ISDIR(smb_fname->st.st_ex_mode)) {
2224                 /* sorry, but directories don't habe a resource fork */
2225                 rc = -1;
2226                 goto exit;
2227         }
2228
2229         rc = adouble_path(talloc_tos(), smb_fname->base_name, &adpath);
2230         if (rc != 0) {
2231                 goto exit;
2232         }
2233
2234         /* Create an smb_filename with stream_name == NULL. */
2235         smb_fname_base = synthetic_smb_fname(talloc_tos(),
2236                                              adpath, NULL, NULL);
2237         if (smb_fname_base == NULL) {
2238                 errno = ENOMEM;
2239                 rc = -1;
2240                 goto exit;
2241         }
2242
2243         /* Sanitize flags */
2244         if (flags & O_WRONLY) {
2245                 /* We always need read access for the metadata header too */
2246                 flags &= ~O_WRONLY;
2247                 flags |= O_RDWR;
2248         }
2249
2250         hostfd = SMB_VFS_OPEN(handle->conn, smb_fname_base, fsp,
2251                               flags, mode);
2252         if (hostfd == -1) {
2253                 rc = -1;
2254                 goto exit;
2255         }
2256
2257         /* REVIEW: we need this in ad_write() */
2258         fsp->fh->fd = hostfd;
2259
2260         if (flags & (O_CREAT | O_TRUNC)) {
2261                 ad = ad_init(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2262                              handle, ADOUBLE_RSRC, fsp);
2263                 if (ad == NULL) {
2264                         rc = -1;
2265                         goto exit;
2266                 }
2267                 rc = ad_write(ad, smb_fname->base_name);
2268                 if (rc != 0) {
2269                         rc = -1;
2270                         goto exit;
2271                 }
2272         } else {
2273                 ad = ad_alloc(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2274                               handle, ADOUBLE_RSRC, fsp);
2275                 if (ad == NULL) {
2276                         rc = -1;
2277                         goto exit;
2278                 }
2279                 if (ad_read(ad, smb_fname->base_name) == -1) {
2280                         rc = -1;
2281                         goto exit;
2282                 }
2283         }
2284
2285 exit:
2286
2287         TALLOC_FREE(adpath);
2288         TALLOC_FREE(smb_fname_base);
2289
2290         DEBUG(10, ("fruit_open resource fork: rc=%d, fd=%d\n", rc, hostfd));
2291         if (rc != 0) {
2292                 int saved_errno = errno;
2293                 if (hostfd >= 0) {
2294                         /*
2295                          * BUGBUGBUG -- we would need to call
2296                          * fd_close_posix here, but we don't have a
2297                          * full fsp yet
2298                          */
2299                         fsp->fh->fd = hostfd;
2300                         SMB_VFS_CLOSE(fsp);
2301                 }
2302                 hostfd = -1;
2303                 errno = saved_errno;
2304         }
2305         return hostfd;
2306 }
2307
2308 static int fruit_open(vfs_handle_struct *handle,
2309                       struct smb_filename *smb_fname,
2310                       files_struct *fsp, int flags, mode_t mode)
2311 {
2312         DEBUG(10, ("fruit_open called for %s\n",
2313                    smb_fname_str_dbg(smb_fname)));
2314
2315         if (!is_ntfs_stream_smb_fname(smb_fname)) {
2316                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
2317         }
2318
2319         if (is_afpinfo_stream(smb_fname)) {
2320                 return fruit_open_meta(handle, smb_fname, fsp, flags, mode);
2321         } else if (is_afpresource_stream(smb_fname)) {
2322                 return fruit_open_rsrc(handle, smb_fname, fsp, flags, mode);
2323         }
2324
2325         return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
2326 }
2327
2328 static int fruit_rename(struct vfs_handle_struct *handle,
2329                         const struct smb_filename *smb_fname_src,
2330                         const struct smb_filename *smb_fname_dst)
2331 {
2332         int rc = -1;
2333         char *src_adouble_path = NULL;
2334         char *dst_adouble_path = NULL;
2335         struct fruit_config_data *config = NULL;
2336
2337         rc = SMB_VFS_NEXT_RENAME(handle, smb_fname_src, smb_fname_dst);
2338
2339         if (!VALID_STAT(smb_fname_src->st)
2340             || !S_ISREG(smb_fname_src->st.st_ex_mode)) {
2341                 return rc;
2342         }
2343
2344         SMB_VFS_HANDLE_GET_DATA(handle, config,
2345                                 struct fruit_config_data, return -1);
2346
2347         if (config->rsrc == FRUIT_RSRC_XATTR) {
2348                 return rc;
2349         }
2350
2351         rc = adouble_path(talloc_tos(), smb_fname_src->base_name,
2352                           &src_adouble_path);
2353         if (rc != 0) {
2354                 goto done;
2355         }
2356         rc = adouble_path(talloc_tos(), smb_fname_dst->base_name,
2357                           &dst_adouble_path);
2358         if (rc != 0) {
2359                 goto done;
2360         }
2361
2362         DEBUG(10, ("fruit_rename: %s -> %s\n",
2363                    src_adouble_path, dst_adouble_path));
2364
2365         rc = rename(src_adouble_path, dst_adouble_path);
2366         if (errno == ENOENT) {
2367                 rc = 0;
2368         }
2369
2370         TALLOC_FREE(src_adouble_path);
2371         TALLOC_FREE(dst_adouble_path);
2372
2373 done:
2374         return rc;
2375 }
2376
2377 static int fruit_unlink(vfs_handle_struct *handle,
2378                         const struct smb_filename *smb_fname)
2379 {
2380         int rc = -1;
2381         struct fruit_config_data *config = NULL;
2382         char *adp = NULL;
2383
2384         if (!is_ntfs_stream_smb_fname(smb_fname)) {
2385                 return SMB_VFS_NEXT_UNLINK(handle, smb_fname);
2386         }
2387
2388         SMB_VFS_HANDLE_GET_DATA(handle, config,
2389                                 struct fruit_config_data, return -1);
2390
2391         if (is_afpinfo_stream(smb_fname)) {
2392                 if (config->meta == FRUIT_META_STREAM) {
2393                         rc = SMB_VFS_NEXT_UNLINK(handle, smb_fname);
2394                 } else {
2395                         rc = SMB_VFS_REMOVEXATTR(handle->conn,
2396                                                  smb_fname->base_name,
2397                                                  AFPINFO_EA_NETATALK);
2398                 }
2399         } else if (is_afpresource_stream(smb_fname)) {
2400                 if (config->rsrc == FRUIT_RSRC_ADFILE) {
2401                         rc = adouble_path(talloc_tos(),
2402                                           smb_fname->base_name, &adp);
2403                         if (rc != 0) {
2404                                 return -1;
2405                         }
2406                         /* FIXME: direct unlink(), missing smb_fname */
2407                         rc = unlink(adp);
2408                         if ((rc == -1) && (errno == ENOENT)) {
2409                                 rc = 0;
2410                         }
2411                 } else {
2412                         rc = SMB_VFS_REMOVEXATTR(handle->conn,
2413                                      smb_fname->base_name,
2414                                      AFPRESOURCE_EA_NETATALK);
2415                 }
2416         } else {
2417                 rc = SMB_VFS_NEXT_UNLINK(handle, smb_fname);
2418         }
2419
2420         TALLOC_FREE(adp);
2421         return rc;
2422 }
2423
2424 static int fruit_chmod(vfs_handle_struct *handle,
2425                        const char *path,
2426                        mode_t mode)
2427 {
2428         int rc = -1;
2429         char *adp = NULL;
2430         struct fruit_config_data *config = NULL;
2431         SMB_STRUCT_STAT sb;
2432
2433         rc = SMB_VFS_NEXT_CHMOD(handle, path, mode);
2434         if (rc != 0) {
2435                 return rc;
2436         }
2437
2438         SMB_VFS_HANDLE_GET_DATA(handle, config,
2439                                 struct fruit_config_data, return -1);
2440
2441         if (config->rsrc == FRUIT_RSRC_XATTR) {
2442                 return 0;
2443         }
2444
2445         /* FIXME: direct sys_lstat(), missing smb_fname */
2446         rc = sys_lstat(path, &sb, false);
2447         if (rc != 0 || !S_ISREG(sb.st_ex_mode)) {
2448                 return rc;
2449         }
2450
2451         rc = adouble_path(talloc_tos(), path, &adp);
2452         if (rc != 0) {
2453                 return -1;
2454         }
2455
2456         DEBUG(10, ("fruit_chmod: %s\n", adp));
2457
2458         rc = SMB_VFS_NEXT_CHMOD(handle, adp, mode);
2459         if (errno == ENOENT) {
2460                 rc = 0;
2461         }
2462
2463         TALLOC_FREE(adp);
2464         return rc;
2465 }
2466
2467 static int fruit_chown(vfs_handle_struct *handle,
2468                        const char *path,
2469                        uid_t uid,
2470                        gid_t gid)
2471 {
2472         int rc = -1;
2473         char *adp = NULL;
2474         struct fruit_config_data *config = NULL;
2475         SMB_STRUCT_STAT sb;
2476
2477         rc = SMB_VFS_NEXT_CHOWN(handle, path, uid, gid);
2478         if (rc != 0) {
2479                 return rc;
2480         }
2481
2482         SMB_VFS_HANDLE_GET_DATA(handle, config,
2483                                 struct fruit_config_data, return -1);
2484
2485         if (config->rsrc == FRUIT_RSRC_XATTR) {
2486                 return rc;
2487         }
2488
2489         /* FIXME: direct sys_lstat(), missing smb_fname */
2490         rc = sys_lstat(path, &sb, false);
2491         if (rc != 0 || !S_ISREG(sb.st_ex_mode)) {
2492                 return rc;
2493         }
2494
2495         rc = adouble_path(talloc_tos(), path, &adp);
2496         if (rc != 0) {
2497                 goto done;
2498         }
2499
2500         DEBUG(10, ("fruit_chown: %s\n", adp));
2501
2502         rc = SMB_VFS_NEXT_CHOWN(handle, adp, uid, gid);
2503         if (errno == ENOENT) {
2504                 rc = 0;
2505         }
2506
2507  done:
2508         TALLOC_FREE(adp);
2509         return rc;
2510 }
2511
2512 static int fruit_rmdir(struct vfs_handle_struct *handle, const char *path)
2513 {
2514         DIR *dh = NULL;
2515         struct dirent *de;
2516         struct fruit_config_data *config;
2517
2518         SMB_VFS_HANDLE_GET_DATA(handle, config,
2519                                 struct fruit_config_data, return -1);
2520
2521         if (!handle->conn->cwd || !path || (config->rsrc == FRUIT_RSRC_XATTR)) {
2522                 goto exit_rmdir;
2523         }
2524
2525         /*
2526          * Due to there is no way to change bDeleteVetoFiles variable
2527          * from this module, need to clean up ourselves
2528          */
2529         dh = opendir(path);
2530         if (dh == NULL) {
2531                 goto exit_rmdir;
2532         }
2533
2534         while ((de = readdir(dh)) != NULL) {
2535                 if ((strncmp(de->d_name,
2536                              ADOUBLE_NAME_PREFIX,
2537                              strlen(ADOUBLE_NAME_PREFIX))) == 0) {
2538                         char *p = talloc_asprintf(talloc_tos(),
2539                                                   "%s/%s",
2540                                                   path, de->d_name);
2541                         if (p == NULL) {
2542                                 goto exit_rmdir;
2543                         }
2544                         DEBUG(10, ("fruit_rmdir: delete %s\n", p));
2545                         (void)unlink(p);
2546                         TALLOC_FREE(p);
2547                 }
2548         }
2549
2550 exit_rmdir:
2551         if (dh) {
2552                 closedir(dh);
2553         }
2554         return SMB_VFS_NEXT_RMDIR(handle, path);
2555 }
2556
2557 static ssize_t fruit_pread(vfs_handle_struct *handle,
2558                            files_struct *fsp, void *data,
2559                            size_t n, off_t offset)
2560 {
2561         int rc = 0;
2562         struct adouble *ad = (struct adouble *)VFS_FETCH_FSP_EXTENSION(
2563                 handle, fsp);
2564         struct fruit_config_data *config = NULL;
2565         AfpInfo *ai = NULL;
2566         ssize_t len;
2567         char *name = NULL;
2568         char *tmp_base_name = NULL;
2569         NTSTATUS status;
2570
2571         DEBUG(10, ("fruit_pread: offset=%d, size=%d\n", (int)offset, (int)n));
2572
2573         if (!fsp->base_fsp) {
2574                 return SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
2575         }
2576
2577         SMB_VFS_HANDLE_GET_DATA(handle, config,
2578                                 struct fruit_config_data, return -1);
2579
2580         /* fsp_name is not converted with vfs_catia */
2581         tmp_base_name = fsp->base_fsp->fsp_name->base_name;
2582         status = SMB_VFS_TRANSLATE_NAME(handle->conn,
2583                                         fsp->base_fsp->fsp_name->base_name,
2584                                         vfs_translate_to_unix,
2585                                         talloc_tos(), &name);
2586         if (NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED)) {
2587                 name = talloc_strdup(talloc_tos(), tmp_base_name);
2588                 if (name == NULL) {
2589                         rc = -1;
2590                         goto exit;
2591                 }
2592         } else if (!NT_STATUS_IS_OK(status)) {
2593                 errno = map_errno_from_nt_status(status);
2594                 rc = -1;
2595                 goto exit;
2596         }
2597         fsp->base_fsp->fsp_name->base_name = name;
2598
2599         if (ad == NULL) {
2600                 len = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
2601                 if (len == -1) {
2602                         rc = -1;
2603                         goto exit;
2604                 }
2605                 goto exit;
2606         }
2607
2608         if (!fruit_fsp_recheck(ad, fsp)) {
2609                 rc = -1;
2610                 goto exit;
2611         }
2612
2613         if (ad->ad_type == ADOUBLE_META) {
2614                 ai = afpinfo_new(talloc_tos());
2615                 if (ai == NULL) {
2616                         rc = -1;
2617                         goto exit;
2618                 }
2619
2620                 len = ad_read(ad, fsp->base_fsp->fsp_name->base_name);
2621                 if (len == -1) {
2622                         rc = -1;
2623                         goto exit;
2624                 }
2625
2626                 memcpy(&ai->afpi_FinderInfo[0],
2627                        ad_entry(ad, ADEID_FINDERI),
2628                        ADEDLEN_FINDERI);
2629                 len = afpinfo_pack(ai, data);
2630                 if (len != AFP_INFO_SIZE) {
2631                         rc = -1;
2632                         goto exit;
2633                 }
2634         } else {
2635                 len = SMB_VFS_NEXT_PREAD(
2636                         handle, fsp, data, n,
2637                         offset + ad_getentryoff(ad, ADEID_RFORK));
2638                 if (len == -1) {
2639                         rc = -1;
2640                         goto exit;
2641                 }
2642         }
2643 exit:
2644         fsp->base_fsp->fsp_name->base_name = tmp_base_name;
2645         TALLOC_FREE(name);
2646         TALLOC_FREE(ai);
2647         if (rc != 0) {
2648                 len = -1;
2649         }
2650         DEBUG(10, ("fruit_pread: rc=%d, len=%zd\n", rc, len));
2651         return len;
2652 }
2653
2654 static ssize_t fruit_pwrite(vfs_handle_struct *handle,
2655                             files_struct *fsp, const void *data,
2656                             size_t n, off_t offset)
2657 {
2658         int rc = 0;
2659         struct adouble *ad = (struct adouble *)VFS_FETCH_FSP_EXTENSION(
2660                 handle, fsp);
2661         struct fruit_config_data *config = NULL;
2662         AfpInfo *ai = NULL;
2663         ssize_t len;
2664         char *name = NULL;
2665         char *tmp_base_name = NULL;
2666         NTSTATUS status;
2667
2668         DEBUG(10, ("fruit_pwrite: offset=%d, size=%d\n", (int)offset, (int)n));
2669
2670         if (!fsp->base_fsp) {
2671                 return SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2672         }
2673
2674         SMB_VFS_HANDLE_GET_DATA(handle, config,
2675                                 struct fruit_config_data, return -1);
2676
2677         tmp_base_name = fsp->base_fsp->fsp_name->base_name;
2678         status = SMB_VFS_TRANSLATE_NAME(handle->conn,
2679                                         fsp->base_fsp->fsp_name->base_name,
2680                                         vfs_translate_to_unix,
2681                                         talloc_tos(), &name);
2682         if (NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED)) {
2683                 name = talloc_strdup(talloc_tos(), tmp_base_name);
2684                 if (name == NULL) {
2685                         rc = -1;
2686                         goto exit;
2687                 }
2688         } else if (!NT_STATUS_IS_OK(status)) {
2689                 errno = map_errno_from_nt_status(status);
2690                 rc = -1;
2691                 goto exit;
2692         }
2693         fsp->base_fsp->fsp_name->base_name = name;
2694
2695         if (ad == NULL) {
2696                 len = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2697                 if (len != n) {
2698                         rc = -1;
2699                         goto exit;
2700                 }
2701                 goto exit;
2702         }
2703
2704         if (!fruit_fsp_recheck(ad, fsp)) {
2705                 rc = -1;
2706                 goto exit;
2707         }
2708
2709         if (ad->ad_type == ADOUBLE_META) {
2710                 if (n != AFP_INFO_SIZE || offset != 0) {
2711                         DEBUG(1, ("unexpected offset=%jd or size=%jd\n",
2712                                   (intmax_t)offset, (intmax_t)n));
2713                         rc = -1;
2714                         goto exit;
2715                 }
2716                 ai = afpinfo_unpack(talloc_tos(), data);
2717                 if (ai == NULL) {
2718                         rc = -1;
2719                         goto exit;
2720                 }
2721                 memcpy(ad_entry(ad, ADEID_FINDERI),
2722                        &ai->afpi_FinderInfo[0], ADEDLEN_FINDERI);
2723                 rc = ad_write(ad, name);
2724         } else {
2725                 len = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n,
2726                                    offset + ad_getentryoff(ad, ADEID_RFORK));
2727                 if (len != n) {
2728                         rc = -1;
2729                         goto exit;
2730                 }
2731
2732                 if (config->rsrc == FRUIT_RSRC_ADFILE) {
2733                         rc = ad_read(ad, name);
2734                         if (rc == -1) {
2735                                 goto exit;
2736                         }
2737                         rc = 0;
2738
2739                         if ((len + offset) > ad_getentrylen(ad, ADEID_RFORK)) {
2740                                 ad_setentrylen(ad, ADEID_RFORK, len + offset);
2741                                 rc = ad_write(ad, name);
2742                         }
2743                 }
2744         }
2745
2746 exit:
2747         fsp->base_fsp->fsp_name->base_name = tmp_base_name;
2748         TALLOC_FREE(name);
2749         TALLOC_FREE(ai);
2750         if (rc != 0) {
2751                 return -1;
2752         }
2753         return n;
2754 }
2755
2756 /**
2757  * Helper to stat/lstat the base file of an smb_fname.
2758  */
2759 static int fruit_stat_base(vfs_handle_struct *handle,
2760                            struct smb_filename *smb_fname,
2761                            bool follow_links)
2762 {
2763         char *tmp_stream_name;
2764         int rc;
2765
2766         tmp_stream_name = smb_fname->stream_name;
2767         smb_fname->stream_name = NULL;
2768         if (follow_links) {
2769                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
2770         } else {
2771                 rc = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
2772         }
2773         smb_fname->stream_name = tmp_stream_name;
2774         return rc;
2775 }
2776
2777 static int fruit_stat_meta(vfs_handle_struct *handle,
2778                            struct smb_filename *smb_fname,
2779                            bool follow_links)
2780 {
2781         /* Populate the stat struct with info from the base file. */
2782         if (fruit_stat_base(handle, smb_fname, follow_links) == -1) {
2783                 return -1;
2784         }
2785         smb_fname->st.st_ex_size = AFP_INFO_SIZE;
2786         smb_fname->st.st_ex_ino = fruit_inode(&smb_fname->st,
2787                                               smb_fname->stream_name);
2788         return 0;
2789 }
2790
2791 static int fruit_stat_rsrc(vfs_handle_struct *handle,
2792                            struct smb_filename *smb_fname,
2793                            bool follow_links)
2794
2795 {
2796         struct adouble *ad = NULL;
2797
2798         DEBUG(10, ("fruit_stat_rsrc called for %s\n",
2799                    smb_fname_str_dbg(smb_fname)));
2800
2801         ad = ad_get(talloc_tos(), handle, smb_fname->base_name, ADOUBLE_RSRC);
2802         if (ad == NULL) {
2803                 errno = ENOENT;
2804                 return -1;
2805         }
2806
2807         /* Populate the stat struct with info from the base file. */
2808         if (fruit_stat_base(handle, smb_fname, follow_links) == -1) {
2809                 TALLOC_FREE(ad);
2810                 return -1;
2811         }
2812
2813         smb_fname->st.st_ex_size = ad_getentrylen(ad, ADEID_RFORK);
2814         smb_fname->st.st_ex_ino = fruit_inode(&smb_fname->st,
2815                                               smb_fname->stream_name);
2816         TALLOC_FREE(ad);
2817         return 0;
2818 }
2819
2820 static int fruit_stat(vfs_handle_struct *handle,
2821                       struct smb_filename *smb_fname)
2822 {
2823         int rc = -1;
2824
2825         DEBUG(10, ("fruit_stat called for %s\n",
2826                    smb_fname_str_dbg(smb_fname)));
2827
2828         if (!is_ntfs_stream_smb_fname(smb_fname)
2829             || is_ntfs_default_stream_smb_fname(smb_fname)) {
2830                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
2831                 if (rc == 0) {
2832                         update_btime(handle, smb_fname);
2833                 }
2834                 return rc;
2835         }
2836
2837         /*
2838          * Note if lp_posix_paths() is true, we can never
2839          * get here as is_ntfs_stream_smb_fname() is
2840          * always false. So we never need worry about
2841          * not following links here.
2842          */
2843
2844         if (is_afpinfo_stream(smb_fname)) {
2845                 rc = fruit_stat_meta(handle, smb_fname, true);
2846         } else if (is_afpresource_stream(smb_fname)) {
2847                 rc = fruit_stat_rsrc(handle, smb_fname, true);
2848         } else {
2849                 return SMB_VFS_NEXT_STAT(handle, smb_fname);
2850         }
2851
2852         if (rc == 0) {
2853                 update_btime(handle, smb_fname);
2854                 smb_fname->st.st_ex_mode &= ~S_IFMT;
2855                 smb_fname->st.st_ex_mode |= S_IFREG;
2856                 smb_fname->st.st_ex_blocks =
2857                         smb_fname->st.st_ex_size / STAT_ST_BLOCKSIZE + 1;
2858         }
2859         return rc;
2860 }
2861
2862 static int fruit_lstat(vfs_handle_struct *handle,
2863                        struct smb_filename *smb_fname)
2864 {
2865         int rc = -1;
2866
2867         DEBUG(10, ("fruit_lstat called for %s\n",
2868                    smb_fname_str_dbg(smb_fname)));
2869
2870         if (!is_ntfs_stream_smb_fname(smb_fname)
2871             || is_ntfs_default_stream_smb_fname(smb_fname)) {
2872                 rc = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
2873                 if (rc == 0) {
2874                         update_btime(handle, smb_fname);
2875                 }
2876                 return rc;
2877         }
2878
2879         if (is_afpinfo_stream(smb_fname)) {
2880                 rc = fruit_stat_meta(handle, smb_fname, false);
2881         } else if (is_afpresource_stream(smb_fname)) {
2882                 rc = fruit_stat_rsrc(handle, smb_fname, false);
2883         } else {
2884                 return SMB_VFS_NEXT_LSTAT(handle, smb_fname);
2885         }
2886
2887         if (rc == 0) {
2888                 update_btime(handle, smb_fname);
2889                 smb_fname->st.st_ex_mode &= ~S_IFMT;
2890                 smb_fname->st.st_ex_mode |= S_IFREG;
2891                 smb_fname->st.st_ex_blocks =
2892                         smb_fname->st.st_ex_size / STAT_ST_BLOCKSIZE + 1;
2893         }
2894         return rc;
2895 }
2896
2897 static int fruit_fstat_meta(vfs_handle_struct *handle,
2898                             files_struct *fsp,
2899                             SMB_STRUCT_STAT *sbuf)
2900 {
2901         DEBUG(10, ("fruit_fstat_meta called for %s\n",
2902                    smb_fname_str_dbg(fsp->base_fsp->fsp_name)));
2903
2904         /* Populate the stat struct with info from the base file. */
2905         if (fruit_stat_base(handle, fsp->base_fsp->fsp_name, false) == -1) {
2906                 return -1;
2907         }
2908         *sbuf = fsp->base_fsp->fsp_name->st;
2909         sbuf->st_ex_size = AFP_INFO_SIZE;
2910         sbuf->st_ex_ino = fruit_inode(sbuf, fsp->fsp_name->stream_name);
2911
2912         return 0;
2913 }
2914
2915 static int fruit_fstat_rsrc(vfs_handle_struct *handle, files_struct *fsp,
2916                             SMB_STRUCT_STAT *sbuf)
2917 {
2918         struct fruit_config_data *config;
2919         struct adouble *ad = (struct adouble *)VFS_FETCH_FSP_EXTENSION(
2920                 handle, fsp);
2921
2922         DEBUG(10, ("fruit_fstat_rsrc called for %s\n",
2923                    smb_fname_str_dbg(fsp->base_fsp->fsp_name)));
2924
2925         SMB_VFS_HANDLE_GET_DATA(handle, config,
2926                                 struct fruit_config_data, return -1);
2927
2928         if (config->rsrc == FRUIT_RSRC_STREAM) {
2929                 return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
2930         }
2931
2932         /* Populate the stat struct with info from the base file. */
2933         if (fruit_stat_base(handle, fsp->base_fsp->fsp_name, false) == -1) {
2934                 return -1;
2935         }
2936         *sbuf = fsp->base_fsp->fsp_name->st;
2937         sbuf->st_ex_size = ad_getentrylen(ad, ADEID_RFORK);
2938         sbuf->st_ex_ino = fruit_inode(sbuf, fsp->fsp_name->stream_name);
2939
2940         DEBUG(10, ("fruit_fstat_rsrc %s, size: %zd\n",
2941                    smb_fname_str_dbg(fsp->fsp_name),
2942                    (ssize_t)sbuf->st_ex_size));
2943
2944         return 0;
2945 }
2946
2947 static int fruit_fstat(vfs_handle_struct *handle, files_struct *fsp,
2948                        SMB_STRUCT_STAT *sbuf)
2949 {
2950         int rc;
2951         char *name = NULL;
2952         char *tmp_base_name = NULL;
2953         NTSTATUS status;
2954         struct adouble *ad = (struct adouble *)
2955                 VFS_FETCH_FSP_EXTENSION(handle, fsp);
2956
2957         DEBUG(10, ("fruit_fstat called for %s\n",
2958                    smb_fname_str_dbg(fsp->fsp_name)));
2959
2960         if (fsp->base_fsp) {
2961                 tmp_base_name = fsp->base_fsp->fsp_name->base_name;
2962                 /* fsp_name is not converted with vfs_catia */
2963                 status = SMB_VFS_TRANSLATE_NAME(
2964                         handle->conn,
2965                         fsp->base_fsp->fsp_name->base_name,
2966                         vfs_translate_to_unix,
2967                         talloc_tos(), &name);
2968
2969                 if (NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED)) {
2970                         name = talloc_strdup(talloc_tos(), tmp_base_name);
2971                         if (name == NULL) {
2972                                 rc = -1;
2973                                 goto exit;
2974                         }
2975                 } else if (!NT_STATUS_IS_OK(status)) {
2976                         errno = map_errno_from_nt_status(status);
2977                         rc = -1;
2978                         goto exit;
2979                 }
2980                 fsp->base_fsp->fsp_name->base_name = name;
2981         }
2982
2983         if (ad == NULL || fsp->base_fsp == NULL) {
2984                 rc = SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
2985                 goto exit;
2986         }
2987
2988         if (!fruit_fsp_recheck(ad, fsp)) {
2989                 rc = -1;
2990                 goto exit;
2991         }
2992
2993         switch (ad->ad_type) {
2994         case ADOUBLE_META:
2995                 rc = fruit_fstat_meta(handle, fsp, sbuf);
2996                 break;
2997         case ADOUBLE_RSRC:
2998                 rc = fruit_fstat_rsrc(handle, fsp, sbuf);
2999                 break;
3000         default:
3001                 DEBUG(10, ("fruit_fstat %s: bad type\n",
3002                            smb_fname_str_dbg(fsp->fsp_name)));
3003                 rc = -1;
3004                 goto exit;
3005         }
3006
3007         if (rc == 0) {
3008                 sbuf->st_ex_mode &= ~S_IFMT;
3009                 sbuf->st_ex_mode |= S_IFREG;
3010                 sbuf->st_ex_blocks = sbuf->st_ex_size / STAT_ST_BLOCKSIZE + 1;
3011         }
3012
3013 exit:
3014         DEBUG(10, ("fruit_fstat %s, size: %zd\n",
3015                    smb_fname_str_dbg(fsp->fsp_name),
3016                    (ssize_t)sbuf->st_ex_size));
3017         if (tmp_base_name) {
3018                 fsp->base_fsp->fsp_name->base_name = tmp_base_name;
3019         }
3020         TALLOC_FREE(name);
3021         return rc;
3022 }
3023
3024 static NTSTATUS fruit_streaminfo(vfs_handle_struct *handle,
3025                                  struct files_struct *fsp,
3026                                  const char *fname,
3027                                  TALLOC_CTX *mem_ctx,
3028                                  unsigned int *pnum_streams,
3029                                  struct stream_struct **pstreams)
3030 {
3031         struct fruit_config_data *config = NULL;
3032         struct smb_filename *smb_fname = NULL;
3033         struct adouble *ad = NULL;
3034
3035         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
3036                                 return NT_STATUS_UNSUCCESSFUL);
3037         DEBUG(10, ("fruit_streaminfo called for %s\n", fname));
3038
3039         smb_fname = synthetic_smb_fname(talloc_tos(), fname, NULL, NULL);
3040         if (smb_fname == NULL) {
3041                 return NT_STATUS_NO_MEMORY;
3042         }
3043
3044         if (config->meta == FRUIT_META_NETATALK) {
3045                 ad = ad_get(talloc_tos(), handle,
3046                             smb_fname->base_name, ADOUBLE_META);
3047                 if (ad && !empty_finderinfo(ad)) {
3048                         if (!add_fruit_stream(
3049                                     mem_ctx, pnum_streams, pstreams,
3050                                     AFPINFO_STREAM_NAME, AFP_INFO_SIZE,
3051                                     smb_roundup(handle->conn,
3052                                                 AFP_INFO_SIZE))) {
3053                                 TALLOC_FREE(ad);
3054                                 TALLOC_FREE(smb_fname);
3055                                 return NT_STATUS_NO_MEMORY;
3056                         }
3057                 }
3058                 TALLOC_FREE(ad);
3059         }
3060
3061         if (config->rsrc != FRUIT_RSRC_STREAM) {
3062                 ad = ad_get(talloc_tos(), handle, smb_fname->base_name,
3063                             ADOUBLE_RSRC);
3064                 if (ad) {
3065                         if (!add_fruit_stream(
3066                                     mem_ctx, pnum_streams, pstreams,
3067                                     AFPRESOURCE_STREAM_NAME,
3068                                     ad_getentrylen(ad, ADEID_RFORK),
3069                                     smb_roundup(handle->conn,
3070                                                 ad_getentrylen(
3071                                                         ad, ADEID_RFORK)))) {
3072                                 TALLOC_FREE(ad);
3073                                 TALLOC_FREE(smb_fname);
3074                                 return NT_STATUS_NO_MEMORY;
3075                         }
3076                 }
3077                 TALLOC_FREE(ad);
3078         }
3079
3080         TALLOC_FREE(smb_fname);
3081
3082         return SMB_VFS_NEXT_STREAMINFO(handle, fsp, fname, mem_ctx,
3083                                        pnum_streams, pstreams);
3084 }
3085
3086 static int fruit_ntimes(vfs_handle_struct *handle,
3087                         const struct smb_filename *smb_fname,
3088                         struct smb_file_time *ft)
3089 {
3090         int rc = 0;
3091         struct adouble *ad = NULL;
3092
3093         if (null_timespec(ft->create_time)) {
3094                 goto exit;
3095         }
3096
3097         DEBUG(10,("set btime for %s to %s\n", smb_fname_str_dbg(smb_fname),
3098                  time_to_asc(convert_timespec_to_time_t(ft->create_time))));
3099
3100         ad = ad_get(talloc_tos(), handle, smb_fname->base_name, ADOUBLE_META);
3101         if (ad == NULL) {
3102                 goto exit;
3103         }
3104
3105         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX,
3106                    convert_time_t_to_uint32_t(ft->create_time.tv_sec));
3107
3108         rc = ad_write(ad, smb_fname->base_name);
3109
3110 exit:
3111
3112         TALLOC_FREE(ad);
3113         if (rc != 0) {
3114                 DEBUG(1, ("fruit_ntimes: %s\n", smb_fname_str_dbg(smb_fname)));
3115                 return -1;
3116         }
3117         return SMB_VFS_NEXT_NTIMES(handle, smb_fname, ft);
3118 }
3119
3120 static int fruit_fallocate(struct vfs_handle_struct *handle,
3121                            struct files_struct *fsp,
3122                            uint32_t mode,
3123                            off_t offset,
3124                            off_t len)
3125 {
3126         struct adouble *ad =
3127                 (struct adouble *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3128
3129         if (ad == NULL) {
3130                 return SMB_VFS_NEXT_FALLOCATE(handle, fsp, mode, offset, len);
3131         }
3132
3133         if (!fruit_fsp_recheck(ad, fsp)) {
3134                 return -1;
3135         }
3136
3137         /* Let the pwrite code path handle it. */
3138         errno = ENOSYS;
3139         return -1;
3140 }
3141
3142 static int fruit_ftruncate(struct vfs_handle_struct *handle,
3143                            struct files_struct *fsp,
3144                            off_t offset)
3145 {
3146         int rc = 0;
3147         struct adouble *ad =
3148                 (struct adouble *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3149         struct fruit_config_data *config;
3150
3151         DEBUG(10, ("streams_xattr_ftruncate called for file %s offset %.0f\n",
3152                    fsp_str_dbg(fsp), (double)offset));
3153
3154         if (ad == NULL) {
3155                 return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
3156         }
3157
3158         if (!fruit_fsp_recheck(ad, fsp)) {
3159                 return -1;
3160         }
3161
3162         SMB_VFS_HANDLE_GET_DATA(handle, config,
3163                                 struct fruit_config_data, return -1);
3164
3165         switch (ad->ad_type) {
3166         case ADOUBLE_META:
3167                 /*
3168                  * As this request hasn't been seen in the wild,
3169                  * the only sensible use I can imagine is the client
3170                  * truncating the stream to 0 bytes size.
3171                  * We simply remove the metadata on such a request.
3172                  */
3173                 if (offset == 0) {
3174                         rc = SMB_VFS_FREMOVEXATTR(fsp,
3175                                                   AFPRESOURCE_EA_NETATALK);
3176                 }
3177                 break;
3178         case ADOUBLE_RSRC:
3179                 if (config->rsrc == FRUIT_RSRC_XATTR && offset == 0) {
3180                         rc = SMB_VFS_FREMOVEXATTR(fsp,
3181                                                   AFPRESOURCE_EA_NETATALK);
3182                 } else {
3183                         rc = SMB_VFS_NEXT_FTRUNCATE(
3184                                 handle, fsp,
3185                                 offset + ad_getentryoff(ad, ADEID_RFORK));
3186                         if (rc != 0) {
3187                                 return -1;
3188                         }
3189                         ad_setentrylen(ad, ADEID_RFORK, offset);
3190                         rc = ad_write(ad, NULL);
3191                         if (rc != 0) {
3192                                 return -1;
3193                         }
3194                 }
3195                 break;
3196         default:
3197                 return -1;
3198         }
3199
3200         return rc;
3201 }
3202
3203 static NTSTATUS fruit_create_file(vfs_handle_struct *handle,
3204                                   struct smb_request *req,
3205                                   uint16_t root_dir_fid,
3206                                   struct smb_filename *smb_fname,
3207                                   uint32_t access_mask,
3208                                   uint32_t share_access,
3209                                   uint32_t create_disposition,
3210                                   uint32_t create_options,
3211                                   uint32_t file_attributes,
3212                                   uint32_t oplock_request,
3213                                   struct smb2_lease *lease,
3214                                   uint64_t allocation_size,
3215                                   uint32_t private_flags,
3216                                   struct security_descriptor *sd,
3217                                   struct ea_list *ea_list,
3218                                   files_struct **result,
3219                                   int *pinfo,
3220                                   const struct smb2_create_blobs *in_context_blobs,
3221                                   struct smb2_create_blobs *out_context_blobs)
3222 {
3223         NTSTATUS status;
3224         struct fruit_config_data *config = NULL;
3225
3226         status = check_aapl(handle, req, in_context_blobs, out_context_blobs);
3227         if (!NT_STATUS_IS_OK(status)) {
3228                 return status;
3229         }
3230
3231         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
3232                                 return NT_STATUS_UNSUCCESSFUL);
3233
3234         status = SMB_VFS_NEXT_CREATE_FILE(
3235                 handle, req, root_dir_fid, smb_fname,
3236                 access_mask, share_access,
3237                 create_disposition, create_options,
3238                 file_attributes, oplock_request,
3239                 lease,
3240                 allocation_size, private_flags,
3241                 sd, ea_list, result,
3242                 pinfo, in_context_blobs, out_context_blobs);
3243         if (!NT_STATUS_IS_OK(status)) {
3244                 return status;
3245         }
3246
3247         if (is_ntfs_stream_smb_fname(smb_fname)
3248             || (*result == NULL)
3249             || ((*result)->is_directory)) {
3250                 return status;
3251         }
3252
3253         if (config->locking == FRUIT_LOCKING_NETATALK) {
3254                 status = fruit_check_access(
3255                         handle, *result,
3256                         access_mask,
3257                         map_share_mode_to_deny_mode(share_access, 0));
3258                 if (!NT_STATUS_IS_OK(status)) {
3259                         goto fail;
3260                 }
3261         }
3262
3263         return status;
3264
3265 fail:
3266         DEBUG(1, ("fruit_create_file: %s\n", nt_errstr(status)));
3267
3268         if (*result) {
3269                 close_file(req, *result, ERROR_CLOSE);
3270                 *result = NULL;
3271         }
3272
3273         return status;
3274 }
3275
3276 static NTSTATUS fruit_readdir_attr(struct vfs_handle_struct *handle,
3277                                    const struct smb_filename *fname,
3278                                    TALLOC_CTX *mem_ctx,
3279                                    struct readdir_attr_data **pattr_data)
3280 {
3281         struct fruit_config_data *config = NULL;
3282         struct readdir_attr_data *attr_data;
3283         NTSTATUS status;
3284
3285         SMB_VFS_HANDLE_GET_DATA(handle, config,
3286                                 struct fruit_config_data,
3287                                 return NT_STATUS_UNSUCCESSFUL);
3288
3289         if (!config->use_aapl) {
3290                 return SMB_VFS_NEXT_READDIR_ATTR(handle, fname, mem_ctx, pattr_data);
3291         }
3292
3293         DEBUG(10, ("fruit_readdir_attr %s\n", fname->base_name));
3294
3295         *pattr_data = talloc_zero(mem_ctx, struct readdir_attr_data);
3296         if (*pattr_data == NULL) {
3297                 return NT_STATUS_UNSUCCESSFUL;
3298         }
3299         attr_data = *pattr_data;
3300         attr_data->type = RDATTR_AAPL;
3301
3302         /*
3303          * Mac metadata: compressed FinderInfo, resource fork length
3304          * and creation date
3305          */
3306         status = readdir_attr_macmeta(handle, fname, attr_data);
3307         if (!NT_STATUS_IS_OK(status)) {
3308                 /*
3309                  * Error handling is tricky: if we return failure from
3310                  * this function, the corresponding directory entry
3311                  * will to be passed to the client, so we really just
3312                  * want to error out on fatal errors.
3313                  */
3314                 if  (!NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
3315                         goto fail;
3316                 }
3317         }
3318
3319         /*
3320          * UNIX mode
3321          */
3322         if (config->unix_info_enabled) {
3323                 attr_data->attr_data.aapl.unix_mode = fname->st.st_ex_mode;
3324         }
3325
3326         /*
3327          * max_access
3328          */
3329         if (!config->readdir_attr_max_access) {
3330                 attr_data->attr_data.aapl.max_access = FILE_GENERIC_ALL;
3331         } else {
3332                 status = smbd_calculate_access_mask(
3333                         handle->conn,
3334                         fname,
3335                         false,
3336                         SEC_FLAG_MAXIMUM_ALLOWED,
3337                         &attr_data->attr_data.aapl.max_access);
3338                 if (!NT_STATUS_IS_OK(status)) {
3339                         goto fail;
3340                 }
3341         }
3342
3343         return NT_STATUS_OK;
3344
3345 fail:
3346         DEBUG(1, ("fruit_readdir_attr %s, error: %s\n",
3347                   fname->base_name, nt_errstr(status)));
3348         TALLOC_FREE(*pattr_data);
3349         return status;
3350 }
3351
3352 static NTSTATUS fruit_fget_nt_acl(vfs_handle_struct *handle,
3353                                   files_struct *fsp,
3354                                   uint32_t security_info,
3355                                   TALLOC_CTX *mem_ctx,
3356                                   struct security_descriptor **ppdesc)
3357 {
3358         NTSTATUS status;
3359         struct security_ace ace;
3360         struct dom_sid sid;
3361         struct fruit_config_data *config;
3362
3363         SMB_VFS_HANDLE_GET_DATA(handle, config,
3364                                 struct fruit_config_data,
3365                                 return NT_STATUS_UNSUCCESSFUL);
3366
3367         status = SMB_VFS_NEXT_FGET_NT_ACL(handle, fsp, security_info,
3368                                           mem_ctx, ppdesc);
3369         if (!NT_STATUS_IS_OK(status)) {
3370                 return status;
3371         }
3372
3373         /*
3374          * Add MS NFS style ACEs with uid, gid and mode
3375          */
3376         if (!config->unix_info_enabled) {
3377                 return NT_STATUS_OK;
3378         }
3379
3380         /* MS NFS style mode */
3381         sid_compose(&sid, &global_sid_Unix_NFS_Mode, fsp->fsp_name->st.st_ex_mode);
3382         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
3383         status = security_descriptor_dacl_add(*ppdesc, &ace);
3384         if (!NT_STATUS_IS_OK(status)) {
3385                 DEBUG(1,("failed to add MS NFS style ACE\n"));
3386                 return status;
3387         }
3388
3389         /* MS NFS style uid */
3390         sid_compose(&sid, &global_sid_Unix_NFS_Users, fsp->fsp_name->st.st_ex_uid);
3391         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
3392         status = security_descriptor_dacl_add(*ppdesc, &ace);
3393         if (!NT_STATUS_IS_OK(status)) {
3394                 DEBUG(1,("failed to add MS NFS style ACE\n"));
3395                 return status;
3396         }
3397
3398         /* MS NFS style gid */
3399         sid_compose(&sid, &global_sid_Unix_NFS_Groups, fsp->fsp_name->st.st_ex_gid);
3400         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
3401         status = security_descriptor_dacl_add(*ppdesc, &ace);
3402         if (!NT_STATUS_IS_OK(status)) {
3403                 DEBUG(1,("failed to add MS NFS style ACE\n"));
3404                 return status;
3405         }
3406
3407         return NT_STATUS_OK;
3408 }
3409
3410 static NTSTATUS fruit_fset_nt_acl(vfs_handle_struct *handle,
3411                                   files_struct *fsp,
3412                                   uint32_t security_info_sent,
3413                                   const struct security_descriptor *psd)
3414 {
3415         NTSTATUS status;
3416         bool do_chmod;
3417         mode_t ms_nfs_mode;
3418         int result;
3419
3420         DEBUG(1, ("fruit_fset_nt_acl: %s\n", fsp_str_dbg(fsp)));
3421
3422         status = check_ms_nfs(handle, fsp, psd, &ms_nfs_mode, &do_chmod);
3423         if (!NT_STATUS_IS_OK(status)) {
3424                 DEBUG(1, ("fruit_fset_nt_acl: check_ms_nfs failed%s\n", fsp_str_dbg(fsp)));
3425                 return status;
3426         }
3427
3428         status = SMB_VFS_NEXT_FSET_NT_ACL(handle, fsp, security_info_sent, psd);
3429         if (!NT_STATUS_IS_OK(status)) {
3430                 DEBUG(1, ("fruit_fset_nt_acl: SMB_VFS_NEXT_FSET_NT_ACL failed%s\n", fsp_str_dbg(fsp)));
3431                 return status;
3432         }
3433
3434         if (do_chmod) {
3435                 if (fsp->fh->fd != -1) {
3436                         DEBUG(1, ("fchmod: %s\n", fsp_str_dbg(fsp)));
3437                         result = SMB_VFS_FCHMOD(fsp, ms_nfs_mode);
3438                 } else {
3439                         DEBUG(1, ("chmod: %s\n", fsp_str_dbg(fsp)));
3440                         result = SMB_VFS_CHMOD(fsp->conn,
3441                                                fsp->fsp_name->base_name,
3442                                                ms_nfs_mode);
3443                 }
3444
3445                 if (result != 0) {
3446                         DEBUG(1, ("chmod: %s, result: %d, %04o error %s\n", fsp_str_dbg(fsp),
3447                                   result, (unsigned)ms_nfs_mode,
3448                                   strerror(errno)));
3449                         status = map_nt_error_from_unix(errno);
3450                         return status;
3451                 }
3452         }
3453
3454         return NT_STATUS_OK;
3455 }
3456
3457 static struct vfs_fn_pointers vfs_fruit_fns = {
3458         .connect_fn = fruit_connect,
3459
3460         /* File operations */
3461         .chmod_fn = fruit_chmod,
3462         .chown_fn = fruit_chown,
3463         .unlink_fn = fruit_unlink,
3464         .rename_fn = fruit_rename,
3465         .rmdir_fn = fruit_rmdir,
3466         .open_fn = fruit_open,
3467         .pread_fn = fruit_pread,
3468         .pwrite_fn = fruit_pwrite,
3469         .stat_fn = fruit_stat,
3470         .lstat_fn = fruit_lstat,
3471         .fstat_fn = fruit_fstat,
3472         .streaminfo_fn = fruit_streaminfo,
3473         .ntimes_fn = fruit_ntimes,
3474         .ftruncate_fn = fruit_ftruncate,
3475         .fallocate_fn = fruit_fallocate,
3476         .create_file_fn = fruit_create_file,
3477         .readdir_attr_fn = fruit_readdir_attr,
3478
3479         /* NT ACL operations */
3480         .fget_nt_acl_fn = fruit_fget_nt_acl,
3481         .fset_nt_acl_fn = fruit_fset_nt_acl,
3482 };
3483
3484 NTSTATUS vfs_fruit_init(void);
3485 NTSTATUS vfs_fruit_init(void)
3486 {
3487         NTSTATUS ret = smb_register_vfs(SMB_VFS_INTERFACE_VERSION, "fruit",
3488                                         &vfs_fruit_fns);
3489         if (!NT_STATUS_IS_OK(ret)) {
3490                 return ret;
3491         }
3492
3493         vfs_fruit_debug_level = debug_add_class("fruit");
3494         if (vfs_fruit_debug_level == -1) {
3495                 vfs_fruit_debug_level = DBGC_VFS;
3496                 DEBUG(0, ("%s: Couldn't register custom debugging class!\n",
3497                           "vfs_fruit_init"));
3498         } else {
3499                 DEBUG(10, ("%s: Debug class number of '%s': %d\n",
3500                            "vfs_fruit_init","fruit",vfs_fruit_debug_level));
3501         }
3502
3503         return ret;
3504 }