]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/ppp/mp.c
Add two missing eventhandler.h headers
[FreeBSD/FreeBSD.git] / usr.sbin / ppp / mp.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30
31 #include <sys/param.h>
32 #include <netinet/in.h>
33 #include <netinet/in_systm.h>
34 #include <netinet/ip.h>
35 #include <arpa/inet.h>
36 #include <net/if_dl.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39
40 #include <errno.h>
41 #include <paths.h>
42 #include <stdarg.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <sys/stat.h>
47 #include <termios.h>
48 #include <unistd.h>
49
50 #include "layer.h"
51 #ifndef NONAT
52 #include "nat_cmd.h"
53 #endif
54 #include "vjcomp.h"
55 #include "ua.h"
56 #include "defs.h"
57 #include "command.h"
58 #include "mbuf.h"
59 #include "log.h"
60 #include "timer.h"
61 #include "fsm.h"
62 #include "iplist.h"
63 #include "throughput.h"
64 #include "slcompress.h"
65 #include "lqr.h"
66 #include "hdlc.h"
67 #include "ncpaddr.h"
68 #include "ipcp.h"
69 #include "auth.h"
70 #include "lcp.h"
71 #include "async.h"
72 #include "ccp.h"
73 #include "link.h"
74 #include "descriptor.h"
75 #include "physical.h"
76 #include "chat.h"
77 #include "proto.h"
78 #include "filter.h"
79 #include "mp.h"
80 #include "chap.h"
81 #include "cbcp.h"
82 #include "datalink.h"
83 #ifndef NORADIUS
84 #include "radius.h"
85 #endif
86 #include "ipv6cp.h"
87 #include "ncp.h"
88 #include "bundle.h"
89 #include "prompt.h"
90 #include "id.h"
91 #include "arp.h"
92
93 void
94 peerid_Init(struct peerid *peer)
95 {
96   peer->enddisc.class = 0;
97   *peer->enddisc.address = '\0';
98   peer->enddisc.len = 0;
99   *peer->authname = '\0';
100 }
101
102 int
103 peerid_Equal(const struct peerid *p1, const struct peerid *p2)
104 {
105   return !strcmp(p1->authname, p2->authname) &&
106          p1->enddisc.class == p2->enddisc.class &&
107          p1->enddisc.len == p2->enddisc.len &&
108          !memcmp(p1->enddisc.address, p2->enddisc.address, p1->enddisc.len);
109 }
110
111 static u_int32_t
112 inc_seq(unsigned is12bit, u_int32_t seq)
113 {
114   seq++;
115   if (is12bit) {
116     if (seq & 0xfffff000)
117       seq = 0;
118   } else if (seq & 0xff000000)
119     seq = 0;
120   return seq;
121 }
122
123 static int
124 isbefore(unsigned is12bit, u_int32_t seq1, u_int32_t seq2)
125 {
126   u_int32_t max = (is12bit ? 0xfff : 0xffffff) - 0x200;
127
128   if (seq1 > max) {
129     if (seq2 < 0x200 || seq2 > seq1)
130       return 1;
131   } else if ((seq1 > 0x200 || seq2 <= max) && seq1 < seq2)
132     return 1;
133
134   return 0;
135 }
136
137 static int
138 mp_ReadHeader(struct mp *mp, struct mbuf *m, struct mp_header *header)
139 {
140   if (mp->local_is12bit) {
141     u_int16_t val;
142
143     ua_ntohs(MBUF_CTOP(m), &val);
144     if (val & 0x3000) {
145       log_Printf(LogWARN, "Oops - MP header without required zero bits\n");
146       return 0;
147     }
148     header->begin = val & 0x8000 ? 1 : 0;
149     header->end = val & 0x4000 ? 1 : 0;
150     header->seq = val & 0x0fff;
151     return 2;
152   } else {
153     ua_ntohl(MBUF_CTOP(m), &header->seq);
154     if (header->seq & 0x3f000000) {
155       log_Printf(LogWARN, "Oops - MP header without required zero bits\n");
156       return 0;
157     }
158     header->begin = header->seq & 0x80000000 ? 1 : 0;
159     header->end = header->seq & 0x40000000 ? 1 : 0;
160     header->seq &= 0x00ffffff;
161     return 4;
162   }
163 }
164
165 static void
166 mp_LayerStart(void *v __unused, struct fsm *fp __unused)
167 {
168   /* The given FSM (ccp) is about to start up ! */
169 }
170
171 static void
172 mp_LayerUp(void *v __unused, struct fsm *fp)
173 {
174   /* The given fsm (ccp) is now up */
175
176   bundle_CalculateBandwidth(fp->bundle);        /* Against ccp_MTUOverhead */
177 }
178
179 static void
180 mp_LayerDown(void *v __unused, struct fsm *fp __unused)
181 {
182   /* The given FSM (ccp) has been told to come down */
183 }
184
185 static void
186 mp_LayerFinish(void *v __unused, struct fsm *fp)
187 {
188   /* The given fsm (ccp) is now down */
189   if (fp->state == ST_CLOSED && fp->open_mode == OPEN_PASSIVE)
190     fsm_Open(fp);               /* CCP goes to ST_STOPPED */
191 }
192
193 static void
194 mp_UpDown(void *v)
195 {
196   struct mp *mp = (struct mp *)v;
197   int percent;
198
199   percent = MAX(mp->link.stats.total.in.OctetsPerSecond,
200                 mp->link.stats.total.out.OctetsPerSecond) * 800 /
201             mp->bundle->bandwidth;
202   if (percent >= mp->cfg.autoload.max) {
203     log_Printf(LogDEBUG, "%d%% saturation - bring a link up ?\n", percent);
204     bundle_AutoAdjust(mp->bundle, percent, AUTO_UP);
205   } else if (percent <= mp->cfg.autoload.min) {
206     log_Printf(LogDEBUG, "%d%% saturation - bring a link down ?\n", percent);
207     bundle_AutoAdjust(mp->bundle, percent, AUTO_DOWN);
208   }
209 }
210
211 void
212 mp_StopAutoloadTimer(struct mp *mp)
213 {
214   throughput_stop(&mp->link.stats.total);
215 }
216
217 void
218 mp_CheckAutoloadTimer(struct mp *mp)
219 {
220   if (mp->link.stats.total.SamplePeriod != mp->cfg.autoload.period) {
221     throughput_destroy(&mp->link.stats.total);
222     throughput_init(&mp->link.stats.total, mp->cfg.autoload.period);
223     throughput_callback(&mp->link.stats.total, mp_UpDown, mp);
224   }
225
226   if (bundle_WantAutoloadTimer(mp->bundle))
227     throughput_start(&mp->link.stats.total, "MP throughput", 1);
228   else
229     mp_StopAutoloadTimer(mp);
230 }
231
232 void
233 mp_RestartAutoloadTimer(struct mp *mp)
234 {
235   if (mp->link.stats.total.SamplePeriod != mp->cfg.autoload.period)
236     mp_CheckAutoloadTimer(mp);
237   else
238     throughput_clear(&mp->link.stats.total, THROUGHPUT_OVERALL, NULL);
239 }
240
241 void
242 mp_Init(struct mp *mp, struct bundle *bundle)
243 {
244   mp->peer_is12bit = mp->local_is12bit = 0;
245   mp->peer_mrru = mp->local_mrru = 0;
246
247   peerid_Init(&mp->peer);
248
249   mp->out.seq = 0;
250   mp->out.link = 0;
251   mp->out.af = AF_INET;
252   mp->seq.min_in = 0;
253   mp->seq.next_in = 0;
254   mp->inbufs = NULL;
255   mp->bundle = bundle;
256
257   mp->link.type = LOGICAL_LINK;
258   mp->link.name = "mp";
259   mp->link.len = sizeof *mp;
260
261   mp->cfg.autoload.period = SAMPLE_PERIOD;
262   mp->cfg.autoload.min = mp->cfg.autoload.max = 0;
263   throughput_init(&mp->link.stats.total, mp->cfg.autoload.period);
264   throughput_callback(&mp->link.stats.total, mp_UpDown, mp);
265   mp->link.stats.parent = NULL;
266   mp->link.stats.gather = 0;    /* Let the physical links gather stats */
267   memset(mp->link.Queue, '\0', sizeof mp->link.Queue);
268   memset(mp->link.proto_in, '\0', sizeof mp->link.proto_in);
269   memset(mp->link.proto_out, '\0', sizeof mp->link.proto_out);
270
271   mp->fsmp.LayerStart = mp_LayerStart;
272   mp->fsmp.LayerUp = mp_LayerUp;
273   mp->fsmp.LayerDown = mp_LayerDown;
274   mp->fsmp.LayerFinish = mp_LayerFinish;
275   mp->fsmp.object = mp;
276
277   mpserver_Init(&mp->server);
278
279   mp->cfg.mrru = 0;
280   mp->cfg.shortseq = NEG_ENABLED|NEG_ACCEPTED;
281   mp->cfg.negenddisc = NEG_ENABLED|NEG_ACCEPTED;
282   mp->cfg.enddisc.class = 0;
283   *mp->cfg.enddisc.address = '\0';
284   mp->cfg.enddisc.len = 0;
285
286   lcp_Init(&mp->link.lcp, mp->bundle, &mp->link, NULL);
287   ccp_Init(&mp->link.ccp, mp->bundle, &mp->link, &mp->fsmp);
288
289   link_EmptyStack(&mp->link);
290   link_Stack(&mp->link, &protolayer);
291   link_Stack(&mp->link, &ccplayer);
292   link_Stack(&mp->link, &vjlayer);
293 #ifndef NONAT
294   link_Stack(&mp->link, &natlayer);
295 #endif
296 }
297
298 int
299 mp_Up(struct mp *mp, struct datalink *dl)
300 {
301   struct lcp *lcp = &dl->physical->link.lcp;
302
303   if (mp->active) {
304     /* We're adding a link - do a last validation on our parameters */
305     if (!peerid_Equal(&dl->peer, &mp->peer)) {
306       log_Printf(LogPHASE, "%s: Inappropriate peer !\n", dl->name);
307       log_Printf(LogPHASE, "  Attached to peer %s/%s\n", mp->peer.authname,
308                  mp_Enddisc(mp->peer.enddisc.class, mp->peer.enddisc.address,
309                             mp->peer.enddisc.len));
310       log_Printf(LogPHASE, "  New link is peer %s/%s\n", dl->peer.authname,
311                  mp_Enddisc(dl->peer.enddisc.class, dl->peer.enddisc.address,
312                             dl->peer.enddisc.len));
313       return MP_FAILED;
314     }
315     if (mp->local_mrru != lcp->want_mrru ||
316         mp->peer_mrru != lcp->his_mrru ||
317         mp->local_is12bit != lcp->want_shortseq ||
318         mp->peer_is12bit != lcp->his_shortseq) {
319       log_Printf(LogPHASE, "%s: Invalid MRRU/SHORTSEQ MP parameters !\n",
320                 dl->name);
321       return MP_FAILED;
322     }
323     return MP_ADDED;
324   } else {
325     /* First link in multilink mode */
326
327     mp->local_mrru = lcp->want_mrru;
328     mp->peer_mrru = lcp->his_mrru;
329     mp->local_is12bit = lcp->want_shortseq;
330     mp->peer_is12bit = lcp->his_shortseq;
331     mp->peer = dl->peer;
332
333     throughput_destroy(&mp->link.stats.total);
334     throughput_init(&mp->link.stats.total, mp->cfg.autoload.period);
335     throughput_callback(&mp->link.stats.total, mp_UpDown, mp);
336     memset(mp->link.Queue, '\0', sizeof mp->link.Queue);
337     memset(mp->link.proto_in, '\0', sizeof mp->link.proto_in);
338     memset(mp->link.proto_out, '\0', sizeof mp->link.proto_out);
339
340     /* Tell the link who it belongs to */
341     dl->physical->link.stats.parent = &mp->link.stats.total;
342
343     mp->out.seq = 0;
344     mp->out.link = 0;
345     mp->out.af = AF_INET;
346     mp->seq.min_in = 0;
347     mp->seq.next_in = 0;
348
349     /*
350      * Now we create our server socket.
351      * If it already exists, join it.  Otherwise, create and own it
352      */
353     switch (mpserver_Open(&mp->server, &mp->peer)) {
354     case MPSERVER_CONNECTED:
355       log_Printf(LogPHASE, "mp: Transfer link on %s\n",
356                 mp->server.socket.sun_path);
357       mp->server.send.dl = dl;          /* Defer 'till it's safe to send */
358       return MP_LINKSENT;
359     case MPSERVER_FAILED:
360       return MP_FAILED;
361     case MPSERVER_LISTENING:
362       log_Printf(LogPHASE, "mp: Listening on %s\n", mp->server.socket.sun_path);
363       log_Printf(LogPHASE, "    First link: %s\n", dl->name);
364
365       /* Re-point our NCP layers at our MP link */
366       ncp_SetLink(&mp->bundle->ncp, &mp->link);
367
368       /* Our lcp's already up 'cos of the NULL parent */
369       if (ccp_SetOpenMode(&mp->link.ccp)) {
370         fsm_Up(&mp->link.ccp.fsm);
371         fsm_Open(&mp->link.ccp.fsm);
372       }
373
374       mp->active = 1;
375       break;
376     }
377   }
378
379   return MP_UP;
380 }
381
382 void
383 mp_Down(struct mp *mp)
384 {
385   if (mp->active) {
386     struct mbuf *next;
387
388     /* Stop that ! */
389     mp_StopAutoloadTimer(mp);
390
391     /* Don't want any more of these */
392     mpserver_Close(&mp->server);
393
394     /* CCP goes down with a bang */
395     fsm2initial(&mp->link.ccp.fsm);
396
397     /* Received fragments go in the bit-bucket */
398     while (mp->inbufs) {
399       next = mp->inbufs->m_nextpkt;
400       m_freem(mp->inbufs);
401       mp->inbufs = next;
402     }
403
404     peerid_Init(&mp->peer);
405     mp->active = 0;
406   }
407 }
408
409 void
410 mp_linkInit(struct mp_link *mplink)
411 {
412   mplink->seq = 0;
413   mplink->bandwidth = 0;
414 }
415
416 static void
417 mp_Assemble(struct mp *mp, struct mbuf *m, struct physical *p)
418 {
419   struct mp_header mh, h;
420   struct mbuf *q, *last;
421   u_int32_t seq;
422
423   /*
424    * When `m' and `p' are NULL, it means our oldest link has gone down.
425    * We want to determine a new min, and process any intermediate stuff
426    * as normal
427    */
428
429   if (m && mp_ReadHeader(mp, m, &mh) == 0) {
430     m_freem(m);
431     return;
432   }
433
434   if (p) {
435     seq = p->dl->mp.seq;
436     p->dl->mp.seq = mh.seq;
437   } else
438     seq = mp->seq.min_in;
439
440   if (mp->seq.min_in == seq) {
441     /*
442      * We've received new data on the link that has our min (oldest) seq.
443      * Figure out which link now has the smallest (oldest) seq.
444      */
445     struct datalink *dl;
446
447     mp->seq.min_in = (u_int32_t)-1;
448     for (dl = mp->bundle->links; dl; dl = dl->next)
449       if (dl->state == DATALINK_OPEN &&
450           (mp->seq.min_in == (u_int32_t)-1 ||
451            isbefore(mp->local_is12bit, dl->mp.seq, mp->seq.min_in)))
452         mp->seq.min_in = dl->mp.seq;
453   }
454
455   /*
456    * Now process as many of our fragments as we can, adding our new
457    * fragment in as we go, and ordering with the oldest at the top of
458    * the queue.
459    */
460
461   last = NULL;
462   seq = mp->seq.next_in;
463   q = mp->inbufs;
464   while (q || m) {
465     if (!q) {
466       if (last)
467         last->m_nextpkt = m;
468       else
469         mp->inbufs = m;
470       q = m;
471       m = NULL;
472       h = mh;
473     } else {
474       mp_ReadHeader(mp, q, &h);
475
476       if (m && isbefore(mp->local_is12bit, mh.seq, h.seq)) {
477         /* Our received fragment fits in before this one, so link it in */
478         if (last)
479           last->m_nextpkt = m;
480         else
481           mp->inbufs = m;
482         m->m_nextpkt = q;
483         q = m;
484         h = mh;
485         m = NULL;
486       }
487     }
488
489     if (h.seq != seq) {
490       /* we're missing something :-( */
491       if (isbefore(mp->local_is12bit, seq, mp->seq.min_in)) {
492         /* we're never gonna get it */
493         struct mbuf *next;
494
495         /* Zap all older fragments */
496         while (mp->inbufs != q) {
497           log_Printf(LogDEBUG, "Drop frag\n");
498           next = mp->inbufs->m_nextpkt;
499           m_freem(mp->inbufs);
500           mp->inbufs = next;
501         }
502
503         /*
504          * Zap everything until the next `end' fragment OR just before
505          * the next `begin' fragment OR 'till seq.min_in - whichever
506          * comes first.
507          */
508         do {
509           mp_ReadHeader(mp, mp->inbufs, &h);
510           if (h.begin) {
511             /* We might be able to process this ! */
512             h.seq--;  /* We're gonna look for fragment with h.seq+1 */
513             break;
514           }
515           next = mp->inbufs->m_nextpkt;
516           log_Printf(LogDEBUG, "Drop frag %u\n", h.seq);
517           m_freem(mp->inbufs);
518           mp->inbufs = next;
519         } while (mp->inbufs && (isbefore(mp->local_is12bit, mp->seq.min_in,
520                                          h.seq) || h.end));
521
522         /*
523          * Continue processing things from here.
524          * This deals with the possibility that we received a fragment
525          * on the slowest link that invalidates some of our data (because
526          * of the hole at `q'), but where there are subsequent `whole'
527          * packets that have already been received.
528          */
529
530         mp->seq.next_in = seq = inc_seq(mp->local_is12bit, h.seq);
531         last = NULL;
532         q = mp->inbufs;
533       } else
534         /* we may still receive the missing fragment */
535         break;
536     } else if (h.end) {
537       /* We've got something, reassemble */
538       struct mbuf **frag = &q;
539       int len;
540       long long first = -1;
541
542       do {
543         *frag = mp->inbufs;
544         mp->inbufs = mp->inbufs->m_nextpkt;
545         len = mp_ReadHeader(mp, *frag, &h);
546         if (first == -1)
547           first = h.seq;
548         if (frag == &q && !h.begin) {
549           log_Printf(LogWARN, "Oops - MP frag %lu should have a begin flag\n",
550                     (u_long)h.seq);
551           m_freem(q);
552           q = NULL;
553         } else if (frag != &q && h.begin) {
554           log_Printf(LogWARN, "Oops - MP frag %lu should have an end flag\n",
555                     (u_long)h.seq - 1);
556           /*
557            * Stuff our fragment back at the front of the queue and zap
558            * our half-assembled packet.
559            */
560           (*frag)->m_nextpkt = mp->inbufs;
561           mp->inbufs = *frag;
562           *frag = NULL;
563           m_freem(q);
564           q = NULL;
565           frag = &q;
566           h.end = 0;    /* just in case it's a whole packet */
567         } else {
568           (*frag)->m_offset += len;
569           (*frag)->m_len -= len;
570           (*frag)->m_nextpkt = NULL;
571           do
572             frag = &(*frag)->m_next;
573           while (*frag != NULL);
574         }
575       } while (!h.end);
576
577       if (q) {
578         q = m_pullup(q);
579         log_Printf(LogDEBUG, "MP: Reassembled frags %lu-%lu, length %zd\n",
580                    (u_long)first, (u_long)h.seq, m_length(q));
581         link_PullPacket(&mp->link, MBUF_CTOP(q), q->m_len, mp->bundle);
582         m_freem(q);
583       }
584
585       mp->seq.next_in = seq = inc_seq(mp->local_is12bit, h.seq);
586       last = NULL;
587       q = mp->inbufs;
588     } else {
589       /* Look for the next fragment */
590       seq = inc_seq(mp->local_is12bit, seq);
591       last = q;
592       q = q->m_nextpkt;
593     }
594   }
595
596   if (m) {
597     /* We still have to find a home for our new fragment */
598     last = NULL;
599     for (q = mp->inbufs; q; last = q, q = q->m_nextpkt) {
600       mp_ReadHeader(mp, q, &h);
601       if (isbefore(mp->local_is12bit, mh.seq, h.seq))
602         break;
603     }
604     /* Our received fragment fits in here */
605     if (last)
606       last->m_nextpkt = m;
607     else
608       mp->inbufs = m;
609     m->m_nextpkt = q;
610   }
611 }
612
613 struct mbuf *
614 mp_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
615 {
616   struct physical *p = link2physical(l);
617
618   if (!bundle->ncp.mp.active)
619     /* Let someone else deal with it ! */
620     return bp;
621
622   if (p == NULL) {
623     log_Printf(LogWARN, "DecodePacket: Can't do MP inside MP !\n");
624     m_freem(bp);
625   } else {
626     m_settype(bp, MB_MPIN);
627     mp_Assemble(&bundle->ncp.mp, bp, p);
628   }
629
630   return NULL;
631 }
632
633 static void
634 mp_Output(struct mp *mp, struct bundle *bundle, struct link *l,
635           struct mbuf *m, u_int32_t begin, u_int32_t end)
636 {
637   char prepend[4];
638
639   /* Stuff an MP header on the front of our packet and send it */
640
641   if (mp->peer_is12bit) {
642     u_int16_t val;
643
644     val = (begin << 15) | (end << 14) | (u_int16_t)mp->out.seq;
645     ua_htons(&val, prepend);
646     m = m_prepend(m, prepend, 2, 0);
647   } else {
648     u_int32_t val;
649
650     val = (begin << 31) | (end << 30) | (u_int32_t)mp->out.seq;
651     ua_htonl(&val, prepend);
652     m = m_prepend(m, prepend, 4, 0);
653   }
654   if (log_IsKept(LogDEBUG))
655     log_Printf(LogDEBUG, "MP[frag %d]: Send %zd bytes on link `%s'\n",
656                mp->out.seq, m_length(m), l->name);
657   mp->out.seq = inc_seq(mp->peer_is12bit, mp->out.seq);
658
659   if (l->ccp.fsm.state != ST_OPENED && ccp_Required(&l->ccp)) {
660     log_Printf(LogPHASE, "%s: Not transmitting... waiting for CCP\n", l->name);
661     return;
662   }
663
664   link_PushPacket(l, m, bundle, LINK_QUEUES(l) - 1, PROTO_MP);
665 }
666
667 int
668 mp_FillPhysicalQueues(struct bundle *bundle)
669 {
670   struct mp *mp = &bundle->ncp.mp;
671   struct datalink *dl, *fdl;
672   size_t total, add, len;
673   int thislink, nlinks, nopenlinks, sendasip;
674   u_int32_t begin, end;
675   struct mbuf *m, *mo;
676   struct link *bestlink;
677
678   thislink = nlinks = nopenlinks = 0;
679   for (fdl = NULL, dl = bundle->links; dl; dl = dl->next) {
680     /* Include non-open links here as mp->out.link will stay more correct */
681     if (!fdl) {
682       if (thislink == mp->out.link)
683         fdl = dl;
684       else
685         thislink++;
686     }
687     nlinks++;
688     if (dl->state == DATALINK_OPEN)
689       nopenlinks++;
690   }
691
692   if (!fdl) {
693     fdl = bundle->links;
694     if (!fdl)
695       return 0;
696     thislink = 0;
697   }
698
699   total = 0;
700   for (dl = fdl; nlinks > 0; dl = dl->next, nlinks--, thislink++) {
701     if (!dl) {
702       dl = bundle->links;
703       thislink = 0;
704     }
705
706     if (dl->state != DATALINK_OPEN)
707       continue;
708
709     if (dl->physical->out)
710       /* this link has suffered a short write.  Let it continue */
711       continue;
712
713     add = link_QueueLen(&dl->physical->link);
714     if (add) {
715       /* this link has got stuff already queued.  Let it continue */
716       total += add;
717       continue;
718     }
719
720     if (!mp_QueueLen(mp)) {
721       int mrutoosmall;
722
723       /*
724        * If there's only a single open link in our bundle and we haven't got
725        * MP level link compression, queue outbound traffic directly via that
726        * link's protocol stack rather than using the MP link.  This results
727        * in the outbound traffic going out as PROTO_IP or PROTO_IPV6 rather
728        * than PROTO_MP.
729        */
730
731       mrutoosmall = 0;
732       sendasip = nopenlinks < 2;
733       if (sendasip) {
734         if (dl->physical->link.lcp.his_mru < mp->peer_mrru) {
735           /*
736            * Actually, forget it.  This test is done against the MRRU rather
737            * than the packet size so that we don't end up sending some data
738            * in MP fragments and some data in PROTO_IP packets.  That's just
739            * too likely to upset some ppp implementations.
740            */
741           mrutoosmall = 1;
742           sendasip = 0;
743         }
744       }
745
746       bestlink = sendasip ? &dl->physical->link : &mp->link;
747       if (!ncp_PushPacket(&bundle->ncp, &mp->out.af, bestlink))
748         break;  /* Nothing else to send */
749
750       if (mrutoosmall)
751         log_Printf(LogDEBUG, "Don't send data as PROTO_IP, MRU < MRRU\n");
752       else if (sendasip)
753         log_Printf(LogDEBUG, "Sending data as PROTO_IP, not PROTO_MP\n");
754
755       if (sendasip) {
756         add = link_QueueLen(&dl->physical->link);
757         if (add) {
758           /* this link has got stuff already queued.  Let it continue */
759           total += add;
760           continue;
761         }
762       }
763     }
764
765     m = link_Dequeue(&mp->link);
766     if (m) {
767       len = m_length(m);
768       begin = 1;
769       end = 0;
770
771       while (!end) {
772         if (dl->state == DATALINK_OPEN) {
773           /* Write at most his_mru bytes to the physical link */
774           if (len <= dl->physical->link.lcp.his_mru) {
775             mo = m;
776             end = 1;
777             m_settype(mo, MB_MPOUT);
778           } else {
779             /* It's > his_mru, chop the packet (`m') into bits */
780             mo = m_get(dl->physical->link.lcp.his_mru, MB_MPOUT);
781             len -= mo->m_len;
782             m = mbuf_Read(m, MBUF_CTOP(mo), mo->m_len);
783           }
784           mp_Output(mp, bundle, &dl->physical->link, mo, begin, end);
785           begin = 0;
786         }
787
788         if (!end) {
789           nlinks--;
790           dl = dl->next;
791           if (!dl) {
792             dl = bundle->links;
793             thislink = 0;
794           } else
795             thislink++;
796         }
797       }
798     }
799   }
800   mp->out.link = thislink;              /* Start here next time */
801
802   return total;
803 }
804
805 int
806 mp_SetDatalinkBandwidth(struct cmdargs const *arg)
807 {
808   int val;
809
810   if (arg->argc != arg->argn+1)
811     return -1;
812
813   val = atoi(arg->argv[arg->argn]);
814   if (val <= 0) {
815     log_Printf(LogWARN, "The link bandwidth must be greater than zero\n");
816     return 1;
817   }
818   arg->cx->mp.bandwidth = val;
819
820   if (arg->cx->state == DATALINK_OPEN)
821     bundle_CalculateBandwidth(arg->bundle);
822
823   return 0;
824 }
825
826 int
827 mp_ShowStatus(struct cmdargs const *arg)
828 {
829   struct mp *mp = &arg->bundle->ncp.mp;
830
831   prompt_Printf(arg->prompt, "Multilink is %sactive\n", mp->active ? "" : "in");
832   if (mp->active) {
833     struct mbuf *m, *lm;
834     int bufs = 0;
835
836     lm = NULL;
837     prompt_Printf(arg->prompt, "Socket:         %s\n",
838                   mp->server.socket.sun_path);
839     for (m = mp->inbufs; m; m = m->m_nextpkt) {
840       bufs++;
841       lm = m;
842     }
843     prompt_Printf(arg->prompt, "Pending frags:  %d", bufs);
844     if (bufs) {
845       struct mp_header mh;
846       unsigned long first, last;
847
848       first = mp_ReadHeader(mp, mp->inbufs, &mh) ? mh.seq : 0;
849       last = mp_ReadHeader(mp, lm, &mh) ? mh.seq : 0;
850       prompt_Printf(arg->prompt, " (Have %lu - %lu, want %lu, lowest %lu)\n",
851                     first, last, (unsigned long)mp->seq.next_in,
852                     (unsigned long)mp->seq.min_in);
853       prompt_Printf(arg->prompt, "                First has %sbegin bit and "
854                     "%send bit", mh.begin ? "" : "no ", mh.end ? "" : "no ");
855     }
856     prompt_Printf(arg->prompt, "\n");
857   }
858
859   prompt_Printf(arg->prompt, "\nMy Side:\n");
860   if (mp->active) {
861     prompt_Printf(arg->prompt, " Output SEQ:    %u\n", mp->out.seq);
862     prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->local_mrru);
863     prompt_Printf(arg->prompt, " Short Seq:     %s\n",
864                   mp->local_is12bit ? "on" : "off");
865   }
866   prompt_Printf(arg->prompt, " Discriminator: %s\n",
867                 mp_Enddisc(mp->cfg.enddisc.class, mp->cfg.enddisc.address,
868                            mp->cfg.enddisc.len));
869
870   prompt_Printf(arg->prompt, "\nHis Side:\n");
871   if (mp->active) {
872     prompt_Printf(arg->prompt, " Auth Name:     %s\n", mp->peer.authname);
873     prompt_Printf(arg->prompt, " Input SEQ:     %u\n", mp->seq.next_in);
874     prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->peer_mrru);
875     prompt_Printf(arg->prompt, " Short Seq:     %s\n",
876                   mp->peer_is12bit ? "on" : "off");
877   }
878   prompt_Printf(arg->prompt,   " Discriminator: %s\n",
879                 mp_Enddisc(mp->peer.enddisc.class, mp->peer.enddisc.address,
880                            mp->peer.enddisc.len));
881
882   prompt_Printf(arg->prompt, "\nDefaults:\n");
883
884   prompt_Printf(arg->prompt, " MRRU:          ");
885   if (mp->cfg.mrru)
886     prompt_Printf(arg->prompt, "%d (multilink enabled)\n", mp->cfg.mrru);
887   else
888     prompt_Printf(arg->prompt, "disabled\n");
889   prompt_Printf(arg->prompt, " Short Seq:     %s\n",
890                   command_ShowNegval(mp->cfg.shortseq));
891   prompt_Printf(arg->prompt, " Discriminator: %s\n",
892                   command_ShowNegval(mp->cfg.negenddisc));
893   prompt_Printf(arg->prompt, " AutoLoad:      min %d%%, max %d%%,"
894                 " period %d secs\n", mp->cfg.autoload.min,
895                 mp->cfg.autoload.max, mp->cfg.autoload.period);
896
897   return 0;
898 }
899
900 const char *
901 mp_Enddisc(u_char c, const char *address, size_t len)
902 {
903   static char result[100];      /* Used immediately after it's returned */
904   unsigned f, header;
905
906   switch (c) {
907     case ENDDISC_NULL:
908       sprintf(result, "Null Class");
909       break;
910
911     case ENDDISC_LOCAL:
912             snprintf(result, sizeof result, "Local Addr: %.*s", (int)len,
913                 address);
914       break;
915
916     case ENDDISC_IP:
917       if (len == 4)
918         snprintf(result, sizeof result, "IP %s",
919                  inet_ntoa(*(const struct in_addr *)address));
920       else
921         sprintf(result, "IP[%zd] ???", len);
922       break;
923
924     case ENDDISC_MAC:
925       if (len == 6) {
926         const u_char *m = (const u_char *)address;
927         snprintf(result, sizeof result, "MAC %02x:%02x:%02x:%02x:%02x:%02x",
928                  m[0], m[1], m[2], m[3], m[4], m[5]);
929       } else
930         sprintf(result, "MAC[%zd] ???", len);
931       break;
932
933     case ENDDISC_MAGIC:
934       sprintf(result, "Magic: 0x");
935       header = strlen(result);
936       if (len + header + 1 > sizeof result)
937         len = sizeof result - header - 1;
938       for (f = 0; f < len; f++)
939         sprintf(result + header + 2 * f, "%02x", address[f]);
940       break;
941
942     case ENDDISC_PSN:
943             snprintf(result, sizeof result, "PSN: %.*s", (int)len, address);
944       break;
945
946     default:
947       sprintf(result, "%d: ", (int)c);
948       header = strlen(result);
949       if (len + header + 1 > sizeof result)
950         len = sizeof result - header - 1;
951       for (f = 0; f < len; f++)
952         sprintf(result + header + 2 * f, "%02x", address[f]);
953       break;
954   }
955   return result;
956 }
957
958 int
959 mp_SetEnddisc(struct cmdargs const *arg)
960 {
961   struct mp *mp = &arg->bundle->ncp.mp;
962   struct in_addr addr;
963
964   switch (bundle_Phase(arg->bundle)) {
965     case PHASE_DEAD:
966       break;
967     case PHASE_ESTABLISH:
968       /* Make sure none of our links are DATALINK_LCP or greater */
969       if (bundle_HighestState(arg->bundle) >= DATALINK_LCP) {
970         log_Printf(LogWARN, "enddisc: Only changeable before"
971                    " LCP negotiations\n");
972         return 1;
973       }
974       break;
975     default:
976       log_Printf(LogWARN, "enddisc: Only changeable at phase DEAD/ESTABLISH\n");
977       return 1;
978   }
979
980   if (arg->argc == arg->argn) {
981     mp->cfg.enddisc.class = 0;
982     *mp->cfg.enddisc.address = '\0';
983     mp->cfg.enddisc.len = 0;
984   } else if (arg->argc > arg->argn) {
985     if (!strcasecmp(arg->argv[arg->argn], "label")) {
986       mp->cfg.enddisc.class = ENDDISC_LOCAL;
987       strcpy(mp->cfg.enddisc.address, arg->bundle->cfg.label);
988       mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
989     } else if (!strcasecmp(arg->argv[arg->argn], "ip")) {
990       if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
991         ncprange_getip4addr(&arg->bundle->ncp.ipcp.cfg.my_range, &addr);
992       else
993         addr = arg->bundle->ncp.ipcp.my_ip;
994       memcpy(mp->cfg.enddisc.address, &addr.s_addr, sizeof addr.s_addr);
995       mp->cfg.enddisc.class = ENDDISC_IP;
996       mp->cfg.enddisc.len = sizeof arg->bundle->ncp.ipcp.my_ip.s_addr;
997     } else if (!strcasecmp(arg->argv[arg->argn], "mac")) {
998       struct sockaddr_dl hwaddr;
999
1000       if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
1001         ncprange_getip4addr(&arg->bundle->ncp.ipcp.cfg.my_range, &addr);
1002       else
1003         addr = arg->bundle->ncp.ipcp.my_ip;
1004
1005       if (arp_EtherAddr(addr, &hwaddr, 1)) {
1006         mp->cfg.enddisc.class = ENDDISC_MAC;
1007         memcpy(mp->cfg.enddisc.address, hwaddr.sdl_data + hwaddr.sdl_nlen,
1008                hwaddr.sdl_alen);
1009         mp->cfg.enddisc.len = hwaddr.sdl_alen;
1010       } else {
1011         log_Printf(LogWARN, "set enddisc: Can't locate MAC address for %s\n",
1012                   inet_ntoa(addr));
1013         return 4;
1014       }
1015     } else if (!strcasecmp(arg->argv[arg->argn], "magic")) {
1016       int f;
1017
1018       randinit();
1019       for (f = 0; f < 20; f += sizeof(long))
1020         *(long *)(mp->cfg.enddisc.address + f) = random();
1021       mp->cfg.enddisc.class = ENDDISC_MAGIC;
1022       mp->cfg.enddisc.len = 20;
1023     } else if (!strcasecmp(arg->argv[arg->argn], "psn")) {
1024       if (arg->argc > arg->argn+1) {
1025         mp->cfg.enddisc.class = ENDDISC_PSN;
1026         strcpy(mp->cfg.enddisc.address, arg->argv[arg->argn+1]);
1027         mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
1028       } else {
1029         log_Printf(LogWARN, "PSN endpoint requires additional data\n");
1030         return 5;
1031       }
1032     } else {
1033       log_Printf(LogWARN, "%s: Unrecognised endpoint type\n",
1034                 arg->argv[arg->argn]);
1035       return 6;
1036     }
1037   }
1038
1039   return 0;
1040 }
1041
1042 static int
1043 mpserver_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e,
1044                    int *n)
1045 {
1046   struct mpserver *s = descriptor2mpserver(d);
1047   int result;
1048
1049   result = 0;
1050   if (s->send.dl != NULL) {
1051     /* We've connect()ed */
1052     if (!link_QueueLen(&s->send.dl->physical->link) &&
1053         !s->send.dl->physical->out) {
1054       /* Only send if we've transmitted all our data (i.e. the ConfigAck) */
1055       result -= datalink_RemoveFromSet(s->send.dl, r, w, e);
1056       bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
1057       s->send.dl = NULL;
1058       s->fd = -1;
1059     } else
1060       /* Never read from a datalink that's on death row ! */
1061       result -= datalink_RemoveFromSet(s->send.dl, r, NULL, NULL);
1062   } else if (r && s->fd >= 0) {
1063     if (*n < s->fd + 1)
1064       *n = s->fd + 1;
1065     FD_SET(s->fd, r);
1066     log_Printf(LogTIMER, "mp: fdset(r) %d\n", s->fd);
1067     result++;
1068   }
1069   return result;
1070 }
1071
1072 static int
1073 mpserver_IsSet(struct fdescriptor *d, const fd_set *fdset)
1074 {
1075   struct mpserver *s = descriptor2mpserver(d);
1076   return s->fd >= 0 && FD_ISSET(s->fd, fdset);
1077 }
1078
1079 static void
1080 mpserver_Read(struct fdescriptor *d, struct bundle *bundle,
1081               const fd_set *fdset __unused)
1082 {
1083   struct mpserver *s = descriptor2mpserver(d);
1084
1085   bundle_ReceiveDatalink(bundle, s->fd);
1086 }
1087
1088 static int
1089 mpserver_Write(struct fdescriptor *d __unused, struct bundle *bundle __unused,
1090                const fd_set *fdset __unused)
1091 {
1092   /* We never want to write here ! */
1093   log_Printf(LogALERT, "mpserver_Write: Internal error: Bad call !\n");
1094   return 0;
1095 }
1096
1097 void
1098 mpserver_Init(struct mpserver *s)
1099 {
1100   s->desc.type = MPSERVER_DESCRIPTOR;
1101   s->desc.UpdateSet = mpserver_UpdateSet;
1102   s->desc.IsSet = mpserver_IsSet;
1103   s->desc.Read = mpserver_Read;
1104   s->desc.Write = mpserver_Write;
1105   s->send.dl = NULL;
1106   s->fd = -1;
1107   memset(&s->socket, '\0', sizeof s->socket);
1108 }
1109
1110 int
1111 mpserver_Open(struct mpserver *s, struct peerid *peer)
1112 {
1113   int f, l;
1114   mode_t mask;
1115
1116   if (s->fd != -1) {
1117     log_Printf(LogALERT, "Internal error !  mpserver already open\n");
1118     mpserver_Close(s);
1119   }
1120
1121   l = snprintf(s->socket.sun_path, sizeof s->socket.sun_path, "%sppp-%s-%02x-",
1122                _PATH_VARRUN, peer->authname, peer->enddisc.class);
1123   if (l < 0) {
1124     log_Printf(LogERROR, "mpserver: snprintf(): %s\n", strerror(errno));
1125     return MPSERVER_FAILED;
1126   }
1127
1128   for (f = 0;
1129        f < peer->enddisc.len && (size_t)l < sizeof s->socket.sun_path - 2;
1130        f++) {
1131     snprintf(s->socket.sun_path + l, sizeof s->socket.sun_path - l,
1132              "%02x", *(u_char *)(peer->enddisc.address+f));
1133     l += 2;
1134   }
1135
1136   s->socket.sun_family = AF_LOCAL;
1137   s->socket.sun_len = sizeof s->socket;
1138   s->fd = ID0socket(PF_LOCAL, SOCK_DGRAM, 0);
1139   if (s->fd < 0) {
1140     log_Printf(LogERROR, "mpserver: socket(): %s\n", strerror(errno));
1141     return MPSERVER_FAILED;
1142   }
1143
1144   setsockopt(s->fd, SOL_SOCKET, SO_REUSEADDR, (struct sockaddr *)&s->socket,
1145              sizeof s->socket);
1146   mask = umask(0177);
1147
1148   /*
1149    * Try to bind the socket.  If we succeed we play server, if we fail
1150    * we connect() and hand the link off.
1151    */
1152
1153   if (ID0bind_un(s->fd, &s->socket) < 0) {
1154     if (errno != EADDRINUSE) {
1155       log_Printf(LogPHASE, "mpserver: can't create bundle socket %s (%s)\n",
1156                 s->socket.sun_path, strerror(errno));
1157       umask(mask);
1158       close(s->fd);
1159       s->fd = -1;
1160       return MPSERVER_FAILED;
1161     }
1162
1163     /* So we're the sender */
1164     umask(mask);
1165     if (ID0connect_un(s->fd, &s->socket) < 0) {
1166       log_Printf(LogPHASE, "mpserver: can't connect to bundle socket %s (%s)\n",
1167                 s->socket.sun_path, strerror(errno));
1168       if (errno == ECONNREFUSED)
1169         log_Printf(LogPHASE, "          The previous server died badly !\n");
1170       close(s->fd);
1171       s->fd = -1;
1172       return MPSERVER_FAILED;
1173     }
1174
1175     /* Donate our link to the other guy */
1176     return MPSERVER_CONNECTED;
1177   }
1178
1179   return MPSERVER_LISTENING;
1180 }
1181
1182 void
1183 mpserver_Close(struct mpserver *s)
1184 {
1185   if (s->send.dl != NULL) {
1186     bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
1187     s->send.dl = NULL;
1188     s->fd = -1;
1189   } else if (s->fd >= 0) {
1190     close(s->fd);
1191     if (ID0unlink(s->socket.sun_path) == -1)
1192       log_Printf(LogERROR, "%s: Failed to remove: %s\n", s->socket.sun_path,
1193                 strerror(errno));
1194     memset(&s->socket, '\0', sizeof s->socket);
1195     s->fd = -1;
1196   }
1197 }
1198
1199 void
1200 mp_LinkLost(struct mp *mp, struct datalink *dl)
1201 {
1202   if (mp->seq.min_in == dl->mp.seq)
1203     /* We've lost the link that's holding everything up ! */
1204     mp_Assemble(mp, NULL, NULL);
1205 }
1206
1207 size_t
1208 mp_QueueLen(struct mp *mp)
1209 {
1210   return link_QueueLen(&mp->link);
1211 }