mp.c revision 47577
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.20 1999/05/12 09:48:55 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        q = mbuf_Contiguous(q);
494        log_Printf(LogDEBUG, "MP: Reassembled frags %ld-%lu, length %d\n",
495                   first, (u_long)h.seq, mbuf_Length(q));
496        link_PullPacket(&mp->link, MBUF_CTOP(q), q->cnt, mp->bundle);
497        mbuf_Free(q);
498      }
499
500      mp->seq.next_in = seq = inc_seq(mp->local_is12bit, h.seq);
501      last = NULL;
502      q = mp->inbufs;
503    } else {
504      /* Look for the next fragment */
505      seq = inc_seq(mp->local_is12bit, seq);
506      last = q;
507      q = q->pnext;
508    }
509  }
510
511  if (m) {
512    /* We still have to find a home for our new fragment */
513    last = NULL;
514    for (q = mp->inbufs; q; last = q, q = q->pnext) {
515      mp_ReadHeader(mp, q, &h);
516      if (isbefore(mp->local_is12bit, mh.seq, h.seq))
517        break;
518    }
519    /* Our received fragment fits in here */
520    if (last)
521      last->pnext = m;
522    else
523      mp->inbufs = m;
524    m->pnext = q;
525  }
526}
527
528struct mbuf *
529mp_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
530{
531  struct physical *p = link2physical(l);
532
533  if (!bundle->ncp.mp.active)
534    /* Let someone else deal with it ! */
535    return bp;
536
537  if (p == NULL) {
538    log_Printf(LogWARN, "DecodePacket: Can't do MP inside MP !\n");
539    mbuf_Free(bp);
540  } else
541    mp_Assemble(&bundle->ncp.mp, bp, p);
542
543  return NULL;
544}
545
546static void
547mp_Output(struct mp *mp, struct bundle *bundle, struct link *l,
548          struct mbuf *m, u_int32_t begin, u_int32_t end)
549{
550  struct mbuf *mo;
551
552  /* Stuff an MP header on the front of our packet and send it */
553  mo = mbuf_Alloc(4, MB_MP);
554  mo->next = m;
555  if (mp->peer_is12bit) {
556    u_int16_t val;
557
558    val = (begin << 15) | (end << 14) | (u_int16_t)mp->out.seq;
559    ua_htons(&val, MBUF_CTOP(mo));
560    mo->cnt = 2;
561  } else {
562    u_int32_t val;
563
564    val = (begin << 31) | (end << 30) | (u_int32_t)mp->out.seq;
565    ua_htonl(&val, MBUF_CTOP(mo));
566    mo->cnt = 4;
567  }
568  if (log_IsKept(LogDEBUG))
569    log_Printf(LogDEBUG, "MP[frag %d]: Send %d bytes on link `%s'\n",
570              mp->out.seq, mbuf_Length(mo), l->name);
571  mp->out.seq = inc_seq(mp->peer_is12bit, mp->out.seq);
572
573  link_PushPacket(l, mo, bundle, PRI_NORMAL, PROTO_MP);
574}
575
576int
577mp_FillQueues(struct bundle *bundle)
578{
579  struct mp *mp = &bundle->ncp.mp;
580  struct datalink *dl, *fdl;
581  int total, add, len, thislink, nlinks;
582  u_int32_t begin, end;
583  struct mbuf *m, *mo;
584
585  thislink = nlinks = 0;
586  for (fdl = NULL, dl = bundle->links; dl; dl = dl->next) {
587    /* Include non-open links here as mp->out.link will stay more correct */
588    if (!fdl) {
589      if (thislink == mp->out.link)
590        fdl = dl;
591      else
592        thislink++;
593    }
594    nlinks++;
595  }
596
597  if (!fdl) {
598    fdl = bundle->links;
599    if (!fdl)
600      return 0;
601    thislink = 0;
602  }
603
604  total = 0;
605  for (dl = fdl; nlinks > 0; dl = dl->next, nlinks--, thislink++) {
606    if (!dl) {
607      dl = bundle->links;
608      thislink = 0;
609    }
610
611    if (dl->state != DATALINK_OPEN)
612      continue;
613
614    if (dl->physical->out)
615      /* this link has suffered a short write.  Let it continue */
616      continue;
617
618    add = link_QueueLen(&dl->physical->link);
619    total += add;
620    if (add)
621      /* this link has got stuff already queued.  Let it continue */
622      continue;
623
624    if (!link_QueueLen(&mp->link) && !ip_PushPacket(&mp->link, bundle))
625      /* Nothing else to send */
626      break;
627
628    m = link_Dequeue(&mp->link);
629    len = mbuf_Length(m);
630    begin = 1;
631    end = 0;
632
633    while (!end) {
634      if (dl->state == DATALINK_OPEN) {
635        if (len <= dl->mp.weight + LINK_MINWEIGHT) {
636          /*
637           * XXX: Should we remember how much of our `weight' wasn't sent
638           *      so that we can compensate next time ?
639           */
640          mo = m;
641          end = 1;
642        } else {
643          mo = mbuf_Alloc(dl->mp.weight, MB_MP);
644          mo->cnt = dl->mp.weight;
645          len -= mo->cnt;
646          m = mbuf_Read(m, MBUF_CTOP(mo), mo->cnt);
647        }
648        mp_Output(mp, bundle, &dl->physical->link, mo, begin, end);
649        begin = 0;
650      }
651
652      if (!end) {
653        nlinks--;
654        dl = dl->next;
655        if (!dl) {
656          dl = bundle->links;
657          thislink = 0;
658        } else
659          thislink++;
660      }
661    }
662  }
663  mp->out.link = thislink;		/* Start here next time */
664
665  return total;
666}
667
668int
669mp_SetDatalinkWeight(struct cmdargs const *arg)
670{
671  int val;
672
673  if (arg->argc != arg->argn+1)
674    return -1;
675
676  val = atoi(arg->argv[arg->argn]);
677  if (val < LINK_MINWEIGHT) {
678    log_Printf(LogWARN, "Link weights must not be less than %d\n",
679              LINK_MINWEIGHT);
680    return 1;
681  }
682  arg->cx->mp.weight = val;
683  return 0;
684}
685
686int
687mp_ShowStatus(struct cmdargs const *arg)
688{
689  struct mp *mp = &arg->bundle->ncp.mp;
690
691  prompt_Printf(arg->prompt, "Multilink is %sactive\n", mp->active ? "" : "in");
692  if (mp->active) {
693    struct mbuf *m;
694    int bufs = 0;
695
696    prompt_Printf(arg->prompt, "Socket:         %s\n",
697                  mp->server.socket.sun_path);
698    for (m = mp->inbufs; m; m = m->pnext)
699      bufs++;
700    prompt_Printf(arg->prompt, "Pending frags:  %d\n", bufs);
701  }
702
703  prompt_Printf(arg->prompt, "\nMy Side:\n");
704  if (mp->active) {
705    prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->local_mrru);
706    prompt_Printf(arg->prompt, " Short Seq:     %s\n",
707                  mp->local_is12bit ? "on" : "off");
708  }
709  prompt_Printf(arg->prompt, " Discriminator: %s\n",
710                mp_Enddisc(mp->cfg.enddisc.class, mp->cfg.enddisc.address,
711                           mp->cfg.enddisc.len));
712
713  prompt_Printf(arg->prompt, "\nHis Side:\n");
714  if (mp->active) {
715    prompt_Printf(arg->prompt, " Auth Name:     %s\n", mp->peer.authname);
716    prompt_Printf(arg->prompt, " Next SEQ:      %u\n", mp->out.seq);
717    prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->peer_mrru);
718    prompt_Printf(arg->prompt, " Short Seq:     %s\n",
719                  mp->peer_is12bit ? "on" : "off");
720  }
721  prompt_Printf(arg->prompt,   " Discriminator: %s\n",
722                mp_Enddisc(mp->peer.enddisc.class, mp->peer.enddisc.address,
723                           mp->peer.enddisc.len));
724
725  prompt_Printf(arg->prompt, "\nDefaults:\n");
726
727  prompt_Printf(arg->prompt, " MRRU:          ");
728  if (mp->cfg.mrru)
729    prompt_Printf(arg->prompt, "%d (multilink enabled)\n", mp->cfg.mrru);
730  else
731    prompt_Printf(arg->prompt, "disabled\n");
732  prompt_Printf(arg->prompt, " Short Seq:     %s\n",
733                  command_ShowNegval(mp->cfg.shortseq));
734
735  return 0;
736}
737
738const char *
739mp_Enddisc(u_char c, const char *address, int len)
740{
741  static char result[100];	/* Used immediately after it's returned */
742  int f, header;
743
744  switch (c) {
745    case ENDDISC_NULL:
746      sprintf(result, "Null Class");
747      break;
748
749    case ENDDISC_LOCAL:
750      snprintf(result, sizeof result, "Local Addr: %.*s", len, address);
751      break;
752
753    case ENDDISC_IP:
754      if (len == 4)
755        snprintf(result, sizeof result, "IP %s",
756                 inet_ntoa(*(const struct in_addr *)address));
757      else
758        sprintf(result, "IP[%d] ???", len);
759      break;
760
761    case ENDDISC_MAC:
762      if (len == 6) {
763        const u_char *m = (const u_char *)address;
764        snprintf(result, sizeof result, "MAC %02x:%02x:%02x:%02x:%02x:%02x",
765                 m[0], m[1], m[2], m[3], m[4], m[5]);
766      } else
767        sprintf(result, "MAC[%d] ???", len);
768      break;
769
770    case ENDDISC_MAGIC:
771      sprintf(result, "Magic: 0x");
772      header = strlen(result);
773      if (len > sizeof result - header - 1)
774        len = sizeof result - header - 1;
775      for (f = 0; f < len; f++)
776        sprintf(result + header + 2 * f, "%02x", address[f]);
777      break;
778
779    case ENDDISC_PSN:
780      snprintf(result, sizeof result, "PSN: %.*s", len, address);
781      break;
782
783     default:
784      sprintf(result, "%d: ", (int)c);
785      header = strlen(result);
786      if (len > sizeof result - header - 1)
787        len = sizeof result - header - 1;
788      for (f = 0; f < len; f++)
789        sprintf(result + header + 2 * f, "%02x", address[f]);
790      break;
791  }
792  return result;
793}
794
795int
796mp_SetEnddisc(struct cmdargs const *arg)
797{
798  struct mp *mp = &arg->bundle->ncp.mp;
799  struct in_addr addr;
800
801  switch (bundle_Phase(arg->bundle)) {
802    case PHASE_DEAD:
803      break;
804    case PHASE_ESTABLISH:
805      /* Make sure none of our links are DATALINK_LCP or greater */
806      if (bundle_HighestState(arg->bundle) >= DATALINK_LCP) {
807        log_Printf(LogWARN, "enddisc: Only changable before"
808                   " LCP negotiations\n");
809        return 1;
810      }
811      break;
812    default:
813      log_Printf(LogWARN, "enddisc: Only changable at phase DEAD/ESTABLISH\n");
814      return 1;
815  }
816
817  if (arg->argc == arg->argn) {
818    mp->cfg.enddisc.class = 0;
819    *mp->cfg.enddisc.address = '\0';
820    mp->cfg.enddisc.len = 0;
821  } else if (arg->argc > arg->argn) {
822    if (!strcasecmp(arg->argv[arg->argn], "label")) {
823      mp->cfg.enddisc.class = ENDDISC_LOCAL;
824      strcpy(mp->cfg.enddisc.address, arg->bundle->cfg.label);
825      mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
826    } else if (!strcasecmp(arg->argv[arg->argn], "ip")) {
827      if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
828        addr = arg->bundle->ncp.ipcp.cfg.my_range.ipaddr;
829      else
830        addr = arg->bundle->ncp.ipcp.my_ip;
831      memcpy(mp->cfg.enddisc.address, &addr.s_addr, sizeof addr.s_addr);
832      mp->cfg.enddisc.class = ENDDISC_IP;
833      mp->cfg.enddisc.len = sizeof arg->bundle->ncp.ipcp.my_ip.s_addr;
834    } else if (!strcasecmp(arg->argv[arg->argn], "mac")) {
835      struct sockaddr_dl hwaddr;
836      int s;
837
838      if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
839        addr = arg->bundle->ncp.ipcp.cfg.my_range.ipaddr;
840      else
841        addr = arg->bundle->ncp.ipcp.my_ip;
842
843      s = ID0socket(AF_INET, SOCK_DGRAM, 0);
844      if (s < 0) {
845        log_Printf(LogERROR, "set enddisc: socket(): %s\n", strerror(errno));
846        return 2;
847      }
848      if (get_ether_addr(s, addr, &hwaddr)) {
849        mp->cfg.enddisc.class = ENDDISC_MAC;
850        memcpy(mp->cfg.enddisc.address, hwaddr.sdl_data + hwaddr.sdl_nlen,
851               hwaddr.sdl_alen);
852        mp->cfg.enddisc.len = hwaddr.sdl_alen;
853      } else {
854        log_Printf(LogWARN, "set enddisc: Can't locate MAC address for %s\n",
855                  inet_ntoa(addr));
856        close(s);
857        return 4;
858      }
859      close(s);
860    } else if (!strcasecmp(arg->argv[arg->argn], "magic")) {
861      int f;
862
863      randinit();
864      for (f = 0; f < 20; f += sizeof(long))
865        *(long *)(mp->cfg.enddisc.address + f) = random();
866      mp->cfg.enddisc.class = ENDDISC_MAGIC;
867      mp->cfg.enddisc.len = 20;
868    } else if (!strcasecmp(arg->argv[arg->argn], "psn")) {
869      if (arg->argc > arg->argn+1) {
870        mp->cfg.enddisc.class = ENDDISC_PSN;
871        strcpy(mp->cfg.enddisc.address, arg->argv[arg->argn+1]);
872        mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
873      } else {
874        log_Printf(LogWARN, "PSN endpoint requires additional data\n");
875        return 5;
876      }
877    } else {
878      log_Printf(LogWARN, "%s: Unrecognised endpoint type\n",
879                arg->argv[arg->argn]);
880      return 6;
881    }
882  }
883
884  return 0;
885}
886
887static int
888mpserver_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e,
889                   int *n)
890{
891  struct mpserver *s = descriptor2mpserver(d);
892  int result;
893
894  result = 0;
895  if (s->send.dl != NULL) {
896    /* We've connect()ed */
897    if (!link_QueueLen(&s->send.dl->physical->link) &&
898        !s->send.dl->physical->out) {
899      /* Only send if we've transmitted all our data (i.e. the ConfigAck) */
900      result -= datalink_RemoveFromSet(s->send.dl, r, w, e);
901      bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
902      s->send.dl = NULL;
903      s->fd = -1;
904    } else
905      /* Never read from a datalink that's on death row ! */
906      result -= datalink_RemoveFromSet(s->send.dl, r, NULL, NULL);
907  } else if (r && s->fd >= 0) {
908    if (*n < s->fd + 1)
909      *n = s->fd + 1;
910    FD_SET(s->fd, r);
911    log_Printf(LogTIMER, "mp: fdset(r) %d\n", s->fd);
912    result++;
913  }
914  return result;
915}
916
917static int
918mpserver_IsSet(struct descriptor *d, const fd_set *fdset)
919{
920  struct mpserver *s = descriptor2mpserver(d);
921  return s->fd >= 0 && FD_ISSET(s->fd, fdset);
922}
923
924static void
925mpserver_Read(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
926{
927  struct mpserver *s = descriptor2mpserver(d);
928  struct sockaddr in;
929  int fd, size;
930
931  size = sizeof in;
932  fd = accept(s->fd, &in, &size);
933  if (fd < 0) {
934    log_Printf(LogERROR, "mpserver_Read: accept(): %s\n", strerror(errno));
935    return;
936  }
937
938  if (in.sa_family == AF_LOCAL)
939    bundle_ReceiveDatalink(bundle, fd, (struct sockaddr_un *)&in);
940  else
941    close(fd);
942}
943
944static int
945mpserver_Write(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
946{
947  /* We never want to write here ! */
948  log_Printf(LogALERT, "mpserver_Write: Internal error: Bad call !\n");
949  return 0;
950}
951
952void
953mpserver_Init(struct mpserver *s)
954{
955  s->desc.type = MPSERVER_DESCRIPTOR;
956  s->desc.UpdateSet = mpserver_UpdateSet;
957  s->desc.IsSet = mpserver_IsSet;
958  s->desc.Read = mpserver_Read;
959  s->desc.Write = mpserver_Write;
960  s->send.dl = NULL;
961  s->fd = -1;
962  memset(&s->socket, '\0', sizeof s->socket);
963}
964
965int
966mpserver_Open(struct mpserver *s, struct peerid *peer)
967{
968  int f, l;
969  mode_t mask;
970
971  if (s->fd != -1) {
972    log_Printf(LogALERT, "Internal error !  mpserver already open\n");
973    mpserver_Close(s);
974  }
975
976  l = snprintf(s->socket.sun_path, sizeof s->socket.sun_path, "%sppp-%s-%02x-",
977               _PATH_VARRUN, peer->authname, peer->enddisc.class);
978
979  for (f = 0; f < peer->enddisc.len && l < sizeof s->socket.sun_path - 2; f++) {
980    snprintf(s->socket.sun_path + l, sizeof s->socket.sun_path - l,
981             "%02x", *(u_char *)(peer->enddisc.address+f));
982    l += 2;
983  }
984
985  s->socket.sun_family = AF_LOCAL;
986  s->socket.sun_len = sizeof s->socket;
987  s->fd = ID0socket(PF_LOCAL, SOCK_STREAM, 0);
988  if (s->fd < 0) {
989    log_Printf(LogERROR, "mpserver: socket: %s\n", strerror(errno));
990    return MPSERVER_FAILED;
991  }
992
993  setsockopt(s->fd, SOL_SOCKET, SO_REUSEADDR, (struct sockaddr *)&s->socket,
994             sizeof s->socket);
995  mask = umask(0177);
996  if (ID0bind_un(s->fd, &s->socket) < 0) {
997    if (errno != EADDRINUSE) {
998      log_Printf(LogPHASE, "mpserver: can't create bundle socket %s (%s)\n",
999                s->socket.sun_path, strerror(errno));
1000      umask(mask);
1001      close(s->fd);
1002      s->fd = -1;
1003      return MPSERVER_FAILED;
1004    }
1005    umask(mask);
1006    if (ID0connect_un(s->fd, &s->socket) < 0) {
1007      log_Printf(LogPHASE, "mpserver: can't connect to bundle socket %s (%s)\n",
1008                s->socket.sun_path, strerror(errno));
1009      if (errno == ECONNREFUSED)
1010        log_Printf(LogPHASE, "          Has the previous server died badly ?\n");
1011      close(s->fd);
1012      s->fd = -1;
1013      return MPSERVER_FAILED;
1014    }
1015
1016    /* Donate our link to the other guy */
1017    return MPSERVER_CONNECTED;
1018  }
1019
1020  /* Listen for other ppp invocations that want to donate links */
1021  if (listen(s->fd, 5) != 0) {
1022    log_Printf(LogERROR, "mpserver: Unable to listen to socket"
1023              " - BUNDLE overload?\n");
1024    mpserver_Close(s);
1025  }
1026
1027  return MPSERVER_LISTENING;
1028}
1029
1030void
1031mpserver_Close(struct mpserver *s)
1032{
1033  if (s->send.dl != NULL) {
1034    bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
1035    s->send.dl = NULL;
1036    s->fd = -1;
1037  } else if (s->fd >= 0) {
1038    close(s->fd);
1039    if (ID0unlink(s->socket.sun_path) == -1)
1040      log_Printf(LogERROR, "%s: Failed to remove: %s\n", s->socket.sun_path,
1041                strerror(errno));
1042    memset(&s->socket, '\0', sizeof s->socket);
1043    s->fd = -1;
1044  }
1045}
1046
1047void
1048mp_LinkLost(struct mp *mp, struct datalink *dl)
1049{
1050  if (mp->seq.min_in == dl->mp.seq)
1051    /* We've lost the link that's holding everything up ! */
1052    mp_Assemble(mp, NULL, NULL);
1053}
1054
1055void
1056mp_DeleteQueue(struct mp *mp)
1057{
1058  link_DeleteQueue(&mp->link);
1059}
1060