mp.c revision 64652
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 * $FreeBSD: head/usr.sbin/ppp/mp.c 64652 2000-08-15 00:59:21Z brian $
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 NONAT
49#include "nat_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
186static void
187mp_UpDown(void *v)
188{
189  struct mp *mp = (struct mp *)v;
190  int percent;
191
192  percent = mp->link.stats.total.OctetsPerSecond * 800 / mp->bundle->bandwidth;
193  if (percent >= mp->cfg.autoload.max) {
194    log_Printf(LogDEBUG, "%d%% saturation - bring a link up ?\n", percent);
195    bundle_AutoAdjust(mp->bundle, percent, AUTO_UP);
196  } else if (percent <= mp->cfg.autoload.min) {
197    log_Printf(LogDEBUG, "%d%% saturation - bring a link down ?\n", percent);
198    bundle_AutoAdjust(mp->bundle, percent, AUTO_DOWN);
199  }
200}
201
202void
203mp_StopAutoloadTimer(struct mp *mp)
204{
205  throughput_stop(&mp->link.stats.total);
206}
207
208void
209mp_CheckAutoloadTimer(struct mp *mp)
210{
211  if (mp->link.stats.total.SamplePeriod != mp->cfg.autoload.period) {
212    throughput_destroy(&mp->link.stats.total);
213    throughput_init(&mp->link.stats.total, mp->cfg.autoload.period);
214    throughput_callback(&mp->link.stats.total, mp_UpDown, mp);
215  }
216
217  if (bundle_WantAutoloadTimer(mp->bundle))
218    throughput_start(&mp->link.stats.total, "MP throughput", 1);
219  else
220    mp_StopAutoloadTimer(mp);
221}
222
223void
224mp_RestartAutoloadTimer(struct mp *mp)
225{
226  if (mp->link.stats.total.SamplePeriod != mp->cfg.autoload.period)
227    mp_CheckAutoloadTimer(mp);
228  else
229    throughput_clear(&mp->link.stats.total, THROUGHPUT_OVERALL, NULL);
230}
231
232void
233mp_Init(struct mp *mp, struct bundle *bundle)
234{
235  mp->peer_is12bit = mp->local_is12bit = 0;
236  mp->peer_mrru = mp->local_mrru = 0;
237
238  peerid_Init(&mp->peer);
239
240  mp->out.seq = 0;
241  mp->out.link = 0;
242  mp->seq.min_in = 0;
243  mp->seq.next_in = 0;
244  mp->inbufs = NULL;
245  mp->bundle = bundle;
246
247  mp->link.type = LOGICAL_LINK;
248  mp->link.name = "mp";
249  mp->link.len = sizeof *mp;
250
251  mp->cfg.autoload.period = SAMPLE_PERIOD;
252  mp->cfg.autoload.min = mp->cfg.autoload.max = 0;
253  throughput_init(&mp->link.stats.total, mp->cfg.autoload.period);
254  throughput_callback(&mp->link.stats.total, mp_UpDown, mp);
255  mp->link.stats.parent = NULL;
256  mp->link.stats.gather = 0;	/* Let the physical links gather stats */
257  memset(mp->link.Queue, '\0', sizeof mp->link.Queue);
258  memset(mp->link.proto_in, '\0', sizeof mp->link.proto_in);
259  memset(mp->link.proto_out, '\0', sizeof mp->link.proto_out);
260
261  mp->fsmp.LayerStart = mp_LayerStart;
262  mp->fsmp.LayerUp = mp_LayerUp;
263  mp->fsmp.LayerDown = mp_LayerDown;
264  mp->fsmp.LayerFinish = mp_LayerFinish;
265  mp->fsmp.object = mp;
266
267  mpserver_Init(&mp->server);
268
269  mp->cfg.mrru = 0;
270  mp->cfg.shortseq = NEG_ENABLED|NEG_ACCEPTED;
271  mp->cfg.negenddisc = NEG_ENABLED|NEG_ACCEPTED;
272  mp->cfg.enddisc.class = 0;
273  *mp->cfg.enddisc.address = '\0';
274  mp->cfg.enddisc.len = 0;
275
276  lcp_Init(&mp->link.lcp, mp->bundle, &mp->link, NULL);
277  ccp_Init(&mp->link.ccp, mp->bundle, &mp->link, &mp->fsmp);
278
279  link_EmptyStack(&mp->link);
280  link_Stack(&mp->link, &protolayer);
281  link_Stack(&mp->link, &ccplayer);
282  link_Stack(&mp->link, &vjlayer);
283#ifndef NONAT
284  link_Stack(&mp->link, &natlayer);
285#endif
286}
287
288int
289mp_Up(struct mp *mp, struct datalink *dl)
290{
291  struct lcp *lcp = &dl->physical->link.lcp;
292
293  if (mp->active) {
294    /* We're adding a link - do a last validation on our parameters */
295    if (!peerid_Equal(&dl->peer, &mp->peer)) {
296      log_Printf(LogPHASE, "%s: Inappropriate peer !\n", dl->name);
297      log_Printf(LogPHASE, "  Attached to peer %s/%s\n", mp->peer.authname,
298                 mp_Enddisc(mp->peer.enddisc.class, mp->peer.enddisc.address,
299                            mp->peer.enddisc.len));
300      log_Printf(LogPHASE, "  New link is peer %s/%s\n", dl->peer.authname,
301                 mp_Enddisc(dl->peer.enddisc.class, dl->peer.enddisc.address,
302                            dl->peer.enddisc.len));
303      return MP_FAILED;
304    }
305    if (mp->local_mrru != lcp->want_mrru ||
306        mp->peer_mrru != lcp->his_mrru ||
307        mp->local_is12bit != lcp->want_shortseq ||
308        mp->peer_is12bit != lcp->his_shortseq) {
309      log_Printf(LogPHASE, "%s: Invalid MRRU/SHORTSEQ MP parameters !\n",
310                dl->name);
311      return MP_FAILED;
312    }
313    return MP_ADDED;
314  } else {
315    /* First link in multilink mode */
316
317    mp->local_mrru = lcp->want_mrru;
318    mp->peer_mrru = lcp->his_mrru;
319    mp->local_is12bit = lcp->want_shortseq;
320    mp->peer_is12bit = lcp->his_shortseq;
321    mp->peer = dl->peer;
322
323    throughput_destroy(&mp->link.stats.total);
324    throughput_init(&mp->link.stats.total, mp->cfg.autoload.period);
325    throughput_callback(&mp->link.stats.total, mp_UpDown, mp);
326    memset(mp->link.Queue, '\0', sizeof mp->link.Queue);
327    memset(mp->link.proto_in, '\0', sizeof mp->link.proto_in);
328    memset(mp->link.proto_out, '\0', sizeof mp->link.proto_out);
329
330    /* Tell the link who it belongs to */
331    dl->physical->link.stats.parent = &mp->link.stats.total;
332
333    mp->out.seq = 0;
334    mp->out.link = 0;
335    mp->seq.min_in = 0;
336    mp->seq.next_in = 0;
337
338    /*
339     * Now we create our server socket.
340     * If it already exists, join it.  Otherwise, create and own it
341     */
342    switch (mpserver_Open(&mp->server, &mp->peer)) {
343    case MPSERVER_CONNECTED:
344      log_Printf(LogPHASE, "mp: Transfer link on %s\n",
345                mp->server.socket.sun_path);
346      mp->server.send.dl = dl;		/* Defer 'till it's safe to send */
347      return MP_LINKSENT;
348    case MPSERVER_FAILED:
349      return MP_FAILED;
350    case MPSERVER_LISTENING:
351      log_Printf(LogPHASE, "mp: Listening on %s\n", mp->server.socket.sun_path);
352      log_Printf(LogPHASE, "    First link: %s\n", dl->name);
353
354      /* Re-point our IPCP layer at our MP link */
355      ipcp_SetLink(&mp->bundle->ncp.ipcp, &mp->link);
356
357      /* Our lcp's already up 'cos of the NULL parent */
358      if (ccp_SetOpenMode(&mp->link.ccp)) {
359        fsm_Up(&mp->link.ccp.fsm);
360        fsm_Open(&mp->link.ccp.fsm);
361      }
362
363      mp->active = 1;
364      break;
365    }
366  }
367
368  return MP_UP;
369}
370
371void
372mp_Down(struct mp *mp)
373{
374  if (mp->active) {
375    struct mbuf *next;
376
377    /* Stop that ! */
378    mp_StopAutoloadTimer(mp);
379
380    /* Don't want any more of these */
381    mpserver_Close(&mp->server);
382
383    /* CCP goes down with a bang */
384    fsm2initial(&mp->link.ccp.fsm);
385
386    /* Received fragments go in the bit-bucket */
387    while (mp->inbufs) {
388      next = mp->inbufs->m_nextpkt;
389      m_freem(mp->inbufs);
390      mp->inbufs = next;
391    }
392
393    peerid_Init(&mp->peer);
394    mp->active = 0;
395  }
396}
397
398void
399mp_linkInit(struct mp_link *mplink)
400{
401  mplink->seq = 0;
402  mplink->bandwidth = 0;
403}
404
405static void
406mp_Assemble(struct mp *mp, struct mbuf *m, struct physical *p)
407{
408  struct mp_header mh, h;
409  struct mbuf *q, *last;
410  int32_t seq;
411
412  /*
413   * When `m' and `p' are NULL, it means our oldest link has gone down.
414   * We want to determine a new min, and process any intermediate stuff
415   * as normal
416   */
417
418  if (m && mp_ReadHeader(mp, m, &mh) == 0) {
419    m_freem(m);
420    return;
421  }
422
423  if (p) {
424    seq = p->dl->mp.seq;
425    p->dl->mp.seq = mh.seq;
426  } else
427    seq = mp->seq.min_in;
428
429  if (mp->seq.min_in == seq) {
430    /*
431     * We've received new data on the link that has our min (oldest) seq.
432     * Figure out which link now has the smallest (oldest) seq.
433     */
434    struct datalink *dl;
435
436    mp->seq.min_in = (u_int32_t)-1;
437    for (dl = mp->bundle->links; dl; dl = dl->next)
438      if (dl->state == DATALINK_OPEN &&
439          (mp->seq.min_in == -1 ||
440           isbefore(mp->local_is12bit, dl->mp.seq, mp->seq.min_in)))
441        mp->seq.min_in = dl->mp.seq;
442  }
443
444  /*
445   * Now process as many of our fragments as we can, adding our new
446   * fragment in as we go, and ordering with the oldest at the top of
447   * the queue.
448   */
449
450  last = NULL;
451  seq = mp->seq.next_in;
452  q = mp->inbufs;
453  while (q || m) {
454    if (!q) {
455      if (last)
456        last->m_nextpkt = m;
457      else
458        mp->inbufs = m;
459      q = m;
460      m = NULL;
461      h = mh;
462    } else {
463      mp_ReadHeader(mp, q, &h);
464
465      if (m && isbefore(mp->local_is12bit, mh.seq, h.seq)) {
466        /* Our received fragment fits in before this one, so link it in */
467        if (last)
468          last->m_nextpkt = m;
469        else
470          mp->inbufs = m;
471        m->m_nextpkt = q;
472        q = m;
473        h = mh;
474        m = NULL;
475      }
476    }
477
478    if (h.seq != seq) {
479      /* we're missing something :-( */
480      if (isbefore(mp->local_is12bit, seq, mp->seq.min_in)) {
481        /* we're never gonna get it */
482        struct mbuf *next;
483
484        /* Zap all older fragments */
485        while (mp->inbufs != q) {
486          log_Printf(LogDEBUG, "Drop frag\n");
487          next = mp->inbufs->m_nextpkt;
488          m_freem(mp->inbufs);
489          mp->inbufs = next;
490        }
491
492        /*
493         * Zap everything until the next `end' fragment OR just before
494         * the next `begin' fragment OR 'till seq.min_in - whichever
495         * comes first.
496         */
497        do {
498          mp_ReadHeader(mp, mp->inbufs, &h);
499          if (h.begin) {
500            /* We might be able to process this ! */
501            h.seq--;  /* We're gonna look for fragment with h.seq+1 */
502            break;
503          }
504          next = mp->inbufs->m_nextpkt;
505          log_Printf(LogDEBUG, "Drop frag %u\n", h.seq);
506          m_freem(mp->inbufs);
507          mp->inbufs = next;
508        } while (mp->inbufs && (isbefore(mp->local_is12bit, mp->seq.min_in,
509                                         h.seq) || h.end));
510
511        /*
512         * Continue processing things from here.
513         * This deals with the possibility that we received a fragment
514         * on the slowest link that invalidates some of our data (because
515         * of the hole at `q'), but where there are subsequent `whole'
516         * packets that have already been received.
517         */
518
519        mp->seq.next_in = seq = inc_seq(mp->local_is12bit, h.seq);
520        last = NULL;
521        q = mp->inbufs;
522      } else
523        /* we may still receive the missing fragment */
524        break;
525    } else if (h.end) {
526      /* We've got something, reassemble */
527      struct mbuf **frag = &q;
528      int len;
529      u_long first = -1;
530
531      do {
532        *frag = mp->inbufs;
533        mp->inbufs = mp->inbufs->m_nextpkt;
534        len = mp_ReadHeader(mp, *frag, &h);
535        if (first == -1)
536          first = h.seq;
537        (*frag)->m_offset += len;
538        (*frag)->m_len -= len;
539        (*frag)->m_nextpkt = NULL;
540        if (frag == &q && !h.begin) {
541          log_Printf(LogWARN, "Oops - MP frag %lu should have a begin flag\n",
542                    (u_long)h.seq);
543          m_freem(q);
544          q = NULL;
545        } else if (frag != &q && h.begin) {
546          log_Printf(LogWARN, "Oops - MP frag %lu should have an end flag\n",
547                    (u_long)h.seq - 1);
548          /*
549           * Stuff our fragment back at the front of the queue and zap
550           * our half-assembed packet.
551           */
552          (*frag)->m_nextpkt = mp->inbufs;
553          mp->inbufs = *frag;
554          *frag = NULL;
555          m_freem(q);
556          q = NULL;
557          frag = &q;
558          h.end = 0;	/* just in case it's a whole packet */
559        } else
560          do
561            frag = &(*frag)->m_next;
562          while (*frag != NULL);
563      } while (!h.end);
564
565      if (q) {
566        q = m_pullup(q);
567        log_Printf(LogDEBUG, "MP: Reassembled frags %ld-%lu, length %d\n",
568                   first, (u_long)h.seq, m_length(q));
569        link_PullPacket(&mp->link, MBUF_CTOP(q), q->m_len, mp->bundle);
570        m_freem(q);
571      }
572
573      mp->seq.next_in = seq = inc_seq(mp->local_is12bit, h.seq);
574      last = NULL;
575      q = mp->inbufs;
576    } else {
577      /* Look for the next fragment */
578      seq = inc_seq(mp->local_is12bit, seq);
579      last = q;
580      q = q->m_nextpkt;
581    }
582  }
583
584  if (m) {
585    /* We still have to find a home for our new fragment */
586    last = NULL;
587    for (q = mp->inbufs; q; last = q, q = q->m_nextpkt) {
588      mp_ReadHeader(mp, q, &h);
589      if (isbefore(mp->local_is12bit, mh.seq, h.seq))
590        break;
591    }
592    /* Our received fragment fits in here */
593    if (last)
594      last->m_nextpkt = m;
595    else
596      mp->inbufs = m;
597    m->m_nextpkt = q;
598  }
599}
600
601struct mbuf *
602mp_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
603{
604  struct physical *p = link2physical(l);
605
606  if (!bundle->ncp.mp.active)
607    /* Let someone else deal with it ! */
608    return bp;
609
610  if (p == NULL) {
611    log_Printf(LogWARN, "DecodePacket: Can't do MP inside MP !\n");
612    m_freem(bp);
613  } else {
614    m_settype(bp, MB_MPIN);
615    mp_Assemble(&bundle->ncp.mp, bp, p);
616  }
617
618  return NULL;
619}
620
621static void
622mp_Output(struct mp *mp, struct bundle *bundle, struct link *l,
623          struct mbuf *m, u_int32_t begin, u_int32_t end)
624{
625  char prepend[4];
626
627  /* Stuff an MP header on the front of our packet and send it */
628
629  if (mp->peer_is12bit) {
630    u_int16_t val;
631
632    val = (begin << 15) | (end << 14) | (u_int16_t)mp->out.seq;
633    ua_htons(&val, prepend);
634    m = m_prepend(m, prepend, 2, 0);
635  } else {
636    u_int32_t val;
637
638    val = (begin << 31) | (end << 30) | (u_int32_t)mp->out.seq;
639    ua_htonl(&val, prepend);
640    m = m_prepend(m, prepend, 4, 0);
641  }
642  if (log_IsKept(LogDEBUG))
643    log_Printf(LogDEBUG, "MP[frag %d]: Send %d bytes on link `%s'\n",
644               mp->out.seq, m_length(m), l->name);
645  mp->out.seq = inc_seq(mp->peer_is12bit, mp->out.seq);
646
647  link_PushPacket(l, m, bundle, LINK_QUEUES(l) - 1, PROTO_MP);
648}
649
650int
651mp_FillQueues(struct bundle *bundle)
652{
653  struct mp *mp = &bundle->ncp.mp;
654  struct datalink *dl, *fdl;
655  size_t total, add, len;
656  int thislink, nlinks;
657  u_int32_t begin, end;
658  struct mbuf *m, *mo;
659
660  thislink = nlinks = 0;
661  for (fdl = NULL, dl = bundle->links; dl; dl = dl->next) {
662    /* Include non-open links here as mp->out.link will stay more correct */
663    if (!fdl) {
664      if (thislink == mp->out.link)
665        fdl = dl;
666      else
667        thislink++;
668    }
669    nlinks++;
670  }
671
672  if (!fdl) {
673    fdl = bundle->links;
674    if (!fdl)
675      return 0;
676    thislink = 0;
677  }
678
679  total = 0;
680  for (dl = fdl; nlinks > 0; dl = dl->next, nlinks--, thislink++) {
681    if (!dl) {
682      dl = bundle->links;
683      thislink = 0;
684    }
685
686    if (dl->state != DATALINK_OPEN)
687      continue;
688
689    if (dl->physical->out)
690      /* this link has suffered a short write.  Let it continue */
691      continue;
692
693    add = link_QueueLen(&dl->physical->link);
694    total += add;
695    if (add)
696      /* this link has got stuff already queued.  Let it continue */
697      continue;
698
699    if (!link_QueueLen(&mp->link) && !ip_PushPacket(&mp->link, bundle))
700      /* Nothing else to send */
701      break;
702
703    m = link_Dequeue(&mp->link);
704    len = m_length(m);
705    begin = 1;
706    end = 0;
707
708    while (!end) {
709      if (dl->state == DATALINK_OPEN) {
710        /* Write at most his_mru bytes to the physical link */
711        if (len <= dl->physical->link.lcp.his_mru) {
712          mo = m;
713          end = 1;
714          m_settype(mo, MB_MPOUT);
715        } else {
716          /* It's > his_mru, chop the packet (`m') into bits */
717          mo = m_get(dl->physical->link.lcp.his_mru, MB_MPOUT);
718          len -= mo->m_len;
719          m = mbuf_Read(m, MBUF_CTOP(mo), mo->m_len);
720        }
721        mp_Output(mp, bundle, &dl->physical->link, mo, begin, end);
722        begin = 0;
723      }
724
725      if (!end) {
726        nlinks--;
727        dl = dl->next;
728        if (!dl) {
729          dl = bundle->links;
730          thislink = 0;
731        } else
732          thislink++;
733      }
734    }
735  }
736  mp->out.link = thislink;		/* Start here next time */
737
738  return total;
739}
740
741int
742mp_SetDatalinkBandwidth(struct cmdargs const *arg)
743{
744  int val;
745
746  if (arg->argc != arg->argn+1)
747    return -1;
748
749  val = atoi(arg->argv[arg->argn]);
750  if (val <= 0) {
751    log_Printf(LogWARN, "The link bandwidth must be greater than zero\n");
752    return 1;
753  }
754  arg->cx->mp.bandwidth = val;
755
756  if (arg->cx->state == DATALINK_OPEN)
757    bundle_CalculateBandwidth(arg->bundle);
758
759  return 0;
760}
761
762int
763mp_ShowStatus(struct cmdargs const *arg)
764{
765  struct mp *mp = &arg->bundle->ncp.mp;
766
767  prompt_Printf(arg->prompt, "Multilink is %sactive\n", mp->active ? "" : "in");
768  if (mp->active) {
769    struct mbuf *m, *lm;
770    int bufs = 0;
771
772    lm = NULL;
773    prompt_Printf(arg->prompt, "Socket:         %s\n",
774                  mp->server.socket.sun_path);
775    for (m = mp->inbufs; m; m = m->m_nextpkt) {
776      bufs++;
777      lm = m;
778    }
779    prompt_Printf(arg->prompt, "Pending frags:  %d", bufs);
780    if (bufs) {
781      struct mp_header mh;
782      unsigned long first, last;
783
784      first = mp_ReadHeader(mp, mp->inbufs, &mh) ? mh.seq : 0;
785      last = mp_ReadHeader(mp, lm, &mh) ? mh.seq : 0;
786      prompt_Printf(arg->prompt, " (Have %lu - %lu, want %lu, lowest %lu)\n",
787                    first, last, (unsigned long)mp->seq.next_in,
788                    (unsigned long)mp->seq.min_in);
789      prompt_Printf(arg->prompt, "                First has %sbegin bit and "
790                    "%send bit", mh.begin ? "" : "no ", mh.end ? "" : "no ");
791    }
792    prompt_Printf(arg->prompt, "\n");
793  }
794
795  prompt_Printf(arg->prompt, "\nMy Side:\n");
796  if (mp->active) {
797    prompt_Printf(arg->prompt, " Output SEQ:    %u\n", mp->out.seq);
798    prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->local_mrru);
799    prompt_Printf(arg->prompt, " Short Seq:     %s\n",
800                  mp->local_is12bit ? "on" : "off");
801  }
802  prompt_Printf(arg->prompt, " Discriminator: %s\n",
803                mp_Enddisc(mp->cfg.enddisc.class, mp->cfg.enddisc.address,
804                           mp->cfg.enddisc.len));
805
806  prompt_Printf(arg->prompt, "\nHis Side:\n");
807  if (mp->active) {
808    prompt_Printf(arg->prompt, " Auth Name:     %s\n", mp->peer.authname);
809    prompt_Printf(arg->prompt, " Input SEQ:     %u\n", mp->seq.next_in);
810    prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->peer_mrru);
811    prompt_Printf(arg->prompt, " Short Seq:     %s\n",
812                  mp->peer_is12bit ? "on" : "off");
813  }
814  prompt_Printf(arg->prompt,   " Discriminator: %s\n",
815                mp_Enddisc(mp->peer.enddisc.class, mp->peer.enddisc.address,
816                           mp->peer.enddisc.len));
817
818  prompt_Printf(arg->prompt, "\nDefaults:\n");
819
820  prompt_Printf(arg->prompt, " MRRU:          ");
821  if (mp->cfg.mrru)
822    prompt_Printf(arg->prompt, "%d (multilink enabled)\n", mp->cfg.mrru);
823  else
824    prompt_Printf(arg->prompt, "disabled\n");
825  prompt_Printf(arg->prompt, " Short Seq:     %s\n",
826                  command_ShowNegval(mp->cfg.shortseq));
827  prompt_Printf(arg->prompt, " Discriminator: %s\n",
828                  command_ShowNegval(mp->cfg.negenddisc));
829  prompt_Printf(arg->prompt, " AutoLoad:      min %d%%, max %d%%,"
830                " period %d secs\n", mp->cfg.autoload.min,
831                mp->cfg.autoload.max, mp->cfg.autoload.period);
832
833  return 0;
834}
835
836const char *
837mp_Enddisc(u_char c, const char *address, int len)
838{
839  static char result[100];	/* Used immediately after it's returned */
840  int f, header;
841
842  switch (c) {
843    case ENDDISC_NULL:
844      sprintf(result, "Null Class");
845      break;
846
847    case ENDDISC_LOCAL:
848      snprintf(result, sizeof result, "Local Addr: %.*s", len, address);
849      break;
850
851    case ENDDISC_IP:
852      if (len == 4)
853        snprintf(result, sizeof result, "IP %s",
854                 inet_ntoa(*(const struct in_addr *)address));
855      else
856        sprintf(result, "IP[%d] ???", len);
857      break;
858
859    case ENDDISC_MAC:
860      if (len == 6) {
861        const u_char *m = (const u_char *)address;
862        snprintf(result, sizeof result, "MAC %02x:%02x:%02x:%02x:%02x:%02x",
863                 m[0], m[1], m[2], m[3], m[4], m[5]);
864      } else
865        sprintf(result, "MAC[%d] ???", len);
866      break;
867
868    case ENDDISC_MAGIC:
869      sprintf(result, "Magic: 0x");
870      header = strlen(result);
871      if (len > sizeof result - header - 1)
872        len = sizeof result - header - 1;
873      for (f = 0; f < len; f++)
874        sprintf(result + header + 2 * f, "%02x", address[f]);
875      break;
876
877    case ENDDISC_PSN:
878      snprintf(result, sizeof result, "PSN: %.*s", len, address);
879      break;
880
881     default:
882      sprintf(result, "%d: ", (int)c);
883      header = strlen(result);
884      if (len > sizeof result - header - 1)
885        len = sizeof result - header - 1;
886      for (f = 0; f < len; f++)
887        sprintf(result + header + 2 * f, "%02x", address[f]);
888      break;
889  }
890  return result;
891}
892
893int
894mp_SetEnddisc(struct cmdargs const *arg)
895{
896  struct mp *mp = &arg->bundle->ncp.mp;
897  struct in_addr addr;
898
899  switch (bundle_Phase(arg->bundle)) {
900    case PHASE_DEAD:
901      break;
902    case PHASE_ESTABLISH:
903      /* Make sure none of our links are DATALINK_LCP or greater */
904      if (bundle_HighestState(arg->bundle) >= DATALINK_LCP) {
905        log_Printf(LogWARN, "enddisc: Only changable before"
906                   " LCP negotiations\n");
907        return 1;
908      }
909      break;
910    default:
911      log_Printf(LogWARN, "enddisc: Only changable at phase DEAD/ESTABLISH\n");
912      return 1;
913  }
914
915  if (arg->argc == arg->argn) {
916    mp->cfg.enddisc.class = 0;
917    *mp->cfg.enddisc.address = '\0';
918    mp->cfg.enddisc.len = 0;
919  } else if (arg->argc > arg->argn) {
920    if (!strcasecmp(arg->argv[arg->argn], "label")) {
921      mp->cfg.enddisc.class = ENDDISC_LOCAL;
922      strcpy(mp->cfg.enddisc.address, arg->bundle->cfg.label);
923      mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
924    } else if (!strcasecmp(arg->argv[arg->argn], "ip")) {
925      if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
926        addr = arg->bundle->ncp.ipcp.cfg.my_range.ipaddr;
927      else
928        addr = arg->bundle->ncp.ipcp.my_ip;
929      memcpy(mp->cfg.enddisc.address, &addr.s_addr, sizeof addr.s_addr);
930      mp->cfg.enddisc.class = ENDDISC_IP;
931      mp->cfg.enddisc.len = sizeof arg->bundle->ncp.ipcp.my_ip.s_addr;
932    } else if (!strcasecmp(arg->argv[arg->argn], "mac")) {
933      struct sockaddr_dl hwaddr;
934      int s;
935
936      if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
937        addr = arg->bundle->ncp.ipcp.cfg.my_range.ipaddr;
938      else
939        addr = arg->bundle->ncp.ipcp.my_ip;
940
941      s = ID0socket(AF_INET, SOCK_DGRAM, 0);
942      if (s < 0) {
943        log_Printf(LogERROR, "set enddisc: socket(): %s\n", strerror(errno));
944        return 2;
945      }
946      if (get_ether_addr(s, addr, &hwaddr)) {
947        mp->cfg.enddisc.class = ENDDISC_MAC;
948        memcpy(mp->cfg.enddisc.address, hwaddr.sdl_data + hwaddr.sdl_nlen,
949               hwaddr.sdl_alen);
950        mp->cfg.enddisc.len = hwaddr.sdl_alen;
951      } else {
952        log_Printf(LogWARN, "set enddisc: Can't locate MAC address for %s\n",
953                  inet_ntoa(addr));
954        close(s);
955        return 4;
956      }
957      close(s);
958    } else if (!strcasecmp(arg->argv[arg->argn], "magic")) {
959      int f;
960
961      randinit();
962      for (f = 0; f < 20; f += sizeof(long))
963        *(long *)(mp->cfg.enddisc.address + f) = random();
964      mp->cfg.enddisc.class = ENDDISC_MAGIC;
965      mp->cfg.enddisc.len = 20;
966    } else if (!strcasecmp(arg->argv[arg->argn], "psn")) {
967      if (arg->argc > arg->argn+1) {
968        mp->cfg.enddisc.class = ENDDISC_PSN;
969        strcpy(mp->cfg.enddisc.address, arg->argv[arg->argn+1]);
970        mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
971      } else {
972        log_Printf(LogWARN, "PSN endpoint requires additional data\n");
973        return 5;
974      }
975    } else {
976      log_Printf(LogWARN, "%s: Unrecognised endpoint type\n",
977                arg->argv[arg->argn]);
978      return 6;
979    }
980  }
981
982  return 0;
983}
984
985static int
986mpserver_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e,
987                   int *n)
988{
989  struct mpserver *s = descriptor2mpserver(d);
990  int result;
991
992  result = 0;
993  if (s->send.dl != NULL) {
994    /* We've connect()ed */
995    if (!link_QueueLen(&s->send.dl->physical->link) &&
996        !s->send.dl->physical->out) {
997      /* Only send if we've transmitted all our data (i.e. the ConfigAck) */
998      result -= datalink_RemoveFromSet(s->send.dl, r, w, e);
999      bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
1000      s->send.dl = NULL;
1001      s->fd = -1;
1002    } else
1003      /* Never read from a datalink that's on death row ! */
1004      result -= datalink_RemoveFromSet(s->send.dl, r, NULL, NULL);
1005  } else if (r && s->fd >= 0) {
1006    if (*n < s->fd + 1)
1007      *n = s->fd + 1;
1008    FD_SET(s->fd, r);
1009    log_Printf(LogTIMER, "mp: fdset(r) %d\n", s->fd);
1010    result++;
1011  }
1012  return result;
1013}
1014
1015static int
1016mpserver_IsSet(struct fdescriptor *d, const fd_set *fdset)
1017{
1018  struct mpserver *s = descriptor2mpserver(d);
1019  return s->fd >= 0 && FD_ISSET(s->fd, fdset);
1020}
1021
1022static void
1023mpserver_Read(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset)
1024{
1025  struct mpserver *s = descriptor2mpserver(d);
1026
1027  bundle_ReceiveDatalink(bundle, s->fd);
1028}
1029
1030static int
1031mpserver_Write(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset)
1032{
1033  /* We never want to write here ! */
1034  log_Printf(LogALERT, "mpserver_Write: Internal error: Bad call !\n");
1035  return 0;
1036}
1037
1038void
1039mpserver_Init(struct mpserver *s)
1040{
1041  s->desc.type = MPSERVER_DESCRIPTOR;
1042  s->desc.UpdateSet = mpserver_UpdateSet;
1043  s->desc.IsSet = mpserver_IsSet;
1044  s->desc.Read = mpserver_Read;
1045  s->desc.Write = mpserver_Write;
1046  s->send.dl = NULL;
1047  s->fd = -1;
1048  memset(&s->socket, '\0', sizeof s->socket);
1049}
1050
1051int
1052mpserver_Open(struct mpserver *s, struct peerid *peer)
1053{
1054  int f, l;
1055  mode_t mask;
1056
1057  if (s->fd != -1) {
1058    log_Printf(LogALERT, "Internal error !  mpserver already open\n");
1059    mpserver_Close(s);
1060  }
1061
1062  l = snprintf(s->socket.sun_path, sizeof s->socket.sun_path, "%sppp-%s-%02x-",
1063               _PATH_VARRUN, peer->authname, peer->enddisc.class);
1064
1065  for (f = 0; f < peer->enddisc.len && l < sizeof s->socket.sun_path - 2; f++) {
1066    snprintf(s->socket.sun_path + l, sizeof s->socket.sun_path - l,
1067             "%02x", *(u_char *)(peer->enddisc.address+f));
1068    l += 2;
1069  }
1070
1071  s->socket.sun_family = AF_LOCAL;
1072  s->socket.sun_len = sizeof s->socket;
1073  s->fd = ID0socket(PF_LOCAL, SOCK_DGRAM, 0);
1074  if (s->fd < 0) {
1075    log_Printf(LogERROR, "mpserver: socket(): %s\n", strerror(errno));
1076    return MPSERVER_FAILED;
1077  }
1078
1079  setsockopt(s->fd, SOL_SOCKET, SO_REUSEADDR, (struct sockaddr *)&s->socket,
1080             sizeof s->socket);
1081  mask = umask(0177);
1082
1083  /*
1084   * Try to bind the socket.  If we succeed we play server, if we fail
1085   * we connect() and hand the link off.
1086   */
1087
1088  if (ID0bind_un(s->fd, &s->socket) < 0) {
1089    if (errno != EADDRINUSE) {
1090      log_Printf(LogPHASE, "mpserver: can't create bundle socket %s (%s)\n",
1091                s->socket.sun_path, strerror(errno));
1092      umask(mask);
1093      close(s->fd);
1094      s->fd = -1;
1095      return MPSERVER_FAILED;
1096    }
1097
1098    /* So we're the sender */
1099    umask(mask);
1100    if (ID0connect_un(s->fd, &s->socket) < 0) {
1101      log_Printf(LogPHASE, "mpserver: can't connect to bundle socket %s (%s)\n",
1102                s->socket.sun_path, strerror(errno));
1103      if (errno == ECONNREFUSED)
1104        log_Printf(LogPHASE, "          The previous server died badly !\n");
1105      close(s->fd);
1106      s->fd = -1;
1107      return MPSERVER_FAILED;
1108    }
1109
1110    /* Donate our link to the other guy */
1111    return MPSERVER_CONNECTED;
1112  }
1113
1114  return MPSERVER_LISTENING;
1115}
1116
1117void
1118mpserver_Close(struct mpserver *s)
1119{
1120  if (s->send.dl != NULL) {
1121    bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
1122    s->send.dl = NULL;
1123    s->fd = -1;
1124  } else if (s->fd >= 0) {
1125    close(s->fd);
1126    if (ID0unlink(s->socket.sun_path) == -1)
1127      log_Printf(LogERROR, "%s: Failed to remove: %s\n", s->socket.sun_path,
1128                strerror(errno));
1129    memset(&s->socket, '\0', sizeof s->socket);
1130    s->fd = -1;
1131  }
1132}
1133
1134void
1135mp_LinkLost(struct mp *mp, struct datalink *dl)
1136{
1137  if (mp->seq.min_in == dl->mp.seq)
1138    /* We've lost the link that's holding everything up ! */
1139    mp_Assemble(mp, NULL, NULL);
1140}
1141
1142void
1143mp_DeleteQueue(struct mp *mp)
1144{
1145  link_DeleteQueue(&mp->link);
1146}
1147