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