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