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