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