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