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