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