mp.c revision 36285
1/*-
2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 *	$Id: mp.c,v 1.1.2.29 1998/05/15 18:21:41 brian Exp $
27 */
28
29#include <sys/types.h>
30#include <netinet/in.h>
31#include <netinet/in_systm.h>
32#include <netinet/ip.h>
33#include <arpa/inet.h>
34#include <net/if_dl.h>
35#include <sys/socket.h>
36#include <sys/un.h>
37
38#include <errno.h>
39#include <paths.h>
40#include <stdlib.h>
41#include <stdio.h>
42#include <string.h>
43#include <sys/stat.h>
44#include <termios.h>
45#include <unistd.h>
46
47#include "command.h"
48#include "mbuf.h"
49#include "log.h"
50#include "defs.h"
51#include "timer.h"
52#include "fsm.h"
53#include "iplist.h"
54#include "throughput.h"
55#include "slcompress.h"
56#include "ipcp.h"
57#include "auth.h"
58#include "lcp.h"
59#include "lqr.h"
60#include "hdlc.h"
61#include "async.h"
62#include "ccp.h"
63#include "link.h"
64#include "descriptor.h"
65#include "physical.h"
66#include "chat.h"
67#include "lcpproto.h"
68#include "filter.h"
69#include "mp.h"
70#include "chap.h"
71#include "datalink.h"
72#include "bundle.h"
73#include "ip.h"
74#include "prompt.h"
75#include "id.h"
76#include "arp.h"
77
78void
79peerid_Init(struct peerid *peer)
80{
81  peer->enddisc.class = 0;
82  *peer->enddisc.address = '\0';
83  peer->enddisc.len = 0;
84  *peer->authname = '\0';
85}
86
87int
88peerid_Equal(const struct peerid *p1, const struct peerid *p2)
89{
90  return !strcmp(p1->authname, p2->authname) &&
91         p1->enddisc.class == p2->enddisc.class &&
92         p1->enddisc.len == p2->enddisc.len &&
93         !memcmp(p1->enddisc.address, p2->enddisc.address, p1->enddisc.len);
94}
95
96static u_int32_t
97inc_seq(unsigned is12bit, u_int32_t seq)
98{
99  seq++;
100  if (is12bit) {
101    if (seq & 0xfffff000)
102      seq = 0;
103  } else if (seq & 0xff000000)
104    seq = 0;
105  return seq;
106}
107
108static int
109isbefore(unsigned is12bit, u_int32_t seq1, u_int32_t seq2)
110{
111  u_int32_t max = (is12bit ? 0xfff : 0xffffff) - 0x200;
112
113  if (seq1 > max) {
114    if (seq2 < 0x200 || seq2 > seq1)
115      return 1;
116  } else if ((seq1 > 0x200 || seq2 <= max) && seq1 < seq2)
117    return 1;
118
119  return 0;
120}
121
122static int
123mp_ReadHeader(struct mp *mp, struct mbuf *m, struct mp_header *header)
124{
125  if (mp->local_is12bit) {
126    header->seq = ntohs(*(u_int16_t *)MBUF_CTOP(m));
127    if (header->seq & 0x3000) {
128      log_Printf(LogWARN, "Oops - MP header without required zero bits\n");
129      return 0;
130    }
131    header->begin = header->seq & 0x8000 ? 1 : 0;
132    header->end = header->seq & 0x4000 ? 1 : 0;
133    header->seq &= 0x0fff;
134    return 2;
135  } else {
136    header->seq = ntohl(*(u_int32_t *)MBUF_CTOP(m));
137    if (header->seq & 0x3f000000) {
138      log_Printf(LogWARN, "Oops - MP header without required zero bits\n");
139      return 0;
140    }
141    header->begin = header->seq & 0x80000000 ? 1 : 0;
142    header->end = header->seq & 0x40000000 ? 1 : 0;
143    header->seq &= 0x00ffffff;
144    return 4;
145  }
146}
147
148static void
149mp_LayerStart(void *v, struct fsm *fp)
150{
151  /* The given FSM (ccp) is about to start up ! */
152}
153
154static void
155mp_LayerUp(void *v, struct fsm *fp)
156{
157  /* The given fsm (ccp) is now up */
158}
159
160static void
161mp_LayerDown(void *v, struct fsm *fp)
162{
163  /* The given FSM (ccp) has been told to come down */
164}
165
166static void
167mp_LayerFinish(void *v, struct fsm *fp)
168{
169  /* The given fsm (ccp) is now down */
170  if (fp->state == ST_CLOSED && fp->open_mode == OPEN_PASSIVE)
171    fsm_Open(fp);		/* CCP goes to ST_STOPPED */
172}
173
174void
175mp_Init(struct mp *mp, struct bundle *bundle)
176{
177  mp->peer_is12bit = mp->local_is12bit = 0;
178  mp->peer_mrru = mp->local_mrru = 0;
179
180  peerid_Init(&mp->peer);
181
182  mp->out.seq = 0;
183  mp->out.link = 0;
184  mp->seq.min_in = 0;
185  mp->seq.next_in = 0;
186  mp->inbufs = NULL;
187  mp->bundle = bundle;
188
189  mp->link.type = MP_LINK;
190  mp->link.name = "mp";
191  mp->link.len = sizeof *mp;
192
193  throughput_init(&mp->link.throughput);
194  memset(mp->link.Queue, '\0', sizeof mp->link.Queue);
195  memset(mp->link.proto_in, '\0', sizeof mp->link.proto_in);
196  memset(mp->link.proto_out, '\0', sizeof mp->link.proto_out);
197
198  mp->fsmp.LayerStart = mp_LayerStart;
199  mp->fsmp.LayerUp = mp_LayerUp;
200  mp->fsmp.LayerDown = mp_LayerDown;
201  mp->fsmp.LayerFinish = mp_LayerFinish;
202  mp->fsmp.object = mp;
203
204  mpserver_Init(&mp->server);
205
206  mp->cfg.mrru = 0;
207  mp->cfg.shortseq = NEG_ENABLED|NEG_ACCEPTED;
208  mp->cfg.enddisc.class = 0;
209  *mp->cfg.enddisc.address = '\0';
210  mp->cfg.enddisc.len = 0;
211
212  lcp_Init(&mp->link.lcp, mp->bundle, &mp->link, NULL);
213  ccp_Init(&mp->link.ccp, mp->bundle, &mp->link, &mp->fsmp);
214}
215
216int
217mp_Up(struct mp *mp, struct datalink *dl)
218{
219  struct lcp *lcp = &dl->physical->link.lcp;
220
221  if (mp->active) {
222    /* We're adding a link - do a last validation on our parameters */
223    if (!peerid_Equal(&dl->peer, &mp->peer)) {
224      log_Printf(LogPHASE, "%s: Inappropriate peer !\n", dl->name);
225      return MP_FAILED;
226    }
227    if (mp->local_mrru != lcp->want_mrru ||
228        mp->peer_mrru != lcp->his_mrru ||
229        mp->local_is12bit != lcp->want_shortseq ||
230        mp->peer_is12bit != lcp->his_shortseq) {
231      log_Printf(LogPHASE, "%s: Invalid MRRU/SHORTSEQ MP parameters !\n",
232                dl->name);
233      return MP_FAILED;
234    }
235    return MP_ADDED;
236  } else {
237    /* First link in multilink mode */
238
239    mp->local_mrru = lcp->want_mrru;
240    mp->peer_mrru = lcp->his_mrru;
241    mp->local_is12bit = lcp->want_shortseq;
242    mp->peer_is12bit = lcp->his_shortseq;
243    mp->peer = dl->peer;
244
245    throughput_init(&mp->link.throughput);
246    memset(mp->link.Queue, '\0', sizeof mp->link.Queue);
247    memset(mp->link.proto_in, '\0', sizeof mp->link.proto_in);
248    memset(mp->link.proto_out, '\0', sizeof mp->link.proto_out);
249
250    mp->out.seq = 0;
251    mp->out.link = 0;
252    mp->seq.min_in = 0;
253    mp->seq.next_in = 0;
254
255    /*
256     * Now we create our server socket.
257     * If it already exists, join it.  Otherwise, create and own it
258     */
259    switch (mpserver_Open(&mp->server, &mp->peer)) {
260    case MPSERVER_CONNECTED:
261      log_Printf(LogPHASE, "mp: Transfer link on %s\n",
262                mp->server.socket.sun_path);
263      mp->server.send.dl = dl;		/* Defer 'till it's safe to send */
264      return MP_LINKSENT;
265    case MPSERVER_FAILED:
266      return MP_FAILED;
267    case MPSERVER_LISTENING:
268      log_Printf(LogPHASE, "mp: Listening on %s\n", mp->server.socket.sun_path);
269      log_Printf(LogPHASE, "    First link: %s\n", dl->name);
270
271      /* Re-point our IPCP layer at our MP link */
272      ipcp_SetLink(&mp->bundle->ncp.ipcp, &mp->link);
273
274      /* Our lcp's already up 'cos of the NULL parent */
275      fsm_Up(&mp->link.ccp.fsm);
276      fsm_Open(&mp->link.ccp.fsm);
277
278      mp->active = 1;
279      break;
280    }
281  }
282
283  return MP_UP;
284}
285
286void
287mp_Down(struct mp *mp)
288{
289  if (mp->active) {
290    struct mbuf *next;
291
292    /* Don't want any more of these */
293    mpserver_Close(&mp->server);
294
295    /* CCP goes down with a bang */
296    fsm_Down(&mp->link.ccp.fsm);
297    fsm_Close(&mp->link.ccp.fsm);
298
299    /* Received fragments go in the bit-bucket */
300    while (mp->inbufs) {
301      next = mp->inbufs->pnext;
302      mbuf_Free(mp->inbufs);
303      mp->inbufs = next;
304    }
305
306    peerid_Init(&mp->peer);
307    mp->active = 0;
308  }
309}
310
311void
312mp_linkInit(struct mp_link *mplink)
313{
314  mplink->seq = 0;
315  mplink->weight = 1500;
316}
317
318void
319mp_Input(struct mp *mp, struct mbuf *m, struct physical *p)
320{
321  struct mp_header mh, h;
322  struct mbuf *q, *last;
323  int32_t seq;
324
325  if (mp_ReadHeader(mp, m, &mh) == 0) {
326    mbuf_Free(m);
327    return;
328  }
329
330  seq = p->dl->mp.seq;
331  p->dl->mp.seq = mh.seq;
332  if (mp->seq.min_in == seq) {
333    /*
334     * We've received new data on the link that has our min (oldest) seq.
335     * Figure out which link now has the smallest (oldest) seq.
336     */
337    struct datalink *dl;
338
339    mp->seq.min_in = p->dl->mp.seq;
340    for (dl = mp->bundle->links; dl; dl = dl->next)
341      if (mp->seq.min_in > dl->mp.seq)
342        mp->seq.min_in = dl->mp.seq;
343  }
344
345  /*
346   * Now process as many of our fragments as we can, adding our new
347   * fragment in as we go, and ordering with the oldest at the top of
348   * the queue.
349   */
350
351  if (!mp->inbufs) {
352    mp->inbufs = m;
353    m = NULL;
354  }
355
356  last = NULL;
357  seq = mp->seq.next_in;
358  q = mp->inbufs;
359  while (q) {
360    mp_ReadHeader(mp, q, &h);
361    if (m && isbefore(mp->local_is12bit, mh.seq, h.seq)) {
362      /* Our received fragment fits in before this one, so link it in */
363      if (last)
364        last->pnext = m;
365      else
366        mp->inbufs = m;
367      m->pnext = q;
368      q = m;
369      h = mh;
370      m = NULL;
371    }
372
373    if (h.seq != seq) {
374      /* we're missing something :-( */
375      if (mp->seq.min_in > seq) {
376        /* we're never gonna get it */
377        struct mbuf *next;
378
379        /* Zap all older fragments */
380        while (mp->inbufs != q) {
381          log_Printf(LogDEBUG, "Drop frag\n");
382          next = mp->inbufs->pnext;
383          mbuf_Free(mp->inbufs);
384          mp->inbufs = next;
385        }
386
387        /*
388         * Zap everything until the next `end' fragment OR just before
389         * the next `begin' fragment OR 'till seq.min_in - whichever
390         * comes first.
391         */
392        do {
393          mp_ReadHeader(mp, mp->inbufs, &h);
394          if (h.begin) {
395            /* We might be able to process this ! */
396            h.seq--;  /* We're gonna look for fragment with h.seq+1 */
397            break;
398          }
399          next = mp->inbufs->pnext;
400          log_Printf(LogDEBUG, "Drop frag %u\n", h.seq);
401          mbuf_Free(mp->inbufs);
402          mp->inbufs = next;
403        } while (mp->inbufs && (h.seq >= mp->seq.min_in || h.end));
404
405        /*
406         * Continue processing things from here.
407         * This deals with the possibility that we received a fragment
408         * on the slowest link that invalidates some of our data (because
409         * of the hole at `q'), but where there are subsequent `whole'
410         * packets that have already been received.
411         */
412
413        mp->seq.next_in = seq = inc_seq(mp->local_is12bit, h.seq);
414        last = NULL;
415        q = mp->inbufs;
416      } else
417        /* we may still receive the missing fragment */
418        break;
419    } else if (h.end) {
420      /* We've got something, reassemble */
421      struct mbuf **frag = &q;
422      int len;
423      u_long first = -1;
424
425      do {
426        *frag = mp->inbufs;
427        mp->inbufs = mp->inbufs->pnext;
428        len = mp_ReadHeader(mp, *frag, &h);
429        if (first == -1)
430          first = h.seq;
431        (*frag)->offset += len;
432        (*frag)->cnt -= len;
433        (*frag)->pnext = NULL;
434        if (frag == &q && !h.begin) {
435          log_Printf(LogWARN, "Oops - MP frag %lu should have a begin flag\n",
436                    (u_long)h.seq);
437          mbuf_Free(q);
438          q = NULL;
439        } else if (frag != &q && h.begin) {
440          log_Printf(LogWARN, "Oops - MP frag %lu should have an end flag\n",
441                    (u_long)h.seq - 1);
442          /*
443           * Stuff our fragment back at the front of the queue and zap
444           * our half-assembed packet.
445           */
446          (*frag)->pnext = mp->inbufs;
447          mp->inbufs = *frag;
448          *frag = NULL;
449          mbuf_Free(q);
450          q = NULL;
451          frag = &q;
452          h.end = 0;	/* just in case it's a whole packet */
453        } else
454          do
455            frag = &(*frag)->next;
456          while (*frag != NULL);
457      } while (!h.end);
458
459      if (q) {
460        u_short proto;
461        u_char ch;
462
463        q = mbuf_Read(q, &ch, 1);
464        proto = ch;
465        if (!(proto & 1)) {
466          q = mbuf_Read(q, &ch, 1);
467          proto <<= 8;
468          proto += ch;
469        }
470        if (log_IsKept(LogDEBUG))
471          log_Printf(LogDEBUG, "MP: Reassembled frags %ld-%lu, length %d\n",
472                    first, (u_long)h.seq, mbuf_Length(q));
473        hdlc_DecodePacket(mp->bundle, proto, q, &mp->link);
474      }
475
476      mp->seq.next_in = seq = inc_seq(mp->local_is12bit, h.seq);
477      last = NULL;
478      q = mp->inbufs;
479    } else {
480      /* Look for the next fragment */
481      seq = inc_seq(mp->local_is12bit, seq);
482      last = q;
483      q = q->pnext;
484    }
485  }
486
487  if (m) {
488    /* We still have to find a home for our new fragment */
489    last = NULL;
490    for (q = mp->inbufs; q; last = q, q = q->pnext) {
491      mp_ReadHeader(mp, q, &h);
492      if (isbefore(mp->local_is12bit, mh.seq, h.seq))
493        break;
494    }
495    /* Our received fragment fits in here */
496    if (last)
497      last->pnext = m;
498    else
499      mp->inbufs = m;
500    m->pnext = q;
501  }
502}
503
504static void
505mp_Output(struct mp *mp, struct link *l, struct mbuf *m, u_int32_t begin,
506          u_int32_t end)
507{
508  struct mbuf *mo;
509
510  /* Stuff an MP header on the front of our packet and send it */
511  mo = mbuf_Alloc(4, MB_MP);
512  mo->next = m;
513  if (mp->peer_is12bit) {
514    u_int16_t *seq16;
515
516    seq16 = (u_int16_t *)MBUF_CTOP(mo);
517    *seq16 = htons((begin << 15) | (end << 14) | (u_int16_t)mp->out.seq);
518    mo->cnt = 2;
519  } else {
520    u_int32_t *seq32;
521
522    seq32 = (u_int32_t *)MBUF_CTOP(mo);
523    *seq32 = htonl((begin << 31) | (end << 30) | (u_int32_t)mp->out.seq);
524    mo->cnt = 4;
525  }
526  if (log_IsKept(LogDEBUG))
527    log_Printf(LogDEBUG, "MP[frag %d]: Send %d bytes on link `%s'\n",
528              mp->out.seq, mbuf_Length(mo), l->name);
529  mp->out.seq = inc_seq(mp->peer_is12bit, mp->out.seq);
530
531  if (!ccp_Compress(&l->ccp, l, PRI_NORMAL, PROTO_MP, mo))
532    hdlc_Output(l, PRI_NORMAL, PROTO_MP, mo);
533}
534
535int
536mp_FillQueues(struct bundle *bundle)
537{
538  struct mp *mp = &bundle->ncp.mp;
539  struct datalink *dl, *fdl;
540  int total, add, len, thislink, nlinks;
541  u_int32_t begin, end;
542  struct mbuf *m, *mo;
543
544  thislink = nlinks = 0;
545  for (fdl = NULL, dl = bundle->links; dl; dl = dl->next) {
546    if (!fdl) {
547      if (thislink == mp->out.link)
548        fdl = dl;
549      else
550        thislink++;
551    }
552    nlinks++;
553  }
554
555  if (!fdl) {
556    fdl = bundle->links;
557    if (!fdl)
558      return 0;
559    thislink = 0;
560  }
561
562  total = 0;
563  for (dl = fdl; nlinks > 0; dl = dl->next, nlinks--, thislink++) {
564    if (!dl) {
565      dl = bundle->links;
566      thislink = 0;
567    }
568
569    if (dl->state != DATALINK_OPEN)
570      continue;
571
572    if (dl->physical->out)
573      /* this link has suffered a short write.  Let it continue */
574      continue;
575
576    add = link_QueueLen(&dl->physical->link);
577    total += add;
578    if (add)
579      /* this link has got stuff already queued.  Let it continue */
580      continue;
581
582    if (!link_QueueLen(&mp->link) && !ip_FlushPacket(&mp->link, bundle))
583      /* Nothing else to send */
584      break;
585
586    m = link_Dequeue(&mp->link);
587    len = mbuf_Length(m);
588    begin = 1;
589    end = 0;
590
591    while (!end) {
592      if (dl->state == DATALINK_OPEN) {
593        if (len <= dl->mp.weight + LINK_MINWEIGHT) {
594          /*
595           * XXX: Should we remember how much of our `weight' wasn't sent
596           *      so that we can compensate next time ?
597           */
598          mo = m;
599          end = 1;
600        } else {
601          mo = mbuf_Alloc(dl->mp.weight, MB_MP);
602          mo->cnt = dl->mp.weight;
603          len -= mo->cnt;
604          m = mbuf_Read(m, MBUF_CTOP(mo), mo->cnt);
605        }
606        mp_Output(mp, &dl->physical->link, mo, begin, end);
607        begin = 0;
608      }
609
610      if (!end) {
611        nlinks--;
612        dl = dl->next;
613        if (!dl) {
614          dl = bundle->links;
615          thislink = 0;
616        } else
617          thislink++;
618      }
619    }
620  }
621  mp->out.link = thislink;		/* Start here next time */
622
623  return total;
624}
625
626int
627mp_SetDatalinkWeight(struct cmdargs const *arg)
628{
629  int val;
630
631  if (arg->argc != arg->argn+1)
632    return -1;
633
634  val = atoi(arg->argv[arg->argn]);
635  if (val < LINK_MINWEIGHT) {
636    log_Printf(LogWARN, "Link weights must not be less than %d\n",
637              LINK_MINWEIGHT);
638    return 1;
639  }
640  arg->cx->mp.weight = val;
641  return 0;
642}
643
644int
645mp_ShowStatus(struct cmdargs const *arg)
646{
647  struct mp *mp = &arg->bundle->ncp.mp;
648
649  prompt_Printf(arg->prompt, "Multilink is %sactive\n", mp->active ? "" : "in");
650  if (mp->active) {
651    struct mbuf *m;
652    int bufs = 0;
653
654    prompt_Printf(arg->prompt, "Socket:         %s\n",
655                  mp->server.socket.sun_path);
656    for (m = mp->inbufs; m; m = m->pnext)
657      bufs++;
658    prompt_Printf(arg->prompt, "Pending frags:  %d\n", bufs);
659  }
660
661  prompt_Printf(arg->prompt, "\nMy Side:\n");
662  if (mp->active) {
663    prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->local_mrru);
664    prompt_Printf(arg->prompt, " Short Seq:     %s\n",
665                  mp->local_is12bit ? "on" : "off");
666  }
667  prompt_Printf(arg->prompt, " Discriminator: %s\n",
668                mp_Enddisc(mp->cfg.enddisc.class, mp->cfg.enddisc.address,
669                           mp->cfg.enddisc.len));
670
671  prompt_Printf(arg->prompt, "\nHis Side:\n");
672  if (mp->active) {
673    prompt_Printf(arg->prompt, " Auth Name:     %s\n", mp->peer.authname);
674    prompt_Printf(arg->prompt, " Next SEQ:      %u\n", mp->out.seq);
675    prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->peer_mrru);
676    prompt_Printf(arg->prompt, " Short Seq:     %s\n",
677                  mp->peer_is12bit ? "on" : "off");
678  }
679  prompt_Printf(arg->prompt,   " Discriminator: %s\n",
680                mp_Enddisc(mp->peer.enddisc.class, mp->peer.enddisc.address,
681                           mp->peer.enddisc.len));
682
683  prompt_Printf(arg->prompt, "\nDefaults:\n");
684
685  prompt_Printf(arg->prompt, " MRRU:          ");
686  if (mp->cfg.mrru)
687    prompt_Printf(arg->prompt, "%d (multilink enabled)\n", mp->cfg.mrru);
688  else
689    prompt_Printf(arg->prompt, "disabled\n");
690  prompt_Printf(arg->prompt, " Short Seq:     %s\n",
691                  command_ShowNegval(mp->cfg.shortseq));
692
693  return 0;
694}
695
696const char *
697mp_Enddisc(u_char c, const char *address, int len)
698{
699  static char result[100];
700  int f, header;
701
702  switch (c) {
703    case ENDDISC_NULL:
704      sprintf(result, "Null Class");
705      break;
706
707    case ENDDISC_LOCAL:
708      snprintf(result, sizeof result, "Local Addr: %.*s", len, address);
709      break;
710
711    case ENDDISC_IP:
712      if (len == 4)
713        snprintf(result, sizeof result, "IP %s",
714                 inet_ntoa(*(const struct in_addr *)address));
715      else
716        sprintf(result, "IP[%d] ???", len);
717      break;
718
719    case ENDDISC_MAC:
720      if (len == 6) {
721        const u_char *m = (const u_char *)address;
722        snprintf(result, sizeof result, "MAC %02x:%02x:%02x:%02x:%02x:%02x",
723                 m[0], m[1], m[2], m[3], m[4], m[5]);
724      } else
725        sprintf(result, "MAC[%d] ???", len);
726      break;
727
728    case ENDDISC_MAGIC:
729      sprintf(result, "Magic: 0x");
730      header = strlen(result);
731      if (len > sizeof result - header - 1)
732        len = sizeof result - header - 1;
733      for (f = 0; f < len; f++)
734        sprintf(result + header + 2 * f, "%02x", address[f]);
735      break;
736
737    case ENDDISC_PSN:
738      snprintf(result, sizeof result, "PSN: %.*s", len, address);
739      break;
740
741     default:
742      sprintf(result, "%d: ", (int)c);
743      header = strlen(result);
744      if (len > sizeof result - header - 1)
745        len = sizeof result - header - 1;
746      for (f = 0; f < len; f++)
747        sprintf(result + header + 2 * f, "%02x", address[f]);
748      break;
749  }
750  return result;
751}
752
753int
754mp_SetEnddisc(struct cmdargs const *arg)
755{
756  struct mp *mp = &arg->bundle->ncp.mp;
757  struct in_addr addr;
758
759  if (bundle_Phase(arg->bundle) != PHASE_DEAD) {
760    log_Printf(LogWARN, "set enddisc: Only available at phase DEAD\n");
761    return 1;
762  }
763
764  if (arg->argc == arg->argn) {
765    mp->cfg.enddisc.class = 0;
766    *mp->cfg.enddisc.address = '\0';
767    mp->cfg.enddisc.len = 0;
768  } else if (arg->argc > arg->argn) {
769    if (!strcasecmp(arg->argv[arg->argn], "label")) {
770      mp->cfg.enddisc.class = ENDDISC_LOCAL;
771      strcpy(mp->cfg.enddisc.address, arg->bundle->cfg.label);
772      mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
773    } else if (!strcasecmp(arg->argv[arg->argn], "ip")) {
774      if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
775        addr = arg->bundle->ncp.ipcp.cfg.my_range.ipaddr;
776      else
777        addr = arg->bundle->ncp.ipcp.my_ip;
778      memcpy(mp->cfg.enddisc.address, &addr.s_addr, sizeof addr.s_addr);
779      mp->cfg.enddisc.class = ENDDISC_IP;
780      mp->cfg.enddisc.len = sizeof arg->bundle->ncp.ipcp.my_ip.s_addr;
781    } else if (!strcasecmp(arg->argv[arg->argn], "mac")) {
782      struct sockaddr_dl hwaddr;
783      int s;
784
785      if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
786        addr = arg->bundle->ncp.ipcp.cfg.my_range.ipaddr;
787      else
788        addr = arg->bundle->ncp.ipcp.my_ip;
789
790      s = ID0socket(AF_INET, SOCK_DGRAM, 0);
791      if (s < 0) {
792        log_Printf(LogERROR, "set enddisc: socket(): %s\n", strerror(errno));
793        return 2;
794      }
795      if (get_ether_addr(s, addr, &hwaddr)) {
796        mp->cfg.enddisc.class = ENDDISC_MAC;
797        memcpy(mp->cfg.enddisc.address, hwaddr.sdl_data + hwaddr.sdl_nlen,
798               hwaddr.sdl_alen);
799        mp->cfg.enddisc.len = hwaddr.sdl_alen;
800      } else {
801        log_Printf(LogWARN, "set enddisc: Can't locate MAC address for %s\n",
802                  inet_ntoa(addr));
803        close(s);
804        return 4;
805      }
806      close(s);
807    } else if (!strcasecmp(arg->argv[arg->argn], "magic")) {
808      int f;
809
810      randinit();
811      for (f = 0; f < 20; f += sizeof(long))
812        *(long *)(mp->cfg.enddisc.address + f) = random();
813      mp->cfg.enddisc.class = ENDDISC_MAGIC;
814      mp->cfg.enddisc.len = 20;
815    } else if (!strcasecmp(arg->argv[arg->argn], "psn")) {
816      if (arg->argc > arg->argn+1) {
817        mp->cfg.enddisc.class = ENDDISC_PSN;
818        strcpy(mp->cfg.enddisc.address, arg->argv[arg->argn+1]);
819        mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
820      } else {
821        log_Printf(LogWARN, "PSN endpoint requires additional data\n");
822        return 5;
823      }
824    } else {
825      log_Printf(LogWARN, "%s: Unrecognised endpoint type\n",
826                arg->argv[arg->argn]);
827      return 6;
828    }
829  }
830
831  return 0;
832}
833
834static int
835mpserver_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e,
836                   int *n)
837{
838  struct mpserver *s = descriptor2mpserver(d);
839
840  if (s->send.dl != NULL) {
841    /* We've connect()ed */
842    if (!link_QueueLen(&s->send.dl->physical->link) &&
843        !s->send.dl->physical->out) {
844      /* Only send if we've transmitted all our data (i.e. the ConfigAck) */
845      datalink_RemoveFromSet(s->send.dl, r, w, e);
846      bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
847      s->send.dl = NULL;
848      close(s->fd);
849      s->fd = -1;
850    } else
851      /* Never read from a datalink that's on death row ! */
852      datalink_RemoveFromSet(s->send.dl, r, NULL, NULL);
853  } else if (r && s->fd >= 0) {
854    if (*n < s->fd + 1)
855      *n = s->fd + 1;
856    FD_SET(s->fd, r);
857    log_Printf(LogTIMER, "mp: fdset(r) %d\n", s->fd);
858    return 1;
859  }
860  return 0;
861}
862
863static int
864mpserver_IsSet(struct descriptor *d, const fd_set *fdset)
865{
866  struct mpserver *s = descriptor2mpserver(d);
867  return s->fd >= 0 && FD_ISSET(s->fd, fdset);
868}
869
870static void
871mpserver_Read(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
872{
873  struct mpserver *s = descriptor2mpserver(d);
874  struct sockaddr in;
875  int fd, size;
876
877  size = sizeof in;
878  fd = accept(s->fd, &in, &size);
879  if (fd < 0) {
880    log_Printf(LogERROR, "mpserver_Read: accept(): %s\n", strerror(errno));
881    return;
882  }
883
884  if (in.sa_family == AF_LOCAL)
885    bundle_ReceiveDatalink(bundle, fd, (struct sockaddr_un *)&in);
886
887  close(fd);
888}
889
890static void
891mpserver_Write(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
892{
893  /* We never want to write here ! */
894  log_Printf(LogERROR, "mpserver_Write: Internal error: Bad call !\n");
895}
896
897void
898mpserver_Init(struct mpserver *s)
899{
900  s->desc.type = MPSERVER_DESCRIPTOR;
901  s->desc.next = NULL;
902  s->desc.UpdateSet = mpserver_UpdateSet;
903  s->desc.IsSet = mpserver_IsSet;
904  s->desc.Read = mpserver_Read;
905  s->desc.Write = mpserver_Write;
906  s->send.dl = NULL;
907  s->fd = -1;
908  memset(&s->socket, '\0', sizeof s->socket);
909}
910
911int
912mpserver_Open(struct mpserver *s, struct peerid *peer)
913{
914  int f, l;
915  mode_t mask;
916
917  if (s->fd != -1) {
918    log_Printf(LogERROR, "Internal error !  mpserver already open\n");
919    mpserver_Close(s);
920  }
921
922  l = snprintf(s->socket.sun_path, sizeof s->socket.sun_path, "%sppp-%s-%02x-",
923               _PATH_VARRUN, peer->authname, peer->enddisc.class);
924
925  for (f = 0; f < peer->enddisc.len && l < sizeof s->socket.sun_path - 2; f++) {
926    snprintf(s->socket.sun_path + l, sizeof s->socket.sun_path - l,
927             "%02x", *(u_char *)(peer->enddisc.address+f));
928    l += 2;
929  }
930
931  s->socket.sun_family = AF_LOCAL;
932  s->socket.sun_len = sizeof s->socket;
933  s->fd = ID0socket(PF_LOCAL, SOCK_STREAM, 0);
934  if (s->fd < 0) {
935    log_Printf(LogERROR, "mpserver: socket: %s\n", strerror(errno));
936    return MPSERVER_FAILED;
937  }
938
939  setsockopt(s->fd, SOL_SOCKET, SO_REUSEADDR, (struct sockaddr *)&s->socket,
940             sizeof s->socket);
941  mask = umask(0177);
942  if (ID0bind_un(s->fd, &s->socket) < 0) {
943    if (errno != EADDRINUSE) {
944      log_Printf(LogPHASE, "mpserver: can't create bundle socket %s (%s)\n",
945                s->socket.sun_path, strerror(errno));
946      umask(mask);
947      close(s->fd);
948      s->fd = -1;
949      return MPSERVER_FAILED;
950    }
951    umask(mask);
952    if (ID0connect_un(s->fd, &s->socket) < 0) {
953      log_Printf(LogPHASE, "mpserver: can't connect to bundle socket %s (%s)\n",
954                s->socket.sun_path, strerror(errno));
955      if (errno == ECONNREFUSED)
956        log_Printf(LogPHASE, "          Has the previous server died badly ?\n");
957      close(s->fd);
958      s->fd = -1;
959      return MPSERVER_FAILED;
960    }
961
962    /* Donate our link to the other guy */
963    return MPSERVER_CONNECTED;
964  }
965
966  /* Listen for other ppp invocations that want to donate links */
967  if (listen(s->fd, 5) != 0) {
968    log_Printf(LogERROR, "mpserver: Unable to listen to socket"
969              " - BUNDLE overload?\n");
970    mpserver_Close(s);
971  }
972
973  return MPSERVER_LISTENING;
974}
975
976void
977mpserver_Close(struct mpserver *s)
978{
979  if (s->send.dl != NULL) {
980    bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
981    s->send.dl = NULL;
982    close(s->fd);
983    s->fd = -1;
984  } else if (s->fd >= 0) {
985    close(s->fd);
986    if (ID0unlink(s->socket.sun_path) == -1)
987      log_Printf(LogERROR, "%s: Failed to remove: %s\n", s->socket.sun_path,
988                strerror(errno));
989    memset(&s->socket, '\0', sizeof s->socket);
990    s->fd = -1;
991  }
992}
993