]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/volume.c
Fix build
[netatalk.git] / etc / afpd / volume.c
1 /*
2  * Copyright (c) 1990,1993 Regents of The University of Michigan.
3  * All Rights Reserved.  See COPYRIGHT.
4  */
5
6 #ifdef HAVE_CONFIG_H
7 #include "config.h"
8 #endif /* HAVE_CONFIG_H */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <ctype.h>
13 #include <pwd.h>
14 #include <grp.h>
15 #include <utime.h>
16 #include <errno.h>
17 #include <string.h>
18 #include <sys/param.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
22 #include <inttypes.h>
23 #include <time.h>
24
25 #include <atalk/dsi.h>
26 #include <atalk/adouble.h>
27 #include <atalk/afp.h>
28 #include <atalk/util.h>
29 #include <atalk/volinfo.h>
30 #include <atalk/logger.h>
31 #include <atalk/vfs.h>
32 #include <atalk/uuid.h>
33 #include <atalk/ea.h>
34 #include <atalk/bstrlib.h>
35 #include <atalk/bstradd.h>
36 #include <atalk/ftw.h>
37 #include <atalk/globals.h>
38 #include <atalk/fce_api.h>
39 #include <atalk/errchk.h>
40 #include <atalk/iniparser.h>
41
42 #ifdef CNID_DB
43 #include <atalk/cnid.h>
44 #endif /* CNID_DB*/
45
46 #include "directory.h"
47 #include "file.h"
48 #include "volume.h"
49 #include "unix.h"
50 #include "mangle.h"
51 #include "fork.h"
52 #include "hash.h"
53 #include "acls.h"
54
55 extern int afprun(int root, char *cmd, int *outfd);
56
57 /* Globals */
58 struct vol *current_vol;        /* last volume from getvolbyvid() */
59
60 static struct vol *Volumes = NULL;
61 static uint16_t    lastvid = 0;
62 static char     *Trash = "\02\024Network Trash Folder";
63
64 #define VOLOPT_ALLOW      0  /* user allow list */
65 #define VOLOPT_DENY       1  /* user deny list */
66 #define VOLOPT_RWLIST     2  /* user rw list */
67 #define VOLOPT_ROLIST     3  /* user ro list */
68 #define VOLOPT_PASSWORD   4  /* volume password */
69 #define VOLOPT_CASEFOLD   5  /* character case mangling */
70 #define VOLOPT_FLAGS      6  /* various flags */
71 #define VOLOPT_DBPATH     7  /* path to database */
72 #define VOLOPT_LIMITSIZE  8  /* Limit the size of the volume */
73 /* Usable slot: 9 */
74 #define VOLOPT_VETO          10  /* list of veto filespec */
75 #define VOLOPT_PREEXEC       11  /* preexec command */
76 #define VOLOPT_ROOTPREEXEC   12  /* root preexec command */
77 #define VOLOPT_POSTEXEC      13  /* postexec command */
78 #define VOLOPT_ROOTPOSTEXEC  14  /* root postexec command */
79 #define VOLOPT_ENCODING      15  /* mac encoding (pre OSX)*/
80 #define VOLOPT_MACCHARSET    16
81 #define VOLOPT_CNIDSCHEME    17
82 #define VOLOPT_ADOUBLE       18  /* adouble version */
83 /* Usable slot: 19/20 */
84 #define VOLOPT_UMASK         21
85 #define VOLOPT_ALLOWED_HOSTS 22
86 #define VOLOPT_DENIED_HOSTS  23
87 #define VOLOPT_DPERM         24  /* dperm default directories perms */
88 #define VOLOPT_FPERM         25  /* fperm default files perms */
89 #define VOLOPT_DFLTPERM      26  /* perm */
90 #define VOLOPT_EA_VFS        27  /* Extended Attributes vfs indirection */
91 #define VOLOPT_CNIDSERVER    28  /* CNID Server ip address*/
92 #define VOLOPT_CNIDPORT      30  /* CNID server tcp port */
93
94 #define VOLOPT_MAX           31  /* <== IMPORTANT !!!!!! */
95 #define VOLOPT_NUM           (VOLOPT_MAX + 1)
96
97 #define VOLPASSLEN  8
98
99 struct vol_option {
100     char *c_value;
101     int i_value;
102 };
103
104 typedef struct _special_folder {
105     const char *name;
106     int precreate;
107     mode_t mode;
108     int hide;
109 } _special_folder;
110
111 static const _special_folder special_folders[] = {
112     {"Network Trash Folder",     1,  0777,  1},
113     {".AppleDesktop",            1,  0777,  0},
114     {NULL, 0, 0, 0}};
115
116 /* Forward declarations */
117 static void handle_special_folders (const struct vol *);
118 static void deletevol(struct vol *vol);
119 static void volume_free(struct vol *vol);
120 static void check_ea_sys_support(struct vol *vol);
121 static char *get_vol_uuid(const AFPObj *obj, const char *volname);
122
123 static void volfree(struct vol_option *options, const struct vol_option *save)
124 {
125     int i;
126
127     if (save) {
128         for (i = 0; i < VOLOPT_MAX; i++) {
129             if (options[i].c_value && (options[i].c_value != save[i].c_value))
130                 free(options[i].c_value);
131         }
132     } else {
133         for (i = 0; i < VOLOPT_MAX; i++) {
134             if (options[i].c_value)
135                 free(options[i].c_value);
136         }
137     }
138 }
139
140
141 #define is_var(a, b) (strncmp((a), (b), 2) == 0)
142
143 /*
144  * Handle variable substitutions. here's what we understand:
145  * $b   -> basename of path
146  * $c   -> client ip/appletalk address
147  * $d   -> volume pathname on server
148  * $f   -> full name (whatever's in the gecos field)
149  * $g   -> group
150  * $h   -> hostname
151  * $i   -> client ip/appletalk address without port
152  * $s   -> server name (hostname if it doesn't exist)
153  * $u   -> username (guest is usually nobody)
154  * $v   -> volume name or basename if null
155  * $$   -> $
156  *
157  * This get's called from readvolfile with
158  * path = NULL, volname = NULL for xlating the volumes path
159  * path = path, volname = NULL for xlating the volumes name
160  * ... and from volumes options parsing code when xlating eg dbpath with
161  * path = path, volname = volname
162  *
163  * Using this information we can reject xlation of any variable depeninding on a login
164  * context which is not given in the afp master, where we must evaluate this whole stuff
165  * too for the Zeroconf announcements.
166  */
167 static char *volxlate(AFPObj *obj,
168                       char *dest,
169                       size_t destlen,
170                       char *src,
171                       struct passwd *pwd,
172                       char *path,
173                       char *volname)
174 {
175     char *p, *r;
176     const char *q;
177     int len;
178     char *ret;
179     int afpmaster = 0;
180     int xlatevolname = 0;
181
182     if (parent_or_child == 0)
183         afpmaster = 1;
184
185     if (path && !volname)
186         /* cf above */
187         xlatevolname = 1;
188
189     if (!src) {
190         return NULL;
191     }
192     if (!dest) {
193         dest = calloc(destlen +1, 1);
194     }
195     ret = dest;
196     if (!ret) {
197         return NULL;
198     }
199     strlcpy(dest, src, destlen +1);
200     if ((p = strchr(src, '$')) == NULL) /* nothing to do */
201         return ret;
202
203     /* first part of the path. just forward to the next variable. */
204     len = MIN((size_t)(p - src), destlen);
205     if (len > 0) {
206         destlen -= len;
207         dest += len;
208     }
209
210     while (p && destlen > 0) {
211         /* now figure out what the variable is */
212         q = NULL;
213         if (is_var(p, "$b")) {
214             if (afpmaster && xlatevolname)
215                 return NULL;
216             if (path) {
217                 if ((q = strrchr(path, '/')) == NULL)
218                     q = path;
219                 else if (*(q + 1) != '\0')
220                     q++;
221             }
222         } else if (is_var(p, "$c")) {
223             if (afpmaster && xlatevolname)
224                 return NULL;
225             DSI *dsi = obj->dsi;
226             len = sprintf(dest, "%s:%u",
227                           getip_string((struct sockaddr *)&dsi->client),
228                           getip_port((struct sockaddr *)&dsi->client));
229             dest += len;
230             destlen -= len;
231         } else if (is_var(p, "$d")) {
232             if (afpmaster && xlatevolname)
233                 return NULL;
234             q = path;
235         } else if (pwd && is_var(p, "$f")) {
236             if (afpmaster && xlatevolname)
237                 return NULL;
238             if ((r = strchr(pwd->pw_gecos, ',')))
239                 *r = '\0';
240             q = pwd->pw_gecos;
241         } else if (pwd && is_var(p, "$g")) {
242             if (afpmaster && xlatevolname)
243                 return NULL;
244             struct group *grp = getgrgid(pwd->pw_gid);
245             if (grp)
246                 q = grp->gr_name;
247         } else if (is_var(p, "$h")) {
248             q = obj->options.hostname;
249         } else if (is_var(p, "$i")) {
250             if (afpmaster && xlatevolname)
251                 return NULL;
252             DSI *dsi = obj->dsi;
253             q = getip_string((struct sockaddr *)&dsi->client);
254         } else if (is_var(p, "$s")) {
255             q = obj->options.hostname;
256         } else if (obj->username && is_var(p, "$u")) {
257             if (afpmaster && xlatevolname)
258                 return NULL;
259             char* sep = NULL;
260             if ( obj->options.ntseparator && (sep = strchr(obj->username, obj->options.ntseparator[0])) != NULL)
261                 q = sep+1;
262             else
263                 q = obj->username;
264         } else if (is_var(p, "$v")) {
265             if (afpmaster && xlatevolname)
266                 return NULL;
267             if (volname) {
268                 q = volname;
269             }
270             else if (path) {
271                 if ((q = strrchr(path, '/')) == NULL)
272                     q = path;
273                 else if (*(q + 1) != '\0')
274                     q++;
275             }
276         } else if (is_var(p, "$$")) {
277             q = "$";
278         } else
279             q = p;
280
281         /* copy the stuff over. if we don't understand something that we
282          * should, just skip it over. */
283         if (q) {
284             len = MIN(p == q ? 2 : strlen(q), destlen);
285             strncpy(dest, q, len);
286             dest += len;
287             destlen -= len;
288         }
289
290         /* stuff up to next $ */
291         src = p + 2;
292         p = strchr(src, '$');
293         len = p ? MIN((size_t)(p - src), destlen) : destlen;
294         if (len > 0) {
295             strncpy(dest, src, len);
296             dest += len;
297             destlen -= len;
298         }
299     }
300     return ret;
301 }
302
303 /* -------------------- */
304 static void setoption(struct vol_option *options, const struct vol_option *save, int opt, const char *val)
305 {
306     if (options[opt].c_value && (!save || options[opt].c_value != save[opt].c_value))
307         free(options[opt].c_value);
308     options[opt].c_value = strdup(val + 1);
309 }
310
311 /* Parse iniconfig and initalize volume options */
312 static void volset(const dictionary *conf, const char *vol, struct vol_option *options, const struct vol_option *save)
313 {
314     const char *val;
315     char *p, *q;
316
317     if (val = iniparser_getstring(conf, vol, "allow", NULL))
318         setoption(options, save, VOLOPT_ALLOW, val);
319
320     if (val = iniparser_getstring(conf, vol, "deny", NULL))
321         setoption(options, save, VOLOPT_DENY, val);
322
323     if (val = iniparser_getstring(conf, vol, "rwlist", NULL))
324         setoption(options, save, VOLOPT_RWLIST, val);
325
326     if (val = iniparser_getstring(conf, vol, "rolist", NULL))
327         setoption(options, save, VOLOPT_ROLIST, val);
328
329     if (val = iniparser_getstring(conf, vol, "volcharset", NULL))
330         setoption(options, save, VOLOPT_ENCODING, val);
331
332     if (val = iniparser_getstring(conf, vol, "maccharset", NULL))
333         setoption(options, save, VOLOPT_MACCHARSET, val);
334
335     if (val = iniparser_getstring(conf, vol, "veto", NULL))
336         setoption(options, save, VOLOPT_VETO, val);
337
338     if (val = iniparser_getstring(conf, vol, "cnidscheme", NULL))
339         setoption(options, save, VOLOPT_CNIDSCHEME, val);
340
341     if (val = iniparser_getstring(conf, vol, "dbpath", NULL))
342         setoption(options, save, VOLOPT_DBPATH, val);
343
344     if (val = iniparser_getstring(conf, vol, "password", NULL))
345         setoption(options, save, VOLOPT_PASSWORD, val);
346
347     if (val = iniparser_getstring(conf, vol, "root_preexec", NULL))
348         setoption(options, save, VOLOPT_ROOTPREEXEC, val);
349
350     if (val = iniparser_getstring(conf, vol, "preexec", NULL))
351         setoption(options, save, VOLOPT_PREEXEC, val);
352
353     if (val = iniparser_getstring(conf, vol, "root_postexec", NULL))
354         setoption(options, save, VOLOPT_ROOTPOSTEXEC, val);
355
356     if (val = iniparser_getstring(conf, vol, "postexec", NULL))
357         setoption(options, save, VOLOPT_POSTEXEC, val);
358
359     if (val = iniparser_getstring(conf, vol, "allowed_hosts", NULL))
360         setoption(options, save, VOLOPT_ALLOWED_HOSTS, val);
361
362     if (val = iniparser_getstring(conf, vol, "denied_hosts", NULL))
363         setoption(options, save, VOLOPT_DENIED_HOSTS, val);
364
365     if (val = iniparser_getstring(conf, vol, "umask", NULL))
366         options[VOLOPT_UMASK].i_value = (int)strtol(val, NULL, 8);
367
368     if (val = iniparser_getstring(conf, vol, "dperm", NULL))
369         options[VOLOPT_DPERM].i_value = (int)strtol(val, NULL, 8);
370
371     if (val = iniparser_getstring(conf, vol, "fperm", NULL))
372         options[VOLOPT_FPERM].i_value = (int)strtol(val, NULL, 8);
373
374     if (val = iniparser_getstring(conf, vol, "perm", NULL))
375         options[VOLOPT_DFLTPERM].i_value = (int)strtol(val, NULL, 8);
376
377     if (val = iniparser_getstring(conf, vol, "volsizelimit", NULL))
378         options[VOLOPT_LIMITSIZE].i_value = (uint32_t)strtoul(val, NULL, 10);
379
380     if (val = iniparser_getstring(conf, vol, "casefold", NULL)) {
381         if (strcasecmp(val, "tolower") == 0)
382             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMLOWER;
383         else if (strcasecmp(val, "toupper") == 0)
384             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMUPPER;
385         else if (strcasecmp(val, "xlatelower") == 0)
386             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UUPPERMLOWER;
387         else if (strcasecmp(val, "xlateupper") == 0)
388             options[VOLOPT_CASEFOLD].i_value = AFPVOL_ULOWERMUPPER;
389     }
390
391     if (val = iniparser_getstring(conf, vol, "adouble", NULL)) {
392         if (strcasecmp(val, "v2") == 0)
393             options[VOLOPT_ADOUBLE].i_value = AD_VERSION2;
394         else if (strcasecmp(val, "ea") == 0)
395             options[VOLOPT_ADOUBLE].i_value = AD_VERSION_EA;
396     }
397
398     if (val = iniparser_getstring(conf, vol, "ea", NULL)) {
399         if (strcasecmp(val, "ad") == 0)
400             options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_AD;
401         else if (strcasecmp(val, "sys") == 0)
402             options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_SYS;
403         else if (strcasecmp(val, "none") == 0)
404             options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_NONE;
405     }
406
407     if (p = iniparser_getstrdup(conf, vol, "cnidserver", NULL)) {
408         if (q = strrchr(val, ':')) {
409             *q = 0;
410             setoption(options, save, VOLOPT_CNIDPORT, q + 1);
411         }
412         setoption(options, save, VOLOPT_CNIDSERVER, p);
413         LOG(log_debug, logtype_afpd, "CNID Server for volume '%s': %s:%s",
414             vol, p, q ? q + 1 : "4700");
415         free(p);
416     }
417
418     if (q = iniparser_getstrdup(conf, vol, "options", NULL)) {
419         if (p = strtok(q, ",")) {
420             while (p) {
421                 if (strcasecmp(p, "ro") == 0)
422                     options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
423                 else if (strcasecmp(p, "nohex") == 0)
424                     options[VOLOPT_FLAGS].i_value |= AFPVOL_NOHEX;
425                 else if (strcasecmp(p, "usedots") == 0)
426                     options[VOLOPT_FLAGS].i_value |= AFPVOL_USEDOTS;
427                 else if (strcasecmp(p, "invisibledots") == 0)
428                     options[VOLOPT_FLAGS].i_value |= AFPVOL_USEDOTS | AFPVOL_INV_DOTS;
429                 else if (strcasecmp(p, "nostat") == 0)
430                     options[VOLOPT_FLAGS].i_value |= AFPVOL_NOSTAT;
431                 else if (strcasecmp(p, "preexec_close") == 0)
432                     options[VOLOPT_PREEXEC].i_value = 1;
433                 else if (strcasecmp(p, "root_preexec_close") == 0)
434                     options[VOLOPT_ROOTPREEXEC].i_value = 1;
435                 else if (strcasecmp(p, "upriv") == 0)
436                     options[VOLOPT_FLAGS].i_value |= AFPVOL_UNIX_PRIV;
437                 else if (strcasecmp(p, "nodev") == 0)
438                     options[VOLOPT_FLAGS].i_value |= AFPVOL_NODEV;
439                 else if (strcasecmp(p, "caseinsensitive") == 0)
440                     options[VOLOPT_FLAGS].i_value |= AFPVOL_CASEINSEN;
441                 else if (strcasecmp(p, "illegalseq") == 0)
442                     options[VOLOPT_FLAGS].i_value |= AFPVOL_EILSEQ;
443                 else if (strcasecmp(p, "tm") == 0)
444                     options[VOLOPT_FLAGS].i_value |= AFPVOL_TM;
445                 else if (strcasecmp(p, "searchdb") == 0)
446                     options[VOLOPT_FLAGS].i_value |= AFPVOL_SEARCHDB;
447                 else if (strcasecmp(p, "nonetids") == 0)
448                     options[VOLOPT_FLAGS].i_value |= AFPVOL_NONETIDS;
449                 else if (strcasecmp(p, "noacls") == 0)
450                     options[VOLOPT_FLAGS].i_value &= ~AFPVOL_ACLS;
451                 else if (strcasecmp(p, "nov2toeaconv") == 0)
452                     options[VOLOPT_FLAGS].i_value |= AFPVOL_NOV2TOEACONV;
453                 p = strtok(NULL, ",");
454             }
455         }
456         free(q);
457     }
458 }
459
460 /* ----------------- */
461 static void showvol(const ucs2_t *name)
462 {
463     struct vol  *volume;
464     for ( volume = Volumes; volume; volume = volume->v_next ) {
465         if (volume->v_hide && !strcasecmp_w( volume->v_name, name ) ) {
466             volume->v_hide = 0;
467             return;
468         }
469     }
470 }
471
472 /* ------------------------------- */
473 static int creatvol(AFPObj *obj, struct passwd *pwd,
474                     char *path, char *name,
475                     struct vol_option *options)
476 {
477     struct vol  *volume;
478     int         suffixlen, vlen, tmpvlen, u8mvlen, macvlen;
479     int         hide = 0;
480     char        tmpname[AFPVOL_U8MNAMELEN+1];
481     ucs2_t      u8mtmpname[(AFPVOL_U8MNAMELEN+1)*2], mactmpname[(AFPVOL_MACNAMELEN+1)*2];
482     char        suffix[6]; /* max is #FFFF */
483     uint16_t   flags;
484
485     LOG(log_debug, logtype_afpd, "createvol: Volume '%s'", name);
486
487     if ( name == NULL || *name == '\0' ) {
488         if ((name = strrchr( path, '/' )) == NULL) {
489             return -1;  /* Obviously not a fully qualified path */
490         }
491
492         /* if you wish to share /, you need to specify a name. */
493         if (*++name == '\0')
494             return -1;
495     }
496
497     /* suffix for mangling use (lastvid + 1)   */
498     /* because v_vid has not been decided yet. */
499     suffixlen = sprintf(suffix, "%c%X", MANGLE_CHAR, lastvid + 1 );
500
501     vlen = strlen( name );
502
503     /* Unicode Volume Name */
504     /* Firstly convert name from unixcharset to UTF8-MAC */
505     flags = CONV_IGNORE;
506     tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
507     if (tmpvlen <= 0) {
508         strcpy(tmpname, "???");
509         tmpvlen = 3;
510     }
511
512     /* Do we have to mangle ? */
513     if ( (flags & CONV_REQMANGLE) || (tmpvlen > obj->options.volnamelen)) {
514         if (tmpvlen + suffixlen > obj->options.volnamelen) {
515             flags = CONV_FORCE;
516             tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, obj->options.volnamelen - suffixlen, &flags);
517             tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
518         }
519         strcat(tmpname, suffix);
520         tmpvlen = strlen(tmpname);
521     }
522
523     /* Secondly convert name from UTF8-MAC to UCS2 */
524     if ( 0 >= ( u8mvlen = convert_string(CH_UTF8_MAC, CH_UCS2, tmpname, tmpvlen, u8mtmpname, AFPVOL_U8MNAMELEN*2)) )
525         return -1;
526
527     LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' -> UTF8-MAC Name: '%s'", name, tmpname);
528
529     /* Maccharset Volume Name */
530     /* Firsty convert name from unixcharset to maccharset */
531     flags = CONV_IGNORE;
532     tmpvlen = convert_charset(obj->options.unixcharset, obj->options.maccharset, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
533     if (tmpvlen <= 0) {
534         strcpy(tmpname, "???");
535         tmpvlen = 3;
536     }
537
538     /* Do we have to mangle ? */
539     if ( (flags & CONV_REQMANGLE) || (tmpvlen > AFPVOL_MACNAMELEN)) {
540         if (tmpvlen + suffixlen > AFPVOL_MACNAMELEN) {
541             flags = CONV_FORCE;
542             tmpvlen = convert_charset(obj->options.unixcharset,
543                                       obj->options.maccharset,
544                                       0,
545                                       name,
546                                       vlen,
547                                       tmpname,
548                                       AFPVOL_MACNAMELEN - suffixlen,
549                                       &flags);
550             tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
551         }
552         strcat(tmpname, suffix);
553         tmpvlen = strlen(tmpname);
554     }
555
556     /* Secondly convert name from maccharset to UCS2 */
557     if ( 0 >= ( macvlen = convert_string(obj->options.maccharset,
558                                          CH_UCS2,
559                                          tmpname,
560                                          tmpvlen,
561                                          mactmpname,
562                                          AFPVOL_U8MNAMELEN*2)) )
563         return -1;
564
565     LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' ->  Longname: '%s'", name, tmpname);
566
567     /* check duplicate */
568     for ( volume = Volumes; volume; volume = volume->v_next ) {
569         if ((utf8_encoding() && (strcasecmp_w(volume->v_u8mname, u8mtmpname) == 0))
570              ||
571             (!utf8_encoding() && (strcasecmp_w(volume->v_macname, mactmpname) == 0))) {
572             LOG (log_error, logtype_afpd,
573                  "Duplicate volume name, check AppleVolumes files: previous: \"%s\", new: \"%s\"",
574                  volume->v_localname, name);
575             if (volume->v_deleted) {
576                 volume->v_new = hide = 1;
577             }
578             else {
579                 return -1;  /* Won't be able to access it, anyway... */
580             }
581         }
582     }
583
584     if (!( volume = (struct vol *)calloc(1, sizeof( struct vol ))) ) {
585         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
586         return -1;
587     }
588     if ( NULL == ( volume->v_localname = strdup(name))) {
589         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
590         free(volume);
591         return -1;
592     }
593
594     if ( NULL == ( volume->v_u8mname = strdup_w(u8mtmpname))) {
595         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
596         volume_free(volume);
597         free(volume);
598         return -1;
599     }
600     if ( NULL == ( volume->v_macname = strdup_w(mactmpname))) {
601         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
602         volume_free(volume);
603         free(volume);
604         return -1;
605     }
606     if (!( volume->v_path = (char *)malloc( strlen( path ) + 1 )) ) {
607         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
608         volume_free(volume);
609         free(volume);
610         return -1;
611     }
612
613     volume->v_name = utf8_encoding()?volume->v_u8mname:volume->v_macname;
614     volume->v_hide = hide;
615     strcpy( volume->v_path, path );
616
617 #ifdef __svr4__
618     volume->v_qfd = -1;
619 #endif /* __svr4__ */
620     /* os X start at 1 and use network order ie. 1 2 3 */
621     volume->v_vid = ++lastvid;
622     volume->v_vid = htons(volume->v_vid);
623 #ifdef HAVE_ACLS
624     if (!check_vol_acl_support(volume)) {
625         LOG(log_debug, logtype_afpd, "creatvol(\"%s\"): disabling ACL support", volume->v_path);
626         options[VOLOPT_FLAGS].i_value &= ~AFPVOL_ACLS;
627     }
628 #endif
629
630     /* handle options */
631     if (options) {
632         volume->v_casefold = options[VOLOPT_CASEFOLD].i_value;
633         volume->v_flags |= options[VOLOPT_FLAGS].i_value;
634
635         if (options[VOLOPT_EA_VFS].i_value)
636             volume->v_vfs_ea = options[VOLOPT_EA_VFS].i_value;
637
638         volume->v_ad_options = 0;
639         if ((volume->v_flags & AFPVOL_NODEV))
640             volume->v_ad_options |= ADVOL_NODEV;
641         if ((volume->v_flags & AFPVOL_UNIX_PRIV))
642             volume->v_ad_options |= ADVOL_UNIXPRIV;
643         if ((volume->v_flags & AFPVOL_INV_DOTS))
644             volume->v_ad_options |= ADVOL_INVDOTS;
645
646         if (options[VOLOPT_PASSWORD].c_value)
647             volume->v_password = strdup(options[VOLOPT_PASSWORD].c_value);
648
649         if (options[VOLOPT_VETO].c_value)
650             volume->v_veto = strdup(options[VOLOPT_VETO].c_value);
651
652         if (options[VOLOPT_ENCODING].c_value)
653             volume->v_volcodepage = strdup(options[VOLOPT_ENCODING].c_value);
654
655         if (options[VOLOPT_MACCHARSET].c_value)
656             volume->v_maccodepage = strdup(options[VOLOPT_MACCHARSET].c_value);
657
658         if (options[VOLOPT_DBPATH].c_value)
659             volume->v_dbpath = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_DBPATH].c_value, pwd, path, name);
660
661         if (options[VOLOPT_CNIDSCHEME].c_value)
662             volume->v_cnidscheme = strdup(options[VOLOPT_CNIDSCHEME].c_value);
663
664         if (options[VOLOPT_CNIDSERVER].c_value)
665             volume->v_cnidserver = strdup(options[VOLOPT_CNIDSERVER].c_value);
666
667         if (options[VOLOPT_CNIDPORT].c_value)
668             volume->v_cnidport = strdup(options[VOLOPT_CNIDPORT].c_value);
669
670         if (options[VOLOPT_UMASK].i_value)
671             volume->v_umask = (mode_t)options[VOLOPT_UMASK].i_value;
672
673         if (options[VOLOPT_DPERM].i_value)
674             volume->v_dperm = (mode_t)options[VOLOPT_DPERM].i_value;
675
676         if (options[VOLOPT_FPERM].i_value)
677             volume->v_fperm = (mode_t)options[VOLOPT_FPERM].i_value;
678
679         if (options[VOLOPT_DFLTPERM].i_value)
680             volume->v_perm = (mode_t)options[VOLOPT_DFLTPERM].i_value;
681
682         if (options[VOLOPT_ADOUBLE].i_value)
683             volume->v_adouble = options[VOLOPT_ADOUBLE].i_value;
684         else
685             volume->v_adouble = AD_VERSION;
686
687         if (options[VOLOPT_LIMITSIZE].i_value)
688             volume->v_limitsize = options[VOLOPT_LIMITSIZE].i_value;
689
690         /* Mac to Unix conversion flags*/
691         volume->v_mtou_flags = 0;
692         if (!(volume->v_flags & AFPVOL_NOHEX))
693             volume->v_mtou_flags |= CONV_ESCAPEHEX;
694         if (!(volume->v_flags & AFPVOL_USEDOTS))
695             volume->v_mtou_flags |= CONV_ESCAPEDOTS;
696         if ((volume->v_flags & AFPVOL_EILSEQ))
697             volume->v_mtou_flags |= CONV__EILSEQ;
698
699         if ((volume->v_casefold & AFPVOL_MTOUUPPER))
700             volume->v_mtou_flags |= CONV_TOUPPER;
701         else if ((volume->v_casefold & AFPVOL_MTOULOWER))
702             volume->v_mtou_flags |= CONV_TOLOWER;
703
704         /* Unix to Mac conversion flags*/
705         volume->v_utom_flags = CONV_IGNORE | CONV_UNESCAPEHEX;
706         if ((volume->v_casefold & AFPVOL_UTOMUPPER))
707             volume->v_utom_flags |= CONV_TOUPPER;
708         else if ((volume->v_casefold & AFPVOL_UTOMLOWER))
709             volume->v_utom_flags |= CONV_TOLOWER;
710
711         if ((volume->v_flags & AFPVOL_EILSEQ))
712             volume->v_utom_flags |= CONV__EILSEQ;
713
714         if (options[VOLOPT_PREEXEC].c_value)
715             volume->v_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_PREEXEC].c_value, pwd, path, name);
716         volume->v_preexec_close = options[VOLOPT_PREEXEC].i_value;
717
718         if (options[VOLOPT_POSTEXEC].c_value)
719             volume->v_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_POSTEXEC].c_value, pwd, path, name);
720
721         if (options[VOLOPT_ROOTPREEXEC].c_value)
722             volume->v_root_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPREEXEC].c_value, pwd, path,  name);
723         volume->v_root_preexec_close = options[VOLOPT_ROOTPREEXEC].i_value;
724
725         if (options[VOLOPT_ROOTPOSTEXEC].c_value)
726             volume->v_root_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPOSTEXEC].c_value, pwd, path,  name);
727     }
728     volume->v_dperm |= volume->v_perm;
729     volume->v_fperm |= volume->v_perm;
730
731     /* Check EA support on volume */
732     if (volume->v_vfs_ea == AFPVOL_EA_AUTO)
733         check_ea_sys_support(volume);
734     initvol_vfs(volume);
735
736     /* get/store uuid from file in afpd master*/
737     if ((parent_or_child == 0) && (volume->v_flags & AFPVOL_TM)) {
738         char *uuid = get_vol_uuid(obj, volume->v_localname);
739         if (!uuid) {
740             LOG(log_error, logtype_afpd, "Volume '%s': couldn't get UUID",
741                 volume->v_localname);
742         } else {
743             volume->v_uuid = uuid;
744             LOG(log_debug, logtype_afpd, "Volume '%s': UUID '%s'",
745                 volume->v_localname, volume->v_uuid);
746         }
747     }
748
749     volume->v_next = Volumes;
750     Volumes = volume;
751     return 0;
752 }
753
754 /* ---------------- */
755 static char *myfgets( char *buf, int size, FILE *fp)
756 {
757     char    *p;
758     int     c;
759
760     p = buf;
761     while ((EOF != ( c = getc( fp )) ) && ( size > 1 )) {
762         if ( c == '\n' || c == '\r' ) {
763             if (p != buf && *(p -1) == '\\') {
764                 p--;
765                 size++;
766                 continue;
767             }
768             *p++ = '\n';
769             break;
770         } else {
771             *p++ = c;
772         }
773         size--;
774     }
775
776     if ( p == buf ) {
777         return( NULL );
778     } else {
779         *p = '\0';
780         return( buf );
781     }
782 }
783
784
785 /* check access list. this function wants something of the following
786  * form:
787  *        @group,name,name2,@group2,name3
788  *
789  * a NULL argument allows everybody to have access.
790  * we return three things:
791  *     -1: no list
792  *      0: list exists, but name isn't in it
793  *      1: in list
794  */
795
796 #ifndef NO_REAL_USER_NAME
797 /* authentication is case insensitive
798  * FIXME should we do the same with group name?
799  */
800 #define access_strcmp strcasecmp
801
802 #else
803 #define access_strcmp strcmp
804
805 #endif
806
807 static int accessvol(const char *args, const char *name)
808 {
809     char buf[MAXPATHLEN + 1], *p;
810     struct group *gr;
811
812     if (!args)
813         return -1;
814
815     strlcpy(buf, args, sizeof(buf));
816     if ((p = strtok(buf, ",")) == NULL) /* nothing, return okay */
817         return -1;
818
819     while (p) {
820         if (*p == '@') { /* it's a group */
821             if ((gr = getgrnam(p + 1)) && gmem(gr->gr_gid))
822                 return 1;
823         } else if (access_strcmp(p, name) == 0) /* it's a user name */
824             return 1;
825         p = strtok(NULL, ",");
826     }
827
828     return 0;
829 }
830
831 static int hostaccessvol(int type, const char *volname, const char *args, const AFPObj *obj)
832 {
833     int mask_int;
834     char buf[MAXPATHLEN + 1], *p, *b;
835     DSI *dsi = obj->dsi;
836     struct sockaddr_storage client;
837
838     if (!args)
839         return -1;
840
841     strlcpy(buf, args, sizeof(buf));
842     if ((p = strtok_r(buf, ",", &b)) == NULL) /* nothing, return okay */
843         return -1;
844
845     while (p) {
846         int ret;
847         char *ipaddr, *mask_char;
848         struct addrinfo hints, *ai;
849
850         ipaddr = strtok(p, "/");
851         mask_char = strtok(NULL,"/");
852
853         /* Get address from string with getaddrinfo */
854         memset(&hints, 0, sizeof hints);
855         hints.ai_family = AF_UNSPEC;
856         hints.ai_socktype = SOCK_STREAM;
857         if ((ret = getaddrinfo(ipaddr, NULL, &hints, &ai)) != 0) {
858             LOG(log_error, logtype_afpd, "hostaccessvol: getaddrinfo: %s\n", gai_strerror(ret));
859             continue;
860         }
861
862         /* netmask */
863         if (mask_char != NULL)
864             mask_int = atoi(mask_char); /* apply_ip_mask does range checking on it */
865         else {
866             if (ai->ai_family == AF_INET) /* IPv4 */
867                 mask_int = 32;
868             else                          /* IPv6 */
869                 mask_int = 128;
870         }
871
872         /* Apply mask to addresses */
873         client = dsi->client;
874         apply_ip_mask((struct sockaddr *)&client, mask_int);
875         apply_ip_mask(ai->ai_addr, mask_int);
876
877         if (compare_ip((struct sockaddr *)&client, ai->ai_addr) == 0) {
878             if (type == VOLOPT_DENIED_HOSTS)
879                 LOG(log_info, logtype_afpd, "AFP access denied for client IP '%s' to volume '%s' by denied list",
880                     getip_string((struct sockaddr *)&client), volname);
881             freeaddrinfo(ai);
882             return 1;
883         }
884
885         /* next address */
886         freeaddrinfo(ai);
887         p = strtok_r(NULL, ",", &b);
888     }
889
890     if (type == VOLOPT_ALLOWED_HOSTS)
891         LOG(log_info, logtype_afpd, "AFP access denied for client IP '%s' to volume '%s', not in allowed list",
892             getip_string((struct sockaddr *)&dsi->client), volname);
893     return 0;
894 }
895
896 /* ----------------------
897  */
898 static int volfile_changed(struct afp_options *p)
899 {
900     struct stat      st;
901
902     if (!stat(p->configfile, &st) && st.st_mtime > p->volfile.mtime) {
903         p->volfile.mtime = st.st_mtime;
904         return 1;
905     }
906     return 0;
907 }
908
909 static int vol_section(const char *sec)
910 {
911     if (STRCMP(sec, ==, INISEC_GLOBAL) == 0)
912         return 0;
913     if (strcmp(sec, INISEC_AFP) == 0)
914         return 0;
915     if (strcmp(sec, INISEC_CNID) == 0)
916         return 0;
917     return 1;
918 }
919
920 /* ----------------------
921  * Read volumes from iniconfig and add the volumes contained within to
922  * the global volume list. This gets called from the forked afpd childs.
923  * The master now reads this too for Zeroconf announcements.
924  */
925 static int readvolfile(AFPObj *obj, struct afp_volume_name *p1, struct passwd *pwent)
926 {
927     char        path[MAXPATHLEN + 1];
928     char        volname[AFPVOL_U8MNAMELEN + 1];
929     char        tmp[MAXPATHLEN + 1];
930     char        *u;
931     const char  *p;
932     int         fd;
933     int         i;
934     struct passwd     *pw;
935     struct vol_option save_options[VOLOPT_NUM];
936     struct vol_option default_options[VOLOPT_NUM];
937     struct vol_option options[VOLOPT_NUM];
938
939     LOG(log_debug, logtype_afpd, "readvolfile: BEGIN");
940
941     p1->mtime = 0;
942
943     memset(default_options, 0, sizeof(default_options));
944
945     /* Enable some default options for all volumes */
946 #ifdef HAVE_ACLS
947     default_options[VOLOPT_FLAGS].i_value |= AFPVOL_ACLS;
948 #endif
949     default_options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_AUTO;
950     default_options[VOLOPT_UMASK].i_value = obj->options.umask;
951     memcpy(save_options, default_options, sizeof(options));
952
953     int secnum = iniparser_getnsec(obj->iniconfig);    
954     const char *secname;
955
956     for (i = 0; i < secnum; secname = iniparser_getsecname(obj->iniconfig, i), i++) { 
957         if (!vol_section(secname))
958             continue;
959         if ((p = iniparser_getstrdup(obj->iniconfig, secname, "path", NULL)) == NULL)
960             continue;
961         strlcpy(path, p, MAXPATHLEN);
962         strcpy(tmp, path);
963         strlcpy(volname, secname, AFPVOL_U8MNAMELEN);
964
965         if (!pwent && obj->username)
966             pwent = getpwnam(obj->username);
967
968         if (volxlate(obj, path, sizeof(path) - 1, tmp, pwent, NULL, NULL) == NULL)
969             continue;
970
971         memcpy(options, default_options, sizeof(options));
972         volset(obj->iniconfig, secname, options, default_options);
973
974         /* check allow/deny lists (if not afpd master loading volumes for Zeroconf reg.):
975            allow -> either no list (-1), or in list (1)
976            deny -> either no list (-1), or not in list (0) */
977         if (parent_or_child == 0
978             ||
979             (accessvol(options[VOLOPT_ALLOW].c_value, obj->username) &&
980              (accessvol(options[VOLOPT_DENY].c_value, obj->username) < 1) &&
981              hostaccessvol(VOLOPT_ALLOWED_HOSTS, volname, options[VOLOPT_ALLOWED_HOSTS].c_value, obj) &&
982              (hostaccessvol(VOLOPT_DENIED_HOSTS, volname, options[VOLOPT_DENIED_HOSTS].c_value, obj) < 1))) {
983
984             /* handle read-only behaviour. semantics:
985              * 1) neither the rolist nor the rwlist exist -> rw
986              * 2) rolist exists -> ro if user is in it.
987              * 3) rwlist exists -> ro unless user is in it. */
988             if (parent_or_child == 1
989                 &&
990                 ((options[VOLOPT_FLAGS].i_value & AFPVOL_RO) == 0)
991                 &&
992                 ((accessvol(options[VOLOPT_ROLIST].c_value, obj->username) == 1) ||
993                  !accessvol(options[VOLOPT_RWLIST].c_value, obj->username)))
994                 options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
995
996             /* do variable substitution for volname */
997             if (volxlate(obj, tmp, sizeof(tmp) - 1, volname, pwent, path, NULL) == NULL) {
998                 volfree(options, default_options);
999                 continue;
1000             }
1001
1002             creatvol(obj, pwent, path, tmp, options);
1003         }
1004         volfree(options, default_options);
1005     }
1006     volfree(save_options, NULL);
1007     p1->loaded = 1;
1008     return( 0 );
1009 }
1010
1011 /* ------------------------------- */
1012 static void volume_free(struct vol *vol)
1013 {
1014     free(vol->v_localname);
1015     vol->v_localname = NULL;
1016     free(vol->v_u8mname);
1017     vol->v_u8mname = NULL;
1018     free(vol->v_macname);
1019     vol->v_macname = NULL;
1020     free(vol->v_path);
1021     free(vol->v_password);
1022     free(vol->v_veto);
1023     free(vol->v_volcodepage);
1024     free(vol->v_maccodepage);
1025     free(vol->v_cnidscheme);
1026     free(vol->v_dbpath);
1027     free(vol->v_gvs);
1028     if (vol->v_uuid)
1029         free(vol->v_uuid);
1030 }
1031
1032 /* ------------------------------- */
1033 static void free_volumes(void )
1034 {
1035     struct vol  *vol;
1036     struct vol  *nvol, *ovol;
1037
1038     for ( vol = Volumes; vol; vol = vol->v_next ) {
1039         if (( vol->v_flags & AFPVOL_OPEN ) ) {
1040             vol->v_deleted = 1;
1041             continue;
1042         }
1043         volume_free(vol);
1044     }
1045
1046     for ( vol = Volumes, ovol = NULL; vol; vol = nvol) {
1047         nvol = vol->v_next;
1048
1049         if (vol->v_localname == NULL) {
1050             if (Volumes == vol) {
1051                 Volumes = nvol;
1052                 ovol = Volumes;
1053             }
1054             else {
1055                 ovol->v_next = nvol;
1056             }
1057             free(vol);
1058         }
1059         else {
1060             ovol = vol;
1061         }
1062     }
1063 }
1064
1065 /* ------------------------------- */
1066 static void volume_unlink(struct vol *volume)
1067 {
1068     struct vol *vol, *ovol, *nvol;
1069
1070     if (volume == Volumes) {
1071         Volumes = Volumes->v_next;
1072         return;
1073     }
1074     for ( vol = Volumes->v_next, ovol = Volumes; vol; vol = nvol) {
1075         nvol = vol->v_next;
1076
1077         if (vol == volume) {
1078             ovol->v_next = nvol;
1079             break;
1080         }
1081         else {
1082             ovol = vol;
1083         }
1084     }
1085 }
1086 /*!
1087  * Read band-size info from Info.plist XML file of an TM sparsebundle
1088  *
1089  * @param path   (r) path to Info.plist file
1090  * @return           band-size in bytes, -1 on error
1091  */
1092 static long long int get_tm_bandsize(const char *path)
1093 {
1094     EC_INIT;
1095     FILE *file = NULL;
1096     char buf[512];
1097     long long int bandsize = -1;
1098
1099     EC_NULL_LOGSTR( file = fopen(path, "r"),
1100                     "get_tm_bandsize(\"%s\"): %s",
1101                     path, strerror(errno) );
1102
1103     while (fgets(buf, sizeof(buf), file) != NULL) {
1104         if (strstr(buf, "band-size") == NULL)
1105             continue;
1106
1107         if (fscanf(file, " <integer>%lld</integer>", &bandsize) != 1) {
1108             LOG(log_error, logtype_afpd, "get_tm_bandsize(\"%s\"): can't parse band-size", path);
1109             EC_FAIL;
1110         }
1111         break;
1112     }
1113
1114 EC_CLEANUP:
1115     if (file)
1116         fclose(file);
1117     LOG(log_debug, logtype_afpd, "get_tm_bandsize(\"%s\"): bandsize: %lld", path, bandsize);
1118     return bandsize;
1119 }
1120
1121 /*!
1122  * Return number on entries in a directory
1123  *
1124  * @param path   (r) path to dir
1125  * @return           number of entries, -1 on error
1126  */
1127 static long long int get_tm_bands(const char *path)
1128 {
1129     EC_INIT;
1130     long long int count = 0;
1131     DIR *dir = NULL;
1132     const struct dirent *entry;
1133
1134     EC_NULL( dir = opendir(path) );
1135
1136     while ((entry = readdir(dir)) != NULL)
1137         count++;
1138     count -= 2; /* All OSens I'm aware of return "." and "..", so just substract them, avoiding string comparison in loop */
1139         
1140 EC_CLEANUP:
1141     if (dir)
1142         closedir(dir);
1143     if (ret != 0)
1144         return -1;
1145     return count;
1146 }
1147
1148 /*!
1149  * Calculate used size of a TimeMachine volume
1150  *
1151  * This assumes that the volume is used only for TimeMachine.
1152  *
1153  * 1) readdir(path of volume)
1154  * 2) for every element that matches regex "\(.*\)\.sparsebundle$" :
1155  * 3) parse "\1.sparsebundle/Info.plist" and read the band-size XML key integer value
1156  * 4) readdir "\1.sparsebundle/bands/" counting files
1157  * 5) calculate used size as: (file_count - 1) * band-size
1158  *
1159  * The result of the calculation is returned in "volume->v_tm_used".
1160  * "volume->v_appended" gets reset to 0.
1161  * "volume->v_tm_cachetime" is updated with the current time from time(NULL).
1162  *
1163  * "volume->v_tm_used" is cached for TM_USED_CACHETIME seconds and updated by
1164  * "volume->v_appended". The latter is increased by X every time the client
1165  * appends X bytes to a file (in fork.c).
1166  *
1167  * @param vol     (rw) volume to calculate
1168  * @return             0 on success, -1 on error
1169  */
1170 #define TM_USED_CACHETIME 60    /* cache for 60 seconds */
1171 static int get_tm_used(struct vol * restrict vol)
1172 {
1173     EC_INIT;
1174     long long int bandsize;
1175     VolSpace used = 0;
1176     bstring infoplist = NULL;
1177     bstring bandsdir = NULL;
1178     DIR *dir = NULL;
1179     const struct dirent *entry;
1180     const char *p;
1181     struct stat st;
1182     long int links;
1183     time_t now = time(NULL);
1184
1185     if (vol->v_tm_cachetime
1186         && ((vol->v_tm_cachetime + TM_USED_CACHETIME) >= now)) {
1187         if (vol->v_tm_used == -1)
1188             EC_FAIL;
1189         vol->v_tm_used += vol->v_appended;
1190         vol->v_appended = 0;
1191         LOG(log_debug, logtype_afpd, "getused(\"%s\"): cached: %" PRIu64 " bytes",
1192             vol->v_path, vol->v_tm_used);
1193         return 0;
1194     }
1195
1196     vol->v_tm_cachetime = now;
1197
1198     EC_NULL( dir = opendir(vol->v_path) );
1199
1200     while ((entry = readdir(dir)) != NULL) {
1201         if (((p = strstr(entry->d_name, "sparsebundle")) != NULL)
1202             && (strlen(entry->d_name) == (p + strlen("sparsebundle") - entry->d_name))) {
1203
1204             EC_NULL_LOG( infoplist = bformat("%s/%s/%s", vol->v_path, entry->d_name, "Info.plist") );
1205             
1206             if ((bandsize = get_tm_bandsize(cfrombstr(infoplist))) == -1)
1207                 continue;
1208
1209             EC_NULL_LOG( bandsdir = bformat("%s/%s/%s/", vol->v_path, entry->d_name, "bands") );
1210
1211             if ((links = get_tm_bands(cfrombstr(bandsdir))) == -1)
1212                 continue;
1213
1214             used += (links - 1) * bandsize;
1215             LOG(log_debug, logtype_afpd, "getused(\"%s\"): bands: %" PRIu64 " bytes",
1216                 cfrombstr(bandsdir), used);
1217         }
1218     }
1219
1220     vol->v_tm_used = used;
1221
1222 EC_CLEANUP:
1223     if (infoplist)
1224         bdestroy(infoplist);
1225     if (bandsdir)
1226         bdestroy(bandsdir);
1227     if (dir)
1228         closedir(dir);
1229
1230     LOG(log_debug, logtype_afpd, "getused(\"%s\"): %" PRIu64 " bytes", vol->v_path, vol->v_tm_used);
1231
1232     EC_EXIT;
1233 }
1234
1235 static int getvolspace(struct vol *vol,
1236                        uint32_t *bfree, uint32_t *btotal,
1237                        VolSpace *xbfree, VolSpace *xbtotal, uint32_t *bsize)
1238 {
1239     int         spaceflag, rc;
1240     uint32_t   maxsize;
1241     VolSpace    used;
1242 #ifndef NO_QUOTA_SUPPORT
1243     VolSpace    qfree, qtotal;
1244 #endif
1245
1246     spaceflag = AFPVOL_GVSMASK & vol->v_flags;
1247     /* report up to 2GB if afp version is < 2.2 (4GB if not) */
1248     maxsize = (afp_version < 22) ? 0x7fffffffL : 0xffffffffL;
1249
1250 #ifdef AFS
1251     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_AFSGVS ) {
1252         if ( afs_getvolspace( vol, xbfree, xbtotal, bsize ) == AFP_OK ) {
1253             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_AFSGVS;
1254             goto getvolspace_done;
1255         }
1256     }
1257 #endif
1258
1259     if (( rc = ustatfs_getvolspace( vol, xbfree, xbtotal, bsize)) != AFP_OK ) {
1260         return( rc );
1261     }
1262
1263 #ifndef NO_QUOTA_SUPPORT
1264     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_UQUOTA ) {
1265         if ( uquota_getvolspace( vol, &qfree, &qtotal, *bsize ) == AFP_OK ) {
1266             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_UQUOTA;
1267             *xbfree = MIN(*xbfree, qfree);
1268             *xbtotal = MIN(*xbtotal, qtotal);
1269             goto getvolspace_done;
1270         }
1271     }
1272 #endif
1273     vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_USTATFS;
1274
1275 getvolspace_done:
1276     if (vol->v_limitsize) {
1277         if (get_tm_used(vol) != 0)
1278             return AFPERR_MISC;
1279
1280         *xbtotal = MIN(*xbtotal, (vol->v_limitsize * 1024 * 1024));
1281         *xbfree = MIN(*xbfree, *xbtotal < vol->v_tm_used ? 0 : *xbtotal - vol->v_tm_used);
1282
1283         LOG(log_debug, logtype_afpd,
1284             "volparams: total: %" PRIu64 ", used: %" PRIu64 ", free: %" PRIu64 " bytes",
1285             *xbtotal, vol->v_tm_used, *xbfree);
1286     }
1287
1288     *bfree = MIN(*xbfree, maxsize);
1289     *btotal = MIN(*xbtotal, maxsize);
1290     return( AFP_OK );
1291 }
1292
1293 #define FCE_TM_DELTA 10  /* send notification every 10 seconds */
1294 void vol_fce_tm_event(void)
1295 {
1296     static time_t last;
1297     time_t now = time(NULL);
1298     struct vol  *vol = Volumes;
1299
1300     if ((last + FCE_TM_DELTA) < now) {
1301         last = now;
1302         for ( ; vol; vol = vol->v_next ) {
1303             if (vol->v_flags & AFPVOL_TM)
1304                 (void)fce_register_tm_size(vol->v_path, vol->v_tm_used + vol->v_appended);
1305         }
1306     }
1307 }
1308
1309 /* -----------------------
1310  * set volume creation date
1311  * avoid duplicate, well at least it tries
1312  */
1313 static void vol_setdate(uint16_t id, struct adouble *adp, time_t date)
1314 {
1315     struct vol  *volume;
1316     struct vol  *vol = Volumes;
1317
1318     for ( volume = Volumes; volume; volume = volume->v_next ) {
1319         if (volume->v_vid == id) {
1320             vol = volume;
1321         }
1322         else if ((time_t)(AD_DATE_FROM_UNIX(date)) == volume->v_ctime) {
1323             date = date+1;
1324             volume = Volumes; /* restart */
1325         }
1326     }
1327     vol->v_ctime = AD_DATE_FROM_UNIX(date);
1328     ad_setdate(adp, AD_DATE_CREATE | AD_DATE_UNIX, date);
1329 }
1330
1331 /* ----------------------- */
1332 static int getvolparams( uint16_t bitmap, struct vol *vol, struct stat *st, char *buf, size_t *buflen)
1333 {
1334     struct adouble  ad;
1335     int         bit = 0, isad = 1;
1336     uint32_t       aint;
1337     u_short     ashort;
1338     uint32_t       bfree, btotal, bsize;
1339     VolSpace            xbfree, xbtotal; /* extended bytes */
1340     char        *data, *nameoff = NULL;
1341     char                *slash;
1342
1343     LOG(log_debug, logtype_afpd, "getvolparams: Volume '%s'", vol->v_localname);
1344
1345     /* courtesy of jallison@whistle.com:
1346      * For MacOS8.x support we need to create the
1347      * .Parent file here if it doesn't exist. */
1348
1349     /* Convert adouble:v2 to adouble:ea on the fly */
1350     (void)ad_convert(vol->v_path, st, vol);
1351
1352     ad_init(&ad, vol);
1353     if (ad_open(&ad, vol->v_path, ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666) != 0 ) {
1354         isad = 0;
1355         vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1356
1357     } else if (ad_get_MD_flags( &ad ) & O_CREAT) {
1358         slash = strrchr( vol->v_path, '/' );
1359         if(slash)
1360             slash++;
1361         else
1362             slash = vol->v_path;
1363         if (ad_getentryoff(&ad, ADEID_NAME)) {
1364             ad_setentrylen( &ad, ADEID_NAME, strlen( slash ));
1365             memcpy(ad_entry( &ad, ADEID_NAME ), slash,
1366                    ad_getentrylen( &ad, ADEID_NAME ));
1367         }
1368         vol_setdate(vol->v_vid, &ad, st->st_mtime);
1369         ad_flush(&ad);
1370     }
1371     else {
1372         if (ad_getdate(&ad, AD_DATE_CREATE, &aint) < 0)
1373             vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1374         else
1375             vol->v_ctime = aint;
1376     }
1377
1378     if (( bitmap & ( (1<<VOLPBIT_BFREE)|(1<<VOLPBIT_BTOTAL) |
1379                      (1<<VOLPBIT_XBFREE)|(1<<VOLPBIT_XBTOTAL) |
1380                      (1<<VOLPBIT_BSIZE)) ) != 0 ) {
1381         if ( getvolspace( vol, &bfree, &btotal, &xbfree, &xbtotal,
1382                           &bsize) != AFP_OK ) {
1383             if ( isad ) {
1384                 ad_close( &ad, ADFLAGS_HF );
1385             }
1386             return( AFPERR_PARAM );
1387         }
1388     }
1389
1390     data = buf;
1391     while ( bitmap != 0 ) {
1392         while (( bitmap & 1 ) == 0 ) {
1393             bitmap = bitmap>>1;
1394             bit++;
1395         }
1396
1397         switch ( bit ) {
1398         case VOLPBIT_ATTR :
1399             ashort = 0;
1400             /* check for read-only.
1401              * NOTE: we don't actually set the read-only flag unless
1402              *       it's passed in that way as it's possible to mount
1403              *       a read-write filesystem under a read-only one. */
1404             if ((vol->v_flags & AFPVOL_RO) ||
1405                 ((utime(vol->v_path, NULL) < 0) && (errno == EROFS))) {
1406                 ashort |= VOLPBIT_ATTR_RO;
1407             }
1408             /* prior 2.1 only VOLPBIT_ATTR_RO is defined */
1409             if (afp_version > 20) {
1410                 if (vol->v_cdb != NULL && (vol->v_cdb->flags & CNID_FLAG_PERSISTENT))
1411                     ashort |= VOLPBIT_ATTR_FILEID;
1412                 ashort |= VOLPBIT_ATTR_CATSEARCH;
1413
1414                 if (afp_version >= 30) {
1415                     ashort |= VOLPBIT_ATTR_UTF8;
1416                     if (vol->v_flags & AFPVOL_UNIX_PRIV)
1417                         ashort |= VOLPBIT_ATTR_UNIXPRIV;
1418                     if (vol->v_flags & AFPVOL_TM)
1419                         ashort |= VOLPBIT_ATTR_TM;
1420                     if (vol->v_flags & AFPVOL_NONETIDS)
1421                         ashort |= VOLPBIT_ATTR_NONETIDS;
1422                     if (afp_version >= 32) {
1423                         if (vol->v_vfs_ea)
1424                             ashort |= VOLPBIT_ATTR_EXT_ATTRS;
1425                         if (vol->v_flags & AFPVOL_ACLS)
1426                             ashort |= VOLPBIT_ATTR_ACLS;
1427                     }
1428                 }
1429             }
1430             ashort = htons(ashort);
1431             memcpy(data, &ashort, sizeof( ashort ));
1432             data += sizeof( ashort );
1433             break;
1434
1435         case VOLPBIT_SIG :
1436             ashort = htons( AFPVOLSIG_DEFAULT );
1437             memcpy(data, &ashort, sizeof( ashort ));
1438             data += sizeof( ashort );
1439             break;
1440
1441         case VOLPBIT_CDATE :
1442             aint = vol->v_ctime;
1443             memcpy(data, &aint, sizeof( aint ));
1444             data += sizeof( aint );
1445             break;
1446
1447         case VOLPBIT_MDATE :
1448             if ( st->st_mtime > vol->v_mtime ) {
1449                 vol->v_mtime = st->st_mtime;
1450             }
1451             aint = AD_DATE_FROM_UNIX(vol->v_mtime);
1452             memcpy(data, &aint, sizeof( aint ));
1453             data += sizeof( aint );
1454             break;
1455
1456         case VOLPBIT_BDATE :
1457             if (!isad ||  (ad_getdate(&ad, AD_DATE_BACKUP, &aint) < 0))
1458                 aint = AD_DATE_START;
1459             memcpy(data, &aint, sizeof( aint ));
1460             data += sizeof( aint );
1461             break;
1462
1463         case VOLPBIT_VID :
1464             memcpy(data, &vol->v_vid, sizeof( vol->v_vid ));
1465             data += sizeof( vol->v_vid );
1466             break;
1467
1468         case VOLPBIT_BFREE :
1469             bfree = htonl( bfree );
1470             memcpy(data, &bfree, sizeof( bfree ));
1471             data += sizeof( bfree );
1472             break;
1473
1474         case VOLPBIT_BTOTAL :
1475             btotal = htonl( btotal );
1476             memcpy(data, &btotal, sizeof( btotal ));
1477             data += sizeof( btotal );
1478             break;
1479
1480 #ifndef NO_LARGE_VOL_SUPPORT
1481         case VOLPBIT_XBFREE :
1482             xbfree = hton64( xbfree );
1483             memcpy(data, &xbfree, sizeof( xbfree ));
1484             data += sizeof( xbfree );
1485             break;
1486
1487         case VOLPBIT_XBTOTAL :
1488             xbtotal = hton64( xbtotal );
1489             memcpy(data, &xbtotal, sizeof( xbtotal ));
1490             data += sizeof( xbfree );
1491             break;
1492 #endif /* ! NO_LARGE_VOL_SUPPORT */
1493
1494         case VOLPBIT_NAME :
1495             nameoff = data;
1496             data += sizeof( uint16_t );
1497             break;
1498
1499         case VOLPBIT_BSIZE:  /* block size */
1500             bsize = htonl(bsize);
1501             memcpy(data, &bsize, sizeof(bsize));
1502             data += sizeof(bsize);
1503             break;
1504
1505         default :
1506             if ( isad ) {
1507                 ad_close( &ad, ADFLAGS_HF );
1508             }
1509             return( AFPERR_BITMAP );
1510         }
1511         bitmap = bitmap>>1;
1512         bit++;
1513     }
1514     if ( nameoff ) {
1515         ashort = htons( data - buf );
1516         memcpy(nameoff, &ashort, sizeof( ashort ));
1517         /* name is always in mac charset */
1518         aint = ucs2_to_charset( vol->v_maccharset, vol->v_macname, data+1, AFPVOL_MACNAMELEN + 1);
1519         if ( aint <= 0 ) {
1520             *buflen = 0;
1521             return AFPERR_MISC;
1522         }
1523
1524         *data++ = aint;
1525         data += aint;
1526     }
1527     if ( isad ) {
1528         ad_close(&ad, ADFLAGS_HF);
1529     }
1530     *buflen = data - buf;
1531     return( AFP_OK );
1532 }
1533
1534 /* ------------------------- */
1535 static int stat_vol(uint16_t bitmap, struct vol *vol, char *rbuf, size_t *rbuflen)
1536 {
1537     struct stat st;
1538     int     ret;
1539     size_t  buflen;
1540
1541     if ( stat( vol->v_path, &st ) < 0 ) {
1542         *rbuflen = 0;
1543         return( AFPERR_PARAM );
1544     }
1545     /* save the volume device number */
1546     vol->v_dev = st.st_dev;
1547
1548     buflen = *rbuflen - sizeof( bitmap );
1549     if (( ret = getvolparams( bitmap, vol, &st,
1550                               rbuf + sizeof( bitmap ), &buflen )) != AFP_OK ) {
1551         *rbuflen = 0;
1552         return( ret );
1553     }
1554     *rbuflen = buflen + sizeof( bitmap );
1555     bitmap = htons( bitmap );
1556     memcpy(rbuf, &bitmap, sizeof( bitmap ));
1557     return( AFP_OK );
1558
1559 }
1560
1561 /* ------------------------------- */
1562 void load_volumes(AFPObj *obj)
1563 {
1564     EC_INIT;
1565     int fd = -1;
1566     struct passwd   *pwent;
1567     struct stat         st;
1568     int retries = 0;
1569
1570     if (parent_or_child == 0) {
1571         LOG(log_debug, logtype_afpd, "load_volumes: AFP MASTER");
1572     } else {
1573         LOG(log_debug, logtype_afpd, "load_volumes: user: %s", obj->username);
1574     }
1575
1576     if (Volumes) {
1577         if (!volfile_changed(&obj->options))
1578             return;
1579         free_volumes();
1580     }
1581
1582     /* try putting a read lock on the volume file twice, sleep 1 second if first attempt fails */
1583
1584     fd = open(obj->options.configfile, O_RDWR);
1585
1586     while (retries < 2) {
1587         if ((read_lock(fd, 0, SEEK_SET, 0)) != 0) {
1588             retries++;
1589             if (!retries) {
1590                 LOG(log_error, logtype_afpd, "readvolfile: can't lock configfile \"%s\"",
1591                     obj->options.configfile);
1592                 EC_FAIL;
1593             }
1594             sleep(1);
1595             continue;
1596         }
1597         break;
1598     }
1599
1600     iniparser_freedict(obj->iniconfig);
1601     obj->iniconfig = iniparser_load(obj->options.configfile);
1602
1603     if (obj->username)
1604         pwent = getpwnam(obj->username);
1605     else
1606         pwent = NULL;
1607
1608     readvolfile(obj, &obj->options.volfile, pwent);
1609
1610     if ( obj->options.flags & OPTION_CLOSEVOL) {
1611         struct vol *vol;
1612         for ( vol = Volumes; vol; vol = vol->v_next ) {
1613             if (vol->v_deleted && !vol->v_new ) {
1614                 of_closevol(vol);
1615                 deletevol(vol);
1616                 vol = Volumes;
1617             }
1618         }
1619     }
1620
1621 EC_CLEANUP:
1622     if (fd != -1)
1623         (void)close(fd);
1624     return;
1625 }
1626
1627 /* ------------------------------- */
1628 int afp_getsrvrparms(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
1629 {
1630     struct timeval  tv;
1631     struct stat     st;
1632     struct vol      *volume;
1633     char    *data;
1634     char        *namebuf;
1635     int         vcnt;
1636     size_t      len;
1637
1638     load_volumes(obj);
1639
1640     data = rbuf + 5;
1641     for ( vcnt = 0, volume = Volumes; volume; volume = volume->v_next ) {
1642         if (!(volume->v_flags & AFPVOL_NOSTAT)) {
1643             struct maccess ma;
1644
1645             if ( stat( volume->v_path, &st ) < 0 ) {
1646                 LOG(log_info, logtype_afpd, "afp_getsrvrparms(%s): stat: %s",
1647                     volume->v_path, strerror(errno) );
1648                 continue;       /* can't access directory */
1649             }
1650             if (!S_ISDIR(st.st_mode)) {
1651                 continue;       /* not a dir */
1652             }
1653             accessmode(volume, volume->v_path, &ma, NULL, &st);
1654             if ((ma.ma_user & (AR_UREAD | AR_USEARCH)) != (AR_UREAD | AR_USEARCH)) {
1655                 continue;   /* no r-x access */
1656             }
1657         }
1658         if (volume->v_hide) {
1659             continue;       /* config file changed but the volume was mounted */
1660         }
1661
1662         if (utf8_encoding()) {
1663             len = ucs2_to_charset_allocate(CH_UTF8_MAC, &namebuf, volume->v_u8mname);
1664         } else {
1665             len = ucs2_to_charset_allocate(obj->options.maccharset, &namebuf, volume->v_macname);
1666         }
1667
1668         if (len == (size_t)-1)
1669             continue;
1670
1671         /* set password bit if there's a volume password */
1672         *data = (volume->v_password) ? AFPSRVR_PASSWD : 0;
1673
1674         *data++ |= 0; /* UNIX PRIVS BIT ..., OSX doesn't seem to use it, so we don't either */
1675         *data++ = len;
1676         memcpy(data, namebuf, len );
1677         data += len;
1678         free(namebuf);
1679         vcnt++;
1680     }
1681
1682     *rbuflen = data - rbuf;
1683     data = rbuf;
1684     if ( gettimeofday( &tv, NULL ) < 0 ) {
1685         LOG(log_error, logtype_afpd, "afp_getsrvrparms(%s): gettimeofday: %s", volume->v_path, strerror(errno) );
1686         *rbuflen = 0;
1687         return AFPERR_PARAM;
1688     }
1689     tv.tv_sec = AD_DATE_FROM_UNIX(tv.tv_sec);
1690     memcpy(data, &tv.tv_sec, sizeof( uint32_t));
1691     data += sizeof( uint32_t);
1692     *data = vcnt;
1693     return( AFP_OK );
1694 }
1695
1696 /* ------------------------- */
1697 static int volume_codepage(AFPObj *obj, struct vol *volume)
1698 {
1699     struct charset_functions *charset;
1700     /* Codepages */
1701
1702     if (!volume->v_volcodepage)
1703         volume->v_volcodepage = strdup("UTF8");
1704
1705     if ( (charset_t) -1 == ( volume->v_volcharset = add_charset(volume->v_volcodepage)) ) {
1706         LOG (log_error, logtype_afpd, "Setting codepage %s as volume codepage failed", volume->v_volcodepage);
1707         return -1;
1708     }
1709
1710     if ( NULL == (charset = find_charset_functions(volume->v_volcodepage)) || charset->flags & CHARSET_ICONV ) {
1711         LOG (log_warning, logtype_afpd, "WARNING: volume encoding %s is *not* supported by netatalk, expect problems !!!!", volume->v_volcodepage);
1712     }
1713
1714     if (!volume->v_maccodepage)
1715         volume->v_maccodepage = strdup(obj->options.maccodepage);
1716
1717     if ( (charset_t) -1 == ( volume->v_maccharset = add_charset(volume->v_maccodepage)) ) {
1718         LOG (log_error, logtype_afpd, "Setting codepage %s as mac codepage failed", volume->v_maccodepage);
1719         return -1;
1720     }
1721
1722     if ( NULL == ( charset = find_charset_functions(volume->v_maccodepage)) || ! (charset->flags & CHARSET_CLIENT) ) {
1723         LOG (log_error, logtype_afpd, "Fatal error: mac charset %s not supported", volume->v_maccodepage);
1724         return -1;
1725     }
1726     volume->v_kTextEncoding = htonl(charset->kTextEncoding);
1727     return 0;
1728 }
1729
1730 /* ------------------------- */
1731 static int volume_openDB(const AFPObj *obj, struct vol *volume)
1732 {
1733     int flags = 0;
1734
1735     if ((volume->v_flags & AFPVOL_NODEV)) {
1736         flags |= CNID_FLAG_NODEV;
1737     }
1738
1739     if (volume->v_cnidscheme == NULL) {
1740         volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
1741         LOG(log_info, logtype_afpd, "Volume %s use CNID scheme %s.",
1742             volume->v_path, volume->v_cnidscheme);
1743     }
1744
1745     LOG(log_info, logtype_afpd, "CNID server: %s:%s",
1746         volume->v_cnidserver ? volume->v_cnidserver : obj->options.Cnid_srv,
1747         volume->v_cnidport ? volume->v_cnidport : obj->options.Cnid_port);
1748
1749     volume->v_cdb = cnid_open(volume->v_path,
1750                               volume->v_umask,
1751                               volume->v_cnidscheme,
1752                               flags,
1753                               volume->v_cnidserver ? volume->v_cnidserver : obj->options.Cnid_srv,
1754                               volume->v_cnidport ? volume->v_cnidport : obj->options.Cnid_port);
1755
1756     if ( ! volume->v_cdb && ! (flags & CNID_FLAG_MEMORY)) {
1757         /* The first attempt failed and it wasn't yet an attempt to open in-memory */
1758         LOG(log_error, logtype_afpd, "Can't open volume \"%s\" CNID backend \"%s\" ",
1759             volume->v_path, volume->v_cnidscheme);
1760         LOG(log_error, logtype_afpd, "Reopen volume %s using in memory temporary CNID DB.",
1761             volume->v_path);
1762         flags |= CNID_FLAG_MEMORY;
1763         volume->v_cdb = cnid_open (volume->v_path, volume->v_umask, "tdb", flags, NULL, NULL);
1764 #ifdef SERVERTEXT
1765         /* kill ourself with SIGUSR2 aka msg pending */
1766         if (volume->v_cdb) {
1767             setmessage("Something wrong with the volume's CNID DB, using temporary CNID DB instead."
1768                        "Check server messages for details!");
1769             kill(getpid(), SIGUSR2);
1770             /* deactivate cnid caching/storing in AppleDouble files */
1771         }
1772 #endif
1773     }
1774
1775     return (!volume->v_cdb)?-1:0;
1776 }
1777
1778 /*
1779   Check if the underlying filesystem supports EAs for ea:sys volumes.
1780   If not, switch to ea:ad.
1781   As we can't check (requires write access) on ro-volumes, we switch ea:auto
1782   volumes that are options:ro to ea:none.
1783 */
1784 static void check_ea_sys_support(struct vol *vol)
1785 {
1786     uid_t process_uid = 0;
1787     char eaname[] = {"org.netatalk.supports-eas.XXXXXX"};
1788     const char *eacontent = "yes";
1789
1790     if (vol->v_vfs_ea == AFPVOL_EA_AUTO) {
1791
1792         if ((vol->v_flags & AFPVOL_RO) == AFPVOL_RO) {
1793             LOG(log_info, logtype_afpd, "read-only volume '%s', can't test for EA support, disabling EAs", vol->v_localname);
1794             vol->v_vfs_ea = AFPVOL_EA_NONE;
1795             return;
1796         }
1797
1798         mktemp(eaname);
1799
1800         process_uid = geteuid();
1801         if (process_uid)
1802             if (seteuid(0) == -1) {
1803                 LOG(log_error, logtype_afpd, "check_ea_sys_support: can't seteuid(0): %s", strerror(errno));
1804                 exit(EXITERR_SYS);
1805             }
1806
1807         if ((sys_setxattr(vol->v_path, eaname, eacontent, 4, 0)) == 0) {
1808             sys_removexattr(vol->v_path, eaname);
1809             vol->v_vfs_ea = AFPVOL_EA_SYS;
1810         } else {
1811             LOG(log_warning, logtype_afpd, "volume \"%s\" does not support Extended Attributes, using ea:ad instead",
1812                 vol->v_localname);
1813             vol->v_vfs_ea = AFPVOL_EA_AD;
1814         }
1815
1816         if (process_uid) {
1817             if (seteuid(process_uid) == -1) {
1818                 LOG(log_error, logtype_afpd, "can't seteuid back %s", strerror(errno));
1819                 exit(EXITERR_SYS);
1820             }
1821         }
1822     }
1823 }
1824
1825 /* -------------------------
1826  * we are the user here
1827  */
1828 int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
1829 {
1830     struct stat st;
1831     char    *volname;
1832     char        *p;
1833
1834     struct vol  *volume;
1835     struct dir  *dir;
1836     int     len, ret;
1837     size_t  namelen;
1838     uint16_t   bitmap;
1839     char        path[ MAXPATHLEN + 1];
1840     char        *vol_uname;
1841     char        *vol_mname;
1842     char        *volname_tmp;
1843
1844     ibuf += 2;
1845     memcpy(&bitmap, ibuf, sizeof( bitmap ));
1846     bitmap = ntohs( bitmap );
1847     ibuf += sizeof( bitmap );
1848
1849     *rbuflen = 0;
1850     if (( bitmap & (1<<VOLPBIT_VID)) == 0 ) {
1851         return AFPERR_BITMAP;
1852     }
1853
1854     len = (unsigned char)*ibuf++;
1855     volname = obj->oldtmp;
1856
1857     if ((volname_tmp = strchr(volname,'+')) != NULL)
1858         volname = volname_tmp+1;
1859
1860     if (utf8_encoding()) {
1861         namelen = convert_string(CH_UTF8_MAC, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
1862     } else {
1863         namelen = convert_string(obj->options.maccharset, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
1864     }
1865
1866     if ( namelen <= 0) {
1867         return AFPERR_PARAM;
1868     }
1869
1870     ibuf += len;
1871     if ((len + 1) & 1) /* pad to an even boundary */
1872         ibuf++;
1873
1874     load_volumes(obj);
1875
1876     for ( volume = Volumes; volume; volume = volume->v_next ) {
1877         if ( strcasecmp_w( (ucs2_t*) volname, volume->v_name ) == 0 ) {
1878             break;
1879         }
1880     }
1881
1882     if ( volume == NULL ) {
1883         return AFPERR_PARAM;
1884     }
1885
1886     /* check for a volume password */
1887     if (volume->v_password && strncmp(ibuf, volume->v_password, VOLPASSLEN)) {
1888         return AFPERR_ACCESS;
1889     }
1890
1891     if (( volume->v_flags & AFPVOL_OPEN  ) ) {
1892         /* the volume is already open */
1893         return stat_vol(bitmap, volume, rbuf, rbuflen);
1894     }
1895
1896     if (volume->v_root_preexec) {
1897         if ((ret = afprun(1, volume->v_root_preexec, NULL)) && volume->v_root_preexec_close) {
1898             LOG(log_error, logtype_afpd, "afp_openvol(%s): root preexec : %d", volume->v_path, ret );
1899             return AFPERR_MISC;
1900         }
1901     }
1902
1903     if (volume->v_preexec) {
1904         if ((ret = afprun(0, volume->v_preexec, NULL)) && volume->v_preexec_close) {
1905             LOG(log_error, logtype_afpd, "afp_openvol(%s): preexec : %d", volume->v_path, ret );
1906             return AFPERR_MISC;
1907         }
1908     }
1909
1910     if ( stat( volume->v_path, &st ) < 0 ) {
1911         return AFPERR_PARAM;
1912     }
1913
1914     if ( chdir( volume->v_path ) < 0 ) {
1915         return AFPERR_PARAM;
1916     }
1917
1918     if ( NULL == getcwd(path, MAXPATHLEN)) {
1919         /* shouldn't be fatal but it will fail later */
1920         LOG(log_error, logtype_afpd, "afp_openvol(%s): volume pathlen too long", volume->v_path);
1921         return AFPERR_MISC;
1922     }
1923
1924     /* Normalize volume path */
1925 #ifdef REALPATH_TAKES_NULL
1926     if ((volume->v_path = realpath(path, NULL)) == NULL)
1927         return AFPERR_MISC;
1928 #else
1929     if ((volume->v_path = malloc(MAXPATHLEN+1)) == NULL)
1930         return AFPERR_MISC;
1931     if (realpath(path, volume->v_path) == NULL) {
1932         free(volume->v_path);
1933         return AFPERR_MISC;
1934     }
1935     /* Safe some memory */
1936     char *tmp;
1937     if ((tmp = strdup(volume->v_path)) == NULL) {
1938         free(volume->v_path);
1939         return AFPERR_MISC;
1940     }
1941     free(volume->v_path);
1942     volume->v_path = tmp;
1943 #endif
1944
1945     if (volume_codepage(obj, volume) < 0) {
1946         ret = AFPERR_MISC;
1947         goto openvol_err;
1948     }
1949
1950     /* initialize volume variables
1951      * FIXME file size
1952      */
1953     if (utf8_encoding()) {
1954         volume->max_filename = UTF8FILELEN_EARLY;
1955     }
1956     else {
1957         volume->max_filename = MACFILELEN;
1958     }
1959
1960     volume->v_flags |= AFPVOL_OPEN;
1961     volume->v_cdb = NULL;
1962
1963     if (utf8_encoding()) {
1964         len = convert_string_allocate(CH_UCS2, CH_UTF8_MAC, volume->v_u8mname, namelen, &vol_mname);
1965     } else {
1966         len = convert_string_allocate(CH_UCS2, obj->options.maccharset, volume->v_macname, namelen, &vol_mname);
1967     }
1968     if ( !vol_mname || len <= 0) {
1969         ret = AFPERR_MISC;
1970         goto openvol_err;
1971     }
1972
1973     if ((vol_uname = strrchr(path, '/')) == NULL)
1974         vol_uname = path;
1975     else if (*(vol_uname + 1) != '\0')
1976         vol_uname++;
1977
1978     if ((dir = dir_new(vol_mname,
1979                        vol_uname,
1980                        volume,
1981                        DIRDID_ROOT_PARENT,
1982                        DIRDID_ROOT,
1983                        bfromcstr(volume->v_path),
1984                        &st)
1985             ) == NULL) {
1986         free(vol_mname);
1987         LOG(log_error, logtype_afpd, "afp_openvol(%s): malloc: %s", volume->v_path, strerror(errno) );
1988         ret = AFPERR_MISC;
1989         goto openvol_err;
1990     }
1991     free(vol_mname);
1992     volume->v_root = dir;
1993     curdir = dir;
1994
1995     if (volume_openDB(obj, volume) < 0) {
1996         LOG(log_error, logtype_afpd, "Fatal error: cannot open CNID or invalid CNID backend for %s: %s",
1997             volume->v_path, volume->v_cnidscheme);
1998         ret = AFPERR_MISC;
1999         goto openvol_err;
2000     }
2001
2002     ret  = stat_vol(bitmap, volume, rbuf, rbuflen);
2003
2004     if (ret == AFP_OK) {
2005         handle_special_folders(volume);
2006         savevolinfo(volume,
2007                     volume->v_cnidserver ? volume->v_cnidserver : obj->options.Cnid_srv,
2008                     volume->v_cnidport   ? volume->v_cnidport   : obj->options.Cnid_port);
2009
2010
2011         /*
2012          * If you mount a volume twice, the second time the trash appears on
2013          * the desk-top.  That's because the Mac remembers the DID for the
2014          * trash (even for volumes in different zones, on different servers).
2015          * Just so this works better, we prime the DID cache with the trash,
2016          * fixing the trash at DID 17.
2017          * FIXME (RL): should it be done inside a CNID backend ? (always returning Trash DID when asked) ?
2018          */
2019         if ((volume->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
2020
2021             /* FIXME find db time stamp */
2022             if (cnid_getstamp(volume->v_cdb, volume->v_stamp, sizeof(volume->v_stamp)) < 0) {
2023                 LOG (log_error, logtype_afpd,
2024                      "afp_openvol(%s): Fatal error: Unable to get stamp value from CNID backend",
2025                      volume->v_path);
2026                 ret = AFPERR_MISC;
2027                 goto openvol_err;
2028             }
2029         }
2030         else {
2031             p = Trash;
2032             cname( volume, volume->v_root, &p );
2033         }
2034         return( AFP_OK );
2035     }
2036
2037 openvol_err:
2038     if (volume->v_root) {
2039         dir_free( volume->v_root );
2040         volume->v_root = NULL;
2041     }
2042
2043     volume->v_flags &= ~AFPVOL_OPEN;
2044     if (volume->v_cdb != NULL) {
2045         cnid_close(volume->v_cdb);
2046         volume->v_cdb = NULL;
2047     }
2048     *rbuflen = 0;
2049     return ret;
2050 }
2051
2052 /* ------------------------- */
2053 static void closevol(struct vol *vol)
2054 {
2055     if (!vol)
2056         return;
2057
2058     dir_free( vol->v_root );
2059     vol->v_root = NULL;
2060     if (vol->v_cdb != NULL) {
2061         cnid_close(vol->v_cdb);
2062         vol->v_cdb = NULL;
2063     }
2064
2065     if (vol->v_postexec) {
2066         afprun(0, vol->v_postexec, NULL);
2067     }
2068     if (vol->v_root_postexec) {
2069         afprun(1, vol->v_root_postexec, NULL);
2070     }
2071 }
2072
2073 /* ------------------------- */
2074 void close_all_vol(void)
2075 {
2076     struct vol  *ovol;
2077     curdir = NULL;
2078     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
2079         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
2080             ovol->v_flags &= ~AFPVOL_OPEN;
2081             closevol(ovol);
2082         }
2083     }
2084 }
2085
2086 /* ------------------------- */
2087 static void deletevol(struct vol *vol)
2088 {
2089     struct vol  *ovol;
2090
2091     vol->v_flags &= ~AFPVOL_OPEN;
2092     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
2093         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
2094             break;
2095         }
2096     }
2097     if ( ovol != NULL ) {
2098         /* Even if chdir fails, we can't say afp_closevol fails. */
2099         if ( chdir( ovol->v_path ) == 0 ) {
2100             curdir = ovol->v_root;
2101         }
2102     }
2103
2104     closevol(vol);
2105     if (vol->v_deleted) {
2106         showvol(vol->v_name);
2107         volume_free(vol);
2108         volume_unlink(vol);
2109         free(vol);
2110     }
2111 }
2112
2113 /* ------------------------- */
2114 int afp_closevol(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2115 {
2116     struct vol  *vol;
2117     uint16_t   vid;
2118
2119     *rbuflen = 0;
2120     ibuf += 2;
2121     memcpy(&vid, ibuf, sizeof( vid ));
2122     if (NULL == ( vol = getvolbyvid( vid )) ) {
2123         return( AFPERR_PARAM );
2124     }
2125
2126     deletevol(vol);
2127     current_vol = NULL;
2128
2129     return( AFP_OK );
2130 }
2131
2132 /* ------------------------- */
2133 struct vol *getvolbyvid(const uint16_t vid )
2134 {
2135     struct vol  *vol;
2136
2137     for ( vol = Volumes; vol; vol = vol->v_next ) {
2138         if ( vid == vol->v_vid ) {
2139             break;
2140         }
2141     }
2142     if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
2143         return( NULL );
2144     }
2145
2146     current_vol = vol;
2147
2148     return( vol );
2149 }
2150
2151 /* --------------------------
2152    poll if a volume is changed by other processes.
2153    return
2154    0 no attention msg sent
2155    1 attention msg sent
2156    -1 error (socket closed)
2157
2158    Note: if attention return -1 no packet has been
2159    sent because the buffer is full, we don't care
2160    either there's no reader or there's a lot of
2161    traffic and another pollvoltime will follow
2162 */
2163 int  pollvoltime(AFPObj *obj)
2164
2165 {
2166     struct vol       *vol;
2167     struct timeval   tv;
2168     struct stat      st;
2169
2170     if (!(afp_version > 21 && obj->options.flags & OPTION_SERVERNOTIF))
2171         return 0;
2172
2173     if ( gettimeofday( &tv, NULL ) < 0 )
2174         return 0;
2175
2176     for ( vol = Volumes; vol; vol = vol->v_next ) {
2177         if ( (vol->v_flags & AFPVOL_OPEN)  && vol->v_mtime + 30 < tv.tv_sec) {
2178             if ( !stat( vol->v_path, &st ) && vol->v_mtime != st.st_mtime ) {
2179                 vol->v_mtime = st.st_mtime;
2180                 if (!obj->attention(obj->dsi, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED))
2181                     return -1;
2182                 return 1;
2183             }
2184         }
2185     }
2186     return 0;
2187 }
2188
2189 /* ------------------------- */
2190 void setvoltime(AFPObj *obj, struct vol *vol)
2191 {
2192     struct timeval  tv;
2193
2194     if ( gettimeofday( &tv, NULL ) < 0 ) {
2195         LOG(log_error, logtype_afpd, "setvoltime(%s): gettimeofday: %s", vol->v_path, strerror(errno) );
2196         return;
2197     }
2198     if( utime( vol->v_path, NULL ) < 0 ) {
2199         /* write of time failed ... probably a read only filesys,
2200          * where no other users can interfere, so there's no issue here
2201          */
2202     }
2203
2204     /* a little granularity */
2205     if (vol->v_mtime < tv.tv_sec) {
2206         vol->v_mtime = tv.tv_sec;
2207         /* or finder doesn't update free space
2208          * AFP 3.2 and above clients seem to be ok without so many notification
2209          */
2210         if (afp_version < 32 && obj->options.flags & OPTION_SERVERNOTIF) {
2211             obj->attention(obj->dsi, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED);
2212         }
2213     }
2214 }
2215
2216 /* ------------------------- */
2217 int afp_getvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,char *rbuf, size_t *rbuflen)
2218 {
2219     struct vol  *vol;
2220     uint16_t   vid, bitmap;
2221
2222     ibuf += 2;
2223     memcpy(&vid, ibuf, sizeof( vid ));
2224     ibuf += sizeof( vid );
2225     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2226     bitmap = ntohs( bitmap );
2227
2228     if (NULL == ( vol = getvolbyvid( vid )) ) {
2229         *rbuflen = 0;
2230         return( AFPERR_PARAM );
2231     }
2232
2233     return stat_vol(bitmap, vol, rbuf, rbuflen);
2234 }
2235
2236 /* ------------------------- */
2237 int afp_setvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_,  size_t *rbuflen)
2238 {
2239     struct adouble ad;
2240     struct vol  *vol;
2241     uint16_t   vid, bitmap;
2242     uint32_t   aint;
2243
2244     ibuf += 2;
2245     *rbuflen = 0;
2246
2247     memcpy(&vid, ibuf, sizeof( vid ));
2248     ibuf += sizeof( vid );
2249     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2250     bitmap = ntohs( bitmap );
2251     ibuf += sizeof(bitmap);
2252
2253     if (( vol = getvolbyvid( vid )) == NULL ) {
2254         return( AFPERR_PARAM );
2255     }
2256
2257     if ((vol->v_flags & AFPVOL_RO))
2258         return AFPERR_VLOCK;
2259
2260     /* we can only set the backup date. */
2261     if (bitmap != (1 << VOLPBIT_BDATE))
2262         return AFPERR_BITMAP;
2263
2264     ad_init(&ad, vol);
2265     if ( ad_open(&ad,  vol->v_path, ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_RDWR) < 0 ) {
2266         if (errno == EROFS)
2267             return AFPERR_VLOCK;
2268
2269         return AFPERR_ACCESS;
2270     }
2271
2272     memcpy(&aint, ibuf, sizeof(aint));
2273     ad_setdate(&ad, AD_DATE_BACKUP, aint);
2274     ad_flush(&ad);
2275     ad_close(&ad, ADFLAGS_HF);
2276     return( AFP_OK );
2277 }
2278
2279 /*
2280  * precreate a folder
2281  * this is only intended for folders in the volume root
2282  * It will *not* work if the folder name contains extended characters
2283  */
2284 static int create_special_folder (const struct vol *vol, const struct _special_folder *folder)
2285 {
2286     char        *p,*q,*r;
2287     struct adouble  ad;
2288     uint16_t   attr;
2289     struct stat st;
2290     int     ret;
2291
2292
2293     p = (char *) malloc ( strlen(vol->v_path)+strlen(folder->name)+2);
2294     if ( p == NULL) {
2295         LOG(log_error, logtype_afpd,"malloc failed");
2296         exit (EXITERR_SYS);
2297     }
2298
2299     q=strdup(folder->name);
2300     if ( q == NULL) {
2301         LOG(log_error, logtype_afpd,"malloc failed");
2302         exit (EXITERR_SYS);
2303     }
2304
2305     strcpy(p, vol->v_path);
2306     strcat(p, "/");
2307
2308     r=q;
2309     while (*r) {
2310         if ((vol->v_casefold & AFPVOL_MTOUUPPER))
2311             *r=toupper(*r);
2312         else if ((vol->v_casefold & AFPVOL_MTOULOWER))
2313             *r=tolower(*r);
2314         r++;
2315     }
2316     strcat(p, q);
2317
2318     if ( (ret = stat( p, &st )) < 0 ) {
2319         if (folder->precreate) {
2320             if (ad_mkdir(p, folder->mode)) {
2321                 LOG(log_debug, logtype_afpd,"Creating '%s' failed in %s: %s", p, vol->v_path, strerror(errno));
2322                 free(p);
2323                 free(q);
2324                 return -1;
2325             }
2326             ret = 0;
2327         }
2328     }
2329
2330     if ( !ret && folder->hide) {
2331         /* Hide it */
2332         ad_init(&ad, vol);
2333         if (ad_open(&ad, p, ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666) != 0) {
2334             free(p);
2335             free(q);
2336             return (-1);
2337         }
2338
2339         ad_setname(&ad, folder->name);
2340
2341         ad_getattr(&ad, &attr);
2342         attr |= htons( ntohs( attr ) | ATTRBIT_INVISIBLE );
2343         ad_setattr(&ad, attr);
2344
2345         /* do the same with the finder info */
2346         if (ad_entry(&ad, ADEID_FINDERI)) {
2347             memcpy(&attr, ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, sizeof(attr));
2348             attr   |= htons(FINDERINFO_INVISIBLE);
2349             memcpy(ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,&attr, sizeof(attr));
2350         }
2351
2352         ad_flush(&ad);
2353         ad_close(&ad, ADFLAGS_HF);
2354     }
2355     free(p);
2356     free(q);
2357     return 0;
2358 }
2359
2360 static void handle_special_folders (const struct vol * vol)
2361 {
2362     const _special_folder *p = &special_folders[0];
2363     uid_t process_uid;
2364
2365     process_uid = geteuid();
2366     if (process_uid) {
2367         if (seteuid(0) == -1) {
2368             process_uid = 0;
2369         }
2370     }
2371
2372     for (; p->name != NULL; p++) {
2373         create_special_folder (vol, p);
2374     }
2375
2376     if (process_uid) {
2377         if (seteuid(process_uid) == -1) {
2378             LOG(log_error, logtype_logger, "can't seteuid back %s", strerror(errno));
2379             exit(EXITERR_SYS);
2380         }
2381     }
2382 }
2383
2384 const struct vol *getvolumes(void)
2385 {
2386     return Volumes;
2387 }
2388
2389 void unload_volumes(void)
2390 {
2391     LOG(log_debug, logtype_afpd, "unload_volumes_and_extmap");
2392     free_volumes();
2393 }
2394
2395 /* 
2396  * Get a volumes UUID from the config file.
2397  * If there is none, it is generated and stored there.
2398  *
2399  * Returns pointer to allocated storage on success, NULL on error.
2400  */
2401 static char *get_vol_uuid(const AFPObj *obj, const char *volname)
2402 {
2403     char *volname_conf;
2404     char buf[1024], uuid[UUID_PRINTABLE_STRING_LENGTH], *p;
2405     FILE *fp;
2406     struct stat tmpstat;
2407     int fd;
2408     
2409     if ((fp = fopen(obj->options.uuidconf, "r")) != NULL) {  /* read open? */
2410         /* scan in the conf file */
2411         while (fgets(buf, sizeof(buf), fp) != NULL) { 
2412             p = buf;
2413             while (p && isblank(*p))
2414                 p++;
2415             if (!p || (*p == '#') || (*p == '\n'))
2416                 continue;                             /* invalid line */
2417             if (*p == '"') {
2418                 p++;
2419                 if ((volname_conf = strtok( p, "\"" )) == NULL)
2420                     continue;                         /* syntax error */
2421             } else {
2422                 if ((volname_conf = strtok( p, " \t" )) == NULL)
2423                     continue;                         /* syntax error: invalid name */
2424             }
2425             p = strchr(p, '\0');
2426             p++;
2427             if (*p == '\0')
2428                 continue;                             /* syntax error */
2429             
2430             if (strcmp(volname, volname_conf) != 0)
2431                 continue;                             /* another volume name */
2432                 
2433             while (p && isblank(*p))
2434                 p++;
2435
2436             if (sscanf(p, "%36s", uuid) == 1 ) {
2437                 for (int i=0; uuid[i]; i++)
2438                     uuid[i] = toupper(uuid[i]);
2439                 LOG(log_debug, logtype_afpd, "get_uuid('%s'): UUID: '%s'", volname, uuid);
2440                 fclose(fp);
2441                 return strdup(uuid);
2442             }
2443         }
2444     }
2445
2446     if (fp)
2447         fclose(fp);
2448
2449     /*  not found or no file, reopen in append mode */
2450
2451     if (stat(obj->options.uuidconf, &tmpstat)) {                /* no file */
2452         if (( fd = creat(obj->options.uuidconf, 0644 )) < 0 ) {
2453             LOG(log_error, logtype_afpd, "ERROR: Cannot create %s (%s).",
2454                 obj->options.uuidconf, strerror(errno));
2455             return NULL;
2456         }
2457         if (( fp = fdopen( fd, "w" )) == NULL ) {
2458             LOG(log_error, logtype_afpd, "ERROR: Cannot fdopen %s (%s).",
2459                 obj->options.uuidconf, strerror(errno));
2460             close(fd);
2461             return NULL;
2462         }
2463     } else if ((fp = fopen(obj->options.uuidconf, "a+")) == NULL) { /* not found */
2464         LOG(log_error, logtype_afpd, "Cannot create or append to %s (%s).",
2465             obj->options.uuidconf, strerror(errno));
2466         return NULL;
2467     }
2468     fseek(fp, 0L, SEEK_END);
2469     if(ftell(fp) == 0) {                     /* size = 0 */
2470         fprintf(fp, "# DON'T TOUCH NOR COPY THOUGHTLESSLY!\n");
2471         fprintf(fp, "# This file is auto-generated by afpd\n");
2472         fprintf(fp, "# and stores UUIDs for TM volumes.\n\n");
2473     } else {
2474         fseek(fp, -1L, SEEK_END);
2475         if(fgetc(fp) != '\n') fputc('\n', fp); /* last char is \n? */
2476     }                    
2477     
2478     /* generate uuid and write to file */
2479     atalk_uuid_t id;
2480     const char *cp;
2481     randombytes((void *)id, 16);
2482     cp = uuid_bin2string(id);
2483
2484     LOG(log_debug, logtype_afpd, "get_uuid('%s'): generated UUID '%s'", volname, cp);
2485
2486     fprintf(fp, "\"%s\"\t%36s\n", volname, cp);
2487     fclose(fp);
2488     
2489     return strdup(cp);
2490 }