]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/volume.c
merge from HEAD, better handling of unix priv.
[netatalk.git] / etc / afpd / volume.c
1 /*
2  * $Id: volume.c,v 1.51.2.7.2.33.2.6 2005-05-26 11:49:55 didg Exp $
3  *
4  * Copyright (c) 1990,1993 Regents of The University of Michigan.
5  * All Rights Reserved.  See COPYRIGHT.
6  */
7
8 #ifdef HAVE_CONFIG_H
9 #include "config.h"
10 #endif /* HAVE_CONFIG_H */
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <ctype.h>
15 #include <dirent.h>
16 #include <pwd.h>
17 #include <grp.h>
18 #include <utime.h>
19 #include <errno.h>
20 #ifdef HAVE_STRINGS_H
21 #include <strings.h>
22 #endif
23 /* STDC check */
24 #if STDC_HEADERS
25 #include <string.h>
26 #else /* STDC_HEADERS */
27 #ifndef HAVE_STRCHR
28 #define strchr index
29 #define strrchr index
30 #endif /* HAVE_STRCHR */
31 char *strchr (), *strrchr ();
32 #ifndef HAVE_MEMCPY
33 #define memcpy(d,s,n) bcopy ((s), (d), (n))
34 #define memmove(d,s,n) bcopy ((s), (d), (n))
35 #endif /* ! HAVE_MEMCPY */
36 #endif /* STDC_HEADERS */
37 #include <sys/param.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #include <atalk/asp.h>
42 #include <atalk/dsi.h>
43 #include <atalk/adouble.h>
44 #include <atalk/afp.h>
45 #include <atalk/util.h>
46 #include <atalk/logger.h>
47 #ifdef CNID_DB
48 #include <atalk/cnid.h>
49 #endif /* CNID_DB*/
50
51 #include "globals.h"
52 #include "directory.h"
53 #include "file.h"
54 #include "volume.h"
55 #include "unix.h"
56
57 extern int afprun(int root, char *cmd, int *outfd);
58
59 #ifndef MIN
60 #define MIN(a, b) ((a) < (b) ? (a) : (b))
61 #endif /* ! MIN */
62
63 #ifndef NO_LARGE_VOL_SUPPORT
64 #if BYTE_ORDER == BIG_ENDIAN
65 #define hton64(x)       (x)
66 #define ntoh64(x)       (x)
67 #else /* BYTE_ORDER == BIG_ENDIAN */
68 #define hton64(x)       ((u_int64_t) (htonl(((x) >> 32) & 0xffffffffLL)) | \
69                          (u_int64_t) ((htonl(x) & 0xffffffffLL) << 32))
70 #define ntoh64(x)       (hton64(x))
71 #endif /* BYTE_ORDER == BIG_ENDIAN */
72 #endif /* ! NO_LARGE_VOL_SUPPORT */
73
74 static struct vol *Volumes = NULL;
75 static u_int16_t        lastvid = 0;
76 static char             *Trash = "\02\024Network Trash Folder";
77
78 static struct extmap    *Extmap = NULL, *Defextmap = NULL;
79 static int              Extmap_cnt;
80 static void             free_extmap(void);
81
82 #define VOLOPT_ALLOW      0  /* user allow list */
83 #define VOLOPT_DENY       1  /* user deny list */
84 #define VOLOPT_RWLIST     2  /* user rw list */
85 #define VOLOPT_ROLIST     3  /* user ro list */
86 #define VOLOPT_PASSWORD   4  /* volume password */
87 #define VOLOPT_CASEFOLD   5  /* character case mangling */
88 #define VOLOPT_FLAGS      6  /* various flags */
89 #define VOLOPT_DBPATH     7  /* path to database */
90 #define VOLOPT_MAPCHARS   8  /* does mtou and utom mappings. syntax:
91 m and u can be double-byte hex
92 strings if necessary.
93 m=u -> map both ways
94   m>u -> map m to u
95   m<u -> map u to m
96   !u  -> make u illegal always
97   ~u  -> make u illegal only as the first
98   part of a double-byte character.
99   */
100 #define VOLOPT_VETO          10  /* list of veto filespec */
101 #define VOLOPT_PREEXEC       11  /* preexec command */
102 #define VOLOPT_ROOTPREEXEC   12  /* root preexec command */
103
104 #define VOLOPT_POSTEXEC      13  /* postexec command */
105 #define VOLOPT_ROOTPOSTEXEC  14  /* root postexec command */
106
107 #define VOLOPT_ENCODING      15  /* mac encoding (pre OSX)*/
108 #define VOLOPT_MACCHARSET    16
109 #define VOLOPT_CNIDSCHEME    17
110 #define VOLOPT_ADOUBLE       18  /* adouble version */
111 #ifdef FORCE_UIDGID
112 #warning UIDGID
113 #include "uid.h"
114
115 #define VOLOPT_FORCEUID  19  /* force uid for username x */
116 #define VOLOPT_FORCEGID  20  /* force gid for group x */
117 #define VOLOPT_UMASK     21
118 #else 
119 #define VOLOPT_UMASK     19
120 #endif /* FORCE_UIDGID */
121
122 #define VOLOPT_MAX       (VOLOPT_UMASK +1)
123
124 #define VOLOPT_NUM        (VOLOPT_MAX + 1)
125
126 #define VOLPASSLEN  8
127 #define VOLOPT_DEFAULT     ":DEFAULT:"
128 #define VOLOPT_DEFAULT_LEN 9
129   struct vol_option {
130       char *c_value;
131       int i_value;
132   };
133
134 typedef struct _special_folder {
135         const char *name;
136         int precreate;
137         mode_t mode;
138         int hide;
139 } _special_folder;
140
141 static const _special_folder special_folders[] = {
142   {"Network Trash Folder",     1,  0777,  1},
143   {"Temporary Items",          1,  0777,  1},
144   {".AppleDesktop",            1,  0777,  0},
145 #if 0
146   {"TheFindByContentFolder",   0,     0,  1},
147   {"TheVolumeSettingsFolder",  0,     0,  1},
148 #endif
149   {NULL, 0, 0, 0}};
150
151 typedef struct _volopt_name {
152         const u_int32_t option;
153         const char      *name;
154 } _vol_opt_name;
155
156 static const _vol_opt_name vol_opt_names[] = {
157     {AFPVOL_A2VOL,      "PRODOS"},      /* prodos volume */
158     {AFPVOL_CRLF,       "CRLF"},        /* cr/lf translation */
159     {AFPVOL_NOADOUBLE,  "NOADOUBLE"},   /* don't create .AppleDouble by default */
160     {AFPVOL_RO,         "READONLY"},    /* read-only volume */
161     {AFPVOL_MSWINDOWS,  "MSWINDOWS"},   /* deal with ms-windows yuckiness. this is going away. */
162     {AFPVOL_NOHEX,      "NOHEX"},       /* don't do :hex translation */
163     {AFPVOL_USEDOTS,    "USEDOTS"},     /* use real dots */
164     {AFPVOL_LIMITSIZE,  "LIMITSIZE"},   /* limit size for older macs */
165     {AFPVOL_MAPASCII,   "MAPASCII"},    /* map the ascii range as well */
166     {AFPVOL_DROPBOX,    "DROPBOX"},     /* dropkludge dropbox support */
167     {AFPVOL_NOFILEID,   "NOFILEID"},    /* don't advertise createid resolveid and deleteid calls */
168     {AFPVOL_NOSTAT,     "NOSTAT"},      /* advertise the volume even if we can't stat() it
169                                          * maybe because it will be mounted later in preexec */
170     {AFPVOL_UNIX_PRIV,  "UNIXPRIV"},    /* support unix privileges */
171     {AFPVOL_NODEV,      "NODEV"},       /* always use 0 for device number in cnid calls */
172     {0, NULL}
173 };
174
175 static const _vol_opt_name vol_opt_casefold[] = {
176     {AFPVOL_MTOUUPPER,  "MTOULOWER"},
177     {AFPVOL_MTOULOWER,  "MTOULOWER"},
178     {AFPVOL_UTOMUPPER,  "UTOMUPPER"},
179     {AFPVOL_UTOMLOWER,  "UTOMLOWER"},
180     {0, NULL}
181 };
182
183 static void handle_special_folders (const struct vol *);
184 static int savevoloptions (const struct vol *);
185
186 static __inline__ void volfree(struct vol_option *options,
187                                const struct vol_option *save)
188 {
189     int i;
190
191     if (save) {
192         for (i = 0; i < VOLOPT_MAX; i++) {
193             if (options[i].c_value && (options[i].c_value != save[i].c_value))
194                 free(options[i].c_value);
195         }
196     } else {
197         for (i = 0; i < VOLOPT_MAX; i++) {
198             if (options[i].c_value)
199                 free(options[i].c_value);
200         }
201     }
202 }
203
204
205 /* handle variable substitutions. here's what we understand:
206  * $b   -> basename of path
207  * $c   -> client ip/appletalk address
208  * $d   -> volume pathname on server
209  * $f   -> full name (whatever's in the gecos field)
210  * $g   -> group
211  * $h   -> hostname 
212  * $i   -> client ip/appletalk address without port
213  * $s   -> server name (hostname if it doesn't exist)
214  * $u   -> username (guest is usually nobody)
215  * $v   -> volume name or basename if null
216  * $z   -> zone (may not exist)
217  * $$   -> $
218  *
219  *
220  */
221 #define is_var(a, b) (strncmp((a), (b), 2) == 0)
222
223 static char *volxlate(AFPObj *obj, char *dest, size_t destlen,
224                      char *src, struct passwd *pwd, char *path, char *volname)
225 {
226     char *p, *q;
227     int len;
228     char *ret;
229     
230     if (!src) {
231         return NULL;
232     }
233     if (!dest) {
234         dest = calloc(destlen +1, 1);
235     }
236     ret = dest;
237     if (!ret) {
238         return NULL;
239     }
240     strlcpy(dest, src, destlen +1);
241     if ((p = strchr(src, '$')) == NULL) /* nothing to do */
242         return ret;
243
244     /* first part of the path. just forward to the next variable. */
245     len = MIN(p - src, destlen);
246     if (len > 0) {
247         destlen -= len;
248         dest += len;
249     }
250
251     while (p && destlen > 0) {
252         /* now figure out what the variable is */
253         q = NULL;
254         if (is_var(p, "$b")) {
255             if (path) {
256                 if ((q = strrchr(path, '/')) == NULL)
257                     q = path;
258                 else if (*(q + 1) != '\0')
259                     q++;
260             }
261         } else if (is_var(p, "$c")) {
262             if (obj->proto == AFPPROTO_ASP) {
263                 ASP asp = obj->handle;
264
265                 len = sprintf(dest, "%u.%u", ntohs(asp->asp_sat.sat_addr.s_net),
266                               asp->asp_sat.sat_addr.s_node);
267                 dest += len;
268                 destlen -= len;
269
270             } else if (obj->proto == AFPPROTO_DSI) {
271                 DSI *dsi = obj->handle;
272
273                 len = sprintf(dest, "%s:%u", inet_ntoa(dsi->client.sin_addr),
274                               ntohs(dsi->client.sin_port));
275                 dest += len;
276                 destlen -= len;
277             }
278         } else if (is_var(p, "$d")) {
279              q = path;
280         } else if (is_var(p, "$f")) {
281             if ((q = strchr(pwd->pw_gecos, ',')))
282                 *q = '\0';
283             q = pwd->pw_gecos;
284         } else if (is_var(p, "$g")) {
285             struct group *grp = getgrgid(pwd->pw_gid);
286             if (grp)
287                 q = grp->gr_name;
288         } else if (is_var(p, "$h")) {
289             q = obj->options.hostname;
290         } else if (is_var(p, "$i")) {
291             if (obj->proto == AFPPROTO_ASP) {
292                 ASP asp = obj->handle;
293  
294                 len = sprintf(dest, "%u", ntohs(asp->asp_sat.sat_addr.s_net));
295                 dest += len;
296                 destlen -= len;
297  
298             } else if (obj->proto == AFPPROTO_DSI) {
299                 DSI *dsi = obj->handle;
300  
301                 q = inet_ntoa(dsi->client.sin_addr);
302             }
303         } else if (is_var(p, "$s")) {
304             if (obj->Obj)
305                 q = obj->Obj;
306             else if (obj->options.server) {
307                 q = obj->options.server;
308             } else
309                 q = obj->options.hostname;
310         } else if (is_var(p, "$u")) {
311             q = obj->username;
312         } else if (is_var(p, "$v")) {
313             if (volname) {
314                 q = volname;
315             }
316             else if (path) {
317                 if ((q = strrchr(path, '/')) == NULL)
318                     q = path;
319                 else if (*(q + 1) != '\0')
320                     q++;
321             }
322         } else if (is_var(p, "$z")) {
323             q = obj->Zone;
324         } else if (is_var(p, "$$")) {
325             q = "$";
326         } else
327             q = p;
328
329         /* copy the stuff over. if we don't understand something that we
330          * should, just skip it over. */
331         if (q) {
332             len = MIN(p == q ? 2 : strlen(q), destlen);
333             strncpy(dest, q, len);
334             dest += len;
335             destlen -= len;
336         }
337
338         /* stuff up to next $ */
339         src = p + 2;
340         p = strchr(src, '$');
341         len = p ? MIN(p - src, destlen) : destlen;
342         if (len > 0) {
343             strncpy(dest, src, len);
344             dest += len;
345             destlen -= len;
346         }
347     }
348     return ret;
349 }
350
351 /* to make sure that val is valid, make sure to select an opt that
352    includes val */
353 static int optionok(const char *buf, const char *opt, const char *val) 
354 {
355     if (!strstr(buf,opt))
356         return 0;
357     if (!val[1])
358         return 0;
359     return 1;    
360 }
361
362
363 /* -------------------- */
364 static void setoption(struct vol_option *options, struct vol_option *save, int opt, const char *val)
365 {
366     if (options[opt].c_value && (!save || options[opt].c_value != save[opt].c_value))
367         free(options[opt].c_value);
368     options[opt].c_value = strdup(val + 1);
369 }
370
371 /* ------------------------------------------
372    handle all the options. tmp can't be NULL. */
373 static void volset(struct vol_option *options, struct vol_option *save, 
374                    char *volname, int vlen,
375                    const char *tmp)
376 {
377     char *val;
378
379     val = strchr(tmp, ':');
380     if (!val) {
381         /* we'll assume it's a volume name. */
382         strncpy(volname, tmp, vlen);
383         volname[vlen] = 0;
384         return;
385     }
386 #if 0
387     LOG(log_debug, logtype_afpd, "Parsing volset %s", val);
388 #endif
389     if (optionok(tmp, "allow:", val)) {
390         setoption(options, save, VOLOPT_ALLOW, val);
391
392     } else if (optionok(tmp, "deny:", val)) {
393         setoption(options, save, VOLOPT_DENY, val);
394
395     } else if (optionok(tmp, "rwlist:", val)) {
396         setoption(options, save, VOLOPT_RWLIST, val);
397
398     } else if (optionok(tmp, "rolist:", val)) {
399         setoption(options, save, VOLOPT_ROLIST, val);
400
401     } else if (optionok(tmp, "codepage:", val)) {
402         LOG (log_error, logtype_afpd, "The old codepage system has been removed. Please make sure to read the documentation !!!!");
403         /* Make sure we don't screw anything */
404         exit (EXITERR_CONF);
405     } else if (optionok(tmp, "volcharset:", val)) {
406         setoption(options, save, VOLOPT_ENCODING, val);
407     } else if (optionok(tmp, "maccharset:", val)) {
408         setoption(options, save, VOLOPT_MACCHARSET, val);
409     } else if (optionok(tmp, "veto:", val)) {
410         setoption(options, save, VOLOPT_VETO, val);
411     } else if (optionok(tmp, "cnidscheme:", val)) {
412         setoption(options, save, VOLOPT_CNIDSCHEME, val);
413     } else if (optionok(tmp, "casefold:", val)) {
414         if (strcasecmp(val + 1, "tolower") == 0)
415             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMLOWER;
416         else if (strcasecmp(val + 1, "toupper") == 0)
417             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMUPPER;
418         else if (strcasecmp(val + 1, "xlatelower") == 0)
419             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UUPPERMLOWER;
420         else if (strcasecmp(val + 1, "xlateupper") == 0)
421             options[VOLOPT_CASEFOLD].i_value = AFPVOL_ULOWERMUPPER;
422     } else if (optionok(tmp, "adouble:", val)) {
423         if (strcasecmp(val + 1, "v1") == 0)
424             options[VOLOPT_ADOUBLE].i_value = AD_VERSION1;
425 #if AD_VERSION == AD_VERSION2            
426         else if (strcasecmp(val + 1, "v2") == 0)
427             options[VOLOPT_ADOUBLE].i_value = AD_VERSION2;
428         else if (strcasecmp(val + 1, "osx") == 0)
429             options[VOLOPT_ADOUBLE].i_value = AD_VERSION2_OSX;
430 #endif
431     } else if (optionok(tmp, "options:", val)) {
432         char *p;
433
434         if ((p = strtok(val + 1, ",")) == NULL) /* nothing */
435             return;
436
437         while (p) {
438             if (strcasecmp(p, "prodos") == 0)
439                 options[VOLOPT_FLAGS].i_value |= AFPVOL_A2VOL;
440             else if (strcasecmp(p, "mswindows") == 0) {
441                 options[VOLOPT_FLAGS].i_value |= AFPVOL_MSWINDOWS | AFPVOL_USEDOTS;
442             } else if (strcasecmp(p, "crlf") == 0)
443                 options[VOLOPT_FLAGS].i_value |= AFPVOL_CRLF;
444             else if (strcasecmp(p, "noadouble") == 0)
445                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOADOUBLE;
446             else if (strcasecmp(p, "ro") == 0)
447                 options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
448             else if (strcasecmp(p, "nohex") == 0)
449                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOHEX;
450             else if (strcasecmp(p, "usedots") == 0)
451                 options[VOLOPT_FLAGS].i_value |= AFPVOL_USEDOTS;
452             else if (strcasecmp(p, "limitsize") == 0)
453                 options[VOLOPT_FLAGS].i_value |= AFPVOL_LIMITSIZE;
454             /* support for either "dropbox" or "dropkludge" */
455             else if (strcasecmp(p, "dropbox") == 0)
456                 options[VOLOPT_FLAGS].i_value |= AFPVOL_DROPBOX;
457             else if (strcasecmp(p, "dropkludge") == 0)
458                 options[VOLOPT_FLAGS].i_value |= AFPVOL_DROPBOX;
459             else if (strcasecmp(p, "nofileid") == 0)
460                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOFILEID;
461             else if (strcasecmp(p, "nostat") == 0)
462                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOSTAT;
463             else if (strcasecmp(p, "preexec_close") == 0)
464                 options[VOLOPT_PREEXEC].i_value = 1;
465             else if (strcasecmp(p, "root_preexec_close") == 0)
466                 options[VOLOPT_ROOTPREEXEC].i_value = 1;
467             else if (strcasecmp(p, "upriv") == 0)
468                 options[VOLOPT_FLAGS].i_value |= AFPVOL_UNIX_PRIV;
469             else if (strcasecmp(p, "nodev") == 0)
470                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NODEV;
471             else if (strcasecmp(p, "cachecnid") == 0)
472                 options[VOLOPT_FLAGS].i_value |= AFPVOL_CACHE;
473
474             p = strtok(NULL, ",");
475         }
476
477     } else if (optionok(tmp, "dbpath:", val)) {
478         setoption(options, save, VOLOPT_DBPATH, val);
479
480     } else if (optionok(tmp, "umask:", val)) {
481         options[VOLOPT_UMASK].i_value = (int)strtol(val, (char **)NULL, 8);
482     } else if (optionok(tmp, "mapchars:",val)) {
483         setoption(options, save, VOLOPT_MAPCHARS, val);
484
485     } else if (optionok(tmp, "password:", val)) {
486         setoption(options, save, VOLOPT_PASSWORD, val);
487
488 #ifdef FORCE_UIDGID
489
490         /* this code allows forced uid/gid per volume settings */
491     } else if (optionok(tmp, "forceuid:", val)) {
492         setoption(options, save, VOLOPT_FORCEUID, val);
493     } else if (optionok(tmp, "forcegid:", val)) {
494         setoption(options, save, VOLOPT_FORCEGID, val);
495
496 #endif /* FORCE_UIDGID */
497     } else if (optionok(tmp, "root_preexec:", val)) {
498         setoption(options, save, VOLOPT_ROOTPREEXEC, val);
499
500     } else if (optionok(tmp, "preexec:", val)) {
501         setoption(options, save, VOLOPT_PREEXEC, val);
502
503     } else if (optionok(tmp, "root_postexec:", val)) {
504         setoption(options, save, VOLOPT_ROOTPOSTEXEC, val);
505
506     } else if (optionok(tmp, "postexec:", val)) {
507         setoption(options, save, VOLOPT_POSTEXEC, val);
508
509     } else {
510         /* ignore unknown options */
511         LOG(log_debug, logtype_afpd, "ignoring unknown volume option: %s", tmp);
512
513     } 
514 }
515
516 /* ----------------- */
517 static void showvol(const ucs2_t *name)
518 {
519     struct vol  *volume;
520     for ( volume = Volumes; volume; volume = volume->v_next ) {
521         if (volume->v_hide && !strcasecmp_w( volume->v_name, name ) ) {
522             volume->v_hide = 0;
523             return;
524         }
525     }
526 }
527
528 /* ----------------- 
529  * FIXME should be define elsewhere
530 */
531 static int validupath_adouble(const struct vol *vol, const char *name) 
532 {
533     return (vol->v_flags & AFPVOL_USEDOTS) ? strncasecmp(name,".Apple", 6) && strcasecmp(name, ".Parent")
534                                            : name[0] != '.';
535 }                                           
536
537 /* ----------------- */
538 static int validupath_osx(const struct vol *vol, const char *name) 
539 {
540     return strncasecmp(name,".Apple", 6) && strncasecmp(name,"._", 2);
541 }             
542
543 /* ---------------- */
544 static void initvoladouble(struct vol *vol)
545 {
546     if (vol->v_adouble == AD_VERSION2_OSX) {
547         vol->validupath  = validupath_osx;
548         vol->ad_path     = ad_path_osx;
549     }
550     else {
551         vol->validupath  = validupath_adouble;
552         vol->ad_path     = ad_path;
553     }
554 }
555
556 /* ------------------------------- */
557 static int creatvol(AFPObj *obj, struct passwd *pwd, 
558                     char *path, char *name, 
559                     struct vol_option *options, 
560                     const int user /* user defined volume */
561                     )
562 {
563     struct vol  *volume;
564     int         vlen;
565     int         hide = 0;
566     ucs2_t      tmpname[512];
567
568     if ( name == NULL || *name == '\0' ) {
569         if ((name = strrchr( path, '/' )) == NULL) {
570             return -1;  /* Obviously not a fully qualified path */
571         }
572
573         /* if you wish to share /, you need to specify a name. */
574         if (*++name == '\0')
575             return -1;
576     }
577
578     vlen = strlen( name );
579     if ( vlen > AFPVOL_NAMELEN ) {
580         vlen = AFPVOL_NAMELEN;
581         name[AFPVOL_NAMELEN] = '\0';
582     }
583
584     /* convert name to UCS2 first */
585     if ( 0 >= ( vlen = convert_string(obj->options.unixcharset, CH_UCS2, name, vlen, tmpname, 512)) )
586         return -1;
587
588     for ( volume = Volumes; volume; volume = volume->v_next ) {
589         if ( strcasecmp_w( volume->v_name, tmpname ) == 0 ) {
590            if (volume->v_deleted) {
591                hide = 1;
592            }
593            else {
594                return -1;       /* Won't be able to access it, anyway... */
595            }
596         }
597     }
598
599
600     if (!( volume = (struct vol *)calloc(1, sizeof( struct vol ))) ) {
601         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
602         return -1;
603     }
604     if ( NULL == ( volume->v_name = strdup_w(tmpname))) {
605         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
606         free(volume);
607         return -1;
608     }
609     if (!( volume->v_path = (char *)malloc( strlen( path ) + 1 )) ) {
610         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
611         free(volume->v_name);
612         free(volume);
613         return -1;
614     }
615     volume->v_hide = hide;
616     strcpy( volume->v_path, path );
617
618 #ifdef __svr4__
619     volume->v_qfd = -1;
620 #endif /* __svr4__ */
621     /* os X start at 1 and use network order ie. 1 2 3 */
622     volume->v_vid = ++lastvid;
623     volume->v_vid = htons(volume->v_vid);
624
625     /* handle options */
626     if (options) {
627         /* should we casefold? */
628         volume->v_casefold = options[VOLOPT_CASEFOLD].i_value;
629
630         /* shift in some flags */
631         volume->v_flags = options[VOLOPT_FLAGS].i_value;
632
633         volume->v_ad_options = 0;
634         if ((volume->v_flags & AFPVOL_NODEV))
635             volume->v_ad_options |= ADVOL_NODEV;
636         if ((volume->v_flags & AFPVOL_CACHE))
637             volume->v_ad_options |= ADVOL_CACHE;
638         if ((volume->v_flags & AFPVOL_UNIX_PRIV))
639             volume->v_ad_options |= ADVOL_UNIXPRIV;
640
641         if (options[VOLOPT_PASSWORD].c_value)
642             volume->v_password = strdup(options[VOLOPT_PASSWORD].c_value);
643
644         if (options[VOLOPT_VETO].c_value)
645             volume->v_veto = strdup(options[VOLOPT_VETO].c_value);
646
647         if (options[VOLOPT_ENCODING].c_value)
648             volume->v_volcodepage = strdup(options[VOLOPT_ENCODING].c_value);
649
650         if (options[VOLOPT_MACCHARSET].c_value)
651             volume->v_maccodepage = strdup(options[VOLOPT_MACCHARSET].c_value);
652
653         if (options[VOLOPT_DBPATH].c_value)
654             volume->v_dbpath = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_DBPATH].c_value, pwd, path, name);
655
656        if (options[VOLOPT_CNIDSCHEME].c_value)
657            volume->v_cnidscheme = strdup(options[VOLOPT_CNIDSCHEME].c_value);
658
659         if (options[VOLOPT_UMASK].i_value)
660             volume->v_umask = (mode_t)options[VOLOPT_UMASK].i_value;
661
662         if (options[VOLOPT_ADOUBLE].i_value)
663             volume->v_adouble = options[VOLOPT_ADOUBLE].i_value;
664         else 
665             volume->v_adouble = AD_VERSION;
666 #ifdef FORCE_UIDGID
667         if (options[VOLOPT_FORCEUID].c_value) {
668             volume->v_forceuid = strdup(options[VOLOPT_FORCEUID].c_value);
669         } else {
670             volume->v_forceuid = NULL; /* set as null so as to return 0 later on */
671         }
672
673         if (options[VOLOPT_FORCEGID].c_value) {
674             volume->v_forcegid = strdup(options[VOLOPT_FORCEGID].c_value);
675         } else {
676             volume->v_forcegid = NULL; /* set as null so as to return 0 later on */
677         }
678 #endif
679         if (!user) {
680             if (options[VOLOPT_PREEXEC].c_value)
681                 volume->v_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_PREEXEC].c_value, pwd, path, name);
682             volume->v_preexec_close = options[VOLOPT_PREEXEC].i_value;
683
684             if (options[VOLOPT_POSTEXEC].c_value)
685                 volume->v_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_POSTEXEC].c_value, pwd, path, name);
686
687             if (options[VOLOPT_ROOTPREEXEC].c_value)
688                 volume->v_root_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPREEXEC].c_value, pwd, path,  name);
689             volume->v_root_preexec_close = options[VOLOPT_ROOTPREEXEC].i_value;
690
691             if (options[VOLOPT_ROOTPOSTEXEC].c_value)
692                 volume->v_root_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPOSTEXEC].c_value, pwd, path,  name);
693         }
694     }
695
696     initvoladouble(volume);
697     volume->v_next = Volumes;
698     Volumes = volume;
699     return 0;
700 }
701
702 /* ---------------- */
703 static char *myfgets( buf, size, fp )
704 char    *buf;
705 int             size;
706 FILE    *fp;
707 {
708     char        *p;
709     int         c;
710
711     p = buf;
712     while ((EOF != ( c = getc( fp )) ) && ( size > 0 )) {
713         if ( c == '\n' || c == '\r' ) {
714             *p++ = '\n';
715             break;
716         } else {
717             *p++ = c;
718         }
719         size--;
720     }
721
722     if ( p == buf ) {
723         return( NULL );
724     } else {
725         *p = '\0';
726         return( buf );
727     }
728 }
729
730
731 /* check access list. this function wants something of the following
732  * form:
733  *        @group,name,name2,@group2,name3
734  *
735  * a NULL argument allows everybody to have access.
736  * we return three things:
737  *     -1: no list
738  *      0: list exists, but name isn't in it
739  *      1: in list
740  */
741
742 #ifndef NO_REAL_USER_NAME
743 /* authentication is case insensitive 
744  * FIXME should we do the same with group name?
745 */
746 #define access_strcmp strcasecmp
747
748 #else
749 #define access_strcmp strcmp
750
751 #endif
752
753 static int accessvol(args, name)
754 const char *args;
755 const char *name;
756 {
757     char buf[MAXPATHLEN + 1], *p;
758     struct group *gr;
759
760     if (!args)
761         return -1;
762
763     strlcpy(buf, args, sizeof(buf));
764     if ((p = strtok(buf, ",")) == NULL) /* nothing, return okay */
765         return -1;
766
767     while (p) {
768         if (*p == '@') { /* it's a group */
769             if ((gr = getgrnam(p + 1)) && gmem(gr->gr_gid))
770                 return 1;
771         } else if (access_strcmp(p, name) == 0) /* it's a user name */
772             return 1;
773         p = strtok(NULL, ",");
774     }
775
776     return 0;
777 }
778
779 static void setextmap( ext, type, creator, user)
780 char            *ext, *type, *creator;
781 int                     user;
782 {
783     struct extmap       *em;
784     int                 cnt;
785
786     if (Extmap == NULL) {
787         if (( Extmap = calloc(1, sizeof( struct extmap ))) == NULL ) {
788             LOG(log_error, logtype_afpd, "setextmap: calloc: %s", strerror(errno) );
789             return;
790         }
791     }
792     ext++;
793     for ( em = Extmap, cnt = 0; em->em_ext; em++, cnt++) {
794         if ( (strdiacasecmp( em->em_ext, ext )) == 0 ) {
795             break;
796         }
797     }
798
799     if ( em->em_ext == NULL ) {
800         if (!(Extmap  = realloc( Extmap, sizeof( struct extmap ) * (cnt +2))) ) {
801             LOG(log_error, logtype_afpd, "setextmap: realloc: %s", strerror(errno) );
802             return;
803         }
804         (Extmap +cnt +1)->em_ext = NULL;
805         em = Extmap +cnt;
806     } else if ( !user ) {
807         return;
808     }
809     if (em->em_ext)
810         free(em->em_ext);
811
812     if (!(em->em_ext = strdup(  ext))) {
813         LOG(log_error, logtype_afpd, "setextmap: strdup: %s", strerror(errno) );
814         return;
815     }
816
817     if ( *type == '\0' ) {
818         memcpy(em->em_type, "????", sizeof( em->em_type ));
819     } else {
820         memcpy(em->em_type, type, sizeof( em->em_type ));
821     }
822     if ( *creator == '\0' ) {
823         memcpy(em->em_creator, "UNIX", sizeof( em->em_creator ));
824     } else {
825         memcpy(em->em_creator, creator, sizeof( em->em_creator ));
826     }
827 }
828
829 /* -------------------------- */
830 static int extmap_cmp(const void *map1, const void *map2)
831 {
832     const struct extmap *em1 = map1;
833     const struct extmap *em2 = map2;
834     return strdiacasecmp(em1->em_ext, em2->em_ext);
835 }
836
837 static void sortextmap( void)
838 {
839     struct extmap       *em;
840
841     Extmap_cnt = 0;
842     if ((em = Extmap) == NULL) {
843         return;
844     }
845     while (em->em_ext) {
846         em++;
847         Extmap_cnt++;
848     }
849     if (Extmap_cnt) {
850         qsort(Extmap, Extmap_cnt, sizeof(struct extmap), extmap_cmp);
851         if (*Extmap->em_ext == 0) {
852             /* the first line is really "." the default entry, 
853              * we remove the leading '.' in setextmap
854             */
855             Defextmap = Extmap;
856         }
857     }
858 }
859
860 /* ----------------------
861 */
862 static void free_extmap( void)
863 {
864     struct extmap       *em;
865
866     if (Extmap) {
867         for ( em = Extmap; em->em_ext; em++) {
868              free (em->em_ext);
869         }
870         free(Extmap);
871         Extmap = NULL;
872         Defextmap = Extmap;
873         Extmap_cnt = 0;
874     }
875 }
876
877 /* ----------------------
878 */
879 static int volfile_changed(struct afp_volume_name *p) 
880 {
881     struct stat      st;
882     char *name;
883     
884     if (p->full_name) 
885         name = p->full_name;
886     else
887         name = p->name;
888         
889     if (!stat( name, &st) && st.st_mtime > p->mtime) {
890         p->mtime = st.st_mtime;
891         return 1;
892     }
893     return 0;
894 }
895
896 /* ----------------------
897  * Read a volume configuration file and add the volumes contained within to
898  * the global volume list.  If p2 is non-NULL, the file that is opened is
899  * p1/p2
900  * 
901  * Lines that begin with # and blank lines are ignored.
902  * Volume lines are of the form:
903  *              <unix path> [<volume name>] [allow:<user>,<@group>,...] \
904  *                           [codepage:<file>] [casefold:<num>]
905  *              <extension> TYPE [CREATOR]
906  */
907 static int readvolfile(obj, p1, p2, user, pwent)
908 AFPObj      *obj;
909 struct afp_volume_name  *p1;
910 char        *p2;
911 int             user;
912 struct passwd *pwent;
913 {
914     FILE                *fp;
915     char                path[ MAXPATHLEN + 1], tmp[ MAXPATHLEN + 1],
916     volname[ AFPVOL_NAMELEN + 1 ], buf[ BUFSIZ ],
917     type[ 5 ], creator[ 5 ];
918     char                *u, *p;
919     struct passwd       *pw;
920     struct vol_option   options[VOLOPT_NUM], save_options[VOLOPT_NUM];
921     int                 i;
922     struct stat         st;
923     int                 fd;
924
925     if (!p1->name)
926         return -1;
927     p1->mtime = 0;
928     strcpy( path, p1->name );
929     if ( p2 != NULL ) {
930         strcat( path, "/" );
931         strcat( path, p2 );
932         if (p1->full_name) {
933             free(p1->full_name);
934         }
935         p1->full_name = strdup(path);
936     }
937
938     if (NULL == ( fp = fopen( path, "r" )) ) {
939         return( -1 );
940     }
941     fd = fileno(fp);
942     if (fd != -1 && !fstat( fd, &st) ) {
943         p1->mtime = st.st_mtime;
944     }
945
946     memset(save_options, 0, sizeof(save_options));
947     while ( myfgets( buf, sizeof( buf ), fp ) != NULL ) {
948         initline( strlen( buf ), buf );
949         parseline( sizeof( path ) - 1, path );
950         switch ( *path ) {
951         case '\0' :
952         case '#' :
953             continue;
954
955         case ':':
956             /* change the default options for this file */
957             if (strncmp(path, VOLOPT_DEFAULT, VOLOPT_DEFAULT_LEN) == 0) {
958                 *tmp = '\0';
959                 for (i = 0; i < VOLOPT_NUM; i++) {
960                     if (parseline( sizeof( path ) - VOLOPT_DEFAULT_LEN - 1,
961                                    path + VOLOPT_DEFAULT_LEN) < 0)
962                         break;
963                     volset(save_options, NULL, tmp, sizeof(tmp) - 1,
964                            path + VOLOPT_DEFAULT_LEN);
965                 }
966             }
967             break;
968
969         case '~' :
970             if (( p = strchr( path, '/' )) != NULL ) {
971                 *p++ = '\0';
972             }
973             u = path;
974             u++;
975             if ( *u == '\0' ) {
976                 u = obj->username;
977             }
978             if ( u == NULL || *u == '\0' || ( pw = getpwnam( u )) == NULL ) {
979                 continue;
980             }
981             strcpy( tmp, pw->pw_dir );
982             if ( p != NULL && *p != '\0' ) {
983                 strcat( tmp, "/" );
984                 strcat( tmp, p );
985             }
986             /* Tag a user's home directory with their umask.  Note, this will
987              * be overwritten if the user actually specifies a umask: option
988              * for a '~' volume. */
989             save_options[VOLOPT_UMASK].i_value = obj->options.save_mask;
990             /* fall through */
991
992         case '/' :
993             /* send path through variable substitution */
994             if (*path != '~') /* need to copy path to tmp */
995                 strcpy(tmp, path);
996             if (!pwent)
997                 pwent = getpwnam(obj->username);
998             volxlate(obj, path, sizeof(path) - 1, tmp, pwent, NULL, NULL);
999
1000             /* this is sort of braindead. basically, i want to be
1001              * able to specify things in any order, but i don't want to 
1002              * re-write everything. 
1003              *
1004              * currently we have options: 
1005              *   volname
1006              *   codepage:x
1007              *   casefold:x
1008              *   allow:x,y,@z
1009              *   deny:x,y,@z
1010              *   rwlist:x,y,@z
1011              *   rolist:x,y,@z
1012              *   options:prodos,crlf,noadouble,ro...
1013              *   dbpath:x
1014              *   password:x
1015              *   preexec:x
1016              *
1017              *   namemask:x,y,!z  (not implemented yet)
1018              */
1019             memcpy(options, save_options, sizeof(options));
1020             *volname = '\0';
1021
1022             /* read in up to VOLOP_NUM possible options */
1023             for (i = 0; i < VOLOPT_NUM; i++) {
1024                 if (parseline( sizeof( tmp ) - 1, tmp ) < 0)
1025                     break;
1026
1027                 volset(options, save_options, volname, sizeof(volname) - 1, tmp);
1028             }
1029
1030             /* check allow/deny lists:
1031                allow -> either no list (-1), or in list (1)
1032                deny -> either no list (-1), or not in list (0) */
1033             if (accessvol(options[VOLOPT_ALLOW].c_value, obj->username) &&
1034                     (accessvol(options[VOLOPT_DENY].c_value, obj->username) < 1)) {
1035
1036                 /* handle read-only behaviour. semantics:
1037                  * 1) neither the rolist nor the rwlist exist -> rw
1038                  * 2) rolist exists -> ro if user is in it.
1039                  * 3) rwlist exists -> ro unless user is in it. */
1040                 if (((options[VOLOPT_FLAGS].i_value & AFPVOL_RO) == 0) &&
1041                         ((accessvol(options[VOLOPT_ROLIST].c_value,
1042                                     obj->username) == 1) ||
1043                          !accessvol(options[VOLOPT_RWLIST].c_value,
1044                                     obj->username)))
1045                     options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
1046
1047                 /* do variable substitution for volname */
1048                 volxlate(obj, tmp, sizeof(tmp) - 1, volname, pwent, path, NULL);
1049                 creatvol(obj, pwent, path, tmp, options, p2 != NULL);
1050             }
1051             volfree(options, save_options);
1052             break;
1053
1054         case '.' :
1055             parseline( sizeof( type ) - 1, type );
1056             parseline( sizeof( creator ) - 1, creator );
1057             setextmap( path, type, creator, user);
1058             break;
1059
1060         default :
1061             break;
1062         }
1063     }
1064     volfree(save_options, NULL);
1065     sortextmap();
1066     if ( fclose( fp ) != 0 ) {
1067         LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
1068     }
1069     p1->loaded = 1;
1070     return( 0 );
1071 }
1072
1073 /* ------------------------------- */
1074 static void volume_free(struct vol *vol)
1075 {
1076     free(vol->v_name);
1077     vol->v_name = NULL;
1078     free(vol->v_path);
1079     free(vol->v_password);
1080     free(vol->v_veto);
1081     free(vol->v_volcodepage);
1082     free(vol->v_maccodepage);
1083     free(vol->v_cnidscheme);
1084     free(vol->v_dbpath);
1085     free(vol->v_gvs);
1086 #ifdef FORCE_UIDGID
1087     free(vol->v_forceuid);
1088     free(vol->v_forcegid);
1089 #endif /* FORCE_UIDGID */
1090 }
1091
1092 /* ------------------------------- */
1093 static void free_volumes(void )
1094 {
1095     struct vol  *vol;
1096     struct vol  *nvol, *ovol;
1097
1098     for ( vol = Volumes; vol; vol = vol->v_next ) {
1099         if (( vol->v_flags & AFPVOL_OPEN ) ) {
1100             vol->v_deleted = 1;
1101             continue;
1102         }
1103         volume_free(vol);
1104     }
1105
1106     for ( vol = Volumes, ovol = NULL; vol; vol = nvol) {
1107         nvol = vol->v_next;
1108
1109         if (vol->v_name == NULL) {
1110            if (Volumes == vol) {
1111                Volumes = nvol;
1112                ovol = Volumes;
1113            }
1114            else {
1115               ovol->v_next = nvol;
1116            }
1117            free(vol);
1118         }
1119         else {
1120            ovol = vol;
1121         }
1122     }
1123 }
1124
1125 /* ------------------------------- */
1126 static void volume_unlink(struct vol *volume)
1127 {
1128 struct vol *vol, *ovol, *nvol;
1129
1130     if (volume == Volumes) {
1131         Volumes = Volumes->v_next;
1132         return;
1133     }
1134     for ( vol = Volumes->v_next, ovol = Volumes; vol; vol = nvol) {
1135         nvol = vol->v_next;
1136
1137         if (vol == volume) {
1138             ovol->v_next = nvol;
1139             break;
1140         }
1141         else {
1142            ovol = vol;
1143         }
1144     }
1145 }
1146
1147 static int getvolspace( vol, bfree, btotal, xbfree, xbtotal, bsize )
1148 struct vol      *vol;
1149 u_int32_t       *bfree, *btotal, *bsize;
1150 VolSpace    *xbfree, *xbtotal;
1151 {
1152     int         spaceflag, rc;
1153     u_int32_t   maxsize;
1154 #ifndef NO_QUOTA_SUPPORT
1155     VolSpace    qfree, qtotal;
1156 #endif
1157
1158     spaceflag = AFPVOL_GVSMASK & vol->v_flags;
1159     /* report up to 2GB if afp version is < 2.2 (4GB if not) */
1160     maxsize = (vol->v_flags & AFPVOL_A2VOL) ? 0x01fffe00 :
1161               (((afp_version < 22) || (vol->v_flags & AFPVOL_LIMITSIZE))
1162                ? 0x7fffffffL : 0xffffffffL);
1163
1164 #ifdef AFS
1165     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_AFSGVS ) {
1166         if ( afs_getvolspace( vol, xbfree, xbtotal, bsize ) == AFP_OK ) {
1167             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_AFSGVS;
1168             goto getvolspace_done;
1169         }
1170     }
1171 #endif
1172
1173     if (( rc = ustatfs_getvolspace( vol, xbfree, xbtotal,
1174                                     bsize)) != AFP_OK ) {
1175         return( rc );
1176     }
1177
1178 #define min(a,b)        ((a)<(b)?(a):(b))
1179 #ifndef NO_QUOTA_SUPPORT
1180     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_UQUOTA ) {
1181         if ( uquota_getvolspace( vol, &qfree, &qtotal, *bsize ) == AFP_OK ) {
1182             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_UQUOTA;
1183             *xbfree = min(*xbfree, qfree);
1184             *xbtotal = min( *xbtotal, qtotal);
1185             goto getvolspace_done;
1186         }
1187     }
1188 #endif
1189     vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_USTATFS;
1190
1191 getvolspace_done:
1192     *bfree = min( *xbfree, maxsize);
1193     *btotal = min( *xbtotal, maxsize);
1194     return( AFP_OK );
1195 }
1196
1197 /* ----------------------- 
1198  * set volume creation date
1199  * avoid duplicate, well at least it tries
1200 */
1201 static void vol_setdate(u_int16_t id, struct adouble *adp, time_t date)
1202 {
1203     struct vol  *volume;
1204     struct vol  *vol = Volumes;
1205
1206     for ( volume = Volumes; volume; volume = volume->v_next ) {
1207         if (volume->v_vid == id) {
1208             vol = volume;
1209         }
1210         else if (AD_DATE_FROM_UNIX(date) == volume->v_ctime) {
1211             date = date+1;
1212             volume = Volumes; /* restart */
1213         }
1214     }
1215     vol->v_ctime = AD_DATE_FROM_UNIX(date);
1216     ad_setdate(adp, AD_DATE_CREATE | AD_DATE_UNIX, date);
1217 }
1218
1219 /* ----------------------- */
1220 static int getvolparams( bitmap, vol, st, buf, buflen )
1221 u_int16_t       bitmap;
1222 struct vol      *vol;
1223 struct stat     *st;
1224 char    *buf;
1225 int             *buflen;
1226 {
1227     struct adouble      ad;
1228     int                 bit = 0, isad = 1;
1229     u_int32_t           aint;
1230     u_short             ashort;
1231     u_int32_t           bfree, btotal, bsize;
1232     VolSpace            xbfree, xbtotal; /* extended bytes */
1233     char                *data, *nameoff = NULL;
1234     char                *slash;
1235
1236     /* courtesy of jallison@whistle.com:
1237      * For MacOS8.x support we need to create the
1238      * .Parent file here if it doesn't exist. */
1239
1240     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1241     if ( ad_open( vol->v_path, vol_noadouble(vol) |
1242                   ADFLAGS_HF|ADFLAGS_DIR, O_RDWR | O_CREAT,
1243                   0666, &ad) < 0 ) {
1244         isad = 0;
1245         vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1246
1247     } else if (ad_get_HF_flags( &ad ) & O_CREAT) {
1248         slash = strrchr( vol->v_path, '/' );
1249         if(slash)
1250             slash++;
1251         else
1252             slash = vol->v_path;
1253         if (ad_getentryoff(&ad, ADEID_NAME)) {
1254             ad_setentrylen( &ad, ADEID_NAME, strlen( slash ));
1255             memcpy(ad_entry( &ad, ADEID_NAME ), slash,
1256                ad_getentrylen( &ad, ADEID_NAME ));
1257         }
1258         vol_setdate(vol->v_vid, &ad, st->st_mtime);
1259         ad_flush(&ad, ADFLAGS_HF);
1260     }
1261     else {
1262         if (ad_getdate(&ad, AD_DATE_CREATE, &aint) < 0)
1263             vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1264         else 
1265             vol->v_ctime = aint;
1266     }
1267
1268     if (( bitmap & ( (1<<VOLPBIT_BFREE)|(1<<VOLPBIT_BTOTAL) |
1269                      (1<<VOLPBIT_XBFREE)|(1<<VOLPBIT_XBTOTAL) |
1270                      (1<<VOLPBIT_BSIZE)) ) != 0 ) {
1271         if ( getvolspace( vol, &bfree, &btotal, &xbfree, &xbtotal,
1272                           &bsize) < 0 ) {
1273             if ( isad ) {
1274                 ad_close( &ad, ADFLAGS_HF );
1275             }
1276             return( AFPERR_PARAM );
1277         }
1278     }
1279
1280     data = buf;
1281     while ( bitmap != 0 ) {
1282         while (( bitmap & 1 ) == 0 ) {
1283             bitmap = bitmap>>1;
1284             bit++;
1285         }
1286
1287         switch ( bit ) {
1288         case VOLPBIT_ATTR :
1289             ashort = 0;
1290             if (0 == (vol->v_flags & AFPVOL_NOFILEID) && vol->v_cdb != NULL &&
1291                            (vol->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
1292                 ashort = VOLPBIT_ATTR_FILEID;
1293             }
1294             /* check for read-only.
1295              * NOTE: we don't actually set the read-only flag unless
1296              *       it's passed in that way as it's possible to mount
1297              *       a read-write filesystem under a read-only one. */
1298             if ((vol->v_flags & AFPVOL_RO) ||
1299                     ((utime(vol->v_path, NULL) < 0) && (errno == EROFS))) {
1300                 ashort |= VOLPBIT_ATTR_RO;
1301             }
1302             ashort |= VOLPBIT_ATTR_CATSEARCH;
1303             if (afp_version >= 30) {
1304                 ashort |= VOLPBIT_ATTR_UTF8;
1305                 if (vol->v_flags & AFPVOL_UNIX_PRIV)
1306                     ashort |= VOLPBIT_ATTR_UNIXPRIV;
1307             }
1308             ashort = htons(ashort);
1309             memcpy(data, &ashort, sizeof( ashort ));
1310             data += sizeof( ashort );
1311             break;
1312
1313         case VOLPBIT_SIG :
1314             ashort = htons( AFPVOLSIG_DEFAULT );
1315             memcpy(data, &ashort, sizeof( ashort ));
1316             data += sizeof( ashort );
1317             break;
1318
1319         case VOLPBIT_CDATE :
1320             aint = vol->v_ctime;
1321             memcpy(data, &aint, sizeof( aint ));
1322             data += sizeof( aint );
1323             break;
1324
1325         case VOLPBIT_MDATE :
1326             if ( st->st_mtime > vol->v_mtime ) {
1327                 vol->v_mtime = st->st_mtime;
1328             }
1329             aint = AD_DATE_FROM_UNIX(vol->v_mtime);
1330             memcpy(data, &aint, sizeof( aint ));
1331             data += sizeof( aint );
1332             break;
1333
1334         case VOLPBIT_BDATE :
1335             if (!isad ||  (ad_getdate(&ad, AD_DATE_BACKUP, &aint) < 0))
1336                 aint = AD_DATE_START;
1337             memcpy(data, &aint, sizeof( aint ));
1338             data += sizeof( aint );
1339             break;
1340
1341         case VOLPBIT_VID :
1342             memcpy(data, &vol->v_vid, sizeof( vol->v_vid ));
1343             data += sizeof( vol->v_vid );
1344             break;
1345
1346         case VOLPBIT_BFREE :
1347             bfree = htonl( bfree );
1348             memcpy(data, &bfree, sizeof( bfree ));
1349             data += sizeof( bfree );
1350             break;
1351
1352         case VOLPBIT_BTOTAL :
1353             btotal = htonl( btotal );
1354             memcpy(data, &btotal, sizeof( btotal ));
1355             data += sizeof( btotal );
1356             break;
1357
1358 #ifndef NO_LARGE_VOL_SUPPORT
1359         case VOLPBIT_XBFREE :
1360             xbfree = hton64( xbfree );
1361 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1362             bcopy(&xbfree, data, sizeof(xbfree));
1363 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1364             memcpy(data, &xbfree, sizeof( xbfree ));
1365 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1366             data += sizeof( xbfree );
1367             break;
1368
1369         case VOLPBIT_XBTOTAL :
1370             xbtotal = hton64( xbtotal );
1371 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1372             bcopy(&xbtotal, data, sizeof(xbtotal));
1373 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1374             memcpy(data, &xbtotal, sizeof( xbtotal ));
1375 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1376             data += sizeof( xbfree );
1377             break;
1378 #endif /* ! NO_LARGE_VOL_SUPPORT */
1379
1380         case VOLPBIT_NAME :
1381             nameoff = data;
1382             data += sizeof( u_int16_t );
1383             break;
1384
1385         case VOLPBIT_BSIZE:  /* block size */
1386             bsize = htonl(bsize);
1387             memcpy(data, &bsize, sizeof(bsize));
1388             data += sizeof(bsize);
1389             break;
1390
1391         default :
1392             if ( isad ) {
1393                 ad_close( &ad, ADFLAGS_HF );
1394             }
1395             return( AFPERR_BITMAP );
1396         }
1397         bitmap = bitmap>>1;
1398         bit++;
1399     }
1400     if ( nameoff ) {
1401         ashort = htons( data - buf );
1402         memcpy(nameoff, &ashort, sizeof( ashort ));
1403         aint = ucs2_to_charset( (utf8_encoding()?CH_UTF8_MAC:vol->v_maccharset), vol->v_name, data+1, 255);
1404         if ( aint <= 0 ) {
1405             *buflen = 0;
1406             return AFPERR_MISC;
1407         }
1408                 
1409         *data++ = aint;
1410         data += aint;
1411     }
1412     if ( isad ) {
1413         ad_close( &ad, ADFLAGS_HF );
1414     }
1415     *buflen = data - buf;
1416     return( AFP_OK );
1417 }
1418
1419 /* ------------------------- */
1420 static int stat_vol(u_int16_t bitmap, struct vol *vol, char *rbuf, int *rbuflen)
1421 {
1422     struct stat st;
1423     int         buflen, ret;
1424
1425     if ( stat( vol->v_path, &st ) < 0 ) {
1426         *rbuflen = 0;
1427         return( AFPERR_PARAM );
1428     }
1429     /* save the volume device number */
1430     vol->v_dev = st.st_dev;
1431
1432     buflen = *rbuflen - sizeof( bitmap );
1433     if (( ret = getvolparams( bitmap, vol, &st,
1434                               rbuf + sizeof( bitmap ), &buflen )) != AFP_OK ) {
1435         *rbuflen = 0;
1436         return( ret );
1437     }
1438     *rbuflen = buflen + sizeof( bitmap );
1439     bitmap = htons( bitmap );
1440     memcpy(rbuf, &bitmap, sizeof( bitmap ));
1441     return( AFP_OK );
1442
1443 }
1444
1445 /* ------------------------------- */
1446 void load_volumes(AFPObj *obj)
1447 {
1448     struct passwd       *pwent;
1449
1450     if (Volumes) {
1451         int changed = 0;
1452         
1453         /* check files date */
1454         if (obj->options.defaultvol.loaded) {
1455             changed = volfile_changed(&obj->options.defaultvol);
1456         }
1457         if (obj->options.systemvol.loaded) {
1458             changed |= volfile_changed(&obj->options.systemvol);
1459         }
1460         if (obj->options.uservol.loaded) {
1461             changed |= volfile_changed(&obj->options.uservol);
1462         }
1463         if (!changed)
1464             return;
1465         
1466         free_extmap();
1467         free_volumes();
1468     }
1469     
1470     pwent = getpwnam(obj->username);
1471     if ( (obj->options.flags & OPTION_USERVOLFIRST) == 0 ) {
1472         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent);
1473     }
1474
1475     if ((*obj->username == '\0') || (obj->options.flags & OPTION_NOUSERVOL)) {
1476         readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent);
1477     } else if (pwent) {
1478         /*
1479         * Read user's AppleVolumes or .AppleVolumes file
1480         * If neither are readable, read the default volumes file. if
1481         * that doesn't work, create a user share.
1482         */
1483         if (obj->options.uservol.name) {
1484             free(obj->options.uservol.name);
1485         }
1486         obj->options.uservol.name = strdup(pwent->pw_dir);
1487         if ( readvolfile(obj, &obj->options.uservol,    "AppleVolumes", 1, pwent) < 0 &&
1488                 readvolfile(obj, &obj->options.uservol, ".AppleVolumes", 1, pwent) < 0 &&
1489                 readvolfile(obj, &obj->options.uservol, "applevolumes", 1, pwent) < 0 &&
1490                 readvolfile(obj, &obj->options.uservol, ".applevolumes", 1, pwent) < 0 &&
1491                 obj->options.defaultvol.name != NULL ) {
1492             if (readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent) < 0)
1493                 creatvol(obj, pwent, pwent->pw_dir, NULL, NULL, 1);
1494         }
1495     }
1496     if ( obj->options.flags & OPTION_USERVOLFIRST ) {
1497         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent );
1498     }
1499 }
1500
1501 /* ------------------------------- */
1502 int afp_getsrvrparms(obj, ibuf, ibuflen, rbuf, rbuflen )
1503 AFPObj      *obj;
1504 char    *ibuf, *rbuf;
1505 int     ibuflen, *rbuflen;
1506 {
1507     struct timeval      tv;
1508     struct stat         st;
1509     struct vol          *volume;
1510     char        *data;
1511     char                *namebuf;
1512     int                 vcnt;
1513     size_t              len;
1514
1515     load_volumes(obj);
1516
1517     data = rbuf + 5;
1518     for ( vcnt = 0, volume = Volumes; volume; volume = volume->v_next ) {
1519         if (!(volume->v_flags & AFPVOL_NOSTAT)) {
1520             if ( stat( volume->v_path, &st ) < 0 ) {
1521                 LOG(log_info, logtype_afpd, "afp_getsrvrparms(%s): stat: %s",
1522                         volume->v_path, strerror(errno) );
1523                 continue;               /* can't access directory */
1524             }
1525             if (!S_ISDIR(st.st_mode)) {
1526                 continue;               /* not a dir */
1527             }
1528         }
1529         if (volume->v_hide) {
1530             continue;           /* config file changed but the volume was mounted */
1531         }
1532         len = ucs2_to_charset_allocate((utf8_encoding()?CH_UTF8_MAC:obj->options.maccharset),
1533                                         &namebuf, volume->v_name);
1534         if (len == (size_t)-1)
1535                 continue;
1536
1537         /* set password bit if there's a volume password */
1538         *data = (volume->v_password) ? AFPSRVR_PASSWD : 0;
1539
1540         /* Apple 2 clients running ProDOS-8 expect one volume to have
1541            bit 0 of this byte set.  They will not recognize anything
1542            on the server unless this is the case.  I have not
1543            completely worked this out, but it's related to booting
1544            from the server.  Support for that function is a ways
1545            off.. <shirsch@ibm.net> */
1546         *data |= (volume->v_flags & AFPVOL_A2VOL) ? AFPSRVR_CONFIGINFO : 0;
1547         *data++ |= 0; /* UNIX PRIVS BIT ..., OSX doesn't seem to use it, so we don't either */
1548         *data++ = len;
1549         memcpy(data, namebuf, len );
1550         data += len;
1551         free(namebuf);
1552         vcnt++;
1553     }
1554
1555     *rbuflen = data - rbuf;
1556     data = rbuf;
1557     if ( gettimeofday( &tv, 0 ) < 0 ) {
1558         LOG(log_error, logtype_afpd, "afp_getsrvrparms(%s): gettimeofday: %s", volume->v_path, strerror(errno) );
1559         *rbuflen = 0;
1560         return AFPERR_PARAM;
1561     }
1562     tv.tv_sec = AD_DATE_FROM_UNIX(tv.tv_sec);
1563     memcpy(data, &tv.tv_sec, sizeof( u_int32_t));
1564     data += sizeof( u_int32_t);
1565     *data = vcnt;
1566     return( AFP_OK );
1567 }
1568
1569 /* ------------------------- 
1570  * we are the user here
1571 */
1572 int afp_openvol(obj, ibuf, ibuflen, rbuf, rbuflen )
1573 AFPObj      *obj;
1574 char    *ibuf, *rbuf;
1575 int             ibuflen, *rbuflen;
1576 {
1577     struct stat st;
1578     char        *volname;
1579     char        *p;
1580     struct vol  *volume;
1581     struct dir  *dir;
1582     int         len, ret;
1583     size_t      namelen;
1584     u_int16_t   bitmap;
1585     char        path[ MAXPATHLEN + 1];
1586     char        *vol_uname;
1587     char        *vol_mname;
1588
1589     ibuf += 2;
1590     memcpy(&bitmap, ibuf, sizeof( bitmap ));
1591     bitmap = ntohs( bitmap );
1592     ibuf += sizeof( bitmap );
1593     if (( bitmap & (1<<VOLPBIT_VID)) == 0 ) {
1594         *rbuflen = 0;
1595         return AFPERR_BITMAP;
1596     }
1597
1598     len = (unsigned char)*ibuf++;
1599     volname = obj->oldtmp;
1600     namelen = convert_string( (utf8_encoding()?CH_UTF8_MAC:obj->options.maccharset), CH_UCS2,
1601                               ibuf, len, volname, sizeof(obj->oldtmp));
1602     if ( namelen <= 0){
1603         *rbuflen = 0;
1604         return AFPERR_PARAM;
1605     }
1606
1607     ibuf += len;
1608     if ((len + 1) & 1) /* pad to an even boundary */
1609         ibuf++;
1610
1611     load_volumes(obj);
1612
1613     for ( volume = Volumes; volume; volume = volume->v_next ) {
1614         if ( strcasecmp_w( (ucs2_t*) volname, volume->v_name ) == 0 ) {
1615             break;
1616         }
1617     }
1618
1619     if ( volume == NULL ) {
1620         *rbuflen = 0;
1621         return AFPERR_PARAM;
1622     }
1623
1624     /* check for a volume password */
1625     if (volume->v_password && strncmp(ibuf, volume->v_password, VOLPASSLEN)) {
1626         *rbuflen = 0;
1627         return AFPERR_ACCESS;
1628     }
1629
1630     if (( volume->v_flags & AFPVOL_OPEN  ) ) {
1631         /* the volume is already open */
1632 #ifdef FORCE_UIDGID
1633         set_uidgid ( volume );
1634 #endif
1635         return stat_vol(bitmap, volume, rbuf, rbuflen);
1636     }
1637
1638     /* initialize volume variables
1639      * FIXME file size
1640     */
1641     if (afp_version >= 30) {
1642         volume->max_filename = 255;
1643     }
1644     else {
1645         volume->max_filename = MACFILELEN;
1646     }
1647
1648     volume->v_dir = volume->v_root = NULL;
1649
1650     volume->v_flags |= AFPVOL_OPEN;
1651     volume->v_cdb = NULL;  
1652
1653     if (volume->v_root_preexec) {
1654         if ((ret = afprun(1, volume->v_root_preexec, NULL)) && volume->v_root_preexec_close) {
1655             LOG(log_error, logtype_afpd, "afp_openvol(%s): root preexec : %d", volume->v_path, ret );
1656             ret = AFPERR_MISC;
1657             goto openvol_err;
1658         }
1659     }
1660
1661 #ifdef FORCE_UIDGID
1662     set_uidgid ( volume );
1663 #endif
1664
1665     if (volume->v_preexec) {
1666         if ((ret = afprun(0, volume->v_preexec, NULL)) && volume->v_preexec_close) {
1667             LOG(log_error, logtype_afpd, "afp_openvol(%s): preexec : %d", volume->v_path, ret );
1668             ret = AFPERR_MISC;
1669             goto openvol_err;
1670         }
1671     }
1672
1673     if ( stat( volume->v_path, &st ) < 0 ) {
1674         ret = AFPERR_PARAM;
1675         goto openvol_err;
1676     }
1677
1678     if ( chdir( volume->v_path ) < 0 ) {
1679         ret = AFPERR_PARAM;
1680         goto openvol_err;
1681     }
1682
1683     len = convert_string_allocate( CH_UCS2, (utf8_encoding()?CH_UTF8_MAC:obj->options.maccharset),
1684                                        volume->v_name, namelen, &vol_mname);
1685     if ( !vol_mname || len <= 0) {
1686         ret = AFPERR_MISC;
1687         goto openvol_err;
1688     }
1689     
1690     if ( NULL == getcwd(path, MAXPATHLEN)) {
1691         /* shouldn't be fatal but it will fail later */
1692         LOG(log_error, logtype_afpd, "afp_openvol(%s): volume pathlen too long", volume->v_path);
1693         ret = AFPERR_MISC;
1694         goto openvol_err;
1695     }        
1696     
1697     if ((vol_uname = strrchr(path, '/')) == NULL)
1698          vol_uname = path;
1699     else if (*(vol_uname + 1) != '\0')
1700          vol_uname++;
1701         
1702     if ((dir = dirnew(vol_mname, vol_uname) ) == NULL) {
1703         free(vol_mname);
1704         LOG(log_error, logtype_afpd, "afp_openvol(%s): malloc: %s", volume->v_path, strerror(errno) );
1705         ret = AFPERR_MISC;
1706         goto openvol_err;
1707     }
1708     free(vol_mname);
1709
1710     dir->d_did = DIRDID_ROOT;
1711     dir->d_color = DIRTREE_COLOR_BLACK; /* root node is black */
1712     volume->v_dir = volume->v_root = dir;
1713
1714     curdir = volume->v_dir;
1715     if (volume->v_cnidscheme == NULL) {
1716         volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
1717         LOG(log_warning, logtype_afpd, "Warning: No CNID scheme for volume %s. Using default.",
1718                volume->v_path);
1719     }
1720     if (volume->v_dbpath)
1721         volume->v_cdb = cnid_open (volume->v_dbpath, volume->v_umask, volume->v_cnidscheme, (volume->v_flags & AFPVOL_NODEV));
1722     else
1723         volume->v_cdb = cnid_open (volume->v_path, volume->v_umask, volume->v_cnidscheme, (volume->v_flags & AFPVOL_NODEV));
1724     if (volume->v_cdb == NULL) {
1725         LOG(log_error, logtype_afpd, "Fatal error: cannot open CNID or invalid CNID backend for %s: %s", 
1726             volume->v_path, volume->v_cnidscheme);
1727         ret = AFPERR_MISC;
1728         goto openvol_err;
1729     }
1730
1731     /* Codepages */
1732
1733     if (!volume->v_volcodepage)
1734         volume->v_volcodepage = strdup("UTF8");
1735
1736     if ( (charset_t) -1 == ( volume->v_volcharset = add_charset(volume->v_volcodepage)) ) {
1737         LOG (log_error, logtype_afpd, "Setting codepage %s as volume codepage failed", volume->v_volcodepage);
1738         ret = AFPERR_MISC;
1739         goto openvol_err;
1740     }
1741
1742     if ( NULL == ( volume->v_vol = find_charset_functions(volume->v_volcodepage)) || volume->v_vol->flags & CHARSET_ICONV ) {
1743         LOG (log_warning, logtype_afpd, "WARNING: volume encoding %s is *not* supported by netatalk, expect problems !!!!", volume->v_volcodepage);
1744     }   
1745
1746     if (!volume->v_maccodepage)
1747         volume->v_maccodepage = strdup(obj->options.maccodepage);
1748
1749     if ( (charset_t) -1 == ( volume->v_maccharset = add_charset(volume->v_maccodepage)) ) {
1750         LOG (log_error, logtype_afpd, "Setting codepage %s as mac codepage failed", volume->v_maccodepage);
1751         ret = AFPERR_MISC;
1752         goto openvol_err;
1753     }
1754
1755     if ( NULL == ( volume->v_mac = find_charset_functions(volume->v_maccodepage)) || ! (volume->v_mac->flags & CHARSET_CLIENT) ) {
1756         LOG (log_error, logtype_afpd, "Fatal error: mac charset %s not supported", volume->v_maccodepage);
1757         ret = AFPERR_MISC;
1758         goto openvol_err;
1759     }   
1760
1761     ret  = stat_vol(bitmap, volume, rbuf, rbuflen);
1762     if (ret == AFP_OK) {
1763
1764         if (!(volume->v_flags & AFPVOL_RO)) {
1765             handle_special_folders( volume );
1766             savevoloptions( volume);
1767         }
1768
1769         /*
1770          * If you mount a volume twice, the second time the trash appears on
1771          * the desk-top.  That's because the Mac remembers the DID for the
1772          * trash (even for volumes in different zones, on different servers).
1773          * Just so this works better, we prime the DID cache with the trash,
1774          * fixing the trash at DID 17.
1775          * FIXME (RL): should it be done inside a CNID backend ? (always returning Trash DID when asked) ?
1776          */
1777         if ((volume->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
1778
1779             /* FIXME find db time stamp */
1780             if (cnid_getstamp(volume->v_cdb, volume->v_stamp, sizeof(volume->v_stamp)) < 0) {
1781                 LOG (log_error, logtype_afpd, 
1782                       "afp_openvol(%s): Fatal error: Unable to get stamp value from CNID backend",
1783                       volume->v_path);
1784                 ret = AFPERR_MISC;
1785                 goto openvol_err;
1786             }
1787         }
1788         else {
1789             p = Trash;
1790             cname( volume, volume->v_dir, &p );
1791         }
1792         return( AFP_OK );
1793     }
1794
1795 openvol_err:
1796     if (volume->v_dir) {
1797         dirfree( volume->v_dir );
1798         volume->v_dir = volume->v_root = NULL;
1799     }
1800
1801     volume->v_flags &= ~AFPVOL_OPEN;
1802     if (volume->v_cdb != NULL) {
1803         cnid_close(volume->v_cdb);
1804         volume->v_cdb = NULL;
1805     }
1806     *rbuflen = 0;
1807     return ret;
1808 }
1809
1810 /* ------------------------- */
1811 static void closevol(struct vol *vol)
1812 {
1813     if (!vol)
1814         return;
1815
1816     dirfree( vol->v_root );
1817     vol->v_dir = NULL;
1818     if (vol->v_cdb != NULL) {
1819         cnid_close(vol->v_cdb);
1820         vol->v_cdb = NULL;
1821     }
1822
1823     if (vol->v_postexec) {
1824         afprun(0, vol->v_postexec, NULL);
1825     }
1826     if (vol->v_root_postexec) {
1827         afprun(1, vol->v_root_postexec, NULL);
1828     }
1829 }
1830
1831 /* ------------------------- */
1832 void close_all_vol(void)
1833 {
1834     struct vol  *ovol;
1835     curdir = NULL;
1836     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
1837         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
1838             ovol->v_flags &= ~AFPVOL_OPEN;
1839             closevol(ovol);
1840         }
1841     }
1842 }
1843
1844 /* ------------------------- */
1845 int afp_closevol(obj, ibuf, ibuflen, rbuf, rbuflen )
1846 AFPObj      *obj;
1847 char    *ibuf, *rbuf;
1848 int             ibuflen, *rbuflen;
1849 {
1850     struct vol  *vol, *ovol;
1851     u_int16_t   vid;
1852
1853     *rbuflen = 0;
1854     ibuf += 2;
1855     memcpy(&vid, ibuf, sizeof( vid ));
1856     if (NULL == ( vol = getvolbyvid( vid )) ) {
1857         return( AFPERR_PARAM );
1858     }
1859
1860     vol->v_flags &= ~AFPVOL_OPEN;
1861     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
1862         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
1863             break;
1864         }
1865     }
1866     if ( ovol != NULL ) {
1867         /* Even if chdir fails, we can't say afp_closevol fails. */
1868         if ( chdir( ovol->v_path ) == 0 ) {
1869             curdir = ovol->v_dir;
1870         }
1871     }
1872
1873     closevol(vol);
1874     if (vol->v_deleted) {
1875         showvol(vol->v_name);
1876         volume_free(vol);
1877         volume_unlink(vol);
1878         free(vol);
1879     }
1880     return( AFP_OK );
1881 }
1882
1883 /* ------------------------- */
1884 struct vol *getvolbyvid(const u_int16_t vid )
1885 {
1886     struct vol  *vol;
1887
1888     for ( vol = Volumes; vol; vol = vol->v_next ) {
1889         if ( vid == vol->v_vid ) {
1890             break;
1891         }
1892     }
1893     if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
1894         return( NULL );
1895     }
1896
1897 #ifdef FORCE_UIDGID
1898     set_uidgid ( vol );
1899 #endif /* FORCE_UIDGID */
1900
1901     return( vol );
1902 }
1903
1904 /* ------------------------ */
1905 static int ext_cmp_key(const void *key, const void *obj)
1906 {
1907     const char          *p = key;
1908     const struct extmap *em = obj;
1909     return strdiacasecmp(p, em->em_ext);
1910 }
1911 struct extmap *getextmap(const char *path)
1912 {
1913     char          *p;
1914     struct extmap *em;
1915
1916     if (NULL == ( p = strrchr( path, '.' )) ) {
1917         return( Defextmap );
1918     }
1919     p++;
1920     if (!*p || !Extmap_cnt) {
1921         return( Defextmap );
1922     }
1923     em = bsearch(p, Extmap, Extmap_cnt, sizeof(struct extmap), ext_cmp_key);
1924     if (em) {
1925         return( em );
1926     } else {
1927         return( Defextmap );
1928     }
1929 }
1930
1931 /* ------------------------- */
1932 struct extmap *getdefextmap(void)
1933 {
1934     return( Defextmap );
1935 }
1936
1937 /* --------------------------
1938    poll if a volume is changed by other processes.
1939 */
1940 int  pollvoltime(obj)
1941 AFPObj *obj;
1942 {
1943     struct vol       *vol;
1944     struct timeval   tv;
1945     struct stat      st;
1946     
1947     if (!(afp_version > 21 && obj->options.server_notif)) 
1948          return 0;
1949
1950     if ( gettimeofday( &tv, 0 ) < 0 ) 
1951          return 0;
1952
1953     for ( vol = Volumes; vol; vol = vol->v_next ) {
1954         if ( (vol->v_flags & AFPVOL_OPEN)  && vol->v_mtime + 30 < tv.tv_sec) {
1955             if ( !stat( vol->v_path, &st ) && vol->v_mtime != st.st_mtime ) {
1956                 vol->v_mtime = st.st_mtime;
1957                 if (!obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED))
1958                     return -1;
1959                 return 1;
1960             }
1961         }
1962     }
1963     return 0;
1964 }
1965
1966 /* ------------------------- */
1967 void setvoltime(obj, vol )
1968 AFPObj *obj;
1969 struct vol      *vol;
1970 {
1971     struct timeval      tv;
1972
1973     /* just looking at vol->v_mtime is broken seriously since updates
1974      * from other users afpd processes never are seen.
1975      * This is not the most elegant solution (a shared memory between
1976      * the afpd processes would come closer)
1977      * [RS] */
1978
1979     if ( gettimeofday( &tv, 0 ) < 0 ) {
1980         LOG(log_error, logtype_afpd, "setvoltime(%s): gettimeofday: %s", vol->v_path, strerror(errno) );
1981         return;
1982     }
1983     if( utime( vol->v_path, NULL ) < 0 ) {
1984         /* write of time failed ... probably a read only filesys,
1985          * where no other users can interfere, so there's no issue here
1986          */
1987     }
1988
1989     /* a little granularity */
1990     if (vol->v_mtime < tv.tv_sec) {
1991         vol->v_mtime = tv.tv_sec;
1992         /* or finder doesn't update free space */
1993         if (afp_version > 21 && obj->options.server_notif) {
1994             obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED);
1995         }
1996     }
1997 }
1998
1999 /* ------------------------- */
2000 int afp_getvolparams(obj, ibuf, ibuflen, rbuf, rbuflen )
2001 AFPObj      *obj;
2002 char    *ibuf, *rbuf;
2003 int             ibuflen, *rbuflen;
2004 {
2005     struct vol  *vol;
2006     u_int16_t   vid, bitmap;
2007
2008     ibuf += 2;
2009     memcpy(&vid, ibuf, sizeof( vid ));
2010     ibuf += sizeof( vid );
2011     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2012     bitmap = ntohs( bitmap );
2013
2014     if (NULL == ( vol = getvolbyvid( vid )) ) {
2015         *rbuflen = 0;
2016         return( AFPERR_PARAM );
2017     }
2018
2019     return stat_vol(bitmap, vol, rbuf, rbuflen);
2020 }
2021
2022 /* ------------------------- */
2023 int afp_setvolparams(obj, ibuf, ibuflen, rbuf, rbuflen )
2024 AFPObj      *obj;
2025 char    *ibuf, *rbuf;
2026 int             ibuflen, *rbuflen;
2027 {
2028     struct adouble ad;
2029     struct vol  *vol;
2030     u_int16_t   vid, bitmap;
2031     u_int32_t   aint;
2032
2033     ibuf += 2;
2034     *rbuflen = 0;
2035
2036     memcpy(&vid, ibuf, sizeof( vid ));
2037     ibuf += sizeof( vid );
2038     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2039     bitmap = ntohs( bitmap );
2040     ibuf += sizeof(bitmap);
2041
2042     if (( vol = getvolbyvid( vid )) == NULL ) {
2043         return( AFPERR_PARAM );
2044     }
2045
2046     if ((vol->v_flags & AFPVOL_RO))
2047         return AFPERR_VLOCK;
2048
2049     /* we can only set the backup date. */
2050     if (bitmap != (1 << VOLPBIT_BDATE))
2051         return AFPERR_BITMAP;
2052
2053     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2054     if ( ad_open( vol->v_path, ADFLAGS_HF|ADFLAGS_DIR, O_RDWR,
2055                   0666, &ad) < 0 ) {
2056         if (errno == EROFS)
2057             return AFPERR_VLOCK;
2058
2059         return AFPERR_ACCESS;
2060     }
2061
2062     memcpy(&aint, ibuf, sizeof(aint));
2063     ad_setdate(&ad, AD_DATE_BACKUP, aint);
2064     ad_flush(&ad, ADFLAGS_HF);
2065     ad_close(&ad, ADFLAGS_HF);
2066     return( AFP_OK );
2067 }
2068
2069 /* ------------------------- */
2070 int wincheck(const struct vol *vol, const char *path)
2071 {
2072     int len;
2073
2074     if (!(vol->v_flags & AFPVOL_MSWINDOWS))
2075         return 1;
2076
2077     /* empty paths are not allowed */
2078     if ((len = strlen(path)) == 0)
2079         return 0;
2080
2081     /* leading or trailing whitespaces are not allowed, carriage returns
2082      * and probably other whitespace is okay, tabs are not allowed
2083      */
2084     if ((path[0] == ' ') || (path[len-1] == ' '))
2085         return 0;
2086
2087     /* certain characters are not allowed */
2088     if (strpbrk(path, MSWINDOWS_BADCHARS))
2089         return 0;
2090
2091     /* everything else is okay */
2092     return 1;
2093 }
2094
2095
2096 /*
2097  * precreate a folder 
2098  * this is only intended for folders in the volume root 
2099  * It will *not* work if the folder name contains extended characters 
2100  */
2101 static int create_special_folder (const struct vol *vol, const struct _special_folder *folder)
2102 {
2103         char            *p,*q,*r;
2104         struct adouble  ad;
2105         u_int16_t       attr;
2106         struct stat     st;
2107         int             ret;
2108
2109
2110         p = (char *) malloc ( strlen(vol->v_path)+strlen(folder->name)+2);
2111         if ( p == NULL) {
2112                 LOG(log_error, logtype_afpd,"malloc failed");
2113                 exit (EXITERR_SYS);
2114         }
2115
2116         q=strdup(folder->name);
2117         if ( q == NULL) {
2118                 LOG(log_error, logtype_afpd,"malloc failed");
2119                 exit (EXITERR_SYS);
2120         }
2121
2122         strcpy(p, vol->v_path);
2123         strcat(p, "/");
2124
2125         r=q;
2126         while (*r) {
2127                 if ((vol->v_casefold & AFPVOL_MTOUUPPER))
2128                         *r=toupper(*r);
2129                 else if ((vol->v_casefold & AFPVOL_MTOULOWER))
2130                         *r=tolower(*r);
2131                 r++;
2132         }
2133         strcat(p, q);
2134
2135         if ( (ret = stat( p, &st )) < 0 ) {
2136                 if (folder->precreate) {
2137                     if (ad_mkdir(p, folder->mode)) {
2138                         LOG(log_debug, logtype_afpd,"Creating '%s' failed in %s: %s", p, vol->v_path, strerror(errno));
2139                         free(p);
2140                         free(q);
2141                         return -1;
2142                     }
2143                     ret = 0;
2144                 }
2145         }
2146
2147         if ( !ret && folder->hide) {
2148                 /* Hide it */
2149                 ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2150                 if (ad_open( p, vol_noadouble(vol) | ADFLAGS_HF|ADFLAGS_DIR,
2151                         O_RDWR|O_CREAT, 0666, &ad) < 0) {
2152                         free (p);
2153                         free(q);
2154                         return (-1);
2155                 }
2156                 if ((ad_get_HF_flags( &ad ) & O_CREAT) ) {
2157                     if (ad_getentryoff(&ad, ADEID_NAME)) {
2158                         ad_setentrylen( &ad, ADEID_NAME, strlen(folder->name));
2159                         memcpy(ad_entry( &ad, ADEID_NAME ), folder->name,
2160                                ad_getentrylen( &ad, ADEID_NAME ));
2161                     }
2162                 }
2163  
2164                 ad_getattr(&ad, &attr);
2165                 attr |= htons( ntohs( attr ) | ATTRBIT_INVISIBLE );
2166                 ad_setattr(&ad, attr);
2167 #if 0           
2168                 /* do the same with the finder info */
2169                 if (ad_entry(&ad, ADEID_FINDERI)) {
2170                         memcpy(&attr, ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, sizeof(attr));
2171                         attr   |= htons(FINDERINFO_INVISIBLE);
2172                         memcpy(ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,&attr, sizeof(attr));
2173                 }
2174 #endif    
2175                 ad_flush( &ad, ADFLAGS_HF );
2176                 ad_close( &ad, ADFLAGS_HF );
2177         }
2178         free(p);
2179         free(q);
2180         return 0;
2181 }
2182
2183 static void handle_special_folders (const struct vol * vol)
2184 {
2185         const _special_folder *p = &special_folders[0];
2186
2187         if ((vol->v_flags & AFPVOL_RO))
2188                 return;
2189
2190         for (; p->name != NULL; p++) {
2191                 create_special_folder (vol, p);
2192         }
2193 }
2194
2195 /*
2196  * Save the volume options to a file, used by
2197  * shell utilities.
2198  * Writing the file everytime a volume is opened is
2199  * unnecessary, but it shouldn't hurt much.
2200  */
2201 static int savevoloptions (const struct vol *vol)
2202 {
2203     char buf[16348];
2204     char item[MAXPATHLEN];
2205     int fd;
2206     int ret = 0;
2207     struct flock lock;
2208     const _vol_opt_name *op = &vol_opt_names[0];
2209     const _vol_opt_name *cf = &vol_opt_casefold[0];
2210
2211     strlcpy (item, vol->v_path, sizeof(item));
2212     strlcat (item, "/.AppleDesktop/", sizeof(item));
2213     strlcat (item, VOLINFOFILE, sizeof(item));
2214
2215     if ((fd = open( item, O_RDWR | O_CREAT , 0666)) <0 ) {
2216         LOG(log_debug, logtype_afpd,"Error opening %s: %s", item, strerror(errno));
2217         return (-1);
2218     }
2219
2220     /* try to get a lock */
2221     lock.l_start  = 0;
2222     lock.l_whence = SEEK_SET;
2223     lock.l_len    = 0;
2224     lock.l_type   = F_WRLCK;
2225
2226     if (fcntl(fd, F_SETLK, &lock) < 0) {
2227         if (errno == EACCES || errno == EAGAIN) {
2228             /* ignore, other process already writing the file */
2229             return 0;
2230         } else {
2231             LOG(log_error, logtype_cnid, "savevoloptions: cannot get lock: %s", strerror(errno));
2232             return (-1);
2233         }
2234     }
2235
2236     /* write volume options */
2237     snprintf(buf, sizeof(buf), "MAC_CHARSET:%s\n", vol->v_maccodepage);
2238     snprintf(item, sizeof(item), "VOL_CHARSET:%s\n", vol->v_volcodepage);
2239     strlcat(buf, item, sizeof(buf));
2240
2241     switch (vol->v_adouble) {
2242         case AD_VERSION1:
2243             strlcat(buf, "ADOUBLE_VER:v1\n", sizeof(buf));
2244             break;
2245         case AD_VERSION2:
2246             strlcat(buf, "ADOUBLE_VER:v2\n", sizeof(buf));
2247             break;
2248         case AD_VERSION2_OSX:
2249             strlcat(buf, "ADOUBLE_VER:osx\n", sizeof(buf));
2250             break;
2251     }
2252
2253     strlcat(buf, "CNIDBACKEND:", sizeof(buf));
2254     strlcat(buf, vol->v_cnidscheme, sizeof(buf));
2255     strlcat(buf, "\n", sizeof(buf));
2256
2257     strlcat(buf, "CNIDDBDHOST:", sizeof(buf));
2258     strlcat(buf, Cnid_srv, sizeof(buf));
2259     strlcat(buf, "\n", sizeof(buf));
2260
2261     snprintf(item, sizeof(item), "CNIDDBDPORT:%u\n", Cnid_port);
2262     strlcat(buf, item, sizeof(buf));
2263
2264     strcpy(item, "CNID_DBPATH:");
2265     if (vol->v_dbpath)
2266         strlcat(item, vol->v_dbpath, sizeof(item));
2267     else
2268         strlcat(item, vol->v_path, sizeof(item));
2269     strlcat(item, "\n", sizeof(item));
2270     strlcat(buf, item, sizeof(buf));
2271
2272     /* volume flags */
2273     strcpy(item, "VOLUME_OPTS:");
2274     for (;op->name; op++) {
2275         if ( (vol->v_flags & op->option) ) {
2276             strlcat(item, op->name, sizeof(item));
2277             strlcat(item, " ", sizeof(item));
2278         }
2279     }
2280     strlcat(item, "\n", sizeof(item));
2281     strlcat(buf, item, sizeof(buf));
2282
2283     /* casefold flags */
2284     strcpy(item, "VOLCASEFOLD:");
2285     for (;cf->name; cf++) {
2286         if ( (vol->v_casefold & cf->option) ) {
2287             strlcat(item, cf->name, sizeof(item));
2288             strlcat(item, " ", sizeof(item));
2289         }
2290     }
2291     strlcat(item, "\n", sizeof(item));
2292     strlcat(buf, item, sizeof(buf));
2293
2294     if (strlen(buf) >= sizeof(buf)-1)
2295         LOG(log_debug, logtype_afpd,"Error writing .volinfo file: buffer too small, %s", buf);
2296
2297
2298    if (write( fd, buf, strlen(buf)) < 0) {
2299        LOG(log_debug, logtype_afpd,"Error writing .volinfo file: %s", strerror(errno));
2300        goto done;
2301    }
2302    ftruncate(fd, strlen(buf));
2303
2304 done:
2305    lock.l_type = F_UNLCK;
2306    fcntl(fd, F_SETLK, &lock);
2307    close (fd);
2308    return ret;
2309 }