]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/auth.c
more intuitive parameter
[netatalk.git] / etc / afpd / auth.c
1 /*
2  * Copyright (c) 1990,1993 Regents of The University of Michigan.
3  * All Rights Reserved.  See COPYRIGHT.
4  */
5
6 #ifdef HAVE_CONFIG_H
7 #include "config.h"
8 #endif /* HAVE_CONFIG_H */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <errno.h>
13 #include <unistd.h>
14 #include <sys/types.h>
15 #include <sys/param.h>
16 #include <sys/stat.h>
17 #include <arpa/inet.h>
18
19 #include <atalk/afp.h>
20 #include <atalk/compat.h>
21 #include <atalk/util.h>
22 #include <limits.h>
23 #include <string.h>
24 #include <ctype.h>
25 #include <time.h>
26 #include <pwd.h>
27 #include <grp.h>
28
29 #ifdef TRU64
30 #include <netdb.h>
31 #include <arpa/inet.h>
32 #include <sia.h>
33 #include <siad.h>
34
35 extern void afp_get_cmdline( int *ac, char ***av );
36 #endif /* TRU64 */
37
38 #include <atalk/logger.h>
39 #include <atalk/server_ipc.h>
40 #include <atalk/uuid.h>
41 #include <atalk/globals.h>
42
43 #include "auth.h"
44 #include "uam_auth.h"
45 #include "switch.h"
46 #include "status.h"
47 #include "fork.h"
48 #include "extattrs.h"
49 #ifdef HAVE_ACLS
50 #include "acls.h"
51 #endif
52
53 static int afp_version_index;
54 static struct uam_mod uam_modules = {NULL, NULL, &uam_modules, &uam_modules};
55 static struct uam_obj uam_login = {"", "", 0, {{NULL, NULL, NULL, NULL }}, &uam_login,
56                                    &uam_login};
57 static struct uam_obj uam_changepw = {"", "", 0, {{NULL, NULL, NULL, NULL}}, &uam_changepw,
58                                       &uam_changepw};
59
60 static struct uam_obj *afp_uam = NULL;
61
62
63 void status_versions( char *data, const DSI *dsi)
64 {
65     char                *start = data;
66     uint16_t           status;
67     int         len, num, i, count = 0;
68
69     memcpy(&status, start + AFPSTATUS_VERSOFF, sizeof(status));
70     num = sizeof( afp_versions ) / sizeof( afp_versions[ 0 ] );
71
72     for ( i = 0; i < num; i++ ) {
73         if ( !dsi && (afp_versions[ i ].av_number >= 22)) continue;
74         count++;
75     }
76     data += ntohs( status );
77     *data++ = count;
78
79     for ( i = 0; i < num; i++ ) {
80         if ( !dsi && (afp_versions[ i ].av_number >= 22)) continue;
81         len = strlen( afp_versions[ i ].av_name );
82         *data++ = len;
83         memcpy( data, afp_versions[ i ].av_name , len );
84         data += len;
85     }
86     status = htons( data - start );
87     memcpy(start + AFPSTATUS_UAMSOFF, &status, sizeof(status));
88 }
89
90 void status_uams(char *data, const char *authlist)
91 {
92     char                *start = data;
93     uint16_t           status;
94     struct uam_obj      *uams;
95     int         len, num = 0;
96
97     memcpy(&status, start + AFPSTATUS_UAMSOFF, sizeof(status));
98     uams = &uam_login;
99     while ((uams = uams->uam_prev) != &uam_login) {
100         if (strstr(authlist, uams->uam_path))
101             num++;
102     }
103
104     data += ntohs( status );
105     *data++ = num;
106     while ((uams = uams->uam_prev) != &uam_login) {
107         if (strstr(authlist, uams->uam_path)) {
108             LOG(log_info, logtype_afpd, "uam: \"%s\" available", uams->uam_name);
109             len = strlen( uams->uam_name);
110             *data++ = len;
111             memcpy( data, uams->uam_name, len );
112             data += len;
113         }
114     }
115
116     /* icon offset */
117     status = htons(data - start);
118     memcpy(start + AFPSTATUS_ICONOFF, &status, sizeof(status));
119 }
120
121 /* handle errors by closing the connection. this is only needed
122  * by the afp_* functions. */
123 static int send_reply(const AFPObj *obj, const int err)
124 {
125     if ((err == AFP_OK) || (err == AFPERR_AUTHCONT))
126         return err;
127
128     obj->reply(obj->dsi, err);
129     obj->exit(0);
130
131     return AFP_OK;
132 }
133
134 static int afp_errpwdexpired(AFPObj *obj _U_, char *ibuf _U_, size_t ibuflen _U_, 
135                              char *rbuf _U_, size_t *rbuflen)
136 {
137     *rbuflen = 0;
138     return AFPERR_PWDEXPR;
139 }
140
141 static int afp_null_nolog(AFPObj *obj _U_, char *ibuf _U_, size_t ibuflen _U_, 
142                           char *rbuf _U_, size_t *rbuflen)
143 {
144     *rbuflen = 0;
145     return( AFPERR_NOOP );
146 }
147
148 static int set_auth_switch(const AFPObj *obj, int expired)
149 {
150     int i;
151
152     if (expired) {
153         /*
154          * BF: expired password handling
155          * to allow the user to change his/her password we have to allow login
156          * but every following call except for FPChangePassword will be thrown
157          * away with an AFPERR_PWDEXPR error. (thanks to Leland Wallace from Apple
158          * for clarifying this)
159          */
160
161         for (i=0; i<=0xff; i++) {
162             uam_afpserver_action(i, UAM_AFPSERVER_PREAUTH, afp_errpwdexpired, NULL);
163         }
164         uam_afpserver_action(AFP_LOGOUT, UAM_AFPSERVER_PREAUTH, afp_logout, NULL);
165         uam_afpserver_action(AFP_CHANGEPW, UAM_AFPSERVER_PREAUTH, afp_changepw, NULL);
166     }
167     else {
168         afp_switch = postauth_switch;
169         switch (obj->afp_version) {
170
171         case 33:
172         case 32:
173 #ifdef HAVE_ACLS
174             uam_afpserver_action(AFP_GETACL, UAM_AFPSERVER_POSTAUTH, afp_getacl, NULL);
175             uam_afpserver_action(AFP_SETACL, UAM_AFPSERVER_POSTAUTH, afp_setacl, NULL);
176             uam_afpserver_action(AFP_ACCESS, UAM_AFPSERVER_POSTAUTH, afp_access, NULL);
177 #endif /* HAVE_ACLS */
178             uam_afpserver_action(AFP_GETEXTATTR, UAM_AFPSERVER_POSTAUTH, afp_getextattr, NULL);
179             uam_afpserver_action(AFP_SETEXTATTR, UAM_AFPSERVER_POSTAUTH, afp_setextattr, NULL);
180             uam_afpserver_action(AFP_REMOVEATTR, UAM_AFPSERVER_POSTAUTH, afp_remextattr, NULL);
181             uam_afpserver_action(AFP_LISTEXTATTR, UAM_AFPSERVER_POSTAUTH, afp_listextattr, NULL);
182
183         case 31:
184             uam_afpserver_action(AFP_SYNCDIR, UAM_AFPSERVER_POSTAUTH, afp_syncdir, NULL);
185             uam_afpserver_action(AFP_SYNCFORK, UAM_AFPSERVER_POSTAUTH, afp_syncfork, NULL);
186             uam_afpserver_action(AFP_SPOTLIGHT_PRIVATE, UAM_AFPSERVER_POSTAUTH, afp_null_nolog, NULL);
187             uam_afpserver_action(AFP_ENUMERATE_EXT2, UAM_AFPSERVER_POSTAUTH, afp_enumerate_ext2, NULL);
188
189         case 30:
190             uam_afpserver_action(AFP_ENUMERATE_EXT, UAM_AFPSERVER_POSTAUTH, afp_enumerate_ext, NULL);
191             uam_afpserver_action(AFP_BYTELOCK_EXT,  UAM_AFPSERVER_POSTAUTH, afp_bytelock_ext, NULL);
192             /* catsearch_ext uses the same packet as catsearch FIXME double check this, it wasn't true for enue
193                enumerate_ext */
194             uam_afpserver_action(AFP_CATSEARCH_EXT, UAM_AFPSERVER_POSTAUTH, afp_catsearch_ext, NULL);
195             uam_afpserver_action(AFP_GETSESSTOKEN,  UAM_AFPSERVER_POSTAUTH, afp_getsession, NULL);
196             uam_afpserver_action(AFP_READ_EXT,      UAM_AFPSERVER_POSTAUTH, afp_read_ext, NULL);
197             uam_afpserver_action(AFP_WRITE_EXT,     UAM_AFPSERVER_POSTAUTH, afp_write_ext, NULL);
198             uam_afpserver_action(AFP_DISCTOLDSESS,  UAM_AFPSERVER_POSTAUTH, afp_disconnect, NULL);
199
200         case 22:
201             /*
202              * If first connection to a server is done in classic AFP2.2 version is used
203              * but OSX uses AFP3.x FPzzz command !
204              */
205             uam_afpserver_action(AFP_ZZZ,  UAM_AFPSERVER_POSTAUTH, afp_zzz, NULL);
206             break;
207         }
208     }
209
210     return AFP_OK;
211 }
212
213 #define GROUPSTR_BUFSIZE 1024
214 static const char *print_groups(int ngroups, gid_t *groups)
215 {
216     static char groupsstr[GROUPSTR_BUFSIZE];
217     int i;
218     char *s = groupsstr;
219
220     if (ngroups == 0)
221         return "-";
222
223     for (i = 0; (i < ngroups) && (s < &groupsstr[GROUPSTR_BUFSIZE]); i++) {
224         s += snprintf(s, &groupsstr[GROUPSTR_BUFSIZE] - s, " %u", groups[i]);
225     }
226
227     return groupsstr;
228 }
229
230 static int login(AFPObj *obj, struct passwd *pwd, void (*logout)(void), int expired)
231 {
232 #ifdef ADMIN_GRP
233     int admin = 0;
234 #endif /* ADMIN_GRP */
235
236     if ( pwd->pw_uid == 0 ) {   /* don't allow root login */
237         LOG(log_error, logtype_afpd, "login: root login denied!" );
238         return AFPERR_NOTAUTH;
239     }
240
241     LOG(log_note, logtype_afpd, "%s Login by %s",
242         afp_versions[afp_version_index].av_name, pwd->pw_name);
243
244     if (initgroups( pwd->pw_name, pwd->pw_gid ) < 0) {
245 #ifdef RUN_AS_USER
246         LOG(log_info, logtype_afpd, "running with uid %d", geteuid());
247 #else /* RUN_AS_USER */
248         LOG(log_error, logtype_afpd, "login: %s", strerror(errno));
249         return AFPERR_BADUAM;
250 #endif /* RUN_AS_USER */
251
252     }
253
254     /* Basically if the user is in the admin group, we stay root */
255
256     if ((obj->ngroups = getgroups( 0, NULL )) < 0 ) {
257         LOG(log_error, logtype_afpd, "login: %s getgroups: %s", pwd->pw_name, strerror(errno) );
258         return AFPERR_BADUAM;
259     }
260
261     if ( NULL == (obj->groups = calloc(obj->ngroups, sizeof(gid_t))) ) {
262         LOG(log_error, logtype_afpd, "login: %s calloc: %d", obj->ngroups);
263         return AFPERR_BADUAM;
264     }
265
266     if (( obj->ngroups = getgroups(obj->ngroups, obj->groups )) < 0 ) {
267         LOG(log_error, logtype_afpd, "login: %s getgroups: %s", pwd->pw_name, strerror(errno) );
268         return AFPERR_BADUAM;
269     }
270
271 #ifdef ADMIN_GRP
272     LOG(log_debug, logtype_afpd, "obj->options.admingid == %d", obj->options.admingid);
273
274     if (obj->options.admingid != 0) {
275         int i;
276         for (i = 0; i < obj->ngroups; i++) {
277             if (obj->groups[i] == obj->options.admingid) admin = 1;
278         }
279     }
280     if (admin) {
281         ad_setfuid(0);
282         LOG(log_info, logtype_afpd, "admin login -- %s", pwd->pw_name );
283     }
284     if (!admin)
285 #endif /* ADMIN_GRP */
286 #ifdef TRU64
287     {
288         struct DSI *dsi = obj->handle;
289         struct hostent *hp;
290         char *clientname;
291         int argc;
292         char **argv;
293         char hostname[256];
294
295         afp_get_cmdline( &argc, &argv );
296
297         hp = gethostbyaddr( (char *) &dsi->client.sin_addr,
298                             sizeof( struct in_addr ),
299                             dsi->client.sin_family );
300
301         if( hp )
302             clientname = hp->h_name;
303         else
304             clientname = inet_ntoa( dsi->client.sin_addr );
305
306         sprintf( hostname, "%s@%s", pwd->pw_name, clientname );
307
308         if( sia_become_user( NULL, argc, argv, hostname, pwd->pw_name,
309                              NULL, FALSE, NULL, NULL,
310                              SIA_BEU_REALLOGIN ) != SIASUCCESS )
311             return AFPERR_BADUAM;
312
313         LOG(log_info, logtype_afpd, "session from %s (%s)", hostname,
314             inet_ntoa( dsi->client.sin_addr ) );
315
316         if (setegid( pwd->pw_gid ) < 0 || seteuid( pwd->pw_uid ) < 0) {
317             LOG(log_error, logtype_afpd, "login: %s %s", pwd->pw_name, strerror(errno) );
318             return AFPERR_BADUAM;
319         }
320     }
321 #else /* TRU64 */
322     if (setegid( pwd->pw_gid ) < 0 || seteuid( pwd->pw_uid ) < 0) {
323         LOG(log_error, logtype_afpd, "login: %s %s", pwd->pw_name, strerror(errno) );
324         return AFPERR_BADUAM;
325     }
326 #endif /* TRU64 */
327
328     LOG(log_debug, logtype_afpd, "login: supplementary groups: %s", print_groups(obj->ngroups, obj->groups));
329
330     /* There's probably a better way to do this, but for now, we just play root */
331 #ifdef ADMIN_GRP
332     if (admin)
333         obj->uid = 0;
334     else
335 #endif /* ADMIN_GRP */
336         obj->uid = geteuid();
337
338     set_auth_switch(obj, expired);
339     /* save our euid, we need it for preexec_close */
340     obj->uid = geteuid();
341     obj->logout = logout;
342
343     /* pam_umask or similar might have changed our umask */
344     (void)umask(obj->options.umask);
345
346     return( AFP_OK );
347 }
348
349 /* ---------------------- */
350 int afp_zzz(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
351 {
352     uint32_t data;
353     DSI *dsi = (DSI *)AFPobj->dsi;
354
355     *rbuflen = 0;
356     ibuf += 2;
357     ibuflen -= 2;
358
359     if (ibuflen < 4)
360         return AFPERR_MISC;
361     memcpy(&data, ibuf, 4); /* flag */
362     data = ntohl(data);
363
364     /*
365      * Possible sleeping states:
366      * 1) normal sleep: DSI_SLEEPING (up to 10.3)
367      * 2) extended sleep: DSI_SLEEPING | DSI_EXTSLEEP (starting with 10.4)
368      */
369
370     if (data & AFPZZZ_EXT_WAKEUP) {
371         /* wakeup request from exetended sleep */
372         if (dsi->flags & DSI_EXTSLEEP) {
373             LOG(log_note, logtype_afpd, "afp_zzz: waking up from extended sleep");
374             dsi->flags &= ~(DSI_SLEEPING | DSI_EXTSLEEP);
375         }
376     } else {
377         /* sleep request */
378         dsi->flags |= DSI_SLEEPING;
379         if (data & AFPZZZ_EXT_SLEEP) {
380             LOG(log_note, logtype_afpd, "afp_zzz: entering extended sleep");
381             dsi->flags |= DSI_EXTSLEEP;
382         } else {
383             LOG(log_note, logtype_afpd, "afp_zzz: entering normal sleep");
384         }
385     }
386
387     /*
388      * According to AFP 3.3 spec we should not return anything,
389      * but eg 10.5.8 server still returns the numbers of hours
390      * the server is keeping the sessino (ie max sleeptime).
391      */
392     data = obj->options.sleep / 120; /* hours */
393     if (!data) {
394         data = 1;
395     }
396     *rbuflen = sizeof(data);
397     data = htonl(data);
398     memcpy(rbuf, &data, sizeof(data));
399     rbuf += sizeof(data);
400
401     return AFP_OK;
402 }
403
404 /* ---------------------- */
405 static int create_session_token(AFPObj *obj)
406 {
407     pid_t pid;
408
409     /* use 8 bytes for token as OSX, don't know if it helps */
410     if ( sizeof(pid_t) > SESSIONTOKEN_LEN) {
411         LOG(log_error, logtype_afpd, "sizeof(pid_t) > %u", SESSIONTOKEN_LEN );
412         return AFPERR_MISC;
413     }
414
415     if ( NULL == (obj->sinfo.sessiontoken = malloc(SESSIONTOKEN_LEN)) )
416         return AFPERR_MISC;
417
418     memset(obj->sinfo.sessiontoken, 0, SESSIONTOKEN_LEN);
419     obj->sinfo.sessiontoken_len = SESSIONTOKEN_LEN;
420     pid = getpid();
421     memcpy(obj->sinfo.sessiontoken, &pid, sizeof(pid_t));
422
423     return 0;
424 }
425
426 static int create_session_key(AFPObj *obj)
427 {
428     /* create session key */
429     if (obj->sinfo.sessionkey == NULL) {
430         if (NULL == (obj->sinfo.sessionkey = malloc(SESSIONKEY_LEN)) )
431             return AFPERR_MISC;
432         uam_random_string(obj, obj->sinfo.sessionkey, SESSIONKEY_LEN);
433         obj->sinfo.sessionkey_len = SESSIONKEY_LEN;
434     }
435     return AFP_OK;
436 }
437
438
439 /* ---------------------- */
440 int afp_getsession(
441     AFPObj *obj,
442     char   *ibuf, size_t ibuflen, 
443     char   *rbuf, size_t *rbuflen)
444 {
445     uint16_t           type;
446     uint32_t           idlen = 0;
447     uint32_t       boottime;
448     uint32_t           tklen, tp;
449     char                *token;
450     char                *p;
451
452     *rbuflen = 0;
453     tklen = 0;
454
455     if (ibuflen < 2 + sizeof(type)) {
456         return AFPERR_PARAM;
457     }
458
459     ibuf += 2;
460     ibuflen -= 2;
461
462     memcpy(&type, ibuf, sizeof(type));
463     type = ntohs(type);
464     ibuf += sizeof(type);
465     ibuflen -= sizeof(type);
466
467     if ( obj->sinfo.sessiontoken == NULL ) {
468         if ( create_session_token( obj ) )
469             return AFPERR_MISC;
470     }
471
472     /*
473      *
474      */
475     switch (type) {
476     case 0: /* old version ?*/
477         tklen = obj->sinfo.sessiontoken_len;
478         token = obj->sinfo.sessiontoken;
479         break;
480     case 1: /* disconnect */
481     case 2: /* reconnect update id */
482         if (ibuflen >= sizeof(idlen)) {
483             memcpy(&idlen, ibuf, sizeof(idlen));
484             idlen = ntohl(idlen);
485             ibuf += sizeof(idlen);
486             ibuflen -= sizeof(idlen);
487             if (ibuflen < idlen) {
488                 return AFPERR_PARAM;
489             }
490             /* memcpy (id, ibuf, idlen) */
491             tklen = obj->sinfo.sessiontoken_len;
492             token = obj->sinfo.sessiontoken;
493         }
494         break;
495     case 3:
496     case 4:
497         if (ibuflen >= 8 ) {
498             p = ibuf;
499             memcpy( &idlen, ibuf, sizeof(idlen));
500             idlen = ntohl(idlen);
501             ibuf += sizeof(idlen);
502             ibuflen -= sizeof(idlen);
503             ibuf += sizeof(boottime);
504             ibuflen -= sizeof(boottime);
505             if (ibuflen < idlen || idlen > (90-10)) {
506                 return AFPERR_PARAM;
507             }
508             if (!obj->sinfo.clientid) {
509                 obj->sinfo.clientid = malloc(idlen + 8);
510                 memcpy(obj->sinfo.clientid, p, idlen + 8);
511                 obj->sinfo.clientid_len = idlen + 8;
512             }
513             if (ipc_child_write(obj->ipc_fd, IPC_GETSESSION, idlen+8, p) != 0)
514                 return AFPERR_MISC;
515             tklen = obj->sinfo.sessiontoken_len;
516             token = obj->sinfo.sessiontoken;
517         }
518         break;
519     case 8: /* Panther Kerberos Token */
520         tklen = obj->sinfo.cryptedkey_len;
521         token = obj->sinfo.cryptedkey;
522         break;
523     default:
524         return AFPERR_NOOP;
525         break;
526
527     }
528
529     if (tklen == 0)
530         return AFPERR_MISC;
531
532     tp = htonl(tklen);
533     memcpy(rbuf, &tp, sizeof(tklen));
534     rbuf += sizeof(tklen);
535     *rbuflen += sizeof(tklen);
536
537     memcpy(rbuf, token, tklen);
538     *rbuflen += tklen;
539
540     return AFP_OK;
541 }
542
543 /* ---------------------- */
544 int afp_disconnect(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
545 {
546     DSI                 *dsi = (DSI *)obj->dsi;
547     uint16_t           type;
548     uint32_t           tklen;
549     pid_t               token;
550     int                 i;
551
552     *rbuflen = 0;
553     ibuf += 2;
554
555 #if 0
556     /* check for guest user */
557     if ( 0 == (strcasecmp(obj->username, obj->options.guest)) ) {
558         return AFPERR_MISC;
559     }
560 #endif
561
562     memcpy(&type, ibuf, sizeof(type));
563     type = ntohs(type);
564     ibuf += sizeof(type);
565
566     memcpy(&tklen, ibuf, sizeof(tklen));
567     tklen = ntohl(tklen);
568     ibuf += sizeof(tklen);
569
570     if ( sizeof(pid_t) > SESSIONTOKEN_LEN) {
571         LOG(log_error, logtype_afpd, "sizeof(pid_t) > %u", SESSIONTOKEN_LEN );
572         return AFPERR_MISC;
573     }
574     if (tklen != SESSIONTOKEN_LEN) {
575         return AFPERR_MISC;
576     }
577     tklen = sizeof(pid_t);
578     memcpy(&token, ibuf, tklen);
579
580     /* our stuff is pid + zero pad */
581     ibuf += tklen;
582     for (i = tklen; i < SESSIONTOKEN_LEN; i++, ibuf++) {
583         if (*ibuf != 0) {
584             return AFPERR_MISC;
585         }
586     }
587
588     LOG(log_note, logtype_afpd, "afp_disconnect: trying primary reconnect");
589     dsi->flags |= DSI_RECONINPROG;
590
591     /* Deactivate tickle timer */
592     const struct itimerval none = {{0, 0}, {0, 0}};
593     setitimer(ITIMER_REAL, &none, NULL);
594
595     /* check for old session, possibly transfering session from here to there */
596     if (ipc_child_write(obj->ipc_fd, IPC_DISCOLDSESSION, tklen, &token) != 0)
597         goto exit;
598     /* write uint16_t DSI request ID */
599     if (writet(obj->ipc_fd, &dsi->header.dsi_requestID, 2, 0, 2) != 2) {
600         LOG(log_error, logtype_afpd, "afp_disconnect: couldn't send DSI request ID");
601         goto exit;
602     }
603     /* now send our connected AFP client socket */
604     if (send_fd(obj->ipc_fd, dsi->socket) != 0)
605         goto exit;
606     /* Now see what happens: either afpd master sends us SIGTERM because our session */
607     /* has been transfered to a old disconnected session, or we continue    */
608     sleep(5);
609
610     if (!(dsi->flags & DSI_RECONINPROG)) { /* deleted in SIGTERM handler */
611         /* Reconnect succeeded, we exit now after sleeping some more */
612         sleep(2); /* sleep some more to give the recon. session time */
613         LOG(log_note, logtype_afpd, "afp_disconnect: primary reconnect succeeded");
614         exit(0);
615     }
616
617 exit:
618     /* Reinstall tickle timer */
619     setitimer(ITIMER_REAL, &dsi->timer, NULL);
620
621     LOG(log_error, logtype_afpd, "afp_disconnect: primary reconnect failed");
622     return AFPERR_MISC;
623 }
624
625 /* ---------------------- */
626 static int get_version(AFPObj *obj, char *ibuf, size_t ibuflen, size_t len)
627 {
628     int num,i;
629
630     if (!len || len > ibuflen)
631         return AFPERR_BADVERS;
632
633     num = sizeof( afp_versions ) / sizeof( afp_versions[ 0 ]);
634     for ( i = 0; i < num; i++ ) {
635         if ( strncmp( ibuf, afp_versions[ i ].av_name , len ) == 0 ) {
636             obj->afp_version = afp_versions[ i ].av_number;
637             afp_version_index = i;
638             break;
639         }
640     }
641     if ( i == num )                 /* An inappropo version */
642         return AFPERR_BADVERS ;
643
644     /* FIXME Hack */
645     if (obj->afp_version >= 30 && sizeof(off_t) != 8) {
646         LOG(log_error, logtype_afpd, "get_version: no LARGE_FILE support recompile!" );
647         return AFPERR_BADVERS ;
648     }
649
650     return 0;
651 }
652
653 /* ---------------------- */
654 int afp_login(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
655 {
656     struct passwd *pwd = NULL;
657     size_t len;
658     int     i;
659
660     *rbuflen = 0;
661
662     if ( nologin & 1)
663         return send_reply(obj, AFPERR_SHUTDOWN );
664
665     if (ibuflen < 2)
666         return send_reply(obj, AFPERR_BADVERS );
667
668     ibuf++;
669     len = (unsigned char) *ibuf++;
670     ibuflen -= 2;
671
672     i = get_version(obj, ibuf, ibuflen, len);
673     if (i)
674         return send_reply(obj, i );
675
676     if (ibuflen <= len)
677         return send_reply(obj, AFPERR_BADUAM);
678
679     ibuf += len;
680     ibuflen -= len;
681
682     len = (unsigned char) *ibuf++;
683     ibuflen--;
684
685     if (!len || len > ibuflen)
686         return send_reply(obj, AFPERR_BADUAM);
687
688     if (NULL == (afp_uam = auth_uamfind(UAM_SERVER_LOGIN, ibuf, len)) )
689         return send_reply(obj, AFPERR_BADUAM);
690     ibuf += len;
691     ibuflen -= len;
692
693     if (AFP_OK != (i = create_session_key(obj)) )
694         return send_reply(obj, i);
695
696     i = afp_uam->u.uam_login.login(obj, &pwd, ibuf, ibuflen, rbuf, rbuflen);
697
698     if (!pwd || ( i != AFP_OK && i != AFPERR_PWDEXPR))
699         return send_reply(obj, i);
700
701     return send_reply(obj, login(obj, pwd, afp_uam->u.uam_login.logout, ((i==AFPERR_PWDEXPR)?1:0)));
702 }
703
704 /* ---------------------- */
705 int afp_login_ext(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
706 {
707     struct passwd *pwd = NULL;
708     size_t  len;
709     int     i;
710     char        type;
711     uint16_t   len16;
712     char        *username;
713
714     *rbuflen = 0;
715
716     if ( nologin & 1)
717         return send_reply(obj, AFPERR_SHUTDOWN );
718
719     if (ibuflen < 5)
720         return send_reply(obj, AFPERR_BADVERS );
721
722     ibuf++;
723     ibuf++;     /* pad  */
724     ibuf +=2;   /* flag */
725
726     len = (unsigned char) *ibuf;
727     ibuf++;
728     ibuflen -= 5;
729
730     i = get_version(obj, ibuf, ibuflen, len);
731     if (i)
732         return send_reply(obj, i );
733
734     if (ibuflen <= len)
735         return send_reply(obj, AFPERR_BADUAM);
736
737     ibuf    += len;
738     ibuflen -= len;
739
740     len = (unsigned char) *ibuf;
741     ibuf++;
742     ibuflen--;
743
744     if (!len || len > ibuflen)
745         return send_reply(obj, AFPERR_BADUAM);
746
747     if ((afp_uam = auth_uamfind(UAM_SERVER_LOGIN, ibuf, len)) == NULL)
748         return send_reply(obj, AFPERR_BADUAM);
749     ibuf    += len;
750     ibuflen -= len;
751
752     if (!afp_uam->u.uam_login.login_ext) {
753         LOG(log_error, logtype_afpd, "login_ext: uam %s not AFP 3 ready!", afp_uam->uam_name );
754         return send_reply(obj, AFPERR_BADUAM);
755     }
756     /* user name */
757     if (ibuflen <= 1 +sizeof(len16))
758         return send_reply(obj, AFPERR_PARAM);
759     type = *ibuf;
760     username = ibuf;
761     ibuf++;
762     ibuflen--;
763     if (type != 3)
764         return send_reply(obj, AFPERR_PARAM);
765
766     memcpy(&len16, ibuf, sizeof(len16));
767     ibuf += sizeof(len16);
768     ibuflen -= sizeof(len16);
769     len = ntohs(len16);
770     if (len > ibuflen)
771         return send_reply(obj, AFPERR_PARAM);
772     ibuf += len;
773     ibuflen -= len;
774
775     /* directory service name */
776     if (!ibuflen)
777         return send_reply(obj, AFPERR_PARAM);
778     type = *ibuf;
779     ibuf++;
780     ibuflen--;
781
782     switch(type) {
783     case 1:
784     case 2:
785         if (!ibuflen)
786             return send_reply(obj, AFPERR_PARAM);
787         len = (unsigned char) *ibuf;
788         ibuf++;
789         ibuflen--;
790         break;
791     case 3:
792         /* With "No User Authen" it is equal */
793         if (ibuflen < sizeof(len16))
794             return send_reply(obj, AFPERR_PARAM);
795         memcpy(&len16, ibuf, sizeof(len16));
796         ibuf += sizeof(len16);
797         ibuflen -= sizeof(len16);
798         len = ntohs(len16);
799         break;
800     default:
801         return send_reply(obj, AFPERR_PARAM);
802     }
803 #if 0
804     if (len != 0) {
805         LOG(log_error, logtype_afpd, "login_ext: directory service path not null!" );
806         return send_reply(obj, AFPERR_PARAM);
807     }
808 #endif
809     ibuf += len;
810     ibuflen -= len;
811
812     /* Pad */
813     if (ibuflen && ((unsigned long) ibuf & 1)) { /* pad character */
814         ibuf++;
815         ibuflen--;
816     }
817
818     if (AFP_OK != (i = create_session_key(obj)) ) {
819         return send_reply(obj, i);
820     }
821
822     /* FIXME user name are in UTF8 */
823     i = afp_uam->u.uam_login.login_ext(obj, username, &pwd, ibuf, ibuflen, rbuf, rbuflen);
824
825     if (!pwd || ( i != AFP_OK && i != AFPERR_PWDEXPR))
826         return send_reply(obj, i);
827
828     return send_reply(obj, login(obj, pwd, afp_uam->u.uam_login.logout, ((i==AFPERR_PWDEXPR)?1:0)));
829 }
830
831 /* ---------------------- */
832 int afp_logincont(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
833 {
834     struct passwd *pwd = NULL;
835     int err;
836
837     if ( afp_uam == NULL || afp_uam->u.uam_login.logincont == NULL || ibuflen < 2 ) {
838         *rbuflen = 0;
839         return send_reply(obj, AFPERR_NOTAUTH );
840     }
841
842     ibuf += 2; ibuflen -= 2;
843     err = afp_uam->u.uam_login.logincont(obj, &pwd, ibuf, ibuflen,
844                                          rbuf, rbuflen);
845     if (!pwd || ( err != AFP_OK && err != AFPERR_PWDEXPR))
846         return send_reply(obj, err);
847
848     return send_reply(obj, login(obj, pwd, afp_uam->u.uam_login.logout, ((err==AFPERR_PWDEXPR)?1:0)));
849 }
850
851
852 int afp_logout(AFPObj *obj, char *ibuf _U_, size_t ibuflen  _U_, char *rbuf  _U_, size_t *rbuflen)
853 {
854     DSI *dsi = (DSI *)(obj->dsi);
855
856     LOG(log_note, logtype_afpd, "AFP logout by %s", obj->username);
857     of_close_all_forks();
858     close_all_vol();
859     dsi->flags = DSI_AFP_LOGGED_OUT;
860     *rbuflen = 0;
861     return AFP_OK;
862 }
863
864
865
866 /* change password  --
867  * NOTE: an FPLogin must already have completed successfully for this
868  *       to work. this also does a little pre-processing before it hands
869  *       it off to the uam.
870  */
871 int afp_changepw(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
872 {
873     char username[MACFILELEN + 1], *start = ibuf;
874     struct uam_obj *uam;
875     struct passwd *pwd;
876     size_t len;
877     int    ret;
878
879     *rbuflen = 0;
880     ibuf += 2;
881
882     /* check if password change is allowed, OS-X ignores the flag.
883      * we shouldn't trust the client on this anyway.
884      * not sure about the "right" error code, NOOP for now */
885     if (!(obj->options.passwdbits & PASSWD_SET))
886         return AFPERR_NOOP;
887
888     /* make sure we can deal w/ this uam */
889     len = (unsigned char) *ibuf++;
890     if ((uam = auth_uamfind(UAM_SERVER_CHANGEPW, ibuf, len)) == NULL)
891         return AFPERR_BADUAM;
892
893     ibuf += len;
894     if ((len + 1) & 1) /* pad byte */
895         ibuf++;
896
897     if (obj->afp_version < 30) {
898         len = (unsigned char) *ibuf++;
899         if ( len > sizeof(username) - 1) {
900             return AFPERR_PARAM;
901         }
902         memcpy(username, ibuf, len);
903         username[ len ] = '\0';
904         ibuf += len;
905         if ((len + 1) & 1) /* pad byte */
906             ibuf++;
907     } else {
908         /* AFP > 3.0 doesn't pass the username, APF 3.1 specs page 124 */
909         if ( ibuf[0] != '\0' || ibuf[1] != '\0')
910             return AFPERR_PARAM;
911         ibuf += 2;
912         len = MIN(sizeof(username), strlen(obj->username));
913         memcpy(username, obj->username, len);
914         username[ len ] = '\0';
915     }
916
917
918     LOG(log_info, logtype_afpd, "changing password for <%s>", username);
919
920     if (( pwd = uam_getname( obj, username, sizeof(username))) == NULL )
921         return AFPERR_PARAM;
922
923     /* send it off to the uam. we really don't use ibuflen right now. */
924     if (ibuflen < (size_t)(ibuf - start)) 
925         return AFPERR_PARAM;
926     
927     ibuflen -= (ibuf - start);
928     ret = uam->u.uam_changepw(obj, username, pwd, ibuf, ibuflen,
929                               rbuf, rbuflen);
930     LOG(log_info, logtype_afpd, "password change %s.",
931         (ret == AFPERR_AUTHCONT) ? "continued" :
932         (ret ? "failed" : "succeeded"));
933     if ( ret == AFP_OK )
934         set_auth_switch(obj, 0);
935
936     return ret;
937 }
938
939
940 /* FPGetUserInfo */
941 int afp_getuserinfo(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
942 {
943     uint8_t  thisuser;
944     uint32_t id;
945     uint16_t bitmap;
946     char *bitmapp;
947
948     LOG(log_debug, logtype_afpd, "begin afp_getuserinfo:");
949
950     *rbuflen = 0;
951     ibuf++;
952     thisuser = *ibuf++;
953     ibuf += sizeof(id); /* userid is not used in AFP 2.0 */
954     memcpy(&bitmap, ibuf, sizeof(bitmap));
955     bitmap = ntohs(bitmap);
956
957     /* deal with error cases. we don't have to worry about
958      * AFPERR_ACCESS or AFPERR_NOITEM as geteuid and getegid always
959      * succeed. */
960     if (!thisuser)
961         return AFPERR_PARAM;
962     if ((bitmap & USERIBIT_ALL) != bitmap)
963         return AFPERR_BITMAP;
964
965     /* remember place where we store the possibly modified bitmap later */
966     memcpy(rbuf, ibuf, sizeof(bitmap));
967     bitmapp = rbuf;
968     rbuf += sizeof(bitmap);
969     *rbuflen = sizeof(bitmap);
970
971     /* copy the user/group info */
972     if (bitmap & USERIBIT_USER) {
973         id = htonl(geteuid());
974         memcpy(rbuf, &id, sizeof(id));
975         rbuf += sizeof(id);
976         *rbuflen += sizeof(id);
977     }
978
979     if (bitmap & USERIBIT_GROUP) {
980         id = htonl(getegid());
981         memcpy(rbuf, &id, sizeof(id));
982         rbuf += sizeof(id);
983         *rbuflen += sizeof(id);
984     }
985
986     if (bitmap & USERIBIT_UUID) {
987         if ( ! (obj->options.flags & OPTION_UUID)) {
988             bitmap &= ~USERIBIT_UUID;
989             bitmap = htons(bitmap);
990             memcpy(bitmapp, &bitmap, sizeof(bitmap));
991         } else {
992             LOG(log_debug, logtype_afpd, "afp_getuserinfo: get UUID for \'%s\'", obj->username);
993             int ret;
994             atalk_uuid_t uuid;
995             ret = getuuidfromname( obj->username, UUID_USER, uuid);
996             if (ret != 0) {
997                 LOG(log_info, logtype_afpd, "afp_getuserinfo: error getting UUID !");
998                 return AFPERR_NOITEM;
999             }
1000             LOG(log_debug, logtype_afpd, "afp_getuserinfo: got UUID: %s", uuid_bin2string(uuid));
1001
1002             memcpy(rbuf, uuid, UUID_BINSIZE);
1003             rbuf += UUID_BINSIZE;
1004             *rbuflen += UUID_BINSIZE;
1005         }
1006     }
1007
1008     LOG(log_debug, logtype_afpd, "END afp_getuserinfo:");
1009     return AFP_OK;
1010 }
1011
1012 #define UAM_LIST(type) (((type) == UAM_SERVER_LOGIN || (type) == UAM_SERVER_LOGIN_EXT) ? &uam_login : \
1013                         (((type) == UAM_SERVER_CHANGEPW) ?              \
1014                          &uam_changepw : NULL))
1015
1016 /* just do a linked list search. this could be sped up with a hashed
1017  * list, but i doubt anyone's going to have enough uams to matter. */
1018 struct uam_obj *auth_uamfind(const int type, const char *name,
1019                              const int len)
1020 {
1021     struct uam_obj *prev, *start;
1022
1023     if (!name || !(start = UAM_LIST(type)))
1024         return NULL;
1025
1026     prev = start;
1027     while ((prev = prev->uam_prev) != start)
1028         if (strndiacasecmp(prev->uam_name, name, len) == 0)
1029             return prev;
1030
1031     return NULL;
1032 }
1033
1034 int auth_register(const int type, struct uam_obj *uam)
1035 {
1036     struct uam_obj *start;
1037
1038     if (!uam || !uam->uam_name || (*uam->uam_name == '\0'))
1039         return -1;
1040
1041     if (!(start = UAM_LIST(type)))
1042         return 1; /* we don't know what to do with it, caller must free it */
1043
1044     uam_attach(start, uam);
1045     return 0;
1046 }
1047
1048 /* load all of the modules */
1049 int auth_load(const char *path, const char *list)
1050 {
1051     char name[MAXPATHLEN + 1], buf[MAXPATHLEN + 1], *p;
1052     struct uam_mod *mod;
1053     struct stat st;
1054     size_t len;
1055
1056     if (!path || !*path || !list || (len = strlen(path)) > sizeof(name) - 2)
1057         return -1;
1058
1059     strlcpy(buf, list, sizeof(buf));
1060     if ((p = strtok(buf, ", ")) == NULL)
1061         return -1;
1062
1063     strcpy(name, path);
1064     if (name[len - 1] != '/') {
1065         strcat(name, "/");
1066         len++;
1067     }
1068
1069     while (p) {
1070         strlcpy(name + len, p, sizeof(name) - len);
1071         LOG(log_debug, logtype_afpd, "uam: loading (%s)", name);
1072         /*
1073           if ((stat(name, &st) == 0) && (mod = uam_load(name, p))) {
1074         */
1075         if (stat(name, &st) == 0) {
1076             if ((mod = uam_load(name, p))) {
1077                 uam_attach(&uam_modules, mod);
1078                 LOG(log_debug, logtype_afpd, "uam: %s loaded", p);
1079             } else {
1080                 LOG(log_error, logtype_afpd, "uam: %s load failure",p);
1081             }
1082         } else {
1083             LOG(log_info, logtype_afpd, "uam: uam not found (status=%d)", stat(name, &st));
1084         }
1085         p = strtok(NULL, ", ");
1086     }
1087
1088     return 0;
1089 }
1090
1091 /* get rid of all of the uams */
1092 void auth_unload(void)
1093 {
1094     struct uam_mod *mod, *prev, *start = &uam_modules;
1095
1096     prev = start->uam_prev;
1097     while ((mod = prev) != start) {
1098         prev = prev->uam_prev;
1099         uam_detach(mod);
1100         uam_unload(mod);
1101     }
1102 }