vfs_fruit: Fix CID 1273290 Uninitialized scalar variable
[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 undocumented 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)
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                 if ((off > bufsize) && (eid != ADEID_RFORK)) {
616                         DEBUG(1, ("bogus eid %d: off: %" PRIu32 ", len: %" PRIu32 "\n",
617                                   eid, off, len));
618                         return false;
619                 }
620                 if ((eid != ADEID_RFORK) &&
621                     (eid != ADEID_FINDERI) &&
622                     ((off + len) > bufsize)) {
623                         DEBUG(1, ("bogus eid %d: off: %" PRIu32 ", len: %" PRIu32 "\n",
624                                   eid, off, len));
625                         return false;
626                 }
627
628                 ad->ad_eid[eid].ade_off = off;
629                 ad->ad_eid[eid].ade_len = len;
630         }
631
632         return true;
633 }
634
635 /**
636  * Convert from Apple's ._ file to Netatalk
637  *
638  * Apple's AppleDouble may contain a FinderInfo entry longer then 32
639  * bytes containing packed xattrs. Netatalk can't deal with that, so
640  * we simply discard the packed xattrs.
641  *
642  * @return -1 in case an error occured, 0 if no conversion was done, 1
643  * otherwise
644  **/
645 static int ad_convert(struct adouble *ad, int fd)
646 {
647         int rc = 0;
648         char *map = MAP_FAILED;
649         size_t origlen;
650
651         origlen = ad_getentryoff(ad, ADEID_RFORK) +
652                 ad_getentrylen(ad, ADEID_RFORK);
653
654         /* FIXME: direct use of mmap(), vfs_aio_fork does it too */
655         map = mmap(NULL, origlen, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
656         if (map == MAP_FAILED) {
657                 DEBUG(2, ("mmap AppleDouble: %s\n", strerror(errno)));
658                 rc = -1;
659                 goto exit;
660         }
661
662         memmove(map + ad_getentryoff(ad, ADEID_FINDERI) + ADEDLEN_FINDERI,
663                 map + ad_getentryoff(ad, ADEID_RFORK),
664                 ad_getentrylen(ad, ADEID_RFORK));
665
666         ad_setentrylen(ad, ADEID_FINDERI, ADEDLEN_FINDERI);
667         ad_setentryoff(ad, ADEID_RFORK,
668                        ad_getentryoff(ad, ADEID_FINDERI) + ADEDLEN_FINDERI);
669
670         /*
671          * FIXME: direct ftruncate(), but we don't have a fsp for the
672          * VFS call
673          */
674         rc = ftruncate(fd, ad_getentryoff(ad, ADEID_RFORK)
675                        + ad_getentrylen(ad, ADEID_RFORK));
676
677 exit:
678         if (map != MAP_FAILED) {
679                 munmap(map, origlen);
680         }
681         return rc;
682 }
683
684 /**
685  * Read and parse Netatalk AppleDouble metadata xattr
686  **/
687 static ssize_t ad_header_read_meta(struct adouble *ad, const char *path)
688 {
689         int      rc = 0;
690         ssize_t  ealen;
691         bool     ok;
692
693         DEBUG(10, ("reading meta xattr for %s\n", path));
694
695         ealen = SMB_VFS_GETXATTR(ad->ad_handle->conn, path,
696                                  AFPINFO_EA_NETATALK, ad->ad_data,
697                                  AD_DATASZ_XATTR);
698         if (ealen == -1) {
699                 switch (errno) {
700                 case ENOATTR:
701                 case ENOENT:
702                         if (errno == ENOATTR) {
703                                 errno = ENOENT;
704                         }
705                         rc = -1;
706                         goto exit;
707                 default:
708                         DEBUG(2, ("error reading meta xattr: %s\n",
709                                   strerror(errno)));
710                         rc = -1;
711                         goto exit;
712                 }
713         }
714         if (ealen != AD_DATASZ_XATTR) {
715                 DEBUG(2, ("bad size %zd\n", ealen));
716                 errno = EINVAL;
717                 rc = -1;
718                 goto exit;
719         }
720
721         /* Now parse entries */
722         ok = ad_unpack(ad, ADEID_NUM_XATTR);
723         if (!ok) {
724                 DEBUG(2, ("invalid AppleDouble metadata xattr\n"));
725                 errno = EINVAL;
726                 rc = -1;
727                 goto exit;
728         }
729
730         if (!ad_getentryoff(ad, ADEID_FINDERI)
731             || !ad_getentryoff(ad, ADEID_COMMENT)
732             || !ad_getentryoff(ad, ADEID_FILEDATESI)
733             || !ad_getentryoff(ad, ADEID_AFPFILEI)
734             || !ad_getentryoff(ad, ADEID_PRIVDEV)
735             || !ad_getentryoff(ad, ADEID_PRIVINO)
736             || !ad_getentryoff(ad, ADEID_PRIVSYN)
737             || !ad_getentryoff(ad, ADEID_PRIVID)) {
738                 DEBUG(2, ("invalid AppleDouble metadata xattr\n"));
739                 errno = EINVAL;
740                 rc = -1;
741                 goto exit;
742         }
743
744 exit:
745         DEBUG(10, ("reading meta xattr for %s, rc: %d\n", path, rc));
746
747         if (rc != 0) {
748                 ealen = -1;
749                 if (errno == EINVAL) {
750                         become_root();
751                         removexattr(path, AFPINFO_EA_NETATALK);
752                         unbecome_root();
753                         errno = ENOENT;
754                 }
755         }
756         return ealen;
757 }
758
759 /**
760  * Read and parse resource fork, either ._ AppleDouble file or xattr
761  **/
762 static ssize_t ad_header_read_rsrc(struct adouble *ad, const char *path)
763 {
764         struct fruit_config_data *config = NULL;
765         int fd = -1;
766         int rc = 0;
767         ssize_t len;
768         char *adpath = NULL;
769         bool opened = false;
770         int mode;
771         struct adouble *meta_ad = NULL;
772         SMB_STRUCT_STAT sbuf;
773         bool ok;
774         int saved_errno = 0;
775
776         SMB_VFS_HANDLE_GET_DATA(ad->ad_handle, config,
777                                 struct fruit_config_data, return -1);
778
779         /* Try rw first so we can use the fd in ad_convert() */
780         mode = O_RDWR;
781
782         if (ad->ad_fsp && ad->ad_fsp->fh && (ad->ad_fsp->fh->fd != -1)) {
783                 fd = ad->ad_fsp->fh->fd;
784         } else {
785                 if (config->rsrc == FRUIT_RSRC_XATTR) {
786                         adpath = talloc_strdup(talloc_tos(), path);
787                 } else {
788                         rc = adouble_path(talloc_tos(), path, &adpath);
789                         if (rc != 0) {
790                                 goto exit;
791                         }
792                 }
793
794         retry:
795                 if (config->rsrc == FRUIT_RSRC_XATTR) {
796 #ifndef HAVE_ATTROPEN
797                         errno = ENOSYS;
798                         rc = -1;
799                         goto exit;
800 #else
801                         /* FIXME: direct Solaris xattr syscall */
802                         fd = attropen(adpath, AFPRESOURCE_EA_NETATALK,
803                                       mode, 0);
804 #endif
805                 } else {
806                         /* FIXME: direct open(), don't have an fsp */
807                         fd = open(adpath, mode);
808                 }
809
810                 if (fd == -1) {
811                         switch (errno) {
812                         case EROFS:
813                         case EACCES:
814                                 if (mode == O_RDWR) {
815                                         mode = O_RDONLY;
816                                         goto retry;
817                                 }
818                                 /* fall through ... */
819                         default:
820                                 DEBUG(2, ("open AppleDouble: %s, %s\n",
821                                           adpath, strerror(errno)));
822                                 rc = -1;
823                                 goto exit;
824                         }
825                 }
826                 opened = true;
827         }
828
829         if (config->rsrc == FRUIT_RSRC_XATTR) {
830                 /* FIXME: direct sys_fstat(), don't have an fsp */
831                 rc = sys_fstat(
832                         fd, &sbuf,
833                         lp_fake_directory_create_times(
834                                 SNUM(ad->ad_handle->conn)));
835                 if (rc != 0) {
836                         goto exit;
837                 }
838                 len = sbuf.st_ex_size;
839                 ad_setentrylen(ad, ADEID_RFORK, len);
840         } else {
841                 /* FIXME: direct sys_pread(), don't have an fsp */
842                 len = sys_pread(fd, ad->ad_data, AD_DATASZ_DOT_UND, 0);
843                 if (len != AD_DATASZ_DOT_UND) {
844                         DEBUG(2, ("%s: bad size: %zd\n",
845                                   strerror(errno), len));
846                         rc = -1;
847                         goto exit;
848                 }
849
850                 /* Now parse entries */
851                 ok = ad_unpack(ad, ADEID_NUM_DOT_UND);
852                 if (!ok) {
853                         DEBUG(1, ("invalid AppleDouble ressource %s\n", path));
854                         errno = EINVAL;
855                         rc = -1;
856                         goto exit;
857                 }
858
859                 if ((ad_getentryoff(ad, ADEID_FINDERI)
860                      != ADEDOFF_FINDERI_DOT_UND)
861                     || (ad_getentrylen(ad, ADEID_FINDERI)
862                         < ADEDLEN_FINDERI)
863                     || (ad_getentryoff(ad, ADEID_RFORK)
864                         < ADEDOFF_RFORK_DOT_UND)) {
865                         DEBUG(2, ("invalid AppleDouble ressource %s\n", path));
866                         errno = EINVAL;
867                         rc = -1;
868                         goto exit;
869                 }
870
871                 if ((mode == O_RDWR)
872                     && (ad_getentrylen(ad, ADEID_FINDERI) > ADEDLEN_FINDERI)) {
873                         rc = ad_convert(ad, fd);
874                         if (rc != 0) {
875                                 rc = -1;
876                                 goto exit;
877                         }
878                         /*
879                          * Can't use ad_write() because we might not have a fsp
880                          */
881                         rc = ad_pack(ad);
882                         if (rc != 0) {
883                                 goto exit;
884                         }
885                         /* FIXME: direct sys_pwrite(), don't have an fsp */
886                         len = sys_pwrite(fd, ad->ad_data,
887                                          AD_DATASZ_DOT_UND, 0);
888                         if (len != AD_DATASZ_DOT_UND) {
889                                 DEBUG(2, ("%s: bad size: %zd\n", adpath, len));
890                                 rc = -1;
891                                 goto exit;
892                         }
893
894                         meta_ad = ad_init(talloc_tos(), ad->ad_handle,
895                                           ADOUBLE_META, NULL);
896                         if (meta_ad == NULL) {
897                                 rc = -1;
898                                 goto exit;
899                         }
900
901                         memcpy(ad_entry(meta_ad, ADEID_FINDERI),
902                                ad_entry(ad, ADEID_FINDERI),
903                                ADEDLEN_FINDERI);
904
905                         rc = ad_write(meta_ad, path);
906                         if (rc != 0) {
907                                 rc = -1;
908                                 goto exit;
909                         }
910                 }
911         }
912
913         DEBUG(10, ("opened AppleDouble: %s\n", path));
914
915 exit:
916         if (rc != 0) {
917                 saved_errno = errno;
918                 len = -1;
919         }
920         if (opened && fd != -1) {
921                 close(fd);
922         }
923         TALLOC_FREE(adpath);
924         TALLOC_FREE(meta_ad);
925         if (rc != 0) {
926                 errno = saved_errno;
927         }
928         return len;
929 }
930
931 /**
932  * Read and unpack an AppleDouble metadata xattr or resource
933  **/
934 static ssize_t ad_read(struct adouble *ad, const char *path)
935 {
936         switch (ad->ad_type) {
937         case ADOUBLE_META:
938                 return ad_header_read_meta(ad, path);
939         case ADOUBLE_RSRC:
940                 return ad_header_read_rsrc(ad, path);
941         default:
942                 return -1;
943         }
944 }
945
946 /**
947  * Allocate a struct adouble without initialiing it
948  *
949  * The struct is either hang of the fsp extension context or if fsp is
950  * NULL from ctx.
951  *
952  * @param[in] ctx        talloc context
953  * @param[in] handle     vfs handle
954  * @param[in] type       type of AppleDouble, ADOUBLE_META or ADOUBLE_RSRC
955
956  * @param[in] fsp        if not NULL (for stream IO), the adouble handle is
957  *                       added as an fsp extension
958  *
959  * @return               adouble handle
960  **/
961 static struct adouble *ad_alloc(TALLOC_CTX *ctx, vfs_handle_struct *handle,
962                                 adouble_type_t type, files_struct *fsp)
963 {
964         int rc = 0;
965         size_t adsize = 0;
966         struct adouble *ad;
967         struct fruit_config_data *config;
968
969         SMB_VFS_HANDLE_GET_DATA(handle, config,
970                                 struct fruit_config_data, return NULL);
971
972         switch (type) {
973         case ADOUBLE_META:
974                 adsize = AD_DATASZ_XATTR;
975                 break;
976         case ADOUBLE_RSRC:
977                 if (config->rsrc == FRUIT_RSRC_ADFILE) {
978                         adsize = AD_DATASZ_DOT_UND;
979                 }
980                 break;
981         default:
982                 return NULL;
983         }
984
985         if (!fsp) {
986                 ad = talloc_zero(ctx, struct adouble);
987                 if (ad == NULL) {
988                         rc = -1;
989                         goto exit;
990                 }
991                 if (adsize) {
992                         ad->ad_data = talloc_zero_array(ad, char, adsize);
993                 }
994         } else {
995                 ad = (struct adouble *)VFS_ADD_FSP_EXTENSION(handle, fsp,
996                                                              struct adouble,
997                                                              NULL);
998                 if (ad == NULL) {
999                         rc = -1;
1000                         goto exit;
1001                 }
1002                 if (adsize) {
1003                         ad->ad_data = talloc_zero_array(
1004                                 VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
1005                                 char, adsize);
1006                 }
1007                 ad->ad_fsp = fsp;
1008         }
1009
1010         if (adsize && ad->ad_data == NULL) {
1011                 rc = -1;
1012                 goto exit;
1013         }
1014         ad->ad_handle = handle;
1015         ad->ad_type = type;
1016         ad->ad_magic = AD_MAGIC;
1017         ad->ad_version = AD_VERSION;
1018
1019 exit:
1020         if (rc != 0) {
1021                 TALLOC_FREE(ad);
1022         }
1023         return ad;
1024 }
1025
1026 /**
1027  * Allocate and initialize a new struct adouble
1028  *
1029  * @param[in] ctx        talloc context
1030  * @param[in] handle     vfs handle
1031  * @param[in] type       type of AppleDouble, ADOUBLE_META or ADOUBLE_RSRC
1032  * @param[in] fsp        file handle, may be NULL for a type of e_ad_meta
1033  *
1034  * @return               adouble handle, initialized
1035  **/
1036 static struct adouble *ad_init(TALLOC_CTX *ctx, vfs_handle_struct *handle,
1037                                adouble_type_t type, files_struct *fsp)
1038 {
1039         int rc = 0;
1040         const struct ad_entry_order  *eid;
1041         struct adouble *ad = NULL;
1042         struct fruit_config_data *config;
1043         time_t t = time(NULL);
1044
1045         SMB_VFS_HANDLE_GET_DATA(handle, config,
1046                                 struct fruit_config_data, return NULL);
1047
1048         switch (type) {
1049         case ADOUBLE_META:
1050                 eid = entry_order_meta_xattr;
1051                 break;
1052         case ADOUBLE_RSRC:
1053                 if (config->rsrc == FRUIT_RSRC_ADFILE) {
1054                         eid = entry_order_dot_und;
1055                 } else {
1056                         eid = entry_order_rsrc_xattr;
1057                 }
1058                 break;
1059         default:
1060                 return NULL;
1061         }
1062
1063         ad = ad_alloc(ctx, handle, type, fsp);
1064         if (ad == NULL) {
1065                 return NULL;
1066         }
1067
1068         while (eid->id) {
1069                 ad->ad_eid[eid->id].ade_off = eid->offset;
1070                 ad->ad_eid[eid->id].ade_len = eid->len;
1071                 eid++;
1072         }
1073
1074         /* put something sane in the date fields */
1075         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, t);
1076         ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, t);
1077         ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, t);
1078         ad_setdate(ad, AD_DATE_BACKUP, htonl(AD_DATE_START));
1079
1080         if (rc != 0) {
1081                 TALLOC_FREE(ad);
1082         }
1083         return ad;
1084 }
1085
1086 /**
1087  * Return AppleDouble data for a file
1088  *
1089  * @param[in] ctx      talloc context
1090  * @param[in] handle   vfs handle
1091  * @param[in] path     pathname to file or directory
1092  * @param[in] type     type of AppleDouble, ADOUBLE_META or ADOUBLE_RSRC
1093  *
1094  * @return             talloced struct adouble or NULL on error
1095  **/
1096 static struct adouble *ad_get(TALLOC_CTX *ctx, vfs_handle_struct *handle,
1097                               const char *path, adouble_type_t type)
1098 {
1099         int rc = 0;
1100         ssize_t len;
1101         struct adouble *ad = NULL;
1102
1103         DEBUG(10, ("ad_get(%s) called for %s\n",
1104                    type == ADOUBLE_META ? "meta" : "rsrc", path));
1105
1106         ad = ad_alloc(ctx, handle, type, NULL);
1107         if (ad == NULL) {
1108                 rc = -1;
1109                 goto exit;
1110         }
1111
1112         len = ad_read(ad, path);
1113         if (len == -1) {
1114                 DEBUG(10, ("error reading AppleDouble for %s\n", path));
1115                 rc = -1;
1116                 goto exit;
1117         }
1118
1119 exit:
1120         DEBUG(10, ("ad_get(%s) for %s returning %d\n",
1121                   type == ADOUBLE_META ? "meta" : "rsrc", path, rc));
1122
1123         if (rc != 0) {
1124                 TALLOC_FREE(ad);
1125         }
1126         return ad;
1127 }
1128
1129 /**
1130  * Set AppleDouble metadata on a file or directory
1131  *
1132  * @param[in] ad      adouble handle
1133
1134  * @param[in] path    pathname to file or directory, may be NULL for a
1135  *                    resource fork
1136  *
1137  * @return            status code, 0 means success
1138  **/
1139 static int ad_write(struct adouble *ad, const char *path)
1140 {
1141         int rc = 0;
1142         ssize_t len;
1143
1144         rc = ad_pack(ad);
1145         if (rc != 0) {
1146                 goto exit;
1147         }
1148
1149         switch (ad->ad_type) {
1150         case ADOUBLE_META:
1151                 rc = SMB_VFS_SETXATTR(ad->ad_handle->conn, path,
1152                                       AFPINFO_EA_NETATALK, ad->ad_data,
1153                                       AD_DATASZ_XATTR, 0);
1154                 break;
1155         case ADOUBLE_RSRC:
1156                 if ((ad->ad_fsp == NULL)
1157                     || (ad->ad_fsp->fh == NULL)
1158                     || (ad->ad_fsp->fh->fd == -1)) {
1159                         rc = -1;
1160                         goto exit;
1161                 }
1162                 /* FIXME: direct sys_pwrite(), don't have an fsp */
1163                 len = sys_pwrite(ad->ad_fsp->fh->fd, ad->ad_data,
1164                                  talloc_get_size(ad->ad_data), 0);
1165                 if (len != talloc_get_size(ad->ad_data)) {
1166                         DEBUG(1, ("short write on %s: %zd",
1167                                   fsp_str_dbg(ad->ad_fsp), len));
1168                         rc = -1;
1169                         goto exit;
1170                 }
1171                 break;
1172         default:
1173                 return -1;
1174         }
1175 exit:
1176         return rc;
1177 }
1178
1179 /*****************************************************************************
1180  * Helper functions
1181  *****************************************************************************/
1182
1183 static bool is_afpinfo_stream(const struct smb_filename *smb_fname)
1184 {
1185         if (strncasecmp_m(smb_fname->stream_name,
1186                           AFPINFO_STREAM_NAME,
1187                           strlen(AFPINFO_STREAM_NAME)) == 0) {
1188                 return true;
1189         }
1190         return false;
1191 }
1192
1193 static bool is_afpresource_stream(const struct smb_filename *smb_fname)
1194 {
1195         if (strncasecmp_m(smb_fname->stream_name,
1196                           AFPRESOURCE_STREAM_NAME,
1197                           strlen(AFPRESOURCE_STREAM_NAME)) == 0) {
1198                 return true;
1199         }
1200         return false;
1201 }
1202
1203 /**
1204  * Test whether stream is an Apple stream, not used atm
1205  **/
1206 #if 0
1207 static bool is_apple_stream(const struct smb_filename *smb_fname)
1208 {
1209         if (is_afpinfo_stream(smb_fname)) {
1210                 return true;
1211         }
1212         if (is_afpresource_stream(smb_fname)) {
1213                 return true;
1214         }
1215         return false;
1216 }
1217 #endif
1218
1219 /**
1220  * Initialize config struct from our smb.conf config parameters
1221  **/
1222 static int init_fruit_config(vfs_handle_struct *handle)
1223 {
1224         struct fruit_config_data *config;
1225         int enumval;
1226
1227         config = talloc_zero(handle->conn, struct fruit_config_data);
1228         if (!config) {
1229                 DEBUG(1, ("talloc_zero() failed\n"));
1230                 errno = ENOMEM;
1231                 return -1;
1232         }
1233
1234         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
1235                                "ressource", fruit_rsrc, FRUIT_RSRC_ADFILE);
1236         if (enumval == -1) {
1237                 DEBUG(1, ("value for %s: ressource type unknown\n",
1238                           FRUIT_PARAM_TYPE_NAME));
1239                 return -1;
1240         }
1241         config->rsrc = (enum fruit_rsrc)enumval;
1242
1243         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
1244                                "metadata", fruit_meta, FRUIT_META_NETATALK);
1245         if (enumval == -1) {
1246                 DEBUG(1, ("value for %s: metadata type unknown\n",
1247                           FRUIT_PARAM_TYPE_NAME));
1248                 return -1;
1249         }
1250         config->meta = (enum fruit_meta)enumval;
1251
1252         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
1253                                "locking", fruit_locking, FRUIT_LOCKING_NONE);
1254         if (enumval == -1) {
1255                 DEBUG(1, ("value for %s: locking type unknown\n",
1256                           FRUIT_PARAM_TYPE_NAME));
1257                 return -1;
1258         }
1259         config->locking = (enum fruit_locking)enumval;
1260
1261         enumval = lp_parm_enum(SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
1262                                "encoding", fruit_encoding, FRUIT_ENC_PRIVATE);
1263         if (enumval == -1) {
1264                 DEBUG(1, ("value for %s: encoding type unknown\n",
1265                           FRUIT_PARAM_TYPE_NAME));
1266                 return -1;
1267         }
1268         config->encoding = (enum fruit_encoding)enumval;
1269
1270         if (lp_parm_bool(-1, FRUIT_PARAM_TYPE_NAME, "aapl", true)) {
1271                 config->use_aapl = true;
1272         }
1273
1274         if (lp_parm_bool(SNUM(handle->conn),
1275                          "readdir_attr", "aapl_rsize", true)) {
1276                 config->readdir_attr_rsize = true;
1277         }
1278
1279         if (lp_parm_bool(SNUM(handle->conn),
1280                          "readdir_attr", "aapl_finder_info", true)) {
1281                 config->readdir_attr_finder_info = true;
1282         }
1283
1284         if (lp_parm_bool(SNUM(handle->conn),
1285                          "readdir_attr", "aapl_max_access", true)) {
1286                 config->readdir_attr_max_access = true;
1287         }
1288
1289         SMB_VFS_HANDLE_SET_DATA(handle, config,
1290                                 NULL, struct fruit_config_data,
1291                                 return -1);
1292
1293         return 0;
1294 }
1295
1296 /**
1297  * Prepend "._" to a basename
1298  **/
1299 static int adouble_path(TALLOC_CTX *ctx, const char *path_in, char **path_out)
1300 {
1301         char *parent;
1302         const char *base;
1303
1304         if (!parent_dirname(ctx, path_in, &parent, &base)) {
1305                 return -1;
1306         }
1307
1308         *path_out = talloc_asprintf(ctx, "%s/._%s", parent, base);
1309         if (*path_out == NULL) {
1310                 return -1;
1311         }
1312
1313         return 0;
1314 }
1315
1316 /**
1317  * Allocate and initialize an AfpInfo struct
1318  **/
1319 static AfpInfo *afpinfo_new(TALLOC_CTX *ctx)
1320 {
1321         AfpInfo *ai = talloc_zero(ctx, AfpInfo);
1322         if (ai == NULL) {
1323                 return NULL;
1324         }
1325         ai->afpi_Signature = AFP_Signature;
1326         ai->afpi_Version = AFP_Version;
1327         ai->afpi_BackupTime = AD_DATE_START;
1328         return ai;
1329 }
1330
1331 /**
1332  * Pack an AfpInfo struct into a buffer
1333  *
1334  * Buffer size must be at least AFP_INFO_SIZE
1335  * Returns size of packed buffer
1336  **/
1337 static ssize_t afpinfo_pack(const AfpInfo *ai, char *buf)
1338 {
1339         memset(buf, 0, AFP_INFO_SIZE);
1340
1341         RSIVAL(buf, 0, ai->afpi_Signature);
1342         RSIVAL(buf, 4, ai->afpi_Version);
1343         RSIVAL(buf, 12, ai->afpi_BackupTime);
1344         memcpy(buf + 16, ai->afpi_FinderInfo, sizeof(ai->afpi_FinderInfo));
1345
1346         return AFP_INFO_SIZE;
1347 }
1348
1349 /**
1350  * Unpack a buffer into a AfpInfo structure
1351  *
1352  * Buffer size must be at least AFP_INFO_SIZE
1353  * Returns allocated AfpInfo struct
1354  **/
1355 static AfpInfo *afpinfo_unpack(TALLOC_CTX *ctx, const void *data)
1356 {
1357         AfpInfo *ai = talloc_zero(ctx, AfpInfo);
1358         if (ai == NULL) {
1359                 return NULL;
1360         }
1361
1362         ai->afpi_Signature = RIVAL(data, 0);
1363         ai->afpi_Version = RIVAL(data, 4);
1364         ai->afpi_BackupTime = RIVAL(data, 12);
1365         memcpy(ai->afpi_FinderInfo, (const char *)data + 16,
1366                sizeof(ai->afpi_FinderInfo));
1367
1368         if (ai->afpi_Signature != AFP_Signature
1369             || ai->afpi_Version != AFP_Version) {
1370                 DEBUG(1, ("Bad AfpInfo signature or version\n"));
1371                 TALLOC_FREE(ai);
1372         }
1373
1374         return ai;
1375 }
1376
1377 /**
1378  * Fake an inode number from the md5 hash of the (xattr) name
1379  **/
1380 static SMB_INO_T fruit_inode(const SMB_STRUCT_STAT *sbuf, const char *sname)
1381 {
1382         MD5_CTX ctx;
1383         unsigned char hash[16];
1384         SMB_INO_T result;
1385         char *upper_sname;
1386
1387         upper_sname = talloc_strdup_upper(talloc_tos(), sname);
1388         SMB_ASSERT(upper_sname != NULL);
1389
1390         MD5Init(&ctx);
1391         MD5Update(&ctx, (const unsigned char *)&(sbuf->st_ex_dev),
1392                   sizeof(sbuf->st_ex_dev));
1393         MD5Update(&ctx, (const unsigned char *)&(sbuf->st_ex_ino),
1394                   sizeof(sbuf->st_ex_ino));
1395         MD5Update(&ctx, (unsigned char *)upper_sname,
1396                   talloc_get_size(upper_sname)-1);
1397         MD5Final(hash, &ctx);
1398
1399         TALLOC_FREE(upper_sname);
1400
1401         /* Hopefully all the variation is in the lower 4 (or 8) bytes! */
1402         memcpy(&result, hash, sizeof(result));
1403
1404         DEBUG(10, ("fruit_inode \"%s\": ino=0x%llu\n",
1405                    sname, (unsigned long long)result));
1406
1407         return result;
1408 }
1409
1410 /**
1411  * Ensure ad_fsp is still valid
1412  **/
1413 static bool fruit_fsp_recheck(struct adouble *ad, files_struct *fsp)
1414 {
1415         if (ad->ad_fsp == fsp) {
1416                 return true;
1417         }
1418         ad->ad_fsp = fsp;
1419
1420         return true;
1421 }
1422
1423 static bool add_fruit_stream(TALLOC_CTX *mem_ctx, unsigned int *num_streams,
1424                              struct stream_struct **streams,
1425                              const char *name, off_t size,
1426                              off_t alloc_size)
1427 {
1428         struct stream_struct *tmp;
1429
1430         tmp = talloc_realloc(mem_ctx, *streams, struct stream_struct,
1431                              (*num_streams)+1);
1432         if (tmp == NULL) {
1433                 return false;
1434         }
1435
1436         tmp[*num_streams].name = talloc_asprintf(tmp, "%s:$DATA", name);
1437         if (tmp[*num_streams].name == NULL) {
1438                 return false;
1439         }
1440
1441         tmp[*num_streams].size = size;
1442         tmp[*num_streams].alloc_size = alloc_size;
1443
1444         *streams = tmp;
1445         *num_streams += 1;
1446         return true;
1447 }
1448
1449 static bool empty_finderinfo(const struct adouble *ad)
1450 {
1451
1452         char emptybuf[ADEDLEN_FINDERI] = {0};
1453         if (memcmp(emptybuf,
1454                    ad_entry(ad, ADEID_FINDERI),
1455                    ADEDLEN_FINDERI) == 0) {
1456                 return true;
1457         }
1458         return false;
1459 }
1460
1461 /**
1462  * Update btime with btime from Netatalk
1463  **/
1464 static void update_btime(vfs_handle_struct *handle,
1465                          struct smb_filename *smb_fname)
1466 {
1467         uint32_t t;
1468         struct timespec creation_time = {0};
1469         struct adouble *ad;
1470
1471         ad = ad_get(talloc_tos(), handle, smb_fname->base_name, ADOUBLE_META);
1472         if (ad == NULL) {
1473                 return;
1474         }
1475         if (ad_getdate(ad, AD_DATE_UNIX | AD_DATE_CREATE, &t) != 0) {
1476                 TALLOC_FREE(ad);
1477                 return;
1478         }
1479         TALLOC_FREE(ad);
1480
1481         creation_time.tv_sec = convert_uint32_t_to_time_t(t);
1482         update_stat_ex_create_time(&smb_fname->st, creation_time);
1483
1484         return;
1485 }
1486
1487 /**
1488  * Map an access mask to a Netatalk single byte byte range lock
1489  **/
1490 static off_t access_to_netatalk_brl(enum apple_fork fork_type,
1491                                     uint32_t access_mask)
1492 {
1493         off_t offset;
1494
1495         switch (access_mask) {
1496         case FILE_READ_DATA:
1497                 offset = AD_FILELOCK_OPEN_RD;
1498                 break;
1499
1500         case FILE_WRITE_DATA:
1501         case FILE_APPEND_DATA:
1502                 offset = AD_FILELOCK_OPEN_WR;
1503                 break;
1504
1505         default:
1506                 offset = AD_FILELOCK_OPEN_NONE;
1507                 break;
1508         }
1509
1510         if (fork_type == APPLE_FORK_RSRC) {
1511                 if (offset == AD_FILELOCK_OPEN_NONE) {
1512                         offset = AD_FILELOCK_RSRC_OPEN_NONE;
1513                 } else {
1514                         offset += 2;
1515                 }
1516         }
1517
1518         return offset;
1519 }
1520
1521 /**
1522  * Map a deny mode to a Netatalk brl
1523  **/
1524 static off_t denymode_to_netatalk_brl(enum apple_fork fork_type,
1525                                       uint32_t deny_mode)
1526 {
1527         off_t offset;
1528
1529         switch (deny_mode) {
1530         case DENY_READ:
1531                 offset = AD_FILELOCK_DENY_RD;
1532                 break;
1533
1534         case DENY_WRITE:
1535                 offset = AD_FILELOCK_DENY_WR;
1536                 break;
1537
1538         default:
1539                 smb_panic("denymode_to_netatalk_brl: bad deny mode\n");
1540         }
1541
1542         if (fork_type == APPLE_FORK_RSRC) {
1543                 offset += 2;
1544         }
1545
1546         return offset;
1547 }
1548
1549 /**
1550  * Call fcntl() with an exclusive F_GETLK request in order to
1551  * determine if there's an exisiting shared lock
1552  *
1553  * @return true if the requested lock was found or any error occured
1554  *         false if the lock was not found
1555  **/
1556 static bool test_netatalk_lock(files_struct *fsp, off_t in_offset)
1557 {
1558         bool result;
1559         off_t offset = in_offset;
1560         off_t len = 1;
1561         int type = F_WRLCK;
1562         pid_t pid;
1563
1564         result = SMB_VFS_GETLOCK(fsp, &offset, &len, &type, &pid);
1565         if (result == false) {
1566                 return true;
1567         }
1568
1569         if (type != F_UNLCK) {
1570                 return true;
1571         }
1572
1573         return false;
1574 }
1575
1576 static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
1577                                    files_struct *fsp,
1578                                    uint32_t access_mask,
1579                                    uint32_t deny_mode)
1580 {
1581         NTSTATUS status = NT_STATUS_OK;
1582         struct byte_range_lock *br_lck = NULL;
1583         bool open_for_reading, open_for_writing, deny_read, deny_write;
1584         off_t off;
1585
1586         /* FIXME: hardcoded data fork, add resource fork */
1587         enum apple_fork fork_type = APPLE_FORK_DATA;
1588
1589         DEBUG(10, ("fruit_check_access: %s, am: %s/%s, dm: %s/%s\n",
1590                   fsp_str_dbg(fsp),
1591                   access_mask & FILE_READ_DATA ? "READ" :"-",
1592                   access_mask & FILE_WRITE_DATA ? "WRITE" : "-",
1593                   deny_mode & DENY_READ ? "DENY_READ" : "-",
1594                   deny_mode & DENY_WRITE ? "DENY_WRITE" : "-"));
1595
1596         /*
1597          * Check read access and deny read mode
1598          */
1599         if ((access_mask & FILE_READ_DATA) || (deny_mode & DENY_READ)) {
1600                 /* Check access */
1601                 open_for_reading = test_netatalk_lock(
1602                         fsp, access_to_netatalk_brl(fork_type, FILE_READ_DATA));
1603
1604                 deny_read = test_netatalk_lock(
1605                         fsp, denymode_to_netatalk_brl(fork_type, DENY_READ));
1606
1607                 DEBUG(10, ("read: %s, deny_write: %s\n",
1608                           open_for_reading == true ? "yes" : "no",
1609                           deny_read == true ? "yes" : "no"));
1610
1611                 if (((access_mask & FILE_READ_DATA) && deny_read)
1612                     || ((deny_mode & DENY_READ) && open_for_reading)) {
1613                         return NT_STATUS_SHARING_VIOLATION;
1614                 }
1615
1616                 /* Set locks */
1617                 if (access_mask & FILE_READ_DATA) {
1618                         off = access_to_netatalk_brl(fork_type, FILE_READ_DATA);
1619                         br_lck = do_lock(
1620                                 handle->conn->sconn->msg_ctx, fsp,
1621                                 fsp->op->global->open_persistent_id, 1, off,
1622                                 READ_LOCK, POSIX_LOCK, false,
1623                                 &status, NULL);
1624
1625                         if (!NT_STATUS_IS_OK(status))  {
1626                                 return status;
1627                         }
1628                         TALLOC_FREE(br_lck);
1629                 }
1630
1631                 if (deny_mode & DENY_READ) {
1632                         off = denymode_to_netatalk_brl(fork_type, DENY_READ);
1633                         br_lck = do_lock(
1634                                 handle->conn->sconn->msg_ctx, fsp,
1635                                 fsp->op->global->open_persistent_id, 1, off,
1636                                 READ_LOCK, POSIX_LOCK, false,
1637                                 &status, NULL);
1638
1639                         if (!NT_STATUS_IS_OK(status)) {
1640                                 return status;
1641                         }
1642                         TALLOC_FREE(br_lck);
1643                 }
1644         }
1645
1646         /*
1647          * Check write access and deny write mode
1648          */
1649         if ((access_mask & FILE_WRITE_DATA) || (deny_mode & DENY_WRITE)) {
1650                 /* Check access */
1651                 open_for_writing = test_netatalk_lock(
1652                         fsp, access_to_netatalk_brl(fork_type, FILE_WRITE_DATA));
1653
1654                 deny_write = test_netatalk_lock(
1655                         fsp, denymode_to_netatalk_brl(fork_type, DENY_WRITE));
1656
1657                 DEBUG(10, ("write: %s, deny_write: %s\n",
1658                           open_for_writing == true ? "yes" : "no",
1659                           deny_write == true ? "yes" : "no"));
1660
1661                 if (((access_mask & FILE_WRITE_DATA) && deny_write)
1662                     || ((deny_mode & DENY_WRITE) && open_for_writing)) {
1663                         return NT_STATUS_SHARING_VIOLATION;
1664                 }
1665
1666                 /* Set locks */
1667                 if (access_mask & FILE_WRITE_DATA) {
1668                         off = access_to_netatalk_brl(fork_type, FILE_WRITE_DATA);
1669                         br_lck = do_lock(
1670                                 handle->conn->sconn->msg_ctx, fsp,
1671                                 fsp->op->global->open_persistent_id, 1, off,
1672                                 READ_LOCK, POSIX_LOCK, false,
1673                                 &status, NULL);
1674
1675                         if (!NT_STATUS_IS_OK(status)) {
1676                                 return status;
1677                         }
1678                         TALLOC_FREE(br_lck);
1679
1680                 }
1681                 if (deny_mode & DENY_WRITE) {
1682                         off = denymode_to_netatalk_brl(fork_type, DENY_WRITE);
1683                         br_lck = do_lock(
1684                                 handle->conn->sconn->msg_ctx, fsp,
1685                                 fsp->op->global->open_persistent_id, 1, off,
1686                                 READ_LOCK, POSIX_LOCK, false,
1687                                 &status, NULL);
1688
1689                         if (!NT_STATUS_IS_OK(status)) {
1690                                 return status;
1691                         }
1692                         TALLOC_FREE(br_lck);
1693                 }
1694         }
1695
1696         TALLOC_FREE(br_lck);
1697
1698         return status;
1699 }
1700
1701 static NTSTATUS check_aapl(vfs_handle_struct *handle,
1702                            struct smb_request *req,
1703                            const struct smb2_create_blobs *in_context_blobs,
1704                            struct smb2_create_blobs *out_context_blobs)
1705 {
1706         struct fruit_config_data *config;
1707         NTSTATUS status;
1708         struct smb2_create_blob *aapl = NULL;
1709         uint32_t cmd;
1710         bool ok;
1711         uint8_t p[16];
1712         DATA_BLOB blob = data_blob_talloc(req, NULL, 0);
1713         uint64_t req_bitmap, client_caps;
1714         uint64_t server_caps = SMB2_CRTCTX_AAPL_UNIX_BASED;
1715         smb_ucs2_t *model;
1716         size_t modellen;
1717
1718         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
1719                                 return NT_STATUS_UNSUCCESSFUL);
1720
1721         if (!config->use_aapl
1722             || in_context_blobs == NULL
1723             || out_context_blobs == NULL) {
1724                 return NT_STATUS_OK;
1725         }
1726
1727         aapl = smb2_create_blob_find(in_context_blobs,
1728                                      SMB2_CREATE_TAG_AAPL);
1729         if (aapl == NULL) {
1730                 return NT_STATUS_OK;
1731         }
1732
1733         if (aapl->data.length != 24) {
1734                 DEBUG(1, ("unexpected AAPL ctxt legnth: %ju\n",
1735                           (uintmax_t)aapl->data.length));
1736                 return NT_STATUS_INVALID_PARAMETER;
1737         }
1738
1739         cmd = IVAL(aapl->data.data, 0);
1740         if (cmd != SMB2_CRTCTX_AAPL_SERVER_QUERY) {
1741                 DEBUG(1, ("unsupported AAPL cmd: %d\n", cmd));
1742                 return NT_STATUS_INVALID_PARAMETER;
1743         }
1744
1745         req_bitmap = BVAL(aapl->data.data, 8);
1746         client_caps = BVAL(aapl->data.data, 16);
1747
1748         SIVAL(p, 0, SMB2_CRTCTX_AAPL_SERVER_QUERY);
1749         SIVAL(p, 4, 0);
1750         SBVAL(p, 8, req_bitmap);
1751         ok = data_blob_append(req, &blob, p, 16);
1752         if (!ok) {
1753                 return NT_STATUS_UNSUCCESSFUL;
1754         }
1755
1756         if (req_bitmap & SMB2_CRTCTX_AAPL_SERVER_CAPS) {
1757                 if ((client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR) &&
1758                     (handle->conn->tcon->compat->fs_capabilities & FILE_NAMED_STREAMS)) {
1759                         server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR;
1760                         config->readdir_attr_enabled = true;
1761                 }
1762
1763                 /*
1764                  * The client doesn't set the flag, so we can't check
1765                  * for it and just set it unconditionally
1766                  */
1767                 server_caps |= SMB2_CRTCTX_AAPL_SUPPORTS_NFS_ACE;
1768                 config->unix_info_enabled = true;
1769
1770                 SBVAL(p, 0, server_caps);
1771                 ok = data_blob_append(req, &blob, p, 8);
1772                 if (!ok) {
1773                         return NT_STATUS_UNSUCCESSFUL;
1774                 }
1775         }
1776
1777         if (req_bitmap & SMB2_CRTCTX_AAPL_VOLUME_CAPS) {
1778                 SBVAL(p, 0,
1779                       lp_case_sensitive(SNUM(handle->conn->tcon->compat)) ?
1780                       SMB2_CRTCTX_AAPL_CASE_SENSITIVE : 0);
1781                 ok = data_blob_append(req, &blob, p, 8);
1782                 if (!ok) {
1783                         return NT_STATUS_UNSUCCESSFUL;
1784                 }
1785         }
1786
1787         if (req_bitmap & SMB2_CRTCTX_AAPL_MODEL_INFO) {
1788                 ok = convert_string_talloc(req,
1789                                            CH_UNIX, CH_UTF16LE,
1790                                            "Samba", strlen("Samba"),
1791                                            &model, &modellen);
1792                 if (!ok) {
1793                         return NT_STATUS_UNSUCCESSFUL;
1794                 }
1795
1796                 SIVAL(p, 0, 0);
1797                 SIVAL(p + 4, 0, modellen);
1798                 ok = data_blob_append(req, &blob, p, 8);
1799                 if (!ok) {
1800                         talloc_free(model);
1801                         return NT_STATUS_UNSUCCESSFUL;
1802                 }
1803
1804                 ok = data_blob_append(req, &blob, model, modellen);
1805                 talloc_free(model);
1806                 if (!ok) {
1807                         return NT_STATUS_UNSUCCESSFUL;
1808                 }
1809         }
1810
1811         status = smb2_create_blob_add(out_context_blobs,
1812                                       out_context_blobs,
1813                                       SMB2_CREATE_TAG_AAPL,
1814                                       blob);
1815
1816         return status;
1817 }
1818
1819 static NTSTATUS readdir_attr_macmeta(struct vfs_handle_struct *handle,
1820                                      const struct smb_filename *smb_fname,
1821                                      struct readdir_attr_data *attr_data)
1822 {
1823         NTSTATUS status = NT_STATUS_OK;
1824         uint32_t date_added;
1825         struct adouble *ad = NULL;
1826         struct fruit_config_data *config = NULL;
1827
1828         SMB_VFS_HANDLE_GET_DATA(handle, config,
1829                                 struct fruit_config_data,
1830                                 return NT_STATUS_UNSUCCESSFUL);
1831
1832
1833         /* Ensure we return a default value in the creation_date field */
1834         RSIVAL(&attr_data->attr_data.aapl.finder_info, 12, AD_DATE_START);
1835
1836         /*
1837          * Resource fork length
1838          */
1839
1840         if (config->readdir_attr_rsize) {
1841                 ad = ad_get(talloc_tos(), handle, smb_fname->base_name,
1842                             ADOUBLE_RSRC);
1843                 if (ad) {
1844                         attr_data->attr_data.aapl.rfork_size = ad_getentrylen(
1845                                 ad, ADEID_RFORK);
1846                         TALLOC_FREE(ad);
1847                 }
1848         }
1849
1850         /*
1851          * FinderInfo
1852          */
1853
1854         if (config->readdir_attr_finder_info) {
1855                 ad = ad_get(talloc_tos(), handle, smb_fname->base_name,
1856                             ADOUBLE_META);
1857                 if (ad) {
1858                         if (S_ISREG(smb_fname->st.st_ex_mode)) {
1859                                 /* finder_type */
1860                                 memcpy(&attr_data->attr_data.aapl.finder_info[0],
1861                                        ad_entry(ad, ADEID_FINDERI), 4);
1862
1863                                 /* finder_creator */
1864                                 memcpy(&attr_data->attr_data.aapl.finder_info[0] + 4,
1865                                        ad_entry(ad, ADEID_FINDERI) + 4, 4);
1866                         }
1867
1868                         /* finder_flags */
1869                         memcpy(&attr_data->attr_data.aapl.finder_info[0] + 8,
1870                                ad_entry(ad, ADEID_FINDERI) + 8, 2);
1871
1872                         /* finder_ext_flags */
1873                         memcpy(&attr_data->attr_data.aapl.finder_info[0] + 10,
1874                                ad_entry(ad, ADEID_FINDERI) + 24, 2);
1875
1876                         /* creation date */
1877                         date_added = convert_time_t_to_uint32_t(
1878                                 smb_fname->st.st_ex_btime.tv_sec - AD_DATE_DELTA);
1879                         RSIVAL(&attr_data->attr_data.aapl.finder_info[0], 12, date_added);
1880
1881                         TALLOC_FREE(ad);
1882                 }
1883         }
1884
1885         TALLOC_FREE(ad);
1886         return status;
1887 }
1888
1889 /* Search MS NFS style ACE with UNIX mode */
1890 static NTSTATUS check_ms_nfs(vfs_handle_struct *handle,
1891                              files_struct *fsp,
1892                              const struct security_descriptor *psd,
1893                              mode_t *pmode,
1894                              bool *pdo_chmod)
1895 {
1896         int i;
1897         struct fruit_config_data *config = NULL;
1898
1899         *pdo_chmod = false;
1900
1901         SMB_VFS_HANDLE_GET_DATA(handle, config,
1902                                 struct fruit_config_data,
1903                                 return NT_STATUS_UNSUCCESSFUL);
1904
1905         if (psd->dacl == NULL || !config->unix_info_enabled) {
1906                 return NT_STATUS_OK;
1907         }
1908
1909         for (i = 0; i < psd->dacl->num_aces; i++) {
1910                 if (dom_sid_compare_domain(
1911                             &global_sid_Unix_NFS_Mode,
1912                             &psd->dacl->aces[i].trustee) == 0) {
1913                         *pmode = (mode_t)psd->dacl->aces[i].trustee.sub_auths[2];
1914                         *pmode &= (S_IRWXU | S_IRWXG | S_IRWXO);
1915                         *pdo_chmod = true;
1916
1917                         DEBUG(10, ("MS NFS chmod request %s, %04o\n",
1918                                    fsp_str_dbg(fsp), *pmode));
1919                         break;
1920                 }
1921         }
1922
1923         return NT_STATUS_OK;
1924 }
1925
1926 /****************************************************************************
1927  * VFS ops
1928  ****************************************************************************/
1929
1930 static int fruit_connect(vfs_handle_struct *handle,
1931                          const char *service,
1932                          const char *user)
1933 {
1934         int rc;
1935         char *list = NULL, *newlist = NULL;
1936         struct fruit_config_data *config;
1937
1938         DEBUG(10, ("fruit_connect\n"));
1939
1940         rc = SMB_VFS_NEXT_CONNECT(handle, service, user);
1941         if (rc < 0) {
1942                 return rc;
1943         }
1944
1945         list = lp_veto_files(talloc_tos(), SNUM(handle->conn));
1946
1947         if (list) {
1948                 if (strstr(list, "/" ADOUBLE_NAME_PREFIX "*/") == NULL) {
1949                         newlist = talloc_asprintf(
1950                                 list,
1951                                 "%s/" ADOUBLE_NAME_PREFIX "*/",
1952                                 list);
1953                         lp_do_parameter(SNUM(handle->conn),
1954                                         "veto files",
1955                                         newlist);
1956                 }
1957         } else {
1958                 lp_do_parameter(SNUM(handle->conn),
1959                                 "veto files",
1960                                 "/" ADOUBLE_NAME_PREFIX "*/");
1961         }
1962
1963         TALLOC_FREE(list);
1964
1965         rc = init_fruit_config(handle);
1966         if (rc != 0) {
1967                 return rc;
1968         }
1969
1970         SMB_VFS_HANDLE_GET_DATA(handle, config,
1971                                 struct fruit_config_data, return -1);
1972
1973         if (config->encoding == FRUIT_ENC_NATIVE) {
1974                 lp_do_parameter(
1975                         SNUM(handle->conn),
1976                         "catia:mappings",
1977                         "0x22:0xf020,0x2a:0xf021,0x3a:0xf022,0x3c:0xf023,"
1978                         "0x3e:0xf024,0x3f:0xf025,0x5c:0xf026,0x7c:0xf027,"
1979                         "0x0d:0xf00d");
1980         }
1981
1982         return rc;
1983 }
1984
1985 static int fruit_open_meta(vfs_handle_struct *handle,
1986                            struct smb_filename *smb_fname,
1987                            files_struct *fsp, int flags, mode_t mode)
1988 {
1989         int rc = 0;
1990         struct fruit_config_data *config = NULL;
1991         struct smb_filename *smb_fname_base = NULL;
1992         int baseflags;
1993         int hostfd = -1;
1994         struct adouble *ad = NULL;
1995
1996         DEBUG(10, ("fruit_open_meta for %s\n", smb_fname_str_dbg(smb_fname)));
1997
1998         SMB_VFS_HANDLE_GET_DATA(handle, config,
1999                                 struct fruit_config_data, return -1);
2000
2001         if (config->meta == FRUIT_META_STREAM) {
2002                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
2003         }
2004
2005         /* Create an smb_filename with stream_name == NULL. */
2006         smb_fname_base = synthetic_smb_fname(talloc_tos(),
2007                                              smb_fname->base_name, NULL, NULL);
2008
2009         if (smb_fname_base == NULL) {
2010                 errno = ENOMEM;
2011                 rc = -1;
2012                 goto exit;
2013         }
2014
2015         /*
2016          * We use baseflags to turn off nasty side-effects when opening the
2017          * underlying file.
2018          */
2019         baseflags = flags;
2020         baseflags &= ~O_TRUNC;
2021         baseflags &= ~O_EXCL;
2022         baseflags &= ~O_CREAT;
2023
2024         hostfd = SMB_VFS_OPEN(handle->conn, smb_fname_base, fsp,
2025                               baseflags, mode);
2026
2027         /*
2028          * It is legit to open a stream on a directory, but the base
2029          * fd has to be read-only.
2030          */
2031         if ((hostfd == -1) && (errno == EISDIR)) {
2032                 baseflags &= ~O_ACCMODE;
2033                 baseflags |= O_RDONLY;
2034                 hostfd = SMB_VFS_OPEN(handle->conn, smb_fname_base, fsp,
2035                                       baseflags, mode);
2036         }
2037
2038         TALLOC_FREE(smb_fname_base);
2039
2040         if (hostfd == -1) {
2041                 rc = -1;
2042                 goto exit;
2043         }
2044
2045         if (flags & (O_CREAT | O_TRUNC)) {
2046                 /*
2047                  * The attribute does not exist or needs to be truncated,
2048                  * create an AppleDouble EA
2049                  */
2050                 ad = ad_init(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2051                              handle, ADOUBLE_META, fsp);
2052                 if (ad == NULL) {
2053                         rc = -1;
2054                         goto exit;
2055                 }
2056
2057                 rc = ad_write(ad, smb_fname->base_name);
2058                 if (rc != 0) {
2059                         rc = -1;
2060                         goto exit;
2061                 }
2062         } else {
2063                 ad = ad_alloc(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2064                               handle, ADOUBLE_META, fsp);
2065                 if (ad == NULL) {
2066                         rc = -1;
2067                         goto exit;
2068                 }
2069                 if (ad_read(ad, smb_fname->base_name) == -1) {
2070                         rc = -1;
2071                         goto exit;
2072                 }
2073         }
2074
2075 exit:
2076         DEBUG(10, ("fruit_open meta rc=%d, fd=%d\n", rc, hostfd));
2077         if (rc != 0) {
2078                 int saved_errno = errno;
2079                 if (hostfd >= 0) {
2080                         /*
2081                          * BUGBUGBUG -- we would need to call
2082                          * fd_close_posix here, but we don't have a
2083                          * full fsp yet
2084                          */
2085                         fsp->fh->fd = hostfd;
2086                         SMB_VFS_CLOSE(fsp);
2087                 }
2088                 hostfd = -1;
2089                 errno = saved_errno;
2090         }
2091         return hostfd;
2092 }
2093
2094 static int fruit_open_rsrc(vfs_handle_struct *handle,
2095                            struct smb_filename *smb_fname,
2096                            files_struct *fsp, int flags, mode_t mode)
2097 {
2098         int rc = 0;
2099         struct fruit_config_data *config = NULL;
2100         struct adouble *ad = NULL;
2101         struct smb_filename *smb_fname_base = NULL;
2102         char *adpath = NULL;
2103         int hostfd = -1;
2104
2105         DEBUG(10, ("fruit_open_rsrc for %s\n", smb_fname_str_dbg(smb_fname)));
2106
2107         SMB_VFS_HANDLE_GET_DATA(handle, config,
2108                                 struct fruit_config_data, return -1);
2109
2110         switch (config->rsrc) {
2111         case FRUIT_RSRC_STREAM:
2112                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
2113         case FRUIT_RSRC_XATTR:
2114 #ifdef HAVE_ATTROPEN
2115                 hostfd = attropen(smb_fname->base_name,
2116                                   AFPRESOURCE_EA_NETATALK, flags, mode);
2117                 if (hostfd == -1) {
2118                         return -1;
2119                 }
2120                 ad = ad_init(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2121                              handle, ADOUBLE_RSRC, fsp);
2122                 if (ad == NULL) {
2123                         rc = -1;
2124                         goto exit;
2125                 }
2126                 goto exit;
2127 #else
2128                 errno = ENOTSUP;
2129                 return -1;
2130 #endif
2131         default:
2132                 break;
2133         }
2134
2135         if (!(flags & O_CREAT) && !VALID_STAT(smb_fname->st)) {
2136                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
2137                 if (rc != 0) {
2138                         rc = -1;
2139                         goto exit;
2140                 }
2141         }
2142
2143         if (VALID_STAT(smb_fname->st) && S_ISDIR(smb_fname->st.st_ex_mode)) {
2144                 /* sorry, but directories don't habe a resource fork */
2145                 rc = -1;
2146                 goto exit;
2147         }
2148
2149         rc = adouble_path(talloc_tos(), smb_fname->base_name, &adpath);
2150         if (rc != 0) {
2151                 goto exit;
2152         }
2153
2154         /* Create an smb_filename with stream_name == NULL. */
2155         smb_fname_base = synthetic_smb_fname(talloc_tos(),
2156                                              adpath, NULL, NULL);
2157         if (smb_fname_base == NULL) {
2158                 errno = ENOMEM;
2159                 rc = -1;
2160                 goto exit;
2161         }
2162
2163         /* Sanitize flags */
2164         if (flags & O_WRONLY) {
2165                 /* We always need read access for the metadata header too */
2166                 flags &= ~O_WRONLY;
2167                 flags |= O_RDWR;
2168         }
2169
2170         hostfd = SMB_VFS_OPEN(handle->conn, smb_fname_base, fsp,
2171                               flags, mode);
2172         if (hostfd == -1) {
2173                 rc = -1;
2174                 goto exit;
2175         }
2176
2177         /* REVIEW: we need this in ad_write() */
2178         fsp->fh->fd = hostfd;
2179
2180         if (flags & (O_CREAT | O_TRUNC)) {
2181                 ad = ad_init(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2182                              handle, ADOUBLE_RSRC, fsp);
2183                 if (ad == NULL) {
2184                         rc = -1;
2185                         goto exit;
2186                 }
2187                 rc = ad_write(ad, smb_fname->base_name);
2188                 if (rc != 0) {
2189                         rc = -1;
2190                         goto exit;
2191                 }
2192         } else {
2193                 ad = ad_alloc(VFS_MEMCTX_FSP_EXTENSION(handle, fsp),
2194                               handle, ADOUBLE_RSRC, fsp);
2195                 if (ad == NULL) {
2196                         rc = -1;
2197                         goto exit;
2198                 }
2199                 if (ad_read(ad, smb_fname->base_name) == -1) {
2200                         rc = -1;
2201                         goto exit;
2202                 }
2203         }
2204
2205 exit:
2206
2207         TALLOC_FREE(adpath);
2208         TALLOC_FREE(smb_fname_base);
2209
2210         DEBUG(10, ("fruit_open resource fork: rc=%d, fd=%d\n", rc, hostfd));
2211         if (rc != 0) {
2212                 int saved_errno = errno;
2213                 if (hostfd >= 0) {
2214                         /*
2215                          * BUGBUGBUG -- we would need to call
2216                          * fd_close_posix here, but we don't have a
2217                          * full fsp yet
2218                          */
2219                         fsp->fh->fd = hostfd;
2220                         SMB_VFS_CLOSE(fsp);
2221                 }
2222                 hostfd = -1;
2223                 errno = saved_errno;
2224         }
2225         return hostfd;
2226 }
2227
2228 static int fruit_open(vfs_handle_struct *handle,
2229                       struct smb_filename *smb_fname,
2230                       files_struct *fsp, int flags, mode_t mode)
2231 {
2232         DEBUG(10, ("fruit_open called for %s\n",
2233                    smb_fname_str_dbg(smb_fname)));
2234
2235         if (!is_ntfs_stream_smb_fname(smb_fname)) {
2236                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
2237         }
2238
2239         if (is_afpinfo_stream(smb_fname)) {
2240                 return fruit_open_meta(handle, smb_fname, fsp, flags, mode);
2241         } else if (is_afpresource_stream(smb_fname)) {
2242                 return fruit_open_rsrc(handle, smb_fname, fsp, flags, mode);
2243         }
2244
2245         return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
2246 }
2247
2248 static int fruit_rename(struct vfs_handle_struct *handle,
2249                         const struct smb_filename *smb_fname_src,
2250                         const struct smb_filename *smb_fname_dst)
2251 {
2252         int rc = -1;
2253         char *src_adouble_path = NULL;
2254         char *dst_adouble_path = NULL;
2255         struct fruit_config_data *config = NULL;
2256
2257         rc = SMB_VFS_NEXT_RENAME(handle, smb_fname_src, smb_fname_dst);
2258
2259         if (!VALID_STAT(smb_fname_src->st)
2260             || !S_ISREG(smb_fname_src->st.st_ex_mode)) {
2261                 return rc;
2262         }
2263
2264         SMB_VFS_HANDLE_GET_DATA(handle, config,
2265                                 struct fruit_config_data, return -1);
2266
2267         if (config->rsrc == FRUIT_RSRC_XATTR) {
2268                 return rc;
2269         }
2270
2271         rc = adouble_path(talloc_tos(), smb_fname_src->base_name,
2272                           &src_adouble_path);
2273         if (rc != 0) {
2274                 goto done;
2275         }
2276         rc = adouble_path(talloc_tos(), smb_fname_dst->base_name,
2277                           &dst_adouble_path);
2278         if (rc != 0) {
2279                 goto done;
2280         }
2281
2282         DEBUG(10, ("fruit_rename: %s -> %s\n",
2283                    src_adouble_path, dst_adouble_path));
2284
2285         rc = rename(src_adouble_path, dst_adouble_path);
2286         if (errno == ENOENT) {
2287                 rc = 0;
2288         }
2289
2290         TALLOC_FREE(src_adouble_path);
2291         TALLOC_FREE(dst_adouble_path);
2292
2293 done:
2294         return rc;
2295 }
2296
2297 static int fruit_unlink(vfs_handle_struct *handle,
2298                         const struct smb_filename *smb_fname)
2299 {
2300         int rc = -1;
2301         struct fruit_config_data *config = NULL;
2302         char *adp = NULL;
2303
2304         if (!is_ntfs_stream_smb_fname(smb_fname)) {
2305                 return SMB_VFS_NEXT_UNLINK(handle, smb_fname);
2306         }
2307
2308         SMB_VFS_HANDLE_GET_DATA(handle, config,
2309                                 struct fruit_config_data, return -1);
2310
2311         if (is_afpinfo_stream(smb_fname)) {
2312                 if (config->meta == FRUIT_META_STREAM) {
2313                         rc = SMB_VFS_NEXT_UNLINK(handle, smb_fname);
2314                 } else {
2315                         rc = SMB_VFS_REMOVEXATTR(handle->conn,
2316                                                  smb_fname->base_name,
2317                                                  AFPINFO_EA_NETATALK);
2318                 }
2319         } else if (is_afpresource_stream(smb_fname)) {
2320                 if (config->rsrc == FRUIT_RSRC_ADFILE) {
2321                         rc = adouble_path(talloc_tos(),
2322                                           smb_fname->base_name, &adp);
2323                         if (rc != 0) {
2324                                 return -1;
2325                         }
2326                         /* FIXME: direct unlink(), missing smb_fname */
2327                         rc = unlink(adp);
2328                         if ((rc == -1) && (errno == ENOENT)) {
2329                                 rc = 0;
2330                         }
2331                 } else {
2332                         rc = SMB_VFS_REMOVEXATTR(handle->conn,
2333                                      smb_fname->base_name,
2334                                      AFPRESOURCE_EA_NETATALK);
2335                 }
2336         } else {
2337                 rc = SMB_VFS_NEXT_UNLINK(handle, smb_fname);
2338         }
2339
2340         TALLOC_FREE(adp);
2341         return rc;
2342 }
2343
2344 static int fruit_chmod(vfs_handle_struct *handle,
2345                        const char *path,
2346                        mode_t mode)
2347 {
2348         int rc = -1;
2349         char *adp = NULL;
2350         struct fruit_config_data *config = NULL;
2351         SMB_STRUCT_STAT sb;
2352
2353         rc = SMB_VFS_NEXT_CHMOD(handle, path, mode);
2354         if (rc != 0) {
2355                 return rc;
2356         }
2357
2358         SMB_VFS_HANDLE_GET_DATA(handle, config,
2359                                 struct fruit_config_data, return -1);
2360
2361         if (config->rsrc == FRUIT_RSRC_XATTR) {
2362                 return 0;
2363         }
2364
2365         /* FIXME: direct sys_lstat(), missing smb_fname */
2366         rc = sys_lstat(path, &sb, false);
2367         if (rc != 0 || !S_ISREG(sb.st_ex_mode)) {
2368                 return rc;
2369         }
2370
2371         rc = adouble_path(talloc_tos(), path, &adp);
2372         if (rc != 0) {
2373                 return -1;
2374         }
2375
2376         DEBUG(10, ("fruit_chmod: %s\n", adp));
2377
2378         rc = SMB_VFS_NEXT_CHMOD(handle, adp, mode);
2379         if (errno == ENOENT) {
2380                 rc = 0;
2381         }
2382
2383         TALLOC_FREE(adp);
2384         return rc;
2385 }
2386
2387 static int fruit_chown(vfs_handle_struct *handle,
2388                        const char *path,
2389                        uid_t uid,
2390                        gid_t gid)
2391 {
2392         int rc = -1;
2393         char *adp = NULL;
2394         struct fruit_config_data *config = NULL;
2395         SMB_STRUCT_STAT sb;
2396
2397         rc = SMB_VFS_NEXT_CHOWN(handle, path, uid, gid);
2398         if (rc != 0) {
2399                 return rc;
2400         }
2401
2402         SMB_VFS_HANDLE_GET_DATA(handle, config,
2403                                 struct fruit_config_data, return -1);
2404
2405         if (config->rsrc == FRUIT_RSRC_XATTR) {
2406                 return rc;
2407         }
2408
2409         /* FIXME: direct sys_lstat(), missing smb_fname */
2410         rc = sys_lstat(path, &sb, false);
2411         if (rc != 0 || !S_ISREG(sb.st_ex_mode)) {
2412                 return rc;
2413         }
2414
2415         rc = adouble_path(talloc_tos(), path, &adp);
2416         if (rc != 0) {
2417                 goto done;
2418         }
2419
2420         DEBUG(10, ("fruit_chown: %s\n", adp));
2421
2422         rc = SMB_VFS_NEXT_CHOWN(handle, adp, uid, gid);
2423         if (errno == ENOENT) {
2424                 rc = 0;
2425         }
2426
2427  done:
2428         TALLOC_FREE(adp);
2429         return rc;
2430 }
2431
2432 static int fruit_rmdir(struct vfs_handle_struct *handle, const char *path)
2433 {
2434         DIR *dh = NULL;
2435         struct dirent *de;
2436         struct fruit_config_data *config;
2437
2438         SMB_VFS_HANDLE_GET_DATA(handle, config,
2439                                 struct fruit_config_data, return -1);
2440
2441         if (!handle->conn->cwd || !path || (config->rsrc == FRUIT_RSRC_XATTR)) {
2442                 goto exit_rmdir;
2443         }
2444
2445         /*
2446          * Due to there is no way to change bDeleteVetoFiles variable
2447          * from this module, need to clean up ourselves
2448          */
2449         dh = opendir(path);
2450         if (dh == NULL) {
2451                 goto exit_rmdir;
2452         }
2453
2454         while ((de = readdir(dh)) != NULL) {
2455                 if ((strncmp(de->d_name,
2456                              ADOUBLE_NAME_PREFIX,
2457                              strlen(ADOUBLE_NAME_PREFIX))) == 0) {
2458                         char *p = talloc_asprintf(talloc_tos(),
2459                                                   "%s/%s",
2460                                                   path, de->d_name);
2461                         if (p == NULL) {
2462                                 goto exit_rmdir;
2463                         }
2464                         DEBUG(10, ("fruit_rmdir: delete %s\n", p));
2465                         (void)unlink(p);
2466                         TALLOC_FREE(p);
2467                 }
2468         }
2469
2470 exit_rmdir:
2471         if (dh) {
2472                 closedir(dh);
2473         }
2474         return SMB_VFS_NEXT_RMDIR(handle, path);
2475 }
2476
2477 static ssize_t fruit_pread(vfs_handle_struct *handle,
2478                            files_struct *fsp, void *data,
2479                            size_t n, off_t offset)
2480 {
2481         int rc = 0;
2482         struct adouble *ad = (struct adouble *)VFS_FETCH_FSP_EXTENSION(
2483                 handle, fsp);
2484         struct fruit_config_data *config = NULL;
2485         AfpInfo *ai = NULL;
2486         ssize_t len;
2487         char *name = NULL;
2488         char *tmp_base_name = NULL;
2489         NTSTATUS status;
2490
2491         DEBUG(10, ("fruit_pread: offset=%d, size=%d\n", (int)offset, (int)n));
2492
2493         if (!fsp->base_fsp) {
2494                 return SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
2495         }
2496
2497         SMB_VFS_HANDLE_GET_DATA(handle, config,
2498                                 struct fruit_config_data, return -1);
2499
2500         /* fsp_name is not converted with vfs_catia */
2501         tmp_base_name = fsp->base_fsp->fsp_name->base_name;
2502         status = SMB_VFS_TRANSLATE_NAME(handle->conn,
2503                                         fsp->base_fsp->fsp_name->base_name,
2504                                         vfs_translate_to_unix,
2505                                         talloc_tos(), &name);
2506         if (NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED)) {
2507                 name = talloc_strdup(talloc_tos(), tmp_base_name);
2508                 if (name == NULL) {
2509                         rc = -1;
2510                         goto exit;
2511                 }
2512         } else if (!NT_STATUS_IS_OK(status)) {
2513                 errno = map_errno_from_nt_status(status);
2514                 rc = -1;
2515                 goto exit;
2516         }
2517         fsp->base_fsp->fsp_name->base_name = name;
2518
2519         if (ad == NULL) {
2520                 len = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
2521                 if (len == -1) {
2522                         rc = -1;
2523                         goto exit;
2524                 }
2525                 goto exit;
2526         }
2527
2528         if (!fruit_fsp_recheck(ad, fsp)) {
2529                 rc = -1;
2530                 goto exit;
2531         }
2532
2533         if (ad->ad_type == ADOUBLE_META) {
2534                 ai = afpinfo_new(talloc_tos());
2535                 if (ai == NULL) {
2536                         rc = -1;
2537                         goto exit;
2538                 }
2539
2540                 len = ad_read(ad, fsp->base_fsp->fsp_name->base_name);
2541                 if (len == -1) {
2542                         rc = -1;
2543                         goto exit;
2544                 }
2545
2546                 memcpy(&ai->afpi_FinderInfo[0],
2547                        ad_entry(ad, ADEID_FINDERI),
2548                        ADEDLEN_FINDERI);
2549                 len = afpinfo_pack(ai, data);
2550                 if (len != AFP_INFO_SIZE) {
2551                         rc = -1;
2552                         goto exit;
2553                 }
2554         } else {
2555                 len = SMB_VFS_NEXT_PREAD(
2556                         handle, fsp, data, n,
2557                         offset + ad_getentryoff(ad, ADEID_RFORK));
2558                 if (len == -1) {
2559                         rc = -1;
2560                         goto exit;
2561                 }
2562         }
2563 exit:
2564         fsp->base_fsp->fsp_name->base_name = tmp_base_name;
2565         TALLOC_FREE(name);
2566         TALLOC_FREE(ai);
2567         if (rc != 0) {
2568                 len = -1;
2569         }
2570         DEBUG(10, ("fruit_pread: rc=%d, len=%zd\n", rc, len));
2571         return len;
2572 }
2573
2574 static ssize_t fruit_pwrite(vfs_handle_struct *handle,
2575                             files_struct *fsp, const void *data,
2576                             size_t n, off_t offset)
2577 {
2578         int rc = 0;
2579         struct adouble *ad = (struct adouble *)VFS_FETCH_FSP_EXTENSION(
2580                 handle, fsp);
2581         struct fruit_config_data *config = NULL;
2582         AfpInfo *ai = NULL;
2583         ssize_t len;
2584         char *name = NULL;
2585         char *tmp_base_name = NULL;
2586         NTSTATUS status;
2587
2588         DEBUG(10, ("fruit_pwrite: offset=%d, size=%d\n", (int)offset, (int)n));
2589
2590         if (!fsp->base_fsp) {
2591                 return SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2592         }
2593
2594         SMB_VFS_HANDLE_GET_DATA(handle, config,
2595                                 struct fruit_config_data, return -1);
2596
2597         tmp_base_name = fsp->base_fsp->fsp_name->base_name;
2598         status = SMB_VFS_TRANSLATE_NAME(handle->conn,
2599                                         fsp->base_fsp->fsp_name->base_name,
2600                                         vfs_translate_to_unix,
2601                                         talloc_tos(), &name);
2602         if (NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED)) {
2603                 name = talloc_strdup(talloc_tos(), tmp_base_name);
2604                 if (name == NULL) {
2605                         rc = -1;
2606                         goto exit;
2607                 }
2608         } else if (!NT_STATUS_IS_OK(status)) {
2609                 errno = map_errno_from_nt_status(status);
2610                 rc = -1;
2611                 goto exit;
2612         }
2613         fsp->base_fsp->fsp_name->base_name = name;
2614
2615         if (ad == NULL) {
2616                 len = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2617                 if (len != n) {
2618                         rc = -1;
2619                         goto exit;
2620                 }
2621                 goto exit;
2622         }
2623
2624         if (!fruit_fsp_recheck(ad, fsp)) {
2625                 rc = -1;
2626                 goto exit;
2627         }
2628
2629         if (ad->ad_type == ADOUBLE_META) {
2630                 if (n != AFP_INFO_SIZE || offset != 0) {
2631                         DEBUG(1, ("unexpected offset=%jd or size=%jd\n",
2632                                   (intmax_t)offset, (intmax_t)n));
2633                         rc = -1;
2634                         goto exit;
2635                 }
2636                 ai = afpinfo_unpack(talloc_tos(), data);
2637                 if (ai == NULL) {
2638                         rc = -1;
2639                         goto exit;
2640                 }
2641                 memcpy(ad_entry(ad, ADEID_FINDERI),
2642                        &ai->afpi_FinderInfo[0], ADEDLEN_FINDERI);
2643                 rc = ad_write(ad, name);
2644         } else {
2645                 len = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n,
2646                                    offset + ad_getentryoff(ad, ADEID_RFORK));
2647                 if (len != n) {
2648                         rc = -1;
2649                         goto exit;
2650                 }
2651
2652                 if (config->rsrc == FRUIT_RSRC_ADFILE) {
2653                         rc = ad_read(ad, name);
2654                         if (rc == -1) {
2655                                 goto exit;
2656                         }
2657                         rc = 0;
2658
2659                         if ((len + offset) > ad_getentrylen(ad, ADEID_RFORK)) {
2660                                 ad_setentrylen(ad, ADEID_RFORK, len + offset);
2661                                 rc = ad_write(ad, name);
2662                         }
2663                 }
2664         }
2665
2666 exit:
2667         fsp->base_fsp->fsp_name->base_name = tmp_base_name;
2668         TALLOC_FREE(name);
2669         TALLOC_FREE(ai);
2670         if (rc != 0) {
2671                 return -1;
2672         }
2673         return n;
2674 }
2675
2676 /**
2677  * Helper to stat/lstat the base file of an smb_fname.
2678  */
2679 static int fruit_stat_base(vfs_handle_struct *handle,
2680                            struct smb_filename *smb_fname,
2681                            bool follow_links)
2682 {
2683         char *tmp_stream_name;
2684         int rc;
2685
2686         tmp_stream_name = smb_fname->stream_name;
2687         smb_fname->stream_name = NULL;
2688         if (follow_links) {
2689                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
2690         } else {
2691                 rc = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
2692         }
2693         smb_fname->stream_name = tmp_stream_name;
2694         return rc;
2695 }
2696
2697 static int fruit_stat_meta(vfs_handle_struct *handle,
2698                            struct smb_filename *smb_fname,
2699                            bool follow_links)
2700 {
2701         /* Populate the stat struct with info from the base file. */
2702         if (fruit_stat_base(handle, smb_fname, follow_links) == -1) {
2703                 return -1;
2704         }
2705         smb_fname->st.st_ex_size = AFP_INFO_SIZE;
2706         smb_fname->st.st_ex_ino = fruit_inode(&smb_fname->st,
2707                                               smb_fname->stream_name);
2708         return 0;
2709 }
2710
2711 static int fruit_stat_rsrc(vfs_handle_struct *handle,
2712                            struct smb_filename *smb_fname,
2713                            bool follow_links)
2714
2715 {
2716         struct adouble *ad = NULL;
2717
2718         DEBUG(10, ("fruit_stat_rsrc called for %s\n",
2719                    smb_fname_str_dbg(smb_fname)));
2720
2721         ad = ad_get(talloc_tos(), handle, smb_fname->base_name, ADOUBLE_RSRC);
2722         if (ad == NULL) {
2723                 errno = ENOENT;
2724                 return -1;
2725         }
2726
2727         /* Populate the stat struct with info from the base file. */
2728         if (fruit_stat_base(handle, smb_fname, follow_links) == -1) {
2729                 TALLOC_FREE(ad);
2730                 return -1;
2731         }
2732
2733         smb_fname->st.st_ex_size = ad_getentrylen(ad, ADEID_RFORK);
2734         smb_fname->st.st_ex_ino = fruit_inode(&smb_fname->st,
2735                                               smb_fname->stream_name);
2736         TALLOC_FREE(ad);
2737         return 0;
2738 }
2739
2740 static int fruit_stat(vfs_handle_struct *handle,
2741                       struct smb_filename *smb_fname)
2742 {
2743         int rc = -1;
2744
2745         DEBUG(10, ("fruit_stat called for %s\n",
2746                    smb_fname_str_dbg(smb_fname)));
2747
2748         if (!is_ntfs_stream_smb_fname(smb_fname)
2749             || is_ntfs_default_stream_smb_fname(smb_fname)) {
2750                 rc = SMB_VFS_NEXT_STAT(handle, smb_fname);
2751                 if (rc == 0) {
2752                         update_btime(handle, smb_fname);
2753                 }
2754                 return rc;
2755         }
2756
2757         /*
2758          * Note if lp_posix_paths() is true, we can never
2759          * get here as is_ntfs_stream_smb_fname() is
2760          * always false. So we never need worry about
2761          * not following links here.
2762          */
2763
2764         if (is_afpinfo_stream(smb_fname)) {
2765                 rc = fruit_stat_meta(handle, smb_fname, true);
2766         } else if (is_afpresource_stream(smb_fname)) {
2767                 rc = fruit_stat_rsrc(handle, smb_fname, true);
2768         } else {
2769                 return SMB_VFS_NEXT_STAT(handle, smb_fname);
2770         }
2771
2772         if (rc == 0) {
2773                 update_btime(handle, smb_fname);
2774                 smb_fname->st.st_ex_mode &= ~S_IFMT;
2775                 smb_fname->st.st_ex_mode |= S_IFREG;
2776                 smb_fname->st.st_ex_blocks =
2777                         smb_fname->st.st_ex_size / STAT_ST_BLOCKSIZE + 1;
2778         }
2779         return rc;
2780 }
2781
2782 static int fruit_lstat(vfs_handle_struct *handle,
2783                        struct smb_filename *smb_fname)
2784 {
2785         int rc = -1;
2786
2787         DEBUG(10, ("fruit_lstat called for %s\n",
2788                    smb_fname_str_dbg(smb_fname)));
2789
2790         if (!is_ntfs_stream_smb_fname(smb_fname)
2791             || is_ntfs_default_stream_smb_fname(smb_fname)) {
2792                 rc = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
2793                 if (rc == 0) {
2794                         update_btime(handle, smb_fname);
2795                 }
2796                 return rc;
2797         }
2798
2799         if (is_afpinfo_stream(smb_fname)) {
2800                 rc = fruit_stat_meta(handle, smb_fname, false);
2801         } else if (is_afpresource_stream(smb_fname)) {
2802                 rc = fruit_stat_rsrc(handle, smb_fname, false);
2803         } else {
2804                 return SMB_VFS_NEXT_LSTAT(handle, smb_fname);
2805         }
2806
2807         if (rc == 0) {
2808                 update_btime(handle, smb_fname);
2809                 smb_fname->st.st_ex_mode &= ~S_IFMT;
2810                 smb_fname->st.st_ex_mode |= S_IFREG;
2811                 smb_fname->st.st_ex_blocks =
2812                         smb_fname->st.st_ex_size / STAT_ST_BLOCKSIZE + 1;
2813         }
2814         return rc;
2815 }
2816
2817 static int fruit_fstat_meta(vfs_handle_struct *handle,
2818                             files_struct *fsp,
2819                             SMB_STRUCT_STAT *sbuf)
2820 {
2821         DEBUG(10, ("fruit_fstat_meta called for %s\n",
2822                    smb_fname_str_dbg(fsp->base_fsp->fsp_name)));
2823
2824         /* Populate the stat struct with info from the base file. */
2825         if (fruit_stat_base(handle, fsp->base_fsp->fsp_name, false) == -1) {
2826                 return -1;
2827         }
2828         *sbuf = fsp->base_fsp->fsp_name->st;
2829         sbuf->st_ex_size = AFP_INFO_SIZE;
2830         sbuf->st_ex_ino = fruit_inode(sbuf, fsp->fsp_name->stream_name);
2831
2832         return 0;
2833 }
2834
2835 static int fruit_fstat_rsrc(vfs_handle_struct *handle, files_struct *fsp,
2836                             SMB_STRUCT_STAT *sbuf)
2837 {
2838         struct fruit_config_data *config;
2839         struct adouble *ad = (struct adouble *)VFS_FETCH_FSP_EXTENSION(
2840                 handle, fsp);
2841
2842         DEBUG(10, ("fruit_fstat_rsrc called for %s\n",
2843                    smb_fname_str_dbg(fsp->base_fsp->fsp_name)));
2844
2845         SMB_VFS_HANDLE_GET_DATA(handle, config,
2846                                 struct fruit_config_data, return -1);
2847
2848         if (config->rsrc == FRUIT_RSRC_STREAM) {
2849                 return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
2850         }
2851
2852         /* Populate the stat struct with info from the base file. */
2853         if (fruit_stat_base(handle, fsp->base_fsp->fsp_name, false) == -1) {
2854                 return -1;
2855         }
2856         *sbuf = fsp->base_fsp->fsp_name->st;
2857         sbuf->st_ex_size = ad_getentrylen(ad, ADEID_RFORK);
2858         sbuf->st_ex_ino = fruit_inode(sbuf, fsp->fsp_name->stream_name);
2859
2860         DEBUG(10, ("fruit_fstat_rsrc %s, size: %zd\n",
2861                    smb_fname_str_dbg(fsp->fsp_name),
2862                    (ssize_t)sbuf->st_ex_size));
2863
2864         return 0;
2865 }
2866
2867 static int fruit_fstat(vfs_handle_struct *handle, files_struct *fsp,
2868                        SMB_STRUCT_STAT *sbuf)
2869 {
2870         int rc;
2871         char *name = NULL;
2872         char *tmp_base_name = NULL;
2873         NTSTATUS status;
2874         struct adouble *ad = (struct adouble *)
2875                 VFS_FETCH_FSP_EXTENSION(handle, fsp);
2876
2877         DEBUG(10, ("fruit_fstat called for %s\n",
2878                    smb_fname_str_dbg(fsp->fsp_name)));
2879
2880         if (fsp->base_fsp) {
2881                 tmp_base_name = fsp->base_fsp->fsp_name->base_name;
2882                 /* fsp_name is not converted with vfs_catia */
2883                 status = SMB_VFS_TRANSLATE_NAME(
2884                         handle->conn,
2885                         fsp->base_fsp->fsp_name->base_name,
2886                         vfs_translate_to_unix,
2887                         talloc_tos(), &name);
2888
2889                 if (NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED)) {
2890                         name = talloc_strdup(talloc_tos(), tmp_base_name);
2891                         if (name == NULL) {
2892                                 rc = -1;
2893                                 goto exit;
2894                         }
2895                 } else if (!NT_STATUS_IS_OK(status)) {
2896                         errno = map_errno_from_nt_status(status);
2897                         rc = -1;
2898                         goto exit;
2899                 }
2900                 fsp->base_fsp->fsp_name->base_name = name;
2901         }
2902
2903         if (ad == NULL || fsp->base_fsp == NULL) {
2904                 rc = SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
2905                 goto exit;
2906         }
2907
2908         if (!fruit_fsp_recheck(ad, fsp)) {
2909                 rc = -1;
2910                 goto exit;
2911         }
2912
2913         switch (ad->ad_type) {
2914         case ADOUBLE_META:
2915                 rc = fruit_fstat_meta(handle, fsp, sbuf);
2916                 break;
2917         case ADOUBLE_RSRC:
2918                 rc = fruit_fstat_rsrc(handle, fsp, sbuf);
2919                 break;
2920         default:
2921                 DEBUG(10, ("fruit_fstat %s: bad type\n",
2922                            smb_fname_str_dbg(fsp->fsp_name)));
2923                 rc = -1;
2924                 goto exit;
2925         }
2926
2927         if (rc == 0) {
2928                 sbuf->st_ex_mode &= ~S_IFMT;
2929                 sbuf->st_ex_mode |= S_IFREG;
2930                 sbuf->st_ex_blocks = sbuf->st_ex_size / STAT_ST_BLOCKSIZE + 1;
2931         }
2932
2933 exit:
2934         DEBUG(10, ("fruit_fstat %s, size: %zd\n",
2935                    smb_fname_str_dbg(fsp->fsp_name),
2936                    (ssize_t)sbuf->st_ex_size));
2937         if (tmp_base_name) {
2938                 fsp->base_fsp->fsp_name->base_name = tmp_base_name;
2939         }
2940         TALLOC_FREE(name);
2941         return rc;
2942 }
2943
2944 static NTSTATUS fruit_streaminfo(vfs_handle_struct *handle,
2945                                  struct files_struct *fsp,
2946                                  const char *fname,
2947                                  TALLOC_CTX *mem_ctx,
2948                                  unsigned int *pnum_streams,
2949                                  struct stream_struct **pstreams)
2950 {
2951         struct fruit_config_data *config = NULL;
2952         struct smb_filename *smb_fname = NULL;
2953         struct adouble *ad = NULL;
2954
2955         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
2956                                 return NT_STATUS_UNSUCCESSFUL);
2957         DEBUG(10, ("fruit_streaminfo called for %s\n", fname));
2958
2959         smb_fname = synthetic_smb_fname(talloc_tos(), fname, NULL, NULL);
2960         if (smb_fname == NULL) {
2961                 return NT_STATUS_NO_MEMORY;
2962         }
2963
2964         if (config->meta == FRUIT_META_NETATALK) {
2965                 ad = ad_get(talloc_tos(), handle,
2966                             smb_fname->base_name, ADOUBLE_META);
2967                 if (ad && !empty_finderinfo(ad)) {
2968                         if (!add_fruit_stream(
2969                                     mem_ctx, pnum_streams, pstreams,
2970                                     AFPINFO_STREAM_NAME, AFP_INFO_SIZE,
2971                                     smb_roundup(handle->conn,
2972                                                 AFP_INFO_SIZE))) {
2973                                 TALLOC_FREE(ad);
2974                                 TALLOC_FREE(smb_fname);
2975                                 return NT_STATUS_NO_MEMORY;
2976                         }
2977                 }
2978                 TALLOC_FREE(ad);
2979         }
2980
2981         if (config->rsrc != FRUIT_RSRC_STREAM) {
2982                 ad = ad_get(talloc_tos(), handle, smb_fname->base_name,
2983                             ADOUBLE_RSRC);
2984                 if (ad) {
2985                         if (!add_fruit_stream(
2986                                     mem_ctx, pnum_streams, pstreams,
2987                                     AFPRESOURCE_STREAM_NAME,
2988                                     ad_getentrylen(ad, ADEID_RFORK),
2989                                     smb_roundup(handle->conn,
2990                                                 ad_getentrylen(
2991                                                         ad, ADEID_RFORK)))) {
2992                                 TALLOC_FREE(ad);
2993                                 TALLOC_FREE(smb_fname);
2994                                 return NT_STATUS_NO_MEMORY;
2995                         }
2996                 }
2997                 TALLOC_FREE(ad);
2998         }
2999
3000         TALLOC_FREE(smb_fname);
3001
3002         return SMB_VFS_NEXT_STREAMINFO(handle, fsp, fname, mem_ctx,
3003                                        pnum_streams, pstreams);
3004 }
3005
3006 static int fruit_ntimes(vfs_handle_struct *handle,
3007                         const struct smb_filename *smb_fname,
3008                         struct smb_file_time *ft)
3009 {
3010         int rc = 0;
3011         struct adouble *ad = NULL;
3012
3013         if (null_timespec(ft->create_time)) {
3014                 goto exit;
3015         }
3016
3017         DEBUG(10,("set btime for %s to %s\n", smb_fname_str_dbg(smb_fname),
3018                  time_to_asc(convert_timespec_to_time_t(ft->create_time))));
3019
3020         ad = ad_get(talloc_tos(), handle, smb_fname->base_name, ADOUBLE_META);
3021         if (ad == NULL) {
3022                 goto exit;
3023         }
3024
3025         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX,
3026                    convert_time_t_to_uint32_t(ft->create_time.tv_sec));
3027
3028         rc = ad_write(ad, smb_fname->base_name);
3029
3030 exit:
3031
3032         TALLOC_FREE(ad);
3033         if (rc != 0) {
3034                 DEBUG(1, ("fruit_ntimes: %s\n", smb_fname_str_dbg(smb_fname)));
3035                 return -1;
3036         }
3037         return SMB_VFS_NEXT_NTIMES(handle, smb_fname, ft);
3038 }
3039
3040 static int fruit_fallocate(struct vfs_handle_struct *handle,
3041                            struct files_struct *fsp,
3042                            enum vfs_fallocate_mode mode,
3043                            off_t offset,
3044                            off_t len)
3045 {
3046         struct adouble *ad =
3047                 (struct adouble *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3048
3049         if (ad == NULL) {
3050                 return SMB_VFS_NEXT_FALLOCATE(handle, fsp, mode, offset, len);
3051         }
3052
3053         if (!fruit_fsp_recheck(ad, fsp)) {
3054                 return -1;
3055         }
3056
3057         /* Let the pwrite code path handle it. */
3058         errno = ENOSYS;
3059         return -1;
3060 }
3061
3062 static int fruit_ftruncate(struct vfs_handle_struct *handle,
3063                            struct files_struct *fsp,
3064                            off_t offset)
3065 {
3066         int rc = 0;
3067         struct adouble *ad =
3068                 (struct adouble *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
3069         struct fruit_config_data *config;
3070
3071         DEBUG(10, ("streams_xattr_ftruncate called for file %s offset %.0f\n",
3072                    fsp_str_dbg(fsp), (double)offset));
3073
3074         if (ad == NULL) {
3075                 return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
3076         }
3077
3078         if (!fruit_fsp_recheck(ad, fsp)) {
3079                 return -1;
3080         }
3081
3082         SMB_VFS_HANDLE_GET_DATA(handle, config,
3083                                 struct fruit_config_data, return -1);
3084
3085         switch (ad->ad_type) {
3086         case ADOUBLE_META:
3087                 /*
3088                  * As this request hasn't been seen in the wild,
3089                  * the only sensible use I can imagine is the client
3090                  * truncating the stream to 0 bytes size.
3091                  * We simply remove the metadata on such a request.
3092                  */
3093                 if (offset == 0) {
3094                         rc = SMB_VFS_FREMOVEXATTR(fsp,
3095                                                   AFPRESOURCE_EA_NETATALK);
3096                 }
3097                 break;
3098         case ADOUBLE_RSRC:
3099                 if (config->rsrc == FRUIT_RSRC_XATTR && offset == 0) {
3100                         rc = SMB_VFS_FREMOVEXATTR(fsp,
3101                                                   AFPRESOURCE_EA_NETATALK);
3102                 } else {
3103                         rc = SMB_VFS_NEXT_FTRUNCATE(
3104                                 handle, fsp,
3105                                 offset + ad_getentryoff(ad, ADEID_RFORK));
3106                         if (rc != 0) {
3107                                 return -1;
3108                         }
3109                         ad_setentrylen(ad, ADEID_RFORK, offset);
3110                         rc = ad_write(ad, NULL);
3111                         if (rc != 0) {
3112                                 return -1;
3113                         }
3114                 }
3115                 break;
3116         default:
3117                 return -1;
3118         }
3119
3120         return rc;
3121 }
3122
3123 static NTSTATUS fruit_create_file(vfs_handle_struct *handle,
3124                                   struct smb_request *req,
3125                                   uint16_t root_dir_fid,
3126                                   struct smb_filename *smb_fname,
3127                                   uint32_t access_mask,
3128                                   uint32_t share_access,
3129                                   uint32_t create_disposition,
3130                                   uint32_t create_options,
3131                                   uint32_t file_attributes,
3132                                   uint32_t oplock_request,
3133                                   struct smb2_lease *lease,
3134                                   uint64_t allocation_size,
3135                                   uint32_t private_flags,
3136                                   struct security_descriptor *sd,
3137                                   struct ea_list *ea_list,
3138                                   files_struct **result,
3139                                   int *pinfo,
3140                                   const struct smb2_create_blobs *in_context_blobs,
3141                                   struct smb2_create_blobs *out_context_blobs)
3142 {
3143         NTSTATUS status;
3144         struct fruit_config_data *config = NULL;
3145
3146         status = check_aapl(handle, req, in_context_blobs, out_context_blobs);
3147         if (!NT_STATUS_IS_OK(status)) {
3148                 return status;
3149         }
3150
3151         SMB_VFS_HANDLE_GET_DATA(handle, config, struct fruit_config_data,
3152                                 return NT_STATUS_UNSUCCESSFUL);
3153
3154         status = SMB_VFS_NEXT_CREATE_FILE(
3155                 handle, req, root_dir_fid, smb_fname,
3156                 access_mask, share_access,
3157                 create_disposition, create_options,
3158                 file_attributes, oplock_request,
3159                 lease,
3160                 allocation_size, private_flags,
3161                 sd, ea_list, result,
3162                 pinfo, in_context_blobs, out_context_blobs);
3163         if (!NT_STATUS_IS_OK(status)) {
3164                 return status;
3165         }
3166
3167         if (is_ntfs_stream_smb_fname(smb_fname)
3168             || (*result == NULL)
3169             || ((*result)->is_directory)) {
3170                 return status;
3171         }
3172
3173         if (config->locking == FRUIT_LOCKING_NETATALK) {
3174                 status = fruit_check_access(
3175                         handle, *result,
3176                         access_mask,
3177                         map_share_mode_to_deny_mode(share_access, 0));
3178                 if (!NT_STATUS_IS_OK(status)) {
3179                         goto fail;
3180                 }
3181         }
3182
3183         return status;
3184
3185 fail:
3186         DEBUG(1, ("fruit_create_file: %s\n", nt_errstr(status)));
3187
3188         if (*result) {
3189                 close_file(req, *result, ERROR_CLOSE);
3190                 *result = NULL;
3191         }
3192
3193         return status;
3194 }
3195
3196 static NTSTATUS fruit_readdir_attr(struct vfs_handle_struct *handle,
3197                                    const struct smb_filename *fname,
3198                                    TALLOC_CTX *mem_ctx,
3199                                    struct readdir_attr_data **pattr_data)
3200 {
3201         struct fruit_config_data *config = NULL;
3202         struct readdir_attr_data *attr_data;
3203         NTSTATUS status;
3204
3205         SMB_VFS_HANDLE_GET_DATA(handle, config,
3206                                 struct fruit_config_data,
3207                                 return NT_STATUS_UNSUCCESSFUL);
3208
3209         if (!config->use_aapl) {
3210                 return SMB_VFS_NEXT_READDIR_ATTR(handle, fname, mem_ctx, pattr_data);
3211         }
3212
3213         DEBUG(10, ("fruit_readdir_attr %s\n", fname->base_name));
3214
3215         *pattr_data = talloc_zero(mem_ctx, struct readdir_attr_data);
3216         if (*pattr_data == NULL) {
3217                 return NT_STATUS_UNSUCCESSFUL;
3218         }
3219         attr_data = *pattr_data;
3220         attr_data->type = RDATTR_AAPL;
3221
3222         /*
3223          * Mac metadata: compressed FinderInfo, resource fork length
3224          * and creation date
3225          */
3226         status = readdir_attr_macmeta(handle, fname, attr_data);
3227         if (!NT_STATUS_IS_OK(status)) {
3228                 /*
3229                  * Error handling is tricky: if we return failure from
3230                  * this function, the corresponding directory entry
3231                  * will to be passed to the client, so we really just
3232                  * want to error out on fatal errors.
3233                  */
3234                 if  (!NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
3235                         goto fail;
3236                 }
3237         }
3238
3239         /*
3240          * UNIX mode
3241          */
3242         if (config->unix_info_enabled) {
3243                 attr_data->attr_data.aapl.unix_mode = fname->st.st_ex_mode;
3244         }
3245
3246         /*
3247          * max_access
3248          */
3249         if (!config->readdir_attr_max_access) {
3250                 attr_data->attr_data.aapl.max_access = FILE_GENERIC_ALL;
3251         } else {
3252                 status = smbd_calculate_access_mask(
3253                         handle->conn,
3254                         fname,
3255                         false,
3256                         SEC_FLAG_MAXIMUM_ALLOWED,
3257                         &attr_data->attr_data.aapl.max_access);
3258                 if (!NT_STATUS_IS_OK(status)) {
3259                         goto fail;
3260                 }
3261         }
3262
3263         return NT_STATUS_OK;
3264
3265 fail:
3266         DEBUG(1, ("fruit_readdir_attr %s, error: %s\n",
3267                   fname->base_name, nt_errstr(status)));
3268         TALLOC_FREE(*pattr_data);
3269         return status;
3270 }
3271
3272 static NTSTATUS fruit_fget_nt_acl(vfs_handle_struct *handle,
3273                                   files_struct *fsp,
3274                                   uint32 security_info,
3275                                   TALLOC_CTX *mem_ctx,
3276                                   struct security_descriptor **ppdesc)
3277 {
3278         NTSTATUS status;
3279         struct security_ace ace;
3280         struct dom_sid sid;
3281         struct fruit_config_data *config;
3282
3283         SMB_VFS_HANDLE_GET_DATA(handle, config,
3284                                 struct fruit_config_data,
3285                                 return NT_STATUS_UNSUCCESSFUL);
3286
3287         status = SMB_VFS_NEXT_FGET_NT_ACL(handle, fsp, security_info,
3288                                           mem_ctx, ppdesc);
3289         if (!NT_STATUS_IS_OK(status)) {
3290                 return status;
3291         }
3292
3293         /*
3294          * Add MS NFS style ACEs with uid, gid and mode
3295          */
3296         if (!config->unix_info_enabled) {
3297                 return NT_STATUS_OK;
3298         }
3299
3300         /* MS NFS style mode */
3301         sid_compose(&sid, &global_sid_Unix_NFS_Mode, fsp->fsp_name->st.st_ex_mode);
3302         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
3303         status = security_descriptor_dacl_add(*ppdesc, &ace);
3304         if (!NT_STATUS_IS_OK(status)) {
3305                 DEBUG(1,("failed to add MS NFS style ACE\n"));
3306                 return status;
3307         }
3308
3309         /* MS NFS style uid */
3310         sid_compose(&sid, &global_sid_Unix_NFS_Users, fsp->fsp_name->st.st_ex_uid);
3311         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
3312         status = security_descriptor_dacl_add(*ppdesc, &ace);
3313         if (!NT_STATUS_IS_OK(status)) {
3314                 DEBUG(1,("failed to add MS NFS style ACE\n"));
3315                 return status;
3316         }
3317
3318         /* MS NFS style gid */
3319         sid_compose(&sid, &global_sid_Unix_NFS_Groups, fsp->fsp_name->st.st_ex_gid);
3320         init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
3321         status = security_descriptor_dacl_add(*ppdesc, &ace);
3322         if (!NT_STATUS_IS_OK(status)) {
3323                 DEBUG(1,("failed to add MS NFS style ACE\n"));
3324                 return status;
3325         }
3326
3327         return NT_STATUS_OK;
3328 }
3329
3330 static NTSTATUS fruit_fset_nt_acl(vfs_handle_struct *handle,
3331                                   files_struct *fsp,
3332                                   uint32 security_info_sent,
3333                                   const struct security_descriptor *psd)
3334 {
3335         NTSTATUS status;
3336         bool do_chmod;
3337         mode_t ms_nfs_mode;
3338         int result;
3339
3340         DEBUG(1, ("fruit_fset_nt_acl: %s\n", fsp_str_dbg(fsp)));
3341
3342         status = check_ms_nfs(handle, fsp, psd, &ms_nfs_mode, &do_chmod);
3343         if (!NT_STATUS_IS_OK(status)) {
3344                 DEBUG(1, ("fruit_fset_nt_acl: check_ms_nfs failed%s\n", fsp_str_dbg(fsp)));
3345                 return status;
3346         }
3347
3348         status = SMB_VFS_NEXT_FSET_NT_ACL(handle, fsp, security_info_sent, psd);
3349         if (!NT_STATUS_IS_OK(status)) {
3350                 DEBUG(1, ("fruit_fset_nt_acl: SMB_VFS_NEXT_FSET_NT_ACL failed%s\n", fsp_str_dbg(fsp)));
3351                 return status;
3352         }
3353
3354         if (do_chmod) {
3355                 if (fsp->fh->fd != -1) {
3356                         DEBUG(1, ("fchmod: %s\n", fsp_str_dbg(fsp)));
3357                         result = SMB_VFS_FCHMOD(fsp, ms_nfs_mode);
3358                 } else {
3359                         DEBUG(1, ("chmod: %s\n", fsp_str_dbg(fsp)));
3360                         result = SMB_VFS_CHMOD(fsp->conn,
3361                                                fsp->fsp_name->base_name,
3362                                                ms_nfs_mode);
3363                 }
3364
3365                 if (result != 0) {
3366                         DEBUG(1, ("chmod: %s, result: %d, %04o error %s\n", fsp_str_dbg(fsp),
3367                                   result, ms_nfs_mode, strerror(errno)));
3368                         status = map_nt_error_from_unix(errno);
3369                         return status;
3370                 }
3371         }
3372
3373         return NT_STATUS_OK;
3374 }
3375
3376 static struct vfs_fn_pointers vfs_fruit_fns = {
3377         .connect_fn = fruit_connect,
3378
3379         /* File operations */
3380         .chmod_fn = fruit_chmod,
3381         .chown_fn = fruit_chown,
3382         .unlink_fn = fruit_unlink,
3383         .rename_fn = fruit_rename,
3384         .rmdir_fn = fruit_rmdir,
3385         .open_fn = fruit_open,
3386         .pread_fn = fruit_pread,
3387         .pwrite_fn = fruit_pwrite,
3388         .stat_fn = fruit_stat,
3389         .lstat_fn = fruit_lstat,
3390         .fstat_fn = fruit_fstat,
3391         .streaminfo_fn = fruit_streaminfo,
3392         .ntimes_fn = fruit_ntimes,
3393         .ftruncate_fn = fruit_ftruncate,
3394         .fallocate_fn = fruit_fallocate,
3395         .create_file_fn = fruit_create_file,
3396         .readdir_attr_fn = fruit_readdir_attr,
3397
3398         /* NT ACL operations */
3399         .fget_nt_acl_fn = fruit_fget_nt_acl,
3400         .fset_nt_acl_fn = fruit_fset_nt_acl,
3401 };
3402
3403 NTSTATUS vfs_fruit_init(void);
3404 NTSTATUS vfs_fruit_init(void)
3405 {
3406         NTSTATUS ret = smb_register_vfs(SMB_VFS_INTERFACE_VERSION, "fruit",
3407                                         &vfs_fruit_fns);
3408         if (!NT_STATUS_IS_OK(ret)) {
3409                 return ret;
3410         }
3411
3412         vfs_fruit_debug_level = debug_add_class("fruit");
3413         if (vfs_fruit_debug_level == -1) {
3414                 vfs_fruit_debug_level = DBGC_VFS;
3415                 DEBUG(0, ("%s: Couldn't register custom debugging class!\n",
3416                           "vfs_fruit_init"));
3417         } else {
3418                 DEBUG(10, ("%s: Debug class number of '%s': %d\n",
3419                            "vfs_fruit_init","fruit",vfs_fruit_debug_level));
3420         }
3421
3422         return ret;
3423 }