]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/netatalk_conf.c
start LOG earlier
[netatalk.git] / libatalk / util / netatalk_conf.c
1 /*
2   Copyright (c) 2012 Frank Lahm <franklahm@gmail.com>
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13 */
14
15 #ifdef HAVE_CONFIG_H
16 #include "config.h"
17 #endif /* HAVE_CONFIG_H */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <ctype.h>
22 #include <pwd.h>
23 #include <grp.h>
24 #include <utime.h>
25 #include <errno.h>
26 #include <string.h>
27 #include <sys/param.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 #include <inttypes.h>
32 #include <time.h>
33 #include <regex.h>
34
35 #include <atalk/afp.h>
36 #include <atalk/util.h>
37 #include <atalk/logger.h>
38 #include <atalk/ea.h>
39 #include <atalk/globals.h>
40 #include <atalk/errchk.h>
41 #include <atalk/iniparser.h>
42 #include <atalk/unix.h>
43 #include <atalk/cnid.h>
44 #include <atalk/dsi.h>
45 #include <atalk/uuid.h>
46 #include <atalk/netatalk_conf.h>
47 #include <atalk/bstrlib.h>
48
49 #define VOLPASSLEN  8
50 #ifndef UUID_PRINTABLE_STRING_LENGTH
51 #define UUID_PRINTABLE_STRING_LENGTH 37
52 #endif
53
54 #define IS_VAR(a, b) (strncmp((a), (b), 2) == 0)
55
56 /**************************************************************
57  * Locals
58  **************************************************************/
59
60 static int have_uservol = 0; /* whether there's generic user home share in config ("~" or "~/path", but not "~user") */
61 static struct vol *Volumes = NULL;
62 static uint16_t    lastvid = 0;
63
64 /* 
65  * Get a volumes UUID from the config file.
66  * If there is none, it is generated and stored there.
67  *
68  * Returns pointer to allocated storage on success, NULL on error.
69  */
70 static char *get_vol_uuid(const AFPObj *obj, const char *volname)
71 {
72     char *volname_conf;
73     char buf[1024], uuid[UUID_PRINTABLE_STRING_LENGTH], *p;
74     FILE *fp;
75     struct stat tmpstat;
76     int fd;
77     
78     if ((fp = fopen(obj->options.uuidconf, "r")) != NULL) {  /* read open? */
79         /* scan in the conf file */
80         while (fgets(buf, sizeof(buf), fp) != NULL) { 
81             p = buf;
82             while (p && isblank(*p))
83                 p++;
84             if (!p || (*p == '#') || (*p == '\n'))
85                 continue;                             /* invalid line */
86             if (*p == '"') {
87                 p++;
88                 if ((volname_conf = strtok( p, "\"" )) == NULL)
89                     continue;                         /* syntax error */
90             } else {
91                 if ((volname_conf = strtok( p, " \t" )) == NULL)
92                     continue;                         /* syntax error: invalid name */
93             }
94             p = strchr(p, '\0');
95             p++;
96             if (*p == '\0')
97                 continue;                             /* syntax error */
98             
99             if (strcmp(volname, volname_conf) != 0)
100                 continue;                             /* another volume name */
101                 
102             while (p && isblank(*p))
103                 p++;
104
105             if (sscanf(p, "%36s", uuid) == 1 ) {
106                 for (int i=0; uuid[i]; i++)
107                     uuid[i] = toupper(uuid[i]);
108                 LOG(log_debug, logtype_afpd, "get_uuid('%s'): UUID: '%s'", volname, uuid);
109                 fclose(fp);
110                 return strdup(uuid);
111             }
112         }
113     }
114
115     if (fp)
116         fclose(fp);
117
118     /*  not found or no file, reopen in append mode */
119
120     if (stat(obj->options.uuidconf, &tmpstat)) {                /* no file */
121         if (( fd = creat(obj->options.uuidconf, 0644 )) < 0 ) {
122             LOG(log_error, logtype_afpd, "ERROR: Cannot create %s (%s).",
123                 obj->options.uuidconf, strerror(errno));
124             return NULL;
125         }
126         if (( fp = fdopen( fd, "w" )) == NULL ) {
127             LOG(log_error, logtype_afpd, "ERROR: Cannot fdopen %s (%s).",
128                 obj->options.uuidconf, strerror(errno));
129             close(fd);
130             return NULL;
131         }
132     } else if ((fp = fopen(obj->options.uuidconf, "a+")) == NULL) { /* not found */
133         LOG(log_error, logtype_afpd, "Cannot create or append to %s (%s).",
134             obj->options.uuidconf, strerror(errno));
135         return NULL;
136     }
137     fseek(fp, 0L, SEEK_END);
138     if(ftell(fp) == 0) {                     /* size = 0 */
139         fprintf(fp, "# DON'T TOUCH NOR COPY THOUGHTLESSLY!\n");
140         fprintf(fp, "# This file is auto-generated by afpd\n");
141         fprintf(fp, "# and stores UUIDs for Time Machine volumes.\n\n");
142     } else {
143         fseek(fp, -1L, SEEK_END);
144         if(fgetc(fp) != '\n') fputc('\n', fp); /* last char is \n? */
145     }                    
146     
147     /* generate uuid and write to file */
148     atalk_uuid_t id;
149     const char *cp;
150     randombytes((void *)id, 16);
151     cp = uuid_bin2string(id);
152
153     LOG(log_debug, logtype_afpd, "get_uuid('%s'): generated UUID '%s'", volname, cp);
154
155     fprintf(fp, "\"%s\"\t%36s\n", volname, cp);
156     fclose(fp);
157     
158     return strdup(cp);
159 }
160
161 /*
162   Check if the underlying filesystem supports EAs.
163   If not, switch to ea:ad.
164   As we can't check (requires write access) on ro-volumes, we switch ea:auto
165   volumes that are options:ro to ea:none.
166 */
167 static int do_check_ea_support(const struct vol *vol)
168 {
169     int haseas;
170     char eaname[] = {"org.netatalk.supports-eas.XXXXXX"};
171     const char *eacontent = "yes";
172
173     if ((vol->v_flags & AFPVOL_RO) == AFPVOL_RO) {
174         LOG(log_note, logtype_afpd, "read-only volume '%s', can't test for EA support, assuming yes", vol->v_localname);
175         return 1;
176     }
177
178     mktemp(eaname);
179
180     become_root();
181
182     if ((sys_setxattr(vol->v_path, eaname, eacontent, 4, 0)) == 0) {
183         sys_removexattr(vol->v_path, eaname);
184         haseas = 1;
185     } else {
186         LOG(log_warning, logtype_afpd, "volume \"%s\" does not support Extended Attributes or read-only volume root",
187             vol->v_localname);
188         haseas = 0;
189     }
190
191     unbecome_root();
192
193     return haseas;
194 }
195
196 static void check_ea_support(struct vol *vol)
197 {
198     int haseas;
199     char eaname[] = {"org.netatalk.supports-eas.XXXXXX"};
200     const char *eacontent = "yes";
201
202     haseas = do_check_ea_support(vol);
203
204     if (vol->v_vfs_ea == AFPVOL_EA_AUTO) {
205         if ((vol->v_flags & AFPVOL_RO) == AFPVOL_RO) {
206             LOG(log_info, logtype_afpd, "read-only volume '%s', can't test for EA support, disabling EAs", vol->v_localname);
207             vol->v_vfs_ea = AFPVOL_EA_NONE;
208             return;
209         }
210
211         if (haseas) {
212             vol->v_vfs_ea = AFPVOL_EA_SYS;
213         } else {
214             LOG(log_warning, logtype_afpd, "volume \"%s\" does not support Extended Attributes, using ea:ad instead",
215                 vol->v_localname);
216             vol->v_vfs_ea = AFPVOL_EA_AD;
217         }
218     }
219
220     if (vol->v_adouble == AD_VERSION_EA) {
221         if (!haseas)
222             vol->v_adouble = AD_VERSION2;
223     }
224 }
225
226 /*!
227  * Check whether a volume supports ACLs
228  *
229  * @param vol  (r) volume
230  *
231  * @returns        0 if not, 1 if yes
232  */
233 static int check_vol_acl_support(const struct vol *vol)
234 {
235     int ret = 0;
236
237 #ifdef HAVE_SOLARIS_ACLS
238     ace_t *aces = NULL;
239     ret = 1;
240     if (get_nfsv4_acl(vol->v_path, &aces) == -1)
241         ret = 0;
242 #endif
243 #ifdef HAVE_POSIX_ACLS
244     acl_t acl = NULL;
245     ret = 1;
246     if ((acl = acl_get_file(vol->v_path, ACL_TYPE_ACCESS)) == NULL)
247         ret = 0;
248 #endif
249
250 #ifdef HAVE_SOLARIS_ACLS
251     if (aces) free(aces);
252 #endif
253 #ifdef HAVE_POSIX_ACLS
254     if (acl) acl_free(acl);
255 #endif /* HAVE_POSIX_ACLS */
256
257     LOG(log_debug, logtype_afpd, "Volume \"%s\" ACL support: %s",
258         vol->v_path, ret ? "yes" : "no");
259     return ret;
260 }
261
262 /*
263  * Handle variable substitutions. here's what we understand:
264  * $b   -> basename of path
265  * $c   -> client ip/appletalk address
266  * $d   -> volume pathname on server
267  * $f   -> full name (whatever's in the gecos field)
268  * $g   -> group
269  * $h   -> hostname
270  * $i   -> client ip/appletalk address without port
271  * $s   -> server name (hostname if it doesn't exist)
272  * $u   -> username (guest is usually nobody)
273  * $v   -> volume name or basename if null
274  * $$   -> $
275  *
276  * This get's called from readvolfile with
277  * path = NULL, volname = NULL for xlating the volumes path
278  * path = path, volname = NULL for xlating the volumes name
279  * ... and from volumes options parsing code when xlating eg dbpath with
280  * path = path, volname = volname
281  *
282  * Using this information we can reject xlation of any variable depeninding on a login
283  * context which is not given in the afp master, where we must evaluate this whole stuff
284  * too for the Zeroconf announcements.
285  */
286 static char *volxlate(const AFPObj *obj,
287                       char *dest,
288                       size_t destlen,
289                       const char *src,
290                       const struct passwd *pwd,
291                       const char *path,
292                       const char *volname)
293 {
294     char *p, *r;
295     const char *q;
296     int len;
297     char *ret;
298     int xlatevolname = 0;
299
300     if (path && !volname)
301         /* cf above */
302         xlatevolname = 1;
303
304     if (!src) {
305         return NULL;
306     }
307     if (!dest) {
308         dest = calloc(destlen +1, 1);
309     }
310     ret = dest;
311     if (!ret) {
312         return NULL;
313     }
314     strlcpy(dest, src, destlen +1);
315     if ((p = strchr(src, '$')) == NULL) /* nothing to do */
316         return ret;
317
318     /* first part of the path. just forward to the next variable. */
319     len = MIN((size_t)(p - src), destlen);
320     if (len > 0) {
321         destlen -= len;
322         dest += len;
323     }
324
325     while (p && destlen > 0) {
326         /* now figure out what the variable is */
327         q = NULL;
328         if (IS_VAR(p, "$b")) {
329             if (path) {
330                 if ((q = strrchr(path, '/')) == NULL)
331                     q = path;
332                 else if (*(q + 1) != '\0')
333                     q++;
334             }
335         } else if (IS_VAR(p, "$c")) {
336             if (IS_AFP_SESSION(obj)) {
337                 DSI *dsi = obj->dsi;
338                 len = sprintf(dest, "%s:%u",
339                               getip_string((struct sockaddr *)&dsi->client),
340                               getip_port((struct sockaddr *)&dsi->client));
341                 dest += len;
342                 destlen -= len;
343             }
344         } else if (IS_VAR(p, "$d")) {
345             q = path;
346         } else if (pwd && IS_VAR(p, "$f")) {
347             if ((r = strchr(pwd->pw_gecos, ',')))
348                 *r = '\0';
349             q = pwd->pw_gecos;
350         } else if (pwd && IS_VAR(p, "$g")) {
351             struct group *grp = getgrgid(pwd->pw_gid);
352             if (grp)
353                 q = grp->gr_name;
354         } else if (IS_VAR(p, "$h")) {
355             q = obj->options.hostname;
356         } else if (IS_VAR(p, "$i")) {
357             DSI *dsi = obj->dsi;
358             q = getip_string((struct sockaddr *)&dsi->client);
359         } else if (IS_VAR(p, "$s")) {
360             q = obj->options.hostname;
361         } else if (obj->username[0] && IS_VAR(p, "$u")) {
362             char* sep = NULL;
363             if ( obj->options.ntseparator && (sep = strchr(obj->username, obj->options.ntseparator[0])) != NULL)
364                 q = sep+1;
365             else
366                 q = obj->username;
367         } else if (IS_VAR(p, "$v")) {
368             if (volname) {
369                 q = volname;
370             }
371             else if (path) {
372                 if ((q = strrchr(path, '/')) == NULL)
373                     q = path;
374                 else if (*(q + 1) != '\0')
375                     q++;
376             }
377         } else if (IS_VAR(p, "$$")) {
378             q = "$";
379         } else
380             q = p;
381
382         /* copy the stuff over. if we don't understand something that we
383          * should, just skip it over. */
384         if (q) {
385             len = MIN(p == q ? 2 : strlen(q), destlen);
386             strncpy(dest, q, len);
387             dest += len;
388             destlen -= len;
389         }
390
391         /* stuff up to next $ */
392         src = p + 2;
393         p = strchr(src, '$');
394         len = p ? MIN((size_t)(p - src), destlen) : destlen;
395         if (len > 0) {
396             strncpy(dest, src, len);
397             dest += len;
398             destlen -= len;
399         }
400     }
401     return ret;
402 }
403
404 /*!
405  * check access list
406  *
407  * this function wants something of the following form:
408  * "@group,name,name2,@group2,name3" or "@group name name2 @group2 name3"
409  * A NULL argument allows everybody to have access.
410  * We return three things:
411  *     -1: no list
412  *      0: list exists, but name isn't in it
413  *      1: in list
414  */
415 static int accessvol(const AFPObj *obj, const char *args, const char *name)
416 {
417     char buf[MAXPATHLEN + 1], *p;
418     struct group *gr;
419
420     if (!args)
421         return -1;
422
423     strlcpy(buf, args, sizeof(buf));
424     if ((p = strtok(buf, ", ")) == NULL) /* nothing, return okay */
425         return -1;
426
427     while (p) {
428         if (*p == '@') { /* it's a group */
429             if ((gr = getgrnam(p + 1)) && gmem(gr->gr_gid, obj->ngroups, obj->groups))
430                 return 1;
431         } else if (strcasecmp(p, name) == 0) /* it's a user name */
432             return 1;
433         p = strtok(NULL, ", ");
434     }
435
436     return 0;
437 }
438
439 static int hostaccessvol(const AFPObj *obj, const char *volname, const char *args)
440 {
441     int mask_int;
442     char buf[MAXPATHLEN + 1], *p, *b;
443     struct sockaddr_storage client;
444     const DSI *dsi = obj->dsi;
445
446     if (!args || !dsi)
447         return -1;
448
449     strlcpy(buf, args, sizeof(buf));
450     if ((p = strtok_r(buf, ", ", &b)) == NULL) /* nothing, return okay */
451         return -1;
452
453     while (p) {
454         int ret;
455         char *ipaddr, *mask_char;
456         struct addrinfo hints, *ai;
457
458         ipaddr = strtok(p, "/");
459         mask_char = strtok(NULL,"/");
460
461         /* Get address from string with getaddrinfo */
462         memset(&hints, 0, sizeof hints);
463         hints.ai_family = AF_UNSPEC;
464         hints.ai_socktype = SOCK_STREAM;
465         if ((ret = getaddrinfo(ipaddr, NULL, &hints, &ai)) != 0) {
466             LOG(log_error, logtype_afpd, "hostaccessvol: getaddrinfo: %s\n", gai_strerror(ret));
467             continue;
468         }
469
470         /* netmask */
471         if (mask_char != NULL)
472             mask_int = atoi(mask_char); /* apply_ip_mask does range checking on it */
473         else {
474             if (ai->ai_family == AF_INET) /* IPv4 */
475                 mask_int = 32;
476             else                          /* IPv6 */
477                 mask_int = 128;
478         }
479
480         /* Apply mask to addresses */
481         client = dsi->client;
482         apply_ip_mask((struct sockaddr *)&client, mask_int);
483         apply_ip_mask(ai->ai_addr, mask_int);
484
485         if (compare_ip((struct sockaddr *)&client, ai->ai_addr) == 0) {
486             freeaddrinfo(ai);
487             return 1;
488         }
489
490         /* next address */
491         freeaddrinfo(ai);
492         p = strtok_r(NULL, ", ", &b);
493     }
494
495     return 0;
496 }
497
498 /*!
499  * Get option string from config, use default value if not set
500  *
501  * @param conf    (r) config handle
502  * @param vol     (r) volume name (must be section name ie wo vars expanded)
503  * @param opt     (r) option
504  * @param defsec  (r) if "option" is not found in "vol", try to find it in section "defsec"
505  * @param defval  (r) if neither "vol" nor "defsec" contain "opt" return "defval"
506  *
507  * @returns       const option string from "vol" or "defsec", or "defval" if not found
508  */
509 static const char *getoption(const dictionary *conf, const char *vol, const char *opt, const char *defsec, const char *defval)
510 {
511     EC_INIT;
512     const char *result;
513
514     if ((!(result = iniparser_getstring(conf, vol, opt, NULL))) && (defsec != NULL))
515         result = iniparser_getstring(conf, defsec, opt, NULL);
516     
517 EC_CLEANUP:
518     if (result == NULL)
519         result = defval;
520     return result;
521 }
522
523 /*!
524  * Get boolean option from config, use default value if not set
525  *
526  * @param conf    (r) config handle
527  * @param vol     (r) volume name (must be section name ie wo vars expanded)
528  * @param opt     (r) option
529  * @param defsec  (r) if "option" is not found in "vol", try to find it in section "defsec"
530  * @param defval  (r) if neither "vol" nor "defsec" contain "opt" return "defval"
531  *
532  * @returns       const option string from "vol" or "defsec", or "defval" if not found
533  */
534 static int getoption_bool(const dictionary *conf, const char *vol, const char *opt, const char *defsec, int defval)
535 {
536     EC_INIT;
537     int result;
538
539     if (((result = iniparser_getboolean(conf, vol, opt, -1)) == -1) && (defsec != NULL))
540         result = iniparser_getboolean(conf, defsec, opt, -1);
541     
542 EC_CLEANUP:
543     if (result == -1)
544         result = defval;
545     return result;
546 }
547
548 /*!
549  * Create volume struct
550  *
551  * @param obj      (r) handle
552  * @param pwd      (r) struct passwd of logged in user, may be NULL in master afpd
553  * @param section  (r) volume name wo variables expanded (exactly as in iniconfig)
554  * @param name     (r) volume name
555  * @param path     (r) volume path
556  * @param preset   (r) default preset, may be NULL
557  * @returns            vol on success, NULL on error
558  */
559 static struct vol *creatvol(AFPObj *obj,
560                             const struct passwd *pwd,
561                             const char *section,
562                             const char *name,
563                             const char *path,
564                             const char *preset)
565 {
566     EC_INIT;
567     struct vol  *volume = NULL;
568     int         suffixlen, vlen, tmpvlen, u8mvlen, macvlen;
569     char        tmpname[AFPVOL_U8MNAMELEN+1];
570     ucs2_t      u8mtmpname[(AFPVOL_U8MNAMELEN+1)*2], mactmpname[(AFPVOL_MACNAMELEN+1)*2];
571     char        suffix[6]; /* max is #FFFF */
572     uint16_t    flags;
573     const char  *val;
574     char        *p, *q;
575
576     LOG(log_debug, logtype_afpd, "createvol(volume: '%s', path: \"%s\", preset: '%s'): BEGIN",
577         name, path, preset ? preset : "-");
578
579     if ( name == NULL || *name == '\0' ) {
580         if ((name = strrchr( path, '/' )) == NULL) {
581             EC_FAIL;
582         }
583
584         /* if you wish to share /, you need to specify a name. */
585         if (*++name == '\0')
586             EC_FAIL;
587     }
588
589     /* Once volumes are loaded, we never change options again, we just delete em when they're removed from afp.conf */
590     for (struct vol *vol = Volumes; vol; vol = vol->v_next) {
591         if (STRCMP(path, ==, vol->v_path)) {
592             LOG(log_debug, logtype_afpd, "createvol('%s'): already loaded", name);
593             vol->v_deleted = 0;
594             volume = vol;
595             goto EC_CLEANUP;
596         }
597     }
598
599     /*
600      * Check allow/deny lists:
601      * allow -> either no list (-1), or in list (1)
602      * deny -> either no list (-1), or not in list (0)
603      */
604     if (pwd) {
605         if (accessvol(obj, getoption(obj->iniconfig, section, "invalid users", preset, NULL), pwd->pw_name) == 1)
606             goto EC_CLEANUP;
607         if (accessvol(obj, getoption(obj->iniconfig, section, "valid users", preset, NULL), pwd->pw_name) == 0)
608             goto EC_CLEANUP;
609         if (hostaccessvol(obj, section, getoption(obj->iniconfig, section, "hosts deny", preset, NULL)) == 1)
610             goto EC_CLEANUP;
611         if (hostaccessvol(obj, section, getoption(obj->iniconfig, section, "hosts allow", preset, NULL)) == 0)
612             goto EC_CLEANUP;
613     }
614
615     EC_NULL( volume = calloc(1, sizeof(struct vol)) );
616
617     EC_NULL( volume->v_configname = strdup(section));
618
619     volume->v_vfs_ea = AFPVOL_EA_AUTO;
620     volume->v_umask = obj->options.umask;
621
622     if (val = getoption(obj->iniconfig, section, "password", preset, NULL))
623         EC_NULL( volume->v_password = strdup(val) );
624
625     if (val = getoption(obj->iniconfig, section, "veto files", preset, NULL))
626         EC_NULL( volume->v_veto = strdup(val) );
627
628     /* vol charset is in [G] and [V] */
629     if (val = getoption(obj->iniconfig, section, "vol charset", preset, NULL))
630         EC_NULL( volume->v_volcodepage = strdup(val) );
631     else
632         EC_NULL( volume->v_volcodepage = strdup(obj->options.volcodepage) );
633
634     /* mac charset is in [G] and [V] */
635     if (val = getoption(obj->iniconfig, section, "mac charset", preset, NULL))
636         EC_NULL( volume->v_maccodepage = strdup(val) );
637     else
638         EC_NULL( volume->v_maccodepage = strdup(obj->options.maccodepage) );
639
640     bstring dbpath;
641     EC_NULL_LOG( val = iniparser_getstring(obj->iniconfig, INISEC_GLOBAL, "vol dbpath", _PATH_STATEDIR "CNID/") );
642     EC_NULL_LOG( dbpath = bformat("%s/%s/", val, name) );
643     EC_NULL_LOG( volume->v_dbpath = strdup(bdata(dbpath)) );
644     bdestroy(dbpath);
645
646     if (val = getoption(obj->iniconfig, section, "cnid scheme", preset, NULL))
647         EC_NULL( volume->v_cnidscheme = strdup(val) );
648     else
649         volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
650
651     if (val = getoption(obj->iniconfig, section, "umask", preset, NULL))
652         volume->v_umask = (int)strtol(val, NULL, 8);
653
654     if (val = getoption(obj->iniconfig, section, "directory perm", preset, NULL))
655         volume->v_dperm = (int)strtol(val, NULL, 8);
656
657     if (val = getoption(obj->iniconfig, section, "file perm", preset, NULL))
658         volume->v_fperm = (int)strtol(val, NULL, 8);
659
660     if (val = getoption(obj->iniconfig, section, "vol size limit", preset, NULL))
661         volume->v_limitsize = (uint32_t)strtoul(val, NULL, 10);
662
663     if (val = getoption(obj->iniconfig, section, "preexec", preset, NULL))
664         EC_NULL( volume->v_preexec = volxlate(obj, NULL, MAXPATHLEN, val, pwd, path, name) );
665
666     if (val = getoption(obj->iniconfig, section, "postexec", preset, NULL))
667         EC_NULL( volume->v_postexec = volxlate(obj, NULL, MAXPATHLEN, val, pwd, path, name) );
668
669     if (val = getoption(obj->iniconfig, section, "root preexec", preset, NULL))
670         EC_NULL( volume->v_root_preexec = volxlate(obj, NULL, MAXPATHLEN, val, pwd, path, name) );
671
672     if (val = getoption(obj->iniconfig, section, "root postexec", preset, NULL))
673         EC_NULL( volume->v_root_postexec = volxlate(obj, NULL, MAXPATHLEN, val, pwd, path, name) );
674
675     if (val = getoption(obj->iniconfig, section, "appledouble", preset, NULL)) {
676         if (strcmp(val, "v2") == 0)
677             volume->v_adouble = AD_VERSION2;
678         else if (strcmp(val, "ea") == 0)
679             volume->v_adouble = AD_VERSION_EA;
680     } else {
681         volume->v_adouble = AD_VERSION;
682     }
683
684     if (val = getoption(obj->iniconfig, section, "cnid server", preset, NULL)) {
685         EC_NULL( p = strdup(val) );
686         volume->v_cnidserver = p;
687         if (q = strrchr(val, ':')) {
688             *q++ = 0;
689             volume->v_cnidport = strdup(q);
690         } else {
691             volume->v_cnidport = strdup("4700");
692         }
693
694     } else {
695         volume->v_cnidserver = strdup(obj->options.Cnid_srv);
696         volume->v_cnidport = strdup(obj->options.Cnid_port);
697     }
698
699     if (val = getoption(obj->iniconfig, section, "ea", preset, NULL)) {
700         if (strcasecmp(val, "ad") == 0)
701             volume->v_vfs_ea = AFPVOL_EA_AD;
702         else if (strcasecmp(val, "sys") == 0)
703             volume->v_vfs_ea = AFPVOL_EA_SYS;
704         else if (strcasecmp(val, "none") == 0)
705             volume->v_vfs_ea = AFPVOL_EA_NONE;
706     }
707
708     if (val = getoption(obj->iniconfig, section, "casefold", preset, NULL)) {
709         if (strcasecmp(val, "tolower") == 0)
710             volume->v_casefold = AFPVOL_UMLOWER;
711         else if (strcasecmp(val, "toupper") == 0)
712             volume->v_casefold = AFPVOL_UMUPPER;
713         else if (strcasecmp(val, "xlatelower") == 0)
714             volume->v_casefold = AFPVOL_UUPPERMLOWER;
715         else if (strcasecmp(val, "xlateupper") == 0)
716             volume->v_casefold = AFPVOL_ULOWERMUPPER;
717     }
718
719     if (getoption_bool(obj->iniconfig, section, "read only", preset, 0))
720         volume->v_flags |= AFPVOL_RO;
721     if (getoption_bool(obj->iniconfig, section, "invisible dots", preset, 0))
722         volume->v_flags |= AFPVOL_INV_DOTS;
723     if (!getoption_bool(obj->iniconfig, section, "stat vol", preset, 1))
724         volume->v_flags |= AFPVOL_NOSTAT;
725     if (getoption_bool(obj->iniconfig, section, "unix priv", preset, 1))
726         volume->v_flags |= AFPVOL_UNIX_PRIV;
727     if (!getoption_bool(obj->iniconfig, section, "cnid dev", preset, 1))
728         volume->v_flags |= AFPVOL_NODEV;
729     if (getoption_bool(obj->iniconfig, section, "illegal seq", preset, 0))
730         volume->v_flags |= AFPVOL_EILSEQ;
731     if (getoption_bool(obj->iniconfig, section, "time machine", preset, 0))
732         volume->v_flags |= AFPVOL_TM;
733     if (getoption_bool(obj->iniconfig, section, "search db", preset, 0))
734         volume->v_flags |= AFPVOL_SEARCHDB;
735     if (!getoption_bool(obj->iniconfig, section, "network ids", preset, 1))
736         volume->v_flags |= AFPVOL_NONETIDS;
737 #ifdef HAVE_ACLS
738     if (getoption_bool(obj->iniconfig, section, "acls", preset, 1))
739         volume->v_flags |= AFPVOL_ACLS;
740 #endif
741     if (!getoption_bool(obj->iniconfig, section, "convert adouble", preset, 1))
742         volume->v_flags |= AFPVOL_NOV2TOEACONV;
743
744     if (getoption_bool(obj->iniconfig, section, "preexec close", preset, 0))
745         volume->v_preexec_close = 1;
746     if (getoption_bool(obj->iniconfig, section, "root preexec close", preset, 0))
747         volume->v_root_preexec_close = 1;
748
749     /*
750      * Handle read-only behaviour. semantics:
751      * 1) neither the rolist nor the rwlist exist -> rw
752      * 2) rolist exists -> ro if user is in it.
753      * 3) rwlist exists -> ro unless user is in it.
754      */
755     if (pwd) {
756         if (accessvol(obj, getoption(obj->iniconfig, section, "rolist", preset, NULL), pwd->pw_name) == 1
757             || accessvol(obj, getoption(obj->iniconfig, section, "rwlist", preset, NULL), pwd->pw_name) == 0)
758             volume->v_flags |= AFPVOL_RO;
759     }
760
761     if ((volume->v_flags & AFPVOL_NODEV))
762         volume->v_ad_options |= ADVOL_NODEV;
763     if ((volume->v_flags & AFPVOL_UNIX_PRIV))
764         volume->v_ad_options |= ADVOL_UNIXPRIV;
765     if ((volume->v_flags & AFPVOL_INV_DOTS))
766         volume->v_ad_options |= ADVOL_INVDOTS;
767
768     /* Mac to Unix conversion flags*/
769     if ((volume->v_flags & AFPVOL_EILSEQ))
770         volume->v_mtou_flags |= CONV__EILSEQ;
771
772     if ((volume->v_casefold & AFPVOL_MTOUUPPER))
773         volume->v_mtou_flags |= CONV_TOUPPER;
774     else if ((volume->v_casefold & AFPVOL_MTOULOWER))
775         volume->v_mtou_flags |= CONV_TOLOWER;
776
777     /* Unix to Mac conversion flags*/
778     volume->v_utom_flags = CONV_IGNORE;
779     if ((volume->v_casefold & AFPVOL_UTOMUPPER))
780         volume->v_utom_flags |= CONV_TOUPPER;
781     else if ((volume->v_casefold & AFPVOL_UTOMLOWER))
782         volume->v_utom_flags |= CONV_TOLOWER;
783     if ((volume->v_flags & AFPVOL_EILSEQ))
784         volume->v_utom_flags |= CONV__EILSEQ;
785
786     /* suffix for mangling use (lastvid + 1)   */
787     /* because v_vid has not been decided yet. */
788     suffixlen = sprintf(suffix, "#%X", lastvid + 1 );
789
790
791     vlen = strlen( name );
792
793     /* Unicode Volume Name */
794     /* Firstly convert name from unixcharset to UTF8-MAC */
795     flags = CONV_IGNORE;
796     tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
797     if (tmpvlen <= 0) {
798         strcpy(tmpname, "???");
799         tmpvlen = 3;
800     }
801
802     /* Do we have to mangle ? */
803     if ( (flags & CONV_REQMANGLE) || (tmpvlen > obj->options.volnamelen)) {
804         if (tmpvlen + suffixlen > obj->options.volnamelen) {
805             flags = CONV_FORCE;
806             tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, obj->options.volnamelen - suffixlen, &flags);
807             tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
808         }
809         strcat(tmpname, suffix);
810         tmpvlen = strlen(tmpname);
811     }
812
813     /* Secondly convert name from UTF8-MAC to UCS2 */
814     if ( 0 >= ( u8mvlen = convert_string(CH_UTF8_MAC, CH_UCS2, tmpname, tmpvlen, u8mtmpname, AFPVOL_U8MNAMELEN*2)) )
815         EC_FAIL;
816
817     LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' -> UTF8-MAC Name: '%s'", name, tmpname);
818
819     /* Maccharset Volume Name */
820     /* Firsty convert name from unixcharset to maccharset */
821     flags = CONV_IGNORE;
822     tmpvlen = convert_charset(obj->options.unixcharset, obj->options.maccharset, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
823     if (tmpvlen <= 0) {
824         strcpy(tmpname, "???");
825         tmpvlen = 3;
826     }
827
828     /* Do we have to mangle ? */
829     if ( (flags & CONV_REQMANGLE) || (tmpvlen > AFPVOL_MACNAMELEN)) {
830         if (tmpvlen + suffixlen > AFPVOL_MACNAMELEN) {
831             flags = CONV_FORCE;
832             tmpvlen = convert_charset(obj->options.unixcharset,
833                                       obj->options.maccharset,
834                                       0,
835                                       name,
836                                       vlen,
837                                       tmpname,
838                                       AFPVOL_MACNAMELEN - suffixlen,
839                                       &flags);
840             tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
841         }
842         strcat(tmpname, suffix);
843         tmpvlen = strlen(tmpname);
844     }
845
846     /* Secondly convert name from maccharset to UCS2 */
847     if ( 0 >= ( macvlen = convert_string(obj->options.maccharset,
848                                          CH_UCS2,
849                                          tmpname,
850                                          tmpvlen,
851                                          mactmpname,
852                                          AFPVOL_U8MNAMELEN*2)) )
853         EC_FAIL;
854
855     LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' ->  Longname: '%s'", name, tmpname);
856
857     EC_NULL( volume->v_localname = strdup(name) );
858     EC_NULL( volume->v_u8mname = strdup_w(u8mtmpname) );
859     EC_NULL( volume->v_macname = strdup_w(mactmpname) );
860     EC_NULL( volume->v_path = malloc(strlen(path) + 1) );
861
862     volume->v_name = utf8_encoding(obj) ? volume->v_u8mname : volume->v_macname;
863     strcpy(volume->v_path, path);
864
865 #ifdef __svr4__
866     volume->v_qfd = -1;
867 #endif /* __svr4__ */
868
869     /* os X start at 1 and use network order ie. 1 2 3 */
870     volume->v_vid = ++lastvid;
871     volume->v_vid = htons(volume->v_vid);
872
873 #ifdef HAVE_ACLS
874     if (!check_vol_acl_support(volume)) {
875         LOG(log_debug, logtype_afpd, "creatvol(\"%s\"): disabling ACL support", volume->v_path);
876         volume->v_flags &= ~AFPVOL_ACLS;
877     }
878 #endif
879
880     /* Check EA support on volume */
881     if (volume->v_vfs_ea == AFPVOL_EA_AUTO || volume->v_adouble == AD_VERSION_EA)
882         check_ea_support(volume);
883     initvol_vfs(volume);
884
885     /* get/store uuid from file in afpd master*/
886     if (!(pwd) && (volume->v_flags & AFPVOL_TM)) {
887         char *uuid = get_vol_uuid(obj, volume->v_localname);
888         if (!uuid) {
889             LOG(log_error, logtype_afpd, "Volume '%s': couldn't get UUID",
890                 volume->v_localname);
891         } else {
892             volume->v_uuid = uuid;
893             LOG(log_debug, logtype_afpd, "Volume '%s': UUID '%s'",
894                 volume->v_localname, volume->v_uuid);
895         }
896     }
897
898     /* no errors shall happen beyond this point because the cleanup would mess the volume chain up */
899     volume->v_next = Volumes;
900     Volumes = volume;
901     volume->v_obj = obj;
902
903 EC_CLEANUP:
904     LOG(log_debug, logtype_afpd, "createvol: END: %d", ret);
905     if (ret != 0) {
906         if (volume) {
907             volume_free(volume);
908             free(volume);
909         }
910         return NULL;
911     }
912     return volume;
913 }
914
915 /* ----------------------
916  */
917 static int volfile_changed(struct afp_options *p)
918 {
919     struct stat st;
920
921     if (!stat(p->configfile, &st) && st.st_mtime > p->volfile.mtime) {
922         p->volfile.mtime = st.st_mtime;
923         return 1;
924     }
925     return 0;
926 }
927
928 static int vol_section(const char *sec)
929 {
930     if (STRCMP(sec, ==, INISEC_GLOBAL))
931         return 0;
932     return 1;
933 }
934
935 #define MAXPRESETLEN 100
936 /*!
937  * Read volumes from iniconfig and add the volumes contained within to
938  * the global volume list. This gets called from the forked afpd childs.
939  * The master now reads this too for Zeroconf announcements.
940  */
941 static int readvolfile(AFPObj *obj, const struct passwd *pwent)
942 {
943     EC_INIT;
944     static int regexerr = -1;
945     static regex_t reg;
946     char        path[MAXPATHLEN + 1];
947     char        volname[AFPVOL_U8MNAMELEN + 1];
948     char        tmp[MAXPATHLEN + 1];
949     const char  *preset, *default_preset, *p, *basedir;
950     char        *q, *u;
951     int         i;
952     struct passwd   *pw;
953     regmatch_t match[1];
954
955     LOG(log_debug, logtype_afpd, "readvolfile: BEGIN");
956
957     int secnum = iniparser_getnsec(obj->iniconfig);    
958     LOG(log_debug, logtype_afpd, "readvolfile: sections: %d", secnum);
959     const char *secname;
960
961     if ((default_preset = iniparser_getstring(obj->iniconfig, INISEC_GLOBAL, "vol preset", NULL))) {
962         LOG(log_debug, logtype_afpd, "readvolfile: default_preset: %s", default_preset);
963     }
964
965     for (i = 0; i < secnum; i++) { 
966         secname = iniparser_getsecname(obj->iniconfig, i);
967
968         if (!vol_section(secname))
969             continue;
970         if (STRCMP(secname, ==, INISEC_HOMES)) {
971             have_uservol = 1;
972             if (!IS_AFP_SESSION(obj)
973                 || strcmp(obj->username, obj->options.guest) == 0)
974                 /* not an AFP session, but cnid daemon, dbd or ad util, or guest login */
975                 continue;
976             if (pwent->pw_dir == NULL || STRCMP("", ==, pwent->pw_dir))
977                 /* no user home */
978                 continue;
979
980             /* check if user home matches our "basedir regex" */
981             if ((basedir = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "basedir regex", NULL)) == NULL)
982                 continue;
983             LOG(log_debug, logtype_afpd, "readvolfile: basedir regex: '%s'", basedir);
984
985             if (regexerr != 0 && (regexerr = regcomp(&reg, basedir, REG_EXTENDED)) != 0) {
986                 char errbuf[1024];
987                 regerror(regexerr, &reg, errbuf, sizeof(errbuf));
988                 LOG(log_debug, logtype_default, "readvolfile: bad basedir regex: %s", errbuf);
989             }
990
991             if (regexec(&reg, pwent->pw_dir, 1, match, 0) == REG_NOMATCH) {
992                 LOG(log_debug, logtype_default, "readvolfile: user home \"%s\" doesn't match basedir regex \"%s\"",
993                     pwent->pw_dir, basedir);
994                 continue;
995             }
996
997             strlcpy(tmp, pwent->pw_dir, MAXPATHLEN);
998             strlcat(tmp, "/", MAXPATHLEN);
999             if (p = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "path", NULL))
1000                 strlcat(tmp, p, MAXPATHLEN);
1001         } else {
1002             /* Get path */
1003             if ((p = iniparser_getstring(obj->iniconfig, secname, "path", NULL)) == NULL)
1004                 continue;
1005             strlcpy(tmp, p, MAXPATHLEN);
1006         }
1007
1008         if (volxlate(obj, path, sizeof(path) - 1, tmp, pwent, NULL, NULL) == NULL)
1009             continue;
1010
1011         /* do variable substitution for volume name */
1012         if (STRCMP(secname, ==, INISEC_HOMES)) {
1013             if (p = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "home name", "$u's home"))
1014                 strlcpy(tmp, p, MAXPATHLEN);
1015             else
1016                 strlcpy(tmp, p, MAXPATHLEN);
1017         } else {
1018             strlcpy(tmp, secname, AFPVOL_U8MNAMELEN);
1019         }
1020         if (volxlate(obj, volname, sizeof(volname) - 1, tmp, pwent, path, NULL) == NULL)
1021             continue;
1022
1023         preset = iniparser_getstring(obj->iniconfig, secname, "vol preset", NULL);
1024
1025         creatvol(obj, pwent, secname, volname, path, preset ? preset : default_preset ? default_preset : NULL);
1026     }
1027
1028 EC_CLEANUP:
1029     EC_EXIT;
1030 }
1031
1032 /**************************************************************
1033  * API functions
1034  **************************************************************/
1035
1036 /*!
1037  * Remove a volume from the linked list of volumes
1038  */
1039 void volume_unlink(struct vol *volume)
1040 {
1041     struct vol *vol, *ovol, *nvol;
1042
1043     if (volume == Volumes) {
1044         Volumes = NULL;
1045         return;
1046     }
1047     for ( vol = Volumes->v_next, ovol = Volumes; vol; vol = nvol) {
1048         nvol = vol->v_next;
1049
1050         if (vol == volume) {
1051             ovol->v_next = nvol;
1052             break;
1053         }
1054         else {
1055             ovol = vol;
1056         }
1057     }
1058 }
1059
1060 /*!
1061  * Free all resources allocated in a struct vol, only struct dir *v_root can't be freed
1062  */
1063 void volume_free(struct vol *vol)
1064 {
1065     LOG(log_debug, logtype_afpd, "volume_free('%s'): BEGIN", vol->v_localname);
1066
1067     free(vol->v_localname);
1068     free(vol->v_u8mname);
1069     free(vol->v_macname);
1070     free(vol->v_path);
1071     free(vol->v_password);
1072     free(vol->v_veto);
1073     free(vol->v_volcodepage);
1074     free(vol->v_maccodepage);
1075     free(vol->v_cnidscheme);
1076     free(vol->v_dbpath);
1077     free(vol->v_gvs);
1078     free(vol->v_uuid);
1079     free(vol->v_cnidserver);
1080     free(vol->v_cnidport);
1081     free(vol->v_root_preexec);
1082     free(vol->v_postexec);
1083
1084     LOG(log_debug, logtype_afpd, "volume_free: END");
1085 }
1086
1087 /*!
1088  * Load charsets for a volume
1089  */
1090 int load_charset(struct vol *vol)
1091 {
1092     if ((vol->v_maccharset = add_charset(vol->v_maccodepage)) == (charset_t)-1) {
1093         LOG(log_error, logtype_default, "Setting mac charset '%s' failed", vol->v_maccodepage);
1094         return -1;
1095     }
1096
1097     if ((vol->v_volcharset = add_charset(vol->v_volcodepage)) == (charset_t)-1) {
1098         LOG(log_error, logtype_default, "Setting vol charset '%s' failed", vol->v_volcodepage);
1099         return -1;
1100     }
1101
1102     return 0;
1103 }
1104
1105 /*!
1106  * Initialize volumes and load ini configfile
1107  *
1108  * Depending on the value of obj->uid either access checks are done (!=0) or skipped (=0)
1109  *
1110  * @param obj       (r) handle
1111  * @param delvol_fn (r) callback called for deleted volumes
1112  */
1113 int load_volumes(AFPObj *obj, void (*delvol_fn)(struct vol *))
1114 {
1115     EC_INIT;
1116     int fd = -1;
1117     struct passwd   *pwent = NULL;
1118     struct stat         st;
1119     int retries = 0;
1120     struct vol *vol;
1121
1122     LOG(log_debug, logtype_afpd, "load_volumes: BEGIN");
1123
1124     if (Volumes) {
1125         if (!volfile_changed(&obj->options))
1126             goto EC_CLEANUP;
1127         have_uservol = 0;
1128         for (vol = Volumes; vol; vol = vol->v_next) {
1129             vol->v_deleted = 1;
1130         }
1131     } else {
1132         LOG(log_debug, logtype_afpd, "load_volumes: no volumes yet");
1133         EC_ZERO_LOG( lstat(obj->options.configfile, &st) );
1134         obj->options.volfile.mtime = st.st_mtime;
1135     }
1136
1137     /* try putting a read lock on the volume file twice, sleep 1 second if first attempt fails */
1138
1139     fd = open(obj->options.configfile, O_RDONLY);
1140
1141     while (retries < 2) {
1142         if ((read_lock(fd, 0, SEEK_SET, 0)) != 0) {
1143             retries++;
1144             if (!retries) {
1145                 LOG(log_error, logtype_afpd, "readvolfile: can't lock configfile \"%s\"",
1146                     obj->options.configfile);
1147                 EC_FAIL;
1148             }
1149             sleep(1);
1150             continue;
1151         }
1152         break;
1153     }
1154
1155     if (obj->uid)
1156         pwent = getpwuid(obj->uid);
1157
1158     if (obj->iniconfig)
1159         iniparser_freedict(obj->iniconfig);
1160     LOG(log_debug, logtype_afpd, "load_volumes: loading: %s", obj->options.configfile);
1161     obj->iniconfig = iniparser_load(obj->options.configfile);
1162
1163     EC_ZERO_LOG( readvolfile(obj, pwent) );
1164
1165     for ( vol = Volumes; vol; vol = vol->v_next ) {
1166         if (vol->v_deleted) {
1167             LOG(log_debug, logtype_afpd, "load_volumes: deleted: %s", vol->v_localname);
1168             if (delvol_fn)
1169                 delvol_fn(vol);
1170             vol = Volumes;
1171         }
1172     }
1173
1174 EC_CLEANUP:
1175     if (fd != -1)
1176         (void)close(fd);
1177
1178     LOG(log_debug, logtype_afpd, "load_volumes: END");
1179     EC_EXIT;
1180 }
1181
1182 void unload_volumes(AFPObj *obj)
1183 {
1184     struct vol *vol;
1185
1186     LOG(log_debug, logtype_afpd, "unload_volumes: BEGIN");
1187
1188     for (vol = Volumes; vol; vol = vol->v_next)
1189         volume_free(vol);
1190     Volumes = NULL;
1191     obj->options.volfile.mtime = 0;
1192     
1193     LOG(log_debug, logtype_afpd, "unload_volumes: END");
1194 }
1195
1196 struct vol *getvolumes(void)
1197 {
1198     return Volumes;
1199 }
1200
1201 struct vol *getvolbyvid(const uint16_t vid )
1202 {
1203     struct vol  *vol;
1204
1205     for ( vol = Volumes; vol; vol = vol->v_next ) {
1206         if ( vid == vol->v_vid ) {
1207             break;
1208         }
1209     }
1210     if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
1211         return( NULL );
1212     }
1213
1214     return( vol );
1215 }
1216
1217 /*!
1218  * Search volume by path, creating user home vols as necessary
1219  *
1220  * Path may be absolute or relative. Ordinary volume structs are created when
1221  * the ini config is initially parsed (load_volumes()), but user volumes are
1222  * as load_volumes() only can create the user volume of the logged in user
1223  * in an AFP session in afpd, but not when called from eg cnid_metad or dbd.
1224  * Both cnid_metad and dbd thus need a way to lookup and create struct vols
1225  * for user home by path. This is what this func does as well.
1226  *
1227  * (1) Search "normal" volume list 
1228  * (2) Check if theres a [Homes] section, load_volumes() remembers this for us
1229  * (3) If there is, match "path" with "basedir regex" to get the user home parent dir
1230  * (4) Built user home path by appending the basedir matched in (3) and appending the username
1231  * (5) The next path element then is the username
1232  * (6) Append [Homes]->path subdirectory if defined
1233  * (7) Create volume
1234  *
1235  * @param obj  (rw) handle
1236  * @param path (r)  path, may be relative or absolute
1237  */
1238 struct vol *getvolbypath(AFPObj *obj, const char *path)
1239 {
1240     EC_INIT;
1241     static int regexerr = -1;
1242     static regex_t reg;
1243     struct vol *vol;
1244     struct vol *tmp;
1245     const struct passwd *pw;
1246     char        volname[AFPVOL_U8MNAMELEN + 1];
1247     char        abspath[MAXPATHLEN + 1];
1248     char        volpath[MAXPATHLEN + 1];
1249     char        tmpbuf[MAXPATHLEN + 1];
1250     const char *secname, *basedir, *p = NULL, *subpath = NULL, *subpathconfig;
1251     char *user = NULL, *prw;
1252     regmatch_t match[1];
1253
1254     LOG(log_debug, logtype_afpd, "getvolbypath(\"%s\")", path);
1255
1256     if (path[0] != '/') {
1257         /* relative path, build absolute path */
1258         EC_NULL_LOG( getcwd(abspath, MAXPATHLEN) );
1259         strlcat(abspath, "/", MAXPATHLEN);
1260         strlcat(abspath, path, MAXPATHLEN);
1261         path = abspath;
1262     }
1263
1264
1265     for (tmp = Volumes; tmp; tmp = tmp->v_next) { /* (1) */
1266         if (strncmp(path, tmp->v_path, strlen(tmp->v_path)) == 0) {
1267             vol = tmp;
1268             goto EC_CLEANUP;
1269         }
1270     }
1271
1272     if (!have_uservol) /* (2) */
1273         EC_FAIL_LOG("getvolbypath(\"%s\"): no volume for path", path);
1274
1275     int secnum = iniparser_getnsec(obj->iniconfig);
1276
1277     for (int i = 0; i < secnum; i++) { 
1278         secname = iniparser_getsecname(obj->iniconfig, i);
1279         if (STRCMP(secname, ==, INISEC_HOMES))
1280             break;
1281     }
1282
1283     if (STRCMP(secname, !=, INISEC_HOMES))
1284         EC_FAIL_LOG("getvolbypath(\"%s\"): no volume for path", path);
1285
1286     /* (3) */
1287     EC_NULL_LOG( basedir = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "basedir regex", NULL) );
1288     LOG(log_debug, logtype_afpd, "getvolbypath: user home section: '%s', basedir: '%s'", secname, basedir);
1289
1290     if (regexerr != 0 && (regexerr = regcomp(&reg, basedir, REG_EXTENDED)) != 0) {
1291         char errbuf[1024];
1292         regerror(regexerr, &reg, errbuf, sizeof(errbuf));
1293         printf("error: %s\n", errbuf);
1294         EC_FAIL_LOG("getvolbypath(\"%s\"): bad basedir regex: %s", errbuf);
1295     }
1296
1297     if (regexec(&reg, path, 1, match, 0) == REG_NOMATCH)
1298         EC_FAIL_LOG("getvolbypath(\"%s\"): no volume for path", path);
1299
1300     if (match[0].rm_eo - match[0].rm_so > MAXPATHLEN)
1301         EC_FAIL_LOG("getvolbypath(\"%s\"): path too long", path);
1302
1303     /* (4) */
1304     strncpy(tmpbuf, path + match[0].rm_so, match[0].rm_eo - match[0].rm_so);
1305     tmpbuf[match[0].rm_eo - match[0].rm_so] = 0;
1306
1307     LOG(log_debug, logtype_afpd, "getvolbypath: basedir regex: '%s', basedir match: \"%s\"",
1308         basedir, tmpbuf);
1309
1310     strlcat(tmpbuf, "/", MAXPATHLEN);
1311
1312     /* (5) */
1313     p = path + strlen(basedir);
1314     while (*p == '/')
1315         p++;
1316     EC_NULL_LOG( user = strdup(p) );
1317
1318     if (prw = strchr(user, '/'))
1319         *prw++ = 0;
1320     if (prw != 0)
1321         subpath = prw;
1322
1323     strlcat(tmpbuf, user, MAXPATHLEN);
1324     strlcat(obj->username, user, MAXUSERLEN);
1325     strlcat(tmpbuf, "/", MAXPATHLEN);
1326
1327     /* (6) */
1328     if (subpathconfig = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "path", NULL)) {
1329         if (!subpath || strncmp(subpathconfig, subpath, strlen(subpathconfig)) != 0) {
1330             EC_FAIL;
1331         }
1332         strlcat(tmpbuf, subpathconfig, MAXPATHLEN);
1333         strlcat(tmpbuf, "/", MAXPATHLEN);
1334     }
1335
1336
1337     /* (7) */
1338     if (volxlate(obj, volpath, sizeof(volpath) - 1, tmpbuf, pw, NULL, NULL) == NULL)
1339         return NULL;
1340
1341     EC_NULL( pw = getpwnam(user) );
1342
1343     LOG(log_debug, logtype_afpd, "getvolbypath(\"%s\"): user: %s, homedir: %s => volpath: \"%s\"",
1344         path, user, pw->pw_dir, volpath);
1345
1346     /* do variable substitution for volume name */
1347     p = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "home name", "$u's home");
1348     strlcpy(tmpbuf, p, AFPVOL_U8MNAMELEN);
1349     EC_NULL_LOG( volxlate(obj, volname, sizeof(volname) - 1, tmpbuf, pw, volpath, NULL) );
1350
1351     const char  *preset, *default_preset;
1352     default_preset = iniparser_getstring(obj->iniconfig, INISEC_GLOBAL, "vol preset", NULL);
1353     preset = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "vol preset", NULL);
1354
1355     vol = creatvol(obj, pw, INISEC_HOMES, volname, volpath, preset ? preset : default_preset ? default_preset : NULL);
1356
1357 EC_CLEANUP:
1358     if (user)
1359         free(user);
1360     if (ret != 0)
1361         vol = NULL;
1362     return vol;
1363 }
1364
1365 struct vol *getvolbyname(const char *name)
1366 {
1367     struct vol *vol = NULL;
1368     struct vol *tmp;
1369
1370     for (tmp = Volumes; tmp; tmp = tmp->v_next) {
1371         if (strncmp(name, tmp->v_configname, strlen(tmp->v_configname)) == 0) {
1372             vol = tmp;
1373             break;
1374         }
1375     }
1376     return vol;
1377 }
1378
1379 #define MAXVAL 1024
1380 /*!
1381  * Initialize an AFPObj and options from ini config file
1382  */
1383 int afp_config_parse(AFPObj *AFPObj, char *processname)
1384 {
1385     EC_INIT;
1386     dictionary *config;
1387     struct afp_options *options = &AFPObj->options;
1388     int i, c;
1389     const char *p, *tmp;
1390     char *q, *r;
1391     char val[MAXVAL];
1392
1393     AFPObj->afp_version = 11;
1394     options->configfile  = AFPObj->cmdlineconfigfile ? strdup(AFPObj->cmdlineconfigfile) : strdup(_PATH_CONFDIR "afp.conf");
1395     options->sigconffile = strdup(_PATH_STATEDIR "afp_signature.conf");
1396     options->uuidconf    = strdup(_PATH_STATEDIR "afp_voluuid.conf");
1397     options->flags       = OPTION_ACL2MACCESS | OPTION_UUID | OPTION_SERVERNOTIF | AFPObj->cmdlineflags;
1398     
1399     if ((config = iniparser_load(AFPObj->options.configfile)) == NULL)
1400         return -1;
1401     AFPObj->iniconfig = config;
1402
1403     /* [Global] */
1404     options->logconfig = iniparser_getstrdup(config, INISEC_GLOBAL, "log level", "default:note");
1405     options->logfile   = iniparser_getstrdup(config, INISEC_GLOBAL, "log file",  NULL);
1406
1407     if (processname[0] != '\0') {
1408         set_processname(processname);
1409         setuplog(options->logconfig, options->logfile);
1410     }
1411
1412     /* "server options" boolean options */
1413     if (!iniparser_getboolean(config, INISEC_GLOBAL, "zeroconf", 1))
1414         options->flags |= OPTION_NOZEROCONF;
1415     if (iniparser_getboolean(config, INISEC_GLOBAL, "icon", 0))
1416         options->flags |= OPTION_CUSTOMICON;
1417     if (iniparser_getboolean(config, INISEC_GLOBAL, "advertise ssh", 0))
1418         options->flags |= OPTION_ANNOUNCESSH;
1419     if (iniparser_getboolean(config, INISEC_GLOBAL, "map acls", 1))
1420         options->flags |= OPTION_ACL2MACCESS;
1421     if (iniparser_getboolean(config, INISEC_GLOBAL, "keep sessions", 0))
1422         options->flags |= OPTION_KEEPSESSIONS;
1423     if (iniparser_getboolean(config, INISEC_GLOBAL, "close vol", 0))
1424         options->flags |= OPTION_CLOSEVOL;
1425     if (!iniparser_getboolean(config, INISEC_GLOBAL, "client polling", 1))
1426         options->flags |= OPTION_SERVERNOTIF;
1427     if (!iniparser_getboolean(config, INISEC_GLOBAL, "use sendfile", 1))
1428         options->flags |= OPTION_NOSENDFILE;
1429     if (!iniparser_getboolean(config, INISEC_GLOBAL, "save password", 1))
1430         options->passwdbits |= PASSWD_NOSAVE;
1431     if (iniparser_getboolean(config, INISEC_GLOBAL, "set password", 0))
1432         options->passwdbits |= PASSWD_SET;
1433
1434     /* figure out options w values */
1435     options->loginmesg      = iniparser_getstrdup(config, INISEC_GLOBAL, "login message",      "");
1436     options->guest          = iniparser_getstrdup(config, INISEC_GLOBAL, "guest account",  "nobody");
1437     options->passwdfile     = iniparser_getstrdup(config, INISEC_GLOBAL, "passwd file",_PATH_AFPDPWFILE);
1438     options->uampath        = iniparser_getstrdup(config, INISEC_GLOBAL, "uam path",       _PATH_AFPDUAMPATH);
1439     options->uamlist        = iniparser_getstrdup(config, INISEC_GLOBAL, "uam list",       "uams_dhx.so uams_dhx2.so");
1440     options->port           = iniparser_getstrdup(config, INISEC_GLOBAL, "afp port",       "548");
1441     options->signatureopt   = iniparser_getstrdup(config, INISEC_GLOBAL, "signature",      "");
1442     options->k5service      = iniparser_getstrdup(config, INISEC_GLOBAL, "k5 service",     NULL);
1443     options->k5realm        = iniparser_getstrdup(config, INISEC_GLOBAL, "k5 realm",       NULL);
1444     options->listen         = iniparser_getstrdup(config, INISEC_GLOBAL, "afp listen",     NULL);
1445     options->ntdomain       = iniparser_getstrdup(config, INISEC_GLOBAL, "nt domain",      NULL);
1446     options->ntseparator    = iniparser_getstrdup(config, INISEC_GLOBAL, "nt separator",   NULL);
1447     options->mimicmodel     = iniparser_getstrdup(config, INISEC_GLOBAL, "mimic model",    NULL);
1448     options->adminauthuser  = iniparser_getstrdup(config, INISEC_GLOBAL, "admin auth user",NULL);
1449     options->connections    = iniparser_getint   (config, INISEC_GLOBAL, "max connections",200);
1450     options->passwdminlen   = iniparser_getint   (config, INISEC_GLOBAL, "passwd minlen",  0);
1451     options->tickleval      = iniparser_getint   (config, INISEC_GLOBAL, "tickleval",      30);
1452     options->timeout        = iniparser_getint   (config, INISEC_GLOBAL, "timeout",        4);
1453     options->dsireadbuf     = iniparser_getint   (config, INISEC_GLOBAL, "dsireadbuf",     12);
1454     options->server_quantum = iniparser_getint   (config, INISEC_GLOBAL, "server quantum", DSI_SERVQUANT_DEF);
1455     options->volnamelen     = iniparser_getint   (config, INISEC_GLOBAL, "volnamelen",     80);
1456     options->dircachesize   = iniparser_getint   (config, INISEC_GLOBAL, "dircachesize",   DEFAULT_MAX_DIRCACHE_SIZE);
1457     options->tcp_sndbuf     = iniparser_getint   (config, INISEC_GLOBAL, "tcpsndbuf",      0);
1458     options->tcp_rcvbuf     = iniparser_getint   (config, INISEC_GLOBAL, "tcprcvbuf",      0);
1459     options->fce_fmodwait   = iniparser_getint   (config, INISEC_GLOBAL, "fce holdfmod",   60);
1460     options->sleep          = iniparser_getint   (config, INISEC_GLOBAL, "sleep time",     10);
1461     options->disconnected   = iniparser_getint   (config, INISEC_GLOBAL, "disconnect time",24);
1462
1463     if ((p = iniparser_getstring(config, INISEC_GLOBAL, "hostname", NULL))) {
1464         EC_NULL_LOG( options->hostname = strdup(p) );
1465     } else {
1466         if (gethostname(val, sizeof(val)) < 0 ) {
1467             perror( "gethostname" );
1468             EC_FAIL;
1469         }
1470         if ((q = strchr(val, '.')))
1471             *q = '\0';
1472         options->hostname = strdup(val);
1473     }
1474
1475     if ((p = iniparser_getstring(config, INISEC_GLOBAL, "k5 keytab", NULL))) {
1476         EC_NULL_LOG( options->k5keytab = malloc(strlen(p) + 14) );
1477         snprintf(options->k5keytab, strlen(p) + 14, "KRB5_KTNAME=%s", p);
1478         putenv(options->k5keytab);
1479     }
1480
1481 #ifdef ADMIN_GRP
1482     if ((p = iniparser_getstring(config, INISEC_GLOBAL, "admin group",  NULL))) {
1483          struct group *gr = getgrnam(p);
1484          if (gr != NULL)
1485              options->admingid = gr->gr_gid;
1486     }
1487 #endif /* ADMIN_GRP */
1488
1489     q = iniparser_getstrdup(config, INISEC_GLOBAL, "cnid server", "localhost:4700");
1490     r = strrchr(q, ':');
1491     if (r)
1492         *r = 0;
1493     options->Cnid_srv = strdup(q);
1494     if (r)
1495         options->Cnid_port = strdup(r + 1);
1496     else
1497         options->Cnid_port = strdup("4700");
1498     LOG(log_debug, logtype_afpd, "CNID Server: %s:%s", options->Cnid_srv, options->Cnid_port);
1499     if (q)
1500         free(q);
1501
1502     if ((q = iniparser_getstrdup(config, INISEC_GLOBAL, "fqdn", NULL))) {
1503         /* do a little checking for the domain name. */
1504         r = strchr(q, ':');
1505         if (r)
1506             *r = '\0';
1507         if (gethostbyname(q)) {
1508             if (r)
1509                 *r = ':';
1510             EC_NULL_LOG( options->fqdn = strdup(q) );
1511         } else {
1512             LOG(log_error, logtype_afpd, "error parsing -fqdn, gethostbyname failed for: %s", c);
1513         }
1514         free(q);
1515     }
1516
1517     /* Charset Options */
1518
1519     /* unix charset is in [G] only */
1520     if (!(p = iniparser_getstring(config, INISEC_GLOBAL, "unix charset", NULL))) {
1521         options->unixcharset = CH_UNIX;
1522         options->unixcodepage = strdup("LOCALE");
1523     } else {
1524         if ((options->unixcharset = add_charset(p)) == (charset_t)-1) {
1525             options->unixcharset = CH_UNIX;
1526             options->unixcodepage = strdup("LOCALE");
1527             LOG(log_warning, logtype_afpd, "Setting unix charset to '%s' failed", p);
1528         } else {
1529             options->unixcodepage = strdup(p);
1530         }
1531     }
1532
1533     /* vol charset is in [G[ and [V] */
1534     if (!(p = iniparser_getstring(config, INISEC_GLOBAL, "vol charset", NULL))) {
1535         options->volcodepage = strdup("UTF8");
1536     } else {
1537         options->volcodepage = strdup(p);
1538     }
1539         
1540     /* mac charset is in [G] and [V] */
1541     if (!(p = iniparser_getstring(config, INISEC_GLOBAL, "mac charset", NULL))) {
1542         options->maccharset = CH_MAC;
1543         options->maccodepage = strdup("MAC_ROMAN");
1544     } else {
1545         if ((options->maccharset = add_charset(p)) == (charset_t)-1) {
1546             options->maccharset = CH_MAC;
1547             options->maccodepage = strdup("MAC_ROMAN");
1548             LOG(log_warning, logtype_afpd, "Setting mac charset to '%s' failed", p);
1549         } else {
1550             options->maccodepage = strdup(p);
1551         }
1552     }
1553
1554     /* Check for sane values */
1555     if (options->tickleval <= 0)
1556         options->tickleval = 30;
1557         options->disconnected *= 3600 / options->tickleval;
1558         options->sleep *= 3600 / options->tickleval;
1559     if (options->timeout <= 0)
1560         options->timeout = 4;
1561     if (options->sleep <= 4)
1562         options->disconnected = options->sleep = 4;
1563     if (options->dsireadbuf < 6)
1564         options->dsireadbuf = 6;
1565     if (options->volnamelen < 8)
1566         options->volnamelen = 8; /* max mangled volname "???#FFFF" */
1567     if (options->volnamelen > 255)
1568         options->volnamelen = 255; /* AFP3 spec */
1569
1570 EC_CLEANUP:
1571     EC_EXIT;
1572 }