mp.c revision 38174
1/*-
2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 *	$Id: mp.c,v 1.12 1998/06/30 23:04:17 brian Exp $
27 */
28
29#include <sys/types.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 "defs.h"
48#include "command.h"
49#include "mbuf.h"
50#include "log.h"
51#include "timer.h"
52#include "fsm.h"
53#include "iplist.h"
54#include "throughput.h"
55#include "slcompress.h"
56#include "ipcp.h"
57#include "auth.h"
58#include "lcp.h"
59#include "lqr.h"
60#include "hdlc.h"
61#include "async.h"
62#include "ccp.h"
63#include "link.h"
64#include "descriptor.h"
65#include "physical.h"
66#include "chat.h"
67#include "lcpproto.h"
68#include "filter.h"
69#include "mp.h"
70#include "chap.h"
71#include "cbcp.h"
72#include "datalink.h"
73#include "bundle.h"
74#include "ip.h"
75#include "prompt.h"
76#include "id.h"
77#include "arp.h"
78
79void
80peerid_Init(struct peerid *peer)
81{
82  peer->enddisc.class = 0;
83  *peer->enddisc.address = '\0';
84  peer->enddisc.len = 0;
85  *peer->authname = '\0';
86}
87
88int
89peerid_Equal(const struct peerid *p1, const struct peerid *p2)
90{
91  return !strcmp(p1->authname, p2->authname) &&
92         p1->enddisc.class == p2->enddisc.class &&
93         p1->enddisc.len == p2->enddisc.len &&
94         !memcmp(p1->enddisc.address, p2->enddisc.address, p1->enddisc.len);
95}
96
97static u_int32_t
98inc_seq(unsigned is12bit, u_int32_t seq)
99{
100  seq++;
101  if (is12bit) {
102    if (seq & 0xfffff000)
103      seq = 0;
104  } else if (seq & 0xff000000)
105    seq = 0;
106  return seq;
107}
108
109static int
110isbefore(unsigned is12bit, u_int32_t seq1, u_int32_t seq2)
111{
112  u_int32_t max = (is12bit ? 0xfff : 0xffffff) - 0x200;
113
114  if (seq1 > max) {
115    if (seq2 < 0x200 || seq2 > seq1)
116      return 1;
117  } else if ((seq1 > 0x200 || seq2 <= max) && seq1 < seq2)
118    return 1;
119
120  return 0;
121}
122
123static int
124mp_ReadHeader(struct mp *mp, struct mbuf *m, struct mp_header *header)
125{
126  if (mp->local_is12bit) {
127    header->seq = ntohs(*(u_int16_t *)MBUF_CTOP(m));
128    if (header->seq & 0x3000) {
129      log_Printf(LogWARN, "Oops - MP header without required zero bits\n");
130      return 0;
131    }
132    header->begin = header->seq & 0x8000 ? 1 : 0;
133    header->end = header->seq & 0x4000 ? 1 : 0;
134    header->seq &= 0x0fff;
135    return 2;
136  } else {
137    header->seq = ntohl(*(u_int32_t *)MBUF_CTOP(m));
138    if (header->seq & 0x3f000000) {
139      log_Printf(LogWARN, "Oops - MP header without required zero bits\n");
140      return 0;
141    }
142    header->begin = header->seq & 0x80000000 ? 1 : 0;
143    header->end = header->seq & 0x40000000 ? 1 : 0;
144    header->seq &= 0x00ffffff;
145    return 4;
146  }
147}
148
149static void
150mp_LayerStart(void *v, struct fsm *fp)
151{
152  /* The given FSM (ccp) is about to start up ! */
153}
154
155static void
156mp_LayerUp(void *v, struct fsm *fp)
157{
158  /* The given fsm (ccp) is now up */
159}
160
161static void
162mp_LayerDown(void *v, struct fsm *fp)
163{
164  /* The given FSM (ccp) has been told to come down */
165}
166
167static void
168mp_LayerFinish(void *v, struct fsm *fp)
169{
170  /* The given fsm (ccp) is now down */
171  if (fp->state == ST_CLOSED && fp->open_mode == OPEN_PASSIVE)
172    fsm_Open(fp);		/* CCP goes to ST_STOPPED */
173}
174
175void
176mp_Init(struct mp *mp, struct bundle *bundle)
177{
178  mp->peer_is12bit = mp->local_is12bit = 0;
179  mp->peer_mrru = mp->local_mrru = 0;
180
181  peerid_Init(&mp->peer);
182
183  mp->out.seq = 0;
184  mp->out.link = 0;
185  mp->seq.min_in = 0;
186  mp->seq.next_in = 0;
187  mp->inbufs = NULL;
188  mp->bundle = bundle;
189
190  mp->link.type = MP_LINK;
191  mp->link.name = "mp";
192  mp->link.len = sizeof *mp;
193
194  throughput_init(&mp->link.throughput);
195  memset(mp->link.Queue, '\0', sizeof mp->link.Queue);
196  memset(mp->link.proto_in, '\0', sizeof mp->link.proto_in);
197  memset(mp->link.proto_out, '\0', sizeof mp->link.proto_out);
198
199  mp->fsmp.LayerStart = mp_LayerStart;
200  mp->fsmp.LayerUp = mp_LayerUp;
201  mp->fsmp.LayerDown = mp_LayerDown;
202  mp->fsmp.LayerFinish = mp_LayerFinish;
203  mp->fsmp.object = mp;
204
205  mpserver_Init(&mp->server);
206
207  mp->cfg.mrru = 0;
208  mp->cfg.shortseq = NEG_ENABLED|NEG_ACCEPTED;
209  mp->cfg.enddisc.class = 0;
210  *mp->cfg.enddisc.address = '\0';
211  mp->cfg.enddisc.len = 0;
212
213  lcp_Init(&mp->link.lcp, mp->bundle, &mp->link, NULL);
214  ccp_Init(&mp->link.ccp, mp->bundle, &mp->link, &mp->fsmp);
215}
216
217int
218mp_Up(struct mp *mp, struct datalink *dl)
219{
220  struct lcp *lcp = &dl->physical->link.lcp;
221
222  if (mp->active) {
223    /* We're adding a link - do a last validation on our parameters */
224    if (!peerid_Equal(&dl->peer, &mp->peer)) {
225      log_Printf(LogPHASE, "%s: Inappropriate peer !\n", dl->name);
226      return MP_FAILED;
227    }
228    if (mp->local_mrru != lcp->want_mrru ||
229        mp->peer_mrru != lcp->his_mrru ||
230        mp->local_is12bit != lcp->want_shortseq ||
231        mp->peer_is12bit != lcp->his_shortseq) {
232      log_Printf(LogPHASE, "%s: Invalid MRRU/SHORTSEQ MP parameters !\n",
233                dl->name);
234      return MP_FAILED;
235    }
236    return MP_ADDED;
237  } else {
238    /* First link in multilink mode */
239
240    mp->local_mrru = lcp->want_mrru;
241    mp->peer_mrru = lcp->his_mrru;
242    mp->local_is12bit = lcp->want_shortseq;
243    mp->peer_is12bit = lcp->his_shortseq;
244    mp->peer = dl->peer;
245
246    throughput_init(&mp->link.throughput);
247    memset(mp->link.Queue, '\0', sizeof mp->link.Queue);
248    memset(mp->link.proto_in, '\0', sizeof mp->link.proto_in);
249    memset(mp->link.proto_out, '\0', sizeof mp->link.proto_out);
250
251    mp->out.seq = 0;
252    mp->out.link = 0;
253    mp->seq.min_in = 0;
254    mp->seq.next_in = 0;
255
256    /*
257     * Now we create our server socket.
258     * If it already exists, join it.  Otherwise, create and own it
259     */
260    switch (mpserver_Open(&mp->server, &mp->peer)) {
261    case MPSERVER_CONNECTED:
262      log_Printf(LogPHASE, "mp: Transfer link on %s\n",
263                mp->server.socket.sun_path);
264      mp->server.send.dl = dl;		/* Defer 'till it's safe to send */
265      return MP_LINKSENT;
266    case MPSERVER_FAILED:
267      return MP_FAILED;
268    case MPSERVER_LISTENING:
269      log_Printf(LogPHASE, "mp: Listening on %s\n", mp->server.socket.sun_path);
270      log_Printf(LogPHASE, "    First link: %s\n", dl->name);
271
272      /* Re-point our IPCP layer at our MP link */
273      ipcp_SetLink(&mp->bundle->ncp.ipcp, &mp->link);
274
275      /* Our lcp's already up 'cos of the NULL parent */
276      if (ccp_SetOpenMode(&mp->link.ccp)) {
277        fsm_Up(&mp->link.ccp.fsm);
278        fsm_Open(&mp->link.ccp.fsm);
279      }
280
281      mp->active = 1;
282      break;
283    }
284  }
285
286  return MP_UP;
287}
288
289void
290mp_Down(struct mp *mp)
291{
292  if (mp->active) {
293    struct mbuf *next;
294
295    /* Don't want any more of these */
296    mpserver_Close(&mp->server);
297
298    /* CCP goes down with a bang */
299    fsm2initial(&mp->link.ccp.fsm);
300
301    /* Received fragments go in the bit-bucket */
302    while (mp->inbufs) {
303      next = mp->inbufs->pnext;
304      mbuf_Free(mp->inbufs);
305      mp->inbufs = next;
306    }
307
308    peerid_Init(&mp->peer);
309    mp->active = 0;
310  }
311}
312
313void
314mp_linkInit(struct mp_link *mplink)
315{
316  mplink->seq = 0;
317  mplink->weight = 1500;
318}
319
320void
321mp_Input(struct mp *mp, struct mbuf *m, struct physical *p)
322{
323  struct mp_header mh, h;
324  struct mbuf *q, *last;
325  int32_t seq;
326
327  /*
328   * When `m' and `p' are NULL, it means our oldest link has gone down.
329   * We want to determine a new min, and process any intermediate stuff
330   * as normal
331   */
332
333  if (m && mp_ReadHeader(mp, m, &mh) == 0) {
334    mbuf_Free(m);
335    return;
336  }
337
338  if (p) {
339    seq = p->dl->mp.seq;
340    p->dl->mp.seq = mh.seq;
341  } else
342    seq = mp->seq.min_in;
343
344  if (mp->seq.min_in == seq) {
345    /*
346     * We've received new data on the link that has our min (oldest) seq.
347     * Figure out which link now has the smallest (oldest) seq.
348     */
349    struct datalink *dl;
350
351    mp->seq.min_in = (u_int32_t)-1;
352    for (dl = mp->bundle->links; dl; dl = dl->next)
353      if (dl->state == DATALINK_OPEN &&
354          (mp->seq.min_in == -1 ||
355           isbefore(mp->local_is12bit, dl->mp.seq, mp->seq.min_in)))
356        mp->seq.min_in = dl->mp.seq;
357  }
358
359  /*
360   * Now process as many of our fragments as we can, adding our new
361   * fragment in as we go, and ordering with the oldest at the top of
362   * the queue.
363   */
364
365  if (!mp->inbufs) {
366    mp->inbufs = m;
367    m = NULL;
368  }
369
370  last = NULL;
371  seq = mp->seq.next_in;
372  q = mp->inbufs;
373  while (q) {
374    mp_ReadHeader(mp, q, &h);
375    if (m && isbefore(mp->local_is12bit, mh.seq, h.seq)) {
376      /* Our received fragment fits in before this one, so link it in */
377      if (last)
378        last->pnext = m;
379      else
380        mp->inbufs = m;
381      m->pnext = q;
382      q = m;
383      h = mh;
384      m = NULL;
385    }
386
387    if (h.seq != seq) {
388      /* we're missing something :-( */
389      if (mp->seq.min_in > seq) {
390        /* we're never gonna get it */
391        struct mbuf *next;
392
393        /* Zap all older fragments */
394        while (mp->inbufs != q) {
395          log_Printf(LogDEBUG, "Drop frag\n");
396          next = mp->inbufs->pnext;
397          mbuf_Free(mp->inbufs);
398          mp->inbufs = next;
399        }
400
401        /*
402         * Zap everything until the next `end' fragment OR just before
403         * the next `begin' fragment OR 'till seq.min_in - whichever
404         * comes first.
405         */
406        do {
407          mp_ReadHeader(mp, mp->inbufs, &h);
408          if (h.begin) {
409            /* We might be able to process this ! */
410            h.seq--;  /* We're gonna look for fragment with h.seq+1 */
411            break;
412          }
413          next = mp->inbufs->pnext;
414          log_Printf(LogDEBUG, "Drop frag %u\n", h.seq);
415          mbuf_Free(mp->inbufs);
416          mp->inbufs = next;
417        } while (mp->inbufs && (h.seq >= mp->seq.min_in || h.end));
418
419        /*
420         * Continue processing things from here.
421         * This deals with the possibility that we received a fragment
422         * on the slowest link that invalidates some of our data (because
423         * of the hole at `q'), but where there are subsequent `whole'
424         * packets that have already been received.
425         */
426
427        mp->seq.next_in = seq = inc_seq(mp->local_is12bit, h.seq);
428        last = NULL;
429        q = mp->inbufs;
430      } else
431        /* we may still receive the missing fragment */
432        break;
433    } else if (h.end) {
434      /* We've got something, reassemble */
435      struct mbuf **frag = &q;
436      int len;
437      u_long first = -1;
438
439      do {
440        *frag = mp->inbufs;
441        mp->inbufs = mp->inbufs->pnext;
442        len = mp_ReadHeader(mp, *frag, &h);
443        if (first == -1)
444          first = h.seq;
445        (*frag)->offset += len;
446        (*frag)->cnt -= len;
447        (*frag)->pnext = NULL;
448        if (frag == &q && !h.begin) {
449          log_Printf(LogWARN, "Oops - MP frag %lu should have a begin flag\n",
450                    (u_long)h.seq);
451          mbuf_Free(q);
452          q = NULL;
453        } else if (frag != &q && h.begin) {
454          log_Printf(LogWARN, "Oops - MP frag %lu should have an end flag\n",
455                    (u_long)h.seq - 1);
456          /*
457           * Stuff our fragment back at the front of the queue and zap
458           * our half-assembed packet.
459           */
460          (*frag)->pnext = mp->inbufs;
461          mp->inbufs = *frag;
462          *frag = NULL;
463          mbuf_Free(q);
464          q = NULL;
465          frag = &q;
466          h.end = 0;	/* just in case it's a whole packet */
467        } else
468          do
469            frag = &(*frag)->next;
470          while (*frag != NULL);
471      } while (!h.end);
472
473      if (q) {
474        u_short proto;
475        u_char ch;
476
477        q = mbuf_Read(q, &ch, 1);
478        proto = ch;
479        if (!(proto & 1)) {
480          q = mbuf_Read(q, &ch, 1);
481          proto <<= 8;
482          proto += ch;
483        }
484        if (log_IsKept(LogDEBUG))
485          log_Printf(LogDEBUG, "MP: Reassembled frags %ld-%lu, length %d\n",
486                    first, (u_long)h.seq, mbuf_Length(q));
487        hdlc_DecodePacket(mp->bundle, proto, q, &mp->link);
488      }
489
490      mp->seq.next_in = seq = inc_seq(mp->local_is12bit, h.seq);
491      last = NULL;
492      q = mp->inbufs;
493    } else {
494      /* Look for the next fragment */
495      seq = inc_seq(mp->local_is12bit, seq);
496      last = q;
497      q = q->pnext;
498    }
499  }
500
501  if (m) {
502    /* We still have to find a home for our new fragment */
503    last = NULL;
504    for (q = mp->inbufs; q; last = q, q = q->pnext) {
505      mp_ReadHeader(mp, q, &h);
506      if (isbefore(mp->local_is12bit, mh.seq, h.seq))
507        break;
508    }
509    /* Our received fragment fits in here */
510    if (last)
511      last->pnext = m;
512    else
513      mp->inbufs = m;
514    m->pnext = q;
515  }
516}
517
518static void
519mp_Output(struct mp *mp, struct link *l, struct mbuf *m, u_int32_t begin,
520          u_int32_t end)
521{
522  struct mbuf *mo;
523
524  /* Stuff an MP header on the front of our packet and send it */
525  mo = mbuf_Alloc(4, MB_MP);
526  mo->next = m;
527  if (mp->peer_is12bit) {
528    u_int16_t *seq16;
529
530    seq16 = (u_int16_t *)MBUF_CTOP(mo);
531    *seq16 = htons((begin << 15) | (end << 14) | (u_int16_t)mp->out.seq);
532    mo->cnt = 2;
533  } else {
534    u_int32_t *seq32;
535
536    seq32 = (u_int32_t *)MBUF_CTOP(mo);
537    *seq32 = htonl((begin << 31) | (end << 30) | (u_int32_t)mp->out.seq);
538    mo->cnt = 4;
539  }
540  if (log_IsKept(LogDEBUG))
541    log_Printf(LogDEBUG, "MP[frag %d]: Send %d bytes on link `%s'\n",
542              mp->out.seq, mbuf_Length(mo), l->name);
543  mp->out.seq = inc_seq(mp->peer_is12bit, mp->out.seq);
544
545  if (!ccp_Compress(&l->ccp, l, PRI_NORMAL, PROTO_MP, mo))
546    hdlc_Output(l, PRI_NORMAL, PROTO_MP, mo);
547}
548
549int
550mp_FillQueues(struct bundle *bundle)
551{
552  struct mp *mp = &bundle->ncp.mp;
553  struct datalink *dl, *fdl;
554  int total, add, len, thislink, nlinks;
555  u_int32_t begin, end;
556  struct mbuf *m, *mo;
557
558  thislink = nlinks = 0;
559  for (fdl = NULL, dl = bundle->links; dl; dl = dl->next) {
560    /* Include non-open links here as mp->out.link will stay more correct */
561    if (!fdl) {
562      if (thislink == mp->out.link)
563        fdl = dl;
564      else
565        thislink++;
566    }
567    nlinks++;
568  }
569
570  if (!fdl) {
571    fdl = bundle->links;
572    if (!fdl)
573      return 0;
574    thislink = 0;
575  }
576
577  total = 0;
578  for (dl = fdl; nlinks > 0; dl = dl->next, nlinks--, thislink++) {
579    if (!dl) {
580      dl = bundle->links;
581      thislink = 0;
582    }
583
584    if (dl->state != DATALINK_OPEN)
585      continue;
586
587    if (dl->physical->out)
588      /* this link has suffered a short write.  Let it continue */
589      continue;
590
591    add = link_QueueLen(&dl->physical->link);
592    total += add;
593    if (add)
594      /* this link has got stuff already queued.  Let it continue */
595      continue;
596
597    if (!link_QueueLen(&mp->link) && !ip_FlushPacket(&mp->link, bundle))
598      /* Nothing else to send */
599      break;
600
601    m = link_Dequeue(&mp->link);
602    len = mbuf_Length(m);
603    begin = 1;
604    end = 0;
605
606    while (!end) {
607      if (dl->state == DATALINK_OPEN) {
608        if (len <= dl->mp.weight + LINK_MINWEIGHT) {
609          /*
610           * XXX: Should we remember how much of our `weight' wasn't sent
611           *      so that we can compensate next time ?
612           */
613          mo = m;
614          end = 1;
615        } else {
616          mo = mbuf_Alloc(dl->mp.weight, MB_MP);
617          mo->cnt = dl->mp.weight;
618          len -= mo->cnt;
619          m = mbuf_Read(m, MBUF_CTOP(mo), mo->cnt);
620        }
621        mp_Output(mp, &dl->physical->link, mo, begin, end);
622        begin = 0;
623      }
624
625      if (!end) {
626        nlinks--;
627        dl = dl->next;
628        if (!dl) {
629          dl = bundle->links;
630          thislink = 0;
631        } else
632          thislink++;
633      }
634    }
635  }
636  mp->out.link = thislink;		/* Start here next time */
637
638  return total;
639}
640
641int
642mp_SetDatalinkWeight(struct cmdargs const *arg)
643{
644  int val;
645
646  if (arg->argc != arg->argn+1)
647    return -1;
648
649  val = atoi(arg->argv[arg->argn]);
650  if (val < LINK_MINWEIGHT) {
651    log_Printf(LogWARN, "Link weights must not be less than %d\n",
652              LINK_MINWEIGHT);
653    return 1;
654  }
655  arg->cx->mp.weight = val;
656  return 0;
657}
658
659int
660mp_ShowStatus(struct cmdargs const *arg)
661{
662  struct mp *mp = &arg->bundle->ncp.mp;
663
664  prompt_Printf(arg->prompt, "Multilink is %sactive\n", mp->active ? "" : "in");
665  if (mp->active) {
666    struct mbuf *m;
667    int bufs = 0;
668
669    prompt_Printf(arg->prompt, "Socket:         %s\n",
670                  mp->server.socket.sun_path);
671    for (m = mp->inbufs; m; m = m->pnext)
672      bufs++;
673    prompt_Printf(arg->prompt, "Pending frags:  %d\n", bufs);
674  }
675
676  prompt_Printf(arg->prompt, "\nMy Side:\n");
677  if (mp->active) {
678    prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->local_mrru);
679    prompt_Printf(arg->prompt, " Short Seq:     %s\n",
680                  mp->local_is12bit ? "on" : "off");
681  }
682  prompt_Printf(arg->prompt, " Discriminator: %s\n",
683                mp_Enddisc(mp->cfg.enddisc.class, mp->cfg.enddisc.address,
684                           mp->cfg.enddisc.len));
685
686  prompt_Printf(arg->prompt, "\nHis Side:\n");
687  if (mp->active) {
688    prompt_Printf(arg->prompt, " Auth Name:     %s\n", mp->peer.authname);
689    prompt_Printf(arg->prompt, " Next SEQ:      %u\n", mp->out.seq);
690    prompt_Printf(arg->prompt, " MRRU:          %u\n", mp->peer_mrru);
691    prompt_Printf(arg->prompt, " Short Seq:     %s\n",
692                  mp->peer_is12bit ? "on" : "off");
693  }
694  prompt_Printf(arg->prompt,   " Discriminator: %s\n",
695                mp_Enddisc(mp->peer.enddisc.class, mp->peer.enddisc.address,
696                           mp->peer.enddisc.len));
697
698  prompt_Printf(arg->prompt, "\nDefaults:\n");
699
700  prompt_Printf(arg->prompt, " MRRU:          ");
701  if (mp->cfg.mrru)
702    prompt_Printf(arg->prompt, "%d (multilink enabled)\n", mp->cfg.mrru);
703  else
704    prompt_Printf(arg->prompt, "disabled\n");
705  prompt_Printf(arg->prompt, " Short Seq:     %s\n",
706                  command_ShowNegval(mp->cfg.shortseq));
707
708  return 0;
709}
710
711const char *
712mp_Enddisc(u_char c, const char *address, int len)
713{
714  static char result[100];	/* Used immediately after it's returned */
715  int f, header;
716
717  switch (c) {
718    case ENDDISC_NULL:
719      sprintf(result, "Null Class");
720      break;
721
722    case ENDDISC_LOCAL:
723      snprintf(result, sizeof result, "Local Addr: %.*s", len, address);
724      break;
725
726    case ENDDISC_IP:
727      if (len == 4)
728        snprintf(result, sizeof result, "IP %s",
729                 inet_ntoa(*(const struct in_addr *)address));
730      else
731        sprintf(result, "IP[%d] ???", len);
732      break;
733
734    case ENDDISC_MAC:
735      if (len == 6) {
736        const u_char *m = (const u_char *)address;
737        snprintf(result, sizeof result, "MAC %02x:%02x:%02x:%02x:%02x:%02x",
738                 m[0], m[1], m[2], m[3], m[4], m[5]);
739      } else
740        sprintf(result, "MAC[%d] ???", len);
741      break;
742
743    case ENDDISC_MAGIC:
744      sprintf(result, "Magic: 0x");
745      header = strlen(result);
746      if (len > sizeof result - header - 1)
747        len = sizeof result - header - 1;
748      for (f = 0; f < len; f++)
749        sprintf(result + header + 2 * f, "%02x", address[f]);
750      break;
751
752    case ENDDISC_PSN:
753      snprintf(result, sizeof result, "PSN: %.*s", len, address);
754      break;
755
756     default:
757      sprintf(result, "%d: ", (int)c);
758      header = strlen(result);
759      if (len > sizeof result - header - 1)
760        len = sizeof result - header - 1;
761      for (f = 0; f < len; f++)
762        sprintf(result + header + 2 * f, "%02x", address[f]);
763      break;
764  }
765  return result;
766}
767
768int
769mp_SetEnddisc(struct cmdargs const *arg)
770{
771  struct mp *mp = &arg->bundle->ncp.mp;
772  struct in_addr addr;
773
774  if (bundle_Phase(arg->bundle) != PHASE_DEAD) {
775    log_Printf(LogWARN, "set enddisc: Only available at phase DEAD\n");
776    return 1;
777  }
778
779  if (arg->argc == arg->argn) {
780    mp->cfg.enddisc.class = 0;
781    *mp->cfg.enddisc.address = '\0';
782    mp->cfg.enddisc.len = 0;
783  } else if (arg->argc > arg->argn) {
784    if (!strcasecmp(arg->argv[arg->argn], "label")) {
785      mp->cfg.enddisc.class = ENDDISC_LOCAL;
786      strcpy(mp->cfg.enddisc.address, arg->bundle->cfg.label);
787      mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
788    } else if (!strcasecmp(arg->argv[arg->argn], "ip")) {
789      if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
790        addr = arg->bundle->ncp.ipcp.cfg.my_range.ipaddr;
791      else
792        addr = arg->bundle->ncp.ipcp.my_ip;
793      memcpy(mp->cfg.enddisc.address, &addr.s_addr, sizeof addr.s_addr);
794      mp->cfg.enddisc.class = ENDDISC_IP;
795      mp->cfg.enddisc.len = sizeof arg->bundle->ncp.ipcp.my_ip.s_addr;
796    } else if (!strcasecmp(arg->argv[arg->argn], "mac")) {
797      struct sockaddr_dl hwaddr;
798      int s;
799
800      if (arg->bundle->ncp.ipcp.my_ip.s_addr == INADDR_ANY)
801        addr = arg->bundle->ncp.ipcp.cfg.my_range.ipaddr;
802      else
803        addr = arg->bundle->ncp.ipcp.my_ip;
804
805      s = ID0socket(AF_INET, SOCK_DGRAM, 0);
806      if (s < 0) {
807        log_Printf(LogERROR, "set enddisc: socket(): %s\n", strerror(errno));
808        return 2;
809      }
810      if (get_ether_addr(s, addr, &hwaddr)) {
811        mp->cfg.enddisc.class = ENDDISC_MAC;
812        memcpy(mp->cfg.enddisc.address, hwaddr.sdl_data + hwaddr.sdl_nlen,
813               hwaddr.sdl_alen);
814        mp->cfg.enddisc.len = hwaddr.sdl_alen;
815      } else {
816        log_Printf(LogWARN, "set enddisc: Can't locate MAC address for %s\n",
817                  inet_ntoa(addr));
818        close(s);
819        return 4;
820      }
821      close(s);
822    } else if (!strcasecmp(arg->argv[arg->argn], "magic")) {
823      int f;
824
825      randinit();
826      for (f = 0; f < 20; f += sizeof(long))
827        *(long *)(mp->cfg.enddisc.address + f) = random();
828      mp->cfg.enddisc.class = ENDDISC_MAGIC;
829      mp->cfg.enddisc.len = 20;
830    } else if (!strcasecmp(arg->argv[arg->argn], "psn")) {
831      if (arg->argc > arg->argn+1) {
832        mp->cfg.enddisc.class = ENDDISC_PSN;
833        strcpy(mp->cfg.enddisc.address, arg->argv[arg->argn+1]);
834        mp->cfg.enddisc.len = strlen(mp->cfg.enddisc.address);
835      } else {
836        log_Printf(LogWARN, "PSN endpoint requires additional data\n");
837        return 5;
838      }
839    } else {
840      log_Printf(LogWARN, "%s: Unrecognised endpoint type\n",
841                arg->argv[arg->argn]);
842      return 6;
843    }
844  }
845
846  return 0;
847}
848
849static int
850mpserver_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e,
851                   int *n)
852{
853  struct mpserver *s = descriptor2mpserver(d);
854  int result;
855
856  result = 0;
857  if (s->send.dl != NULL) {
858    /* We've connect()ed */
859    if (!link_QueueLen(&s->send.dl->physical->link) &&
860        !s->send.dl->physical->out) {
861      /* Only send if we've transmitted all our data (i.e. the ConfigAck) */
862      result -= datalink_RemoveFromSet(s->send.dl, r, w, e);
863      bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
864      s->send.dl = NULL;
865      s->fd = -1;
866    } else
867      /* Never read from a datalink that's on death row ! */
868      result -= datalink_RemoveFromSet(s->send.dl, r, NULL, NULL);
869  } else if (r && s->fd >= 0) {
870    if (*n < s->fd + 1)
871      *n = s->fd + 1;
872    FD_SET(s->fd, r);
873    log_Printf(LogTIMER, "mp: fdset(r) %d\n", s->fd);
874    result++;
875  }
876  return result;
877}
878
879static int
880mpserver_IsSet(struct descriptor *d, const fd_set *fdset)
881{
882  struct mpserver *s = descriptor2mpserver(d);
883  return s->fd >= 0 && FD_ISSET(s->fd, fdset);
884}
885
886static void
887mpserver_Read(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
888{
889  struct mpserver *s = descriptor2mpserver(d);
890  struct sockaddr in;
891  int fd, size;
892
893  size = sizeof in;
894  fd = accept(s->fd, &in, &size);
895  if (fd < 0) {
896    log_Printf(LogERROR, "mpserver_Read: accept(): %s\n", strerror(errno));
897    return;
898  }
899
900  if (in.sa_family == AF_LOCAL)
901    bundle_ReceiveDatalink(bundle, fd, (struct sockaddr_un *)&in);
902  else
903    close(fd);
904}
905
906static int
907mpserver_Write(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
908{
909  /* We never want to write here ! */
910  log_Printf(LogALERT, "mpserver_Write: Internal error: Bad call !\n");
911  return 0;
912}
913
914void
915mpserver_Init(struct mpserver *s)
916{
917  s->desc.type = MPSERVER_DESCRIPTOR;
918  s->desc.UpdateSet = mpserver_UpdateSet;
919  s->desc.IsSet = mpserver_IsSet;
920  s->desc.Read = mpserver_Read;
921  s->desc.Write = mpserver_Write;
922  s->send.dl = NULL;
923  s->fd = -1;
924  memset(&s->socket, '\0', sizeof s->socket);
925}
926
927int
928mpserver_Open(struct mpserver *s, struct peerid *peer)
929{
930  int f, l;
931  mode_t mask;
932
933  if (s->fd != -1) {
934    log_Printf(LogALERT, "Internal error !  mpserver already open\n");
935    mpserver_Close(s);
936  }
937
938  l = snprintf(s->socket.sun_path, sizeof s->socket.sun_path, "%sppp-%s-%02x-",
939               _PATH_VARRUN, peer->authname, peer->enddisc.class);
940
941  for (f = 0; f < peer->enddisc.len && l < sizeof s->socket.sun_path - 2; f++) {
942    snprintf(s->socket.sun_path + l, sizeof s->socket.sun_path - l,
943             "%02x", *(u_char *)(peer->enddisc.address+f));
944    l += 2;
945  }
946
947  s->socket.sun_family = AF_LOCAL;
948  s->socket.sun_len = sizeof s->socket;
949  s->fd = ID0socket(PF_LOCAL, SOCK_STREAM, 0);
950  if (s->fd < 0) {
951    log_Printf(LogERROR, "mpserver: socket: %s\n", strerror(errno));
952    return MPSERVER_FAILED;
953  }
954
955  setsockopt(s->fd, SOL_SOCKET, SO_REUSEADDR, (struct sockaddr *)&s->socket,
956             sizeof s->socket);
957  mask = umask(0177);
958  if (ID0bind_un(s->fd, &s->socket) < 0) {
959    if (errno != EADDRINUSE) {
960      log_Printf(LogPHASE, "mpserver: can't create bundle socket %s (%s)\n",
961                s->socket.sun_path, strerror(errno));
962      umask(mask);
963      close(s->fd);
964      s->fd = -1;
965      return MPSERVER_FAILED;
966    }
967    umask(mask);
968    if (ID0connect_un(s->fd, &s->socket) < 0) {
969      log_Printf(LogPHASE, "mpserver: can't connect to bundle socket %s (%s)\n",
970                s->socket.sun_path, strerror(errno));
971      if (errno == ECONNREFUSED)
972        log_Printf(LogPHASE, "          Has the previous server died badly ?\n");
973      close(s->fd);
974      s->fd = -1;
975      return MPSERVER_FAILED;
976    }
977
978    /* Donate our link to the other guy */
979    return MPSERVER_CONNECTED;
980  }
981
982  /* Listen for other ppp invocations that want to donate links */
983  if (listen(s->fd, 5) != 0) {
984    log_Printf(LogERROR, "mpserver: Unable to listen to socket"
985              " - BUNDLE overload?\n");
986    mpserver_Close(s);
987  }
988
989  return MPSERVER_LISTENING;
990}
991
992void
993mpserver_Close(struct mpserver *s)
994{
995  if (s->send.dl != NULL) {
996    bundle_SendDatalink(s->send.dl, s->fd, &s->socket);
997    s->send.dl = NULL;
998    s->fd = -1;
999  } else if (s->fd >= 0) {
1000    close(s->fd);
1001    if (ID0unlink(s->socket.sun_path) == -1)
1002      log_Printf(LogERROR, "%s: Failed to remove: %s\n", s->socket.sun_path,
1003                strerror(errno));
1004    memset(&s->socket, '\0', sizeof s->socket);
1005    s->fd = -1;
1006  }
1007}
1008
1009void
1010mp_LinkLost(struct mp *mp, struct datalink *dl)
1011{
1012  if (mp->seq.min_in == dl->mp.seq)
1013    /* We've lost the link that's holding everything up ! */
1014    mp_Input(mp, NULL, NULL);
1015}
1016