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