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