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