fsm.c revision 78411
1/*-
2 * Copyright (c) 1996 - 2001 Brian Somers <brian@Awfulhak.org>
3 *          based on work by Toshiharu OHNO <tony-o@iij.ad.jp>
4 *                           Internet Initiative Japan, Inc (IIJ)
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 *
28 * $FreeBSD: head/usr.sbin/ppp/fsm.c 78411 2001-06-18 15:00:22Z brian $
29 */
30
31#include <sys/param.h>
32#include <netinet/in.h>
33#include <netinet/in_systm.h>
34#include <netinet/ip.h>
35#include <sys/un.h>
36
37#include <string.h>
38#include <termios.h>
39
40#include "layer.h"
41#include "ua.h"
42#include "mbuf.h"
43#include "log.h"
44#include "defs.h"
45#include "timer.h"
46#include "fsm.h"
47#include "iplist.h"
48#include "lqr.h"
49#include "hdlc.h"
50#include "throughput.h"
51#include "slcompress.h"
52#include "ipcp.h"
53#include "filter.h"
54#include "descriptor.h"
55#include "lcp.h"
56#include "ccp.h"
57#include "link.h"
58#include "mp.h"
59#ifndef NORADIUS
60#include "radius.h"
61#endif
62#include "bundle.h"
63#include "async.h"
64#include "physical.h"
65#include "proto.h"
66
67static void FsmSendConfigReq(struct fsm *);
68static void FsmSendTerminateReq(struct fsm *);
69static void FsmInitRestartCounter(struct fsm *, int);
70
71typedef void (recvfn)(struct fsm *, struct fsmheader *, struct mbuf *);
72static recvfn FsmRecvConfigReq, FsmRecvConfigAck, FsmRecvConfigNak,
73              FsmRecvConfigRej, FsmRecvTermReq, FsmRecvTermAck,
74              FsmRecvCodeRej, FsmRecvProtoRej, FsmRecvEchoReq,
75              FsmRecvEchoRep, FsmRecvDiscReq, FsmRecvIdent,
76              FsmRecvTimeRemain, FsmRecvResetReq, FsmRecvResetAck;
77
78static const struct fsmcodedesc {
79  recvfn *recv;
80  unsigned check_reqid : 1;
81  unsigned inc_reqid : 1;
82  const char *name;
83} FsmCodes[] = {
84  { FsmRecvConfigReq, 0, 0, "ConfigReq"    },
85  { FsmRecvConfigAck, 1, 1, "ConfigAck"    },
86  { FsmRecvConfigNak, 1, 1, "ConfigNak"    },
87  { FsmRecvConfigRej, 1, 1, "ConfigRej"    },
88  { FsmRecvTermReq,   0, 0, "TerminateReq" },
89  { FsmRecvTermAck,   1, 1, "TerminateAck" },
90  { FsmRecvCodeRej,   0, 0, "CodeRej"      },
91  { FsmRecvProtoRej,  0, 0, "ProtocolRej"  },
92  { FsmRecvEchoReq,   0, 0, "EchoRequest"  },
93  { FsmRecvEchoRep,   0, 0, "EchoReply"    },
94  { FsmRecvDiscReq,   0, 0, "DiscardReq"   },
95  { FsmRecvIdent,     0, 1, "Ident"        },
96  { FsmRecvTimeRemain,0, 0, "TimeRemain"   },
97  { FsmRecvResetReq,  0, 0, "ResetReq"     },
98  { FsmRecvResetAck,  0, 1, "ResetAck"     }
99};
100
101static const char *
102Code2Nam(u_int code)
103{
104  if (code == 0 || code > sizeof FsmCodes / sizeof FsmCodes[0])
105    return "Unknown";
106  return FsmCodes[code-1].name;
107}
108
109const char *
110State2Nam(u_int state)
111{
112  static const char * const StateNames[] = {
113    "Initial", "Starting", "Closed", "Stopped", "Closing", "Stopping",
114    "Req-Sent", "Ack-Rcvd", "Ack-Sent", "Opened",
115  };
116
117  if (state >= sizeof StateNames / sizeof StateNames[0])
118    return "unknown";
119  return StateNames[state];
120}
121
122static void
123StoppedTimeout(void *v)
124{
125  struct fsm *fp = (struct fsm *)v;
126
127  log_Printf(fp->LogLevel, "%s: Stopped timer expired\n", fp->link->name);
128  if (fp->OpenTimer.state == TIMER_RUNNING) {
129    log_Printf(LogWARN, "%s: %s: aborting open delay due to stopped timer\n",
130              fp->link->name, fp->name);
131    timer_Stop(&fp->OpenTimer);
132  }
133  if (fp->state == ST_STOPPED)
134    fsm2initial(fp);
135}
136
137void
138fsm_Init(struct fsm *fp, const char *name, u_short proto, int mincode,
139         int maxcode, int LogLevel, struct bundle *bundle,
140         struct link *l, const struct fsm_parent *parent,
141         struct fsm_callbacks *fn, const char * const timer_names[3])
142{
143  fp->name = name;
144  fp->proto = proto;
145  fp->min_code = mincode;
146  fp->max_code = maxcode;
147  fp->state = fp->min_code > CODE_TERMACK ? ST_OPENED : ST_INITIAL;
148  fp->reqid = 1;
149  fp->restart = 1;
150  fp->more.reqs = fp->more.naks = fp->more.rejs = 3;
151  memset(&fp->FsmTimer, '\0', sizeof fp->FsmTimer);
152  memset(&fp->OpenTimer, '\0', sizeof fp->OpenTimer);
153  memset(&fp->StoppedTimer, '\0', sizeof fp->StoppedTimer);
154  fp->LogLevel = LogLevel;
155  fp->link = l;
156  fp->bundle = bundle;
157  fp->parent = parent;
158  fp->fn = fn;
159  fp->FsmTimer.name = timer_names[0];
160  fp->OpenTimer.name = timer_names[1];
161  fp->StoppedTimer.name = timer_names[2];
162}
163
164static void
165NewState(struct fsm *fp, int new)
166{
167  log_Printf(fp->LogLevel, "%s: State change %s --> %s\n",
168	    fp->link->name, State2Nam(fp->state), State2Nam(new));
169  if (fp->state == ST_STOPPED && fp->StoppedTimer.state == TIMER_RUNNING)
170    timer_Stop(&fp->StoppedTimer);
171  fp->state = new;
172  if ((new >= ST_INITIAL && new <= ST_STOPPED) || (new == ST_OPENED)) {
173    timer_Stop(&fp->FsmTimer);
174    if (new == ST_STOPPED && fp->StoppedTimer.load) {
175      timer_Stop(&fp->StoppedTimer);
176      fp->StoppedTimer.func = StoppedTimeout;
177      fp->StoppedTimer.arg = (void *) fp;
178      timer_Start(&fp->StoppedTimer);
179    }
180  }
181}
182
183void
184fsm_Output(struct fsm *fp, u_int code, u_int id, u_char *ptr, int count,
185           int mtype)
186{
187  int plen;
188  struct fsmheader lh;
189  struct mbuf *bp;
190
191  if (log_IsKept(fp->LogLevel)) {
192    log_Printf(fp->LogLevel, "%s: Send%s(%d) state = %s\n",
193              fp->link->name, Code2Nam(code), id, State2Nam(fp->state));
194    switch (code) {
195      case CODE_CONFIGREQ:
196      case CODE_CONFIGACK:
197      case CODE_CONFIGREJ:
198      case CODE_CONFIGNAK:
199        (*fp->fn->DecodeConfig)(fp, ptr, count, MODE_NOP, NULL);
200        if (count < sizeof(struct fsmconfig))
201          log_Printf(fp->LogLevel, "  [EMPTY]\n");
202        break;
203    }
204  }
205
206  plen = sizeof(struct fsmheader) + count;
207  lh.code = code;
208  lh.id = id;
209  lh.length = htons(plen);
210  bp = m_get(plen, mtype);
211  memcpy(MBUF_CTOP(bp), &lh, sizeof(struct fsmheader));
212  if (count)
213    memcpy(MBUF_CTOP(bp) + sizeof(struct fsmheader), ptr, count);
214  log_DumpBp(LogDEBUG, "fsm_Output", bp);
215  link_PushPacket(fp->link, bp, fp->bundle, LINK_QUEUES(fp->link) - 1,
216                  fp->proto);
217
218  if (code == CODE_CONFIGREJ)
219    lcp_SendIdentification(&fp->link->lcp);
220}
221
222static void
223FsmOpenNow(void *v)
224{
225  struct fsm *fp = (struct fsm *)v;
226
227  timer_Stop(&fp->OpenTimer);
228  if (fp->state <= ST_STOPPED) {
229    if (fp->state != ST_STARTING) {
230      /*
231       * In practice, we're only here in ST_STOPPED (when delaying the
232       * first config request) or ST_CLOSED (when openmode == 0).
233       *
234       * The ST_STOPPED bit is breaking the RFC already :-(
235       *
236       * According to the RFC (1661) state transition table, a TLS isn't
237       * required for an Open event when state == Closed, but the RFC
238       * must be wrong as TLS hasn't yet been called (since the last TLF)
239       * ie, Initial gets an `Up' event, Closing gets a RTA etc.
240       */
241      (*fp->fn->LayerStart)(fp);
242      (*fp->parent->LayerStart)(fp->parent->object, fp);
243    }
244    FsmInitRestartCounter(fp, FSM_REQ_TIMER);
245    FsmSendConfigReq(fp);
246    NewState(fp, ST_REQSENT);
247  }
248}
249
250void
251fsm_Open(struct fsm *fp)
252{
253  switch (fp->state) {
254  case ST_INITIAL:
255    NewState(fp, ST_STARTING);
256    (*fp->fn->LayerStart)(fp);
257    (*fp->parent->LayerStart)(fp->parent->object, fp);
258    break;
259  case ST_CLOSED:
260    if (fp->open_mode == OPEN_PASSIVE) {
261      NewState(fp, ST_STOPPED);		/* XXX: This is a hack ! */
262    } else if (fp->open_mode > 0) {
263      if (fp->open_mode > 1)
264        log_Printf(LogPHASE, "%s: Entering STOPPED state for %d seconds\n",
265                  fp->link->name, fp->open_mode);
266      NewState(fp, ST_STOPPED);		/* XXX: This is a not-so-bad hack ! */
267      timer_Stop(&fp->OpenTimer);
268      fp->OpenTimer.load = fp->open_mode * SECTICKS;
269      fp->OpenTimer.func = FsmOpenNow;
270      fp->OpenTimer.arg = (void *)fp;
271      timer_Start(&fp->OpenTimer);
272    } else
273      FsmOpenNow(fp);
274    break;
275  case ST_STOPPED:		/* XXX: restart option */
276  case ST_REQSENT:
277  case ST_ACKRCVD:
278  case ST_ACKSENT:
279  case ST_OPENED:		/* XXX: restart option */
280    break;
281  case ST_CLOSING:		/* XXX: restart option */
282  case ST_STOPPING:		/* XXX: restart option */
283    NewState(fp, ST_STOPPING);
284    break;
285  }
286}
287
288void
289fsm_Up(struct fsm *fp)
290{
291  switch (fp->state) {
292  case ST_INITIAL:
293    log_Printf(fp->LogLevel, "FSM: Using \"%s\" as a transport\n",
294              fp->link->name);
295    NewState(fp, ST_CLOSED);
296    break;
297  case ST_STARTING:
298    FsmInitRestartCounter(fp, FSM_REQ_TIMER);
299    FsmSendConfigReq(fp);
300    NewState(fp, ST_REQSENT);
301    break;
302  default:
303    log_Printf(fp->LogLevel, "%s: Oops, Up at %s\n",
304              fp->link->name, State2Nam(fp->state));
305    break;
306  }
307}
308
309void
310fsm_Down(struct fsm *fp)
311{
312  switch (fp->state) {
313  case ST_CLOSED:
314    NewState(fp, ST_INITIAL);
315    break;
316  case ST_CLOSING:
317    /* This TLF contradicts the RFC (1661), which ``misses it out'' ! */
318    (*fp->fn->LayerFinish)(fp);
319    NewState(fp, ST_INITIAL);
320    (*fp->parent->LayerFinish)(fp->parent->object, fp);
321    break;
322  case ST_STOPPED:
323    NewState(fp, ST_STARTING);
324    (*fp->fn->LayerStart)(fp);
325    (*fp->parent->LayerStart)(fp->parent->object, fp);
326    break;
327  case ST_STOPPING:
328  case ST_REQSENT:
329  case ST_ACKRCVD:
330  case ST_ACKSENT:
331    NewState(fp, ST_STARTING);
332    break;
333  case ST_OPENED:
334    (*fp->fn->LayerDown)(fp);
335    NewState(fp, ST_STARTING);
336    (*fp->parent->LayerDown)(fp->parent->object, fp);
337    break;
338  }
339}
340
341void
342fsm_Close(struct fsm *fp)
343{
344  switch (fp->state) {
345  case ST_STARTING:
346    (*fp->fn->LayerFinish)(fp);
347    NewState(fp, ST_INITIAL);
348    (*fp->parent->LayerFinish)(fp->parent->object, fp);
349    break;
350  case ST_STOPPED:
351    NewState(fp, ST_CLOSED);
352    break;
353  case ST_STOPPING:
354    NewState(fp, ST_CLOSING);
355    break;
356  case ST_OPENED:
357    (*fp->fn->LayerDown)(fp);
358    if (fp->state == ST_OPENED) {
359      FsmInitRestartCounter(fp, FSM_TRM_TIMER);
360      FsmSendTerminateReq(fp);
361      NewState(fp, ST_CLOSING);
362      (*fp->parent->LayerDown)(fp->parent->object, fp);
363    }
364    break;
365  case ST_REQSENT:
366  case ST_ACKRCVD:
367  case ST_ACKSENT:
368    FsmInitRestartCounter(fp, FSM_TRM_TIMER);
369    FsmSendTerminateReq(fp);
370    NewState(fp, ST_CLOSING);
371    break;
372  }
373}
374
375/*
376 *	Send functions
377 */
378static void
379FsmSendConfigReq(struct fsm *fp)
380{
381  if (fp->more.reqs-- > 0 && fp->restart-- > 0) {
382    (*fp->fn->SendConfigReq)(fp);
383    timer_Start(&fp->FsmTimer);		/* Start restart timer */
384  } else {
385    if (fp->more.reqs < 0)
386      log_Printf(LogPHASE, "%s: Too many %s REQs sent - abandoning "
387                 "negotiation\n", fp->link->name, fp->name);
388    lcp_SendIdentification(&fp->link->lcp);
389    fsm_Close(fp);
390  }
391}
392
393static void
394FsmSendTerminateReq(struct fsm *fp)
395{
396  fsm_Output(fp, CODE_TERMREQ, fp->reqid, NULL, 0, MB_UNKNOWN);
397  (*fp->fn->SentTerminateReq)(fp);
398  timer_Start(&fp->FsmTimer);	/* Start restart timer */
399  fp->restart--;		/* Decrement restart counter */
400}
401
402/*
403 *	Timeout actions
404 */
405static void
406FsmTimeout(void *v)
407{
408  struct fsm *fp = (struct fsm *)v;
409
410  if (fp->restart) {
411    switch (fp->state) {
412    case ST_CLOSING:
413    case ST_STOPPING:
414      FsmSendTerminateReq(fp);
415      break;
416    case ST_REQSENT:
417    case ST_ACKSENT:
418      FsmSendConfigReq(fp);
419      break;
420    case ST_ACKRCVD:
421      FsmSendConfigReq(fp);
422      NewState(fp, ST_REQSENT);
423      break;
424    }
425    timer_Start(&fp->FsmTimer);
426  } else {
427    switch (fp->state) {
428    case ST_CLOSING:
429      (*fp->fn->LayerFinish)(fp);
430      NewState(fp, ST_CLOSED);
431      (*fp->parent->LayerFinish)(fp->parent->object, fp);
432      break;
433    case ST_STOPPING:
434      (*fp->fn->LayerFinish)(fp);
435      NewState(fp, ST_STOPPED);
436      (*fp->parent->LayerFinish)(fp->parent->object, fp);
437      break;
438    case ST_REQSENT:		/* XXX: 3p */
439    case ST_ACKSENT:
440    case ST_ACKRCVD:
441      (*fp->fn->LayerFinish)(fp);
442      NewState(fp, ST_STOPPED);
443      (*fp->parent->LayerFinish)(fp->parent->object, fp);
444      break;
445    }
446  }
447}
448
449static void
450FsmInitRestartCounter(struct fsm *fp, int what)
451{
452  timer_Stop(&fp->FsmTimer);
453  fp->FsmTimer.func = FsmTimeout;
454  fp->FsmTimer.arg = (void *)fp;
455  (*fp->fn->InitRestartCounter)(fp, what);
456}
457
458/*
459 * Actions when receive packets
460 */
461static void
462FsmRecvConfigReq(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
463/* RCR */
464{
465  struct fsm_decode dec;
466  int plen, flen;
467  int ackaction = 0;
468
469  plen = m_length(bp);
470  flen = ntohs(lhp->length) - sizeof *lhp;
471  if (plen < flen) {
472    log_Printf(LogWARN, "%s: FsmRecvConfigReq: plen (%d) < flen (%d)\n",
473	      fp->link->name, plen, flen);
474    m_freem(bp);
475    return;
476  }
477
478  /* Check and process easy case */
479  switch (fp->state) {
480  case ST_INITIAL:
481    if (fp->proto == PROTO_CCP && fp->link->lcp.fsm.state == ST_OPENED) {
482      /*
483       * ccp_SetOpenMode() leaves us in initial if we're disabling
484       * & denying everything.
485       */
486      bp = m_prepend(bp, lhp, sizeof *lhp, 2);
487      bp = proto_Prepend(bp, fp->proto, 0, 0);
488      bp = m_pullup(bp);
489      lcp_SendProtoRej(&fp->link->lcp, MBUF_CTOP(bp), bp->m_len);
490      m_freem(bp);
491      return;
492    }
493    /* Drop through */
494  case ST_STARTING:
495    log_Printf(fp->LogLevel, "%s: Oops, RCR in %s.\n",
496              fp->link->name, State2Nam(fp->state));
497    m_freem(bp);
498    return;
499  case ST_CLOSED:
500    (*fp->fn->SendTerminateAck)(fp, lhp->id);
501    m_freem(bp);
502    return;
503  case ST_CLOSING:
504    log_Printf(fp->LogLevel, "%s: Error: Got ConfigReq while state = %s\n",
505              fp->link->name, State2Nam(fp->state));
506  case ST_STOPPING:
507    m_freem(bp);
508    return;
509  case ST_OPENED:
510    (*fp->fn->LayerDown)(fp);
511    (*fp->parent->LayerDown)(fp->parent->object, fp);
512    break;
513  }
514
515  bp = m_pullup(bp);
516  dec.ackend = dec.ack;
517  dec.nakend = dec.nak;
518  dec.rejend = dec.rej;
519  (*fp->fn->DecodeConfig)(fp, MBUF_CTOP(bp), flen, MODE_REQ, &dec);
520  if (flen < sizeof(struct fsmconfig))
521    log_Printf(fp->LogLevel, "  [EMPTY]\n");
522
523  if (dec.nakend == dec.nak && dec.rejend == dec.rej)
524    ackaction = 1;
525
526  switch (fp->state) {
527  case ST_STOPPED:
528    FsmInitRestartCounter(fp, FSM_REQ_TIMER);
529    /* Fall through */
530
531  case ST_OPENED:
532    FsmSendConfigReq(fp);
533    break;
534  }
535
536  if (dec.rejend != dec.rej)
537    fsm_Output(fp, CODE_CONFIGREJ, lhp->id, dec.rej, dec.rejend - dec.rej,
538               MB_UNKNOWN);
539  if (dec.nakend != dec.nak)
540    fsm_Output(fp, CODE_CONFIGNAK, lhp->id, dec.nak, dec.nakend - dec.nak,
541               MB_UNKNOWN);
542  if (ackaction)
543    fsm_Output(fp, CODE_CONFIGACK, lhp->id, dec.ack, dec.ackend - dec.ack,
544               MB_UNKNOWN);
545
546  switch (fp->state) {
547  case ST_STOPPED:
548      /*
549       * According to the RFC (1661) state transition table, a TLS isn't
550       * required for a RCR when state == ST_STOPPED, but the RFC
551       * must be wrong as TLS hasn't yet been called (since the last TLF)
552       */
553    (*fp->fn->LayerStart)(fp);
554    (*fp->parent->LayerStart)(fp->parent->object, fp);
555    /* Fall through */
556
557  case ST_OPENED:
558    if (ackaction)
559      NewState(fp, ST_ACKSENT);
560    else
561      NewState(fp, ST_REQSENT);
562    break;
563  case ST_REQSENT:
564    if (ackaction)
565      NewState(fp, ST_ACKSENT);
566    break;
567  case ST_ACKRCVD:
568    if (ackaction) {
569      NewState(fp, ST_OPENED);
570      if ((*fp->fn->LayerUp)(fp))
571        (*fp->parent->LayerUp)(fp->parent->object, fp);
572      else {
573        (*fp->fn->LayerDown)(fp);
574        FsmInitRestartCounter(fp, FSM_TRM_TIMER);
575        FsmSendTerminateReq(fp);
576        NewState(fp, ST_CLOSING);
577        lcp_SendIdentification(&fp->link->lcp);
578      }
579    }
580    break;
581  case ST_ACKSENT:
582    if (!ackaction)
583      NewState(fp, ST_REQSENT);
584    break;
585  }
586  m_freem(bp);
587
588  if (dec.rejend != dec.rej && --fp->more.rejs <= 0) {
589    log_Printf(LogPHASE, "%s: Too many %s REJs sent - abandoning negotiation\n",
590               fp->link->name, fp->name);
591    lcp_SendIdentification(&fp->link->lcp);
592    fsm_Close(fp);
593  }
594
595  if (dec.nakend != dec.nak && --fp->more.naks <= 0) {
596    log_Printf(LogPHASE, "%s: Too many %s NAKs sent - abandoning negotiation\n",
597               fp->link->name, fp->name);
598    lcp_SendIdentification(&fp->link->lcp);
599    fsm_Close(fp);
600  }
601}
602
603static void
604FsmRecvConfigAck(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
605/* RCA */
606{
607  switch (fp->state) {
608    case ST_CLOSED:
609    case ST_STOPPED:
610    (*fp->fn->SendTerminateAck)(fp, lhp->id);
611    break;
612  case ST_CLOSING:
613  case ST_STOPPING:
614    break;
615  case ST_REQSENT:
616    FsmInitRestartCounter(fp, FSM_REQ_TIMER);
617    NewState(fp, ST_ACKRCVD);
618    break;
619  case ST_ACKRCVD:
620    FsmSendConfigReq(fp);
621    NewState(fp, ST_REQSENT);
622    break;
623  case ST_ACKSENT:
624    FsmInitRestartCounter(fp, FSM_REQ_TIMER);
625    NewState(fp, ST_OPENED);
626    if ((*fp->fn->LayerUp)(fp))
627      (*fp->parent->LayerUp)(fp->parent->object, fp);
628    else {
629      (*fp->fn->LayerDown)(fp);
630      FsmInitRestartCounter(fp, FSM_TRM_TIMER);
631      FsmSendTerminateReq(fp);
632      NewState(fp, ST_CLOSING);
633      lcp_SendIdentification(&fp->link->lcp);
634    }
635    break;
636  case ST_OPENED:
637    (*fp->fn->LayerDown)(fp);
638    FsmSendConfigReq(fp);
639    NewState(fp, ST_REQSENT);
640    (*fp->parent->LayerDown)(fp->parent->object, fp);
641    break;
642  }
643  m_freem(bp);
644}
645
646static void
647FsmRecvConfigNak(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
648/* RCN */
649{
650  struct fsm_decode dec;
651  int plen, flen;
652
653  plen = m_length(bp);
654  flen = ntohs(lhp->length) - sizeof *lhp;
655  if (plen < flen) {
656    m_freem(bp);
657    return;
658  }
659
660  /*
661   * Check and process easy case
662   */
663  switch (fp->state) {
664  case ST_INITIAL:
665  case ST_STARTING:
666    log_Printf(fp->LogLevel, "%s: Oops, RCN in %s.\n",
667              fp->link->name, State2Nam(fp->state));
668    m_freem(bp);
669    return;
670  case ST_CLOSED:
671  case ST_STOPPED:
672    (*fp->fn->SendTerminateAck)(fp, lhp->id);
673    m_freem(bp);
674    return;
675  case ST_CLOSING:
676  case ST_STOPPING:
677    m_freem(bp);
678    return;
679  }
680
681  bp = m_pullup(bp);
682  dec.ackend = dec.ack;
683  dec.nakend = dec.nak;
684  dec.rejend = dec.rej;
685  (*fp->fn->DecodeConfig)(fp, MBUF_CTOP(bp), flen, MODE_NAK, &dec);
686  if (flen < sizeof(struct fsmconfig))
687    log_Printf(fp->LogLevel, "  [EMPTY]\n");
688
689  switch (fp->state) {
690  case ST_REQSENT:
691  case ST_ACKSENT:
692    FsmInitRestartCounter(fp, FSM_REQ_TIMER);
693    FsmSendConfigReq(fp);
694    break;
695  case ST_OPENED:
696    (*fp->fn->LayerDown)(fp);
697    FsmSendConfigReq(fp);
698    NewState(fp, ST_REQSENT);
699    (*fp->parent->LayerDown)(fp->parent->object, fp);
700    break;
701  case ST_ACKRCVD:
702    FsmSendConfigReq(fp);
703    NewState(fp, ST_REQSENT);
704    break;
705  }
706
707  m_freem(bp);
708}
709
710static void
711FsmRecvTermReq(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
712/* RTR */
713{
714  switch (fp->state) {
715  case ST_INITIAL:
716  case ST_STARTING:
717    log_Printf(fp->LogLevel, "%s: Oops, RTR in %s\n",
718              fp->link->name, State2Nam(fp->state));
719    break;
720  case ST_CLOSED:
721  case ST_STOPPED:
722  case ST_CLOSING:
723  case ST_STOPPING:
724  case ST_REQSENT:
725    (*fp->fn->SendTerminateAck)(fp, lhp->id);
726    break;
727  case ST_ACKRCVD:
728  case ST_ACKSENT:
729    (*fp->fn->SendTerminateAck)(fp, lhp->id);
730    NewState(fp, ST_REQSENT);
731    break;
732  case ST_OPENED:
733    (*fp->fn->LayerDown)(fp);
734    (*fp->fn->SendTerminateAck)(fp, lhp->id);
735    FsmInitRestartCounter(fp, FSM_TRM_TIMER);
736    timer_Start(&fp->FsmTimer);			/* Start restart timer */
737    fp->restart = 0;
738    NewState(fp, ST_STOPPING);
739    (*fp->parent->LayerDown)(fp->parent->object, fp);
740    /* A delayed ST_STOPPED is now scheduled */
741    break;
742  }
743  m_freem(bp);
744}
745
746static void
747FsmRecvTermAck(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
748/* RTA */
749{
750  switch (fp->state) {
751  case ST_CLOSING:
752    (*fp->fn->LayerFinish)(fp);
753    NewState(fp, ST_CLOSED);
754    (*fp->parent->LayerFinish)(fp->parent->object, fp);
755    break;
756  case ST_STOPPING:
757    (*fp->fn->LayerFinish)(fp);
758    NewState(fp, ST_STOPPED);
759    (*fp->parent->LayerFinish)(fp->parent->object, fp);
760    break;
761  case ST_ACKRCVD:
762    NewState(fp, ST_REQSENT);
763    break;
764  case ST_OPENED:
765    (*fp->fn->LayerDown)(fp);
766    FsmSendConfigReq(fp);
767    NewState(fp, ST_REQSENT);
768    (*fp->parent->LayerDown)(fp->parent->object, fp);
769    break;
770  }
771  m_freem(bp);
772}
773
774static void
775FsmRecvConfigRej(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
776/* RCJ */
777{
778  struct fsm_decode dec;
779  int plen, flen;
780
781  plen = m_length(bp);
782  flen = ntohs(lhp->length) - sizeof *lhp;
783  if (plen < flen) {
784    m_freem(bp);
785    return;
786  }
787
788  lcp_SendIdentification(&fp->link->lcp);
789
790  /*
791   * Check and process easy case
792   */
793  switch (fp->state) {
794  case ST_INITIAL:
795  case ST_STARTING:
796    log_Printf(fp->LogLevel, "%s: Oops, RCJ in %s.\n",
797              fp->link->name, State2Nam(fp->state));
798    m_freem(bp);
799    return;
800  case ST_CLOSED:
801  case ST_STOPPED:
802    (*fp->fn->SendTerminateAck)(fp, lhp->id);
803    m_freem(bp);
804    return;
805  case ST_CLOSING:
806  case ST_STOPPING:
807    m_freem(bp);
808    return;
809  }
810
811  bp = m_pullup(bp);
812  dec.ackend = dec.ack;
813  dec.nakend = dec.nak;
814  dec.rejend = dec.rej;
815  (*fp->fn->DecodeConfig)(fp, MBUF_CTOP(bp), flen, MODE_REJ, &dec);
816  if (flen < sizeof(struct fsmconfig))
817    log_Printf(fp->LogLevel, "  [EMPTY]\n");
818
819  switch (fp->state) {
820  case ST_REQSENT:
821  case ST_ACKSENT:
822    FsmInitRestartCounter(fp, FSM_REQ_TIMER);
823    FsmSendConfigReq(fp);
824    break;
825  case ST_OPENED:
826    (*fp->fn->LayerDown)(fp);
827    FsmSendConfigReq(fp);
828    NewState(fp, ST_REQSENT);
829    (*fp->parent->LayerDown)(fp->parent->object, fp);
830    break;
831  case ST_ACKRCVD:
832    FsmSendConfigReq(fp);
833    NewState(fp, ST_REQSENT);
834    break;
835  }
836  m_freem(bp);
837}
838
839static void
840FsmRecvCodeRej(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
841{
842  m_freem(bp);
843}
844
845static void
846FsmRecvProtoRej(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
847{
848  struct physical *p = link2physical(fp->link);
849  u_short proto;
850
851  if (m_length(bp) < 2) {
852    m_freem(bp);
853    return;
854  }
855  bp = mbuf_Read(bp, &proto, 2);
856  proto = ntohs(proto);
857  log_Printf(fp->LogLevel, "%s: -- Protocol 0x%04x (%s) was rejected!\n",
858            fp->link->name, proto, hdlc_Protocol2Nam(proto));
859
860  switch (proto) {
861  case PROTO_LQR:
862    if (p)
863      lqr_Stop(p, LQM_LQR);
864    else
865      log_Printf(LogERROR, "%s: FsmRecvProtoRej: Not a physical link !\n",
866                fp->link->name);
867    break;
868  case PROTO_CCP:
869    if (fp->proto == PROTO_LCP) {
870      fp = &fp->link->ccp.fsm;
871      /* Despite the RFC (1661), don't do an out-of-place TLF */
872      /* (*fp->fn->LayerFinish)(fp); */
873      switch (fp->state) {
874      case ST_CLOSED:
875      case ST_CLOSING:
876        NewState(fp, ST_CLOSED);
877      default:
878        NewState(fp, ST_STOPPED);
879        break;
880      }
881      /* See above */
882      /* (*fp->parent->LayerFinish)(fp->parent->object, fp); */
883    }
884    break;
885  case PROTO_IPCP:
886    if (fp->proto == PROTO_LCP) {
887      log_Printf(LogPHASE, "%s: IPCP protocol reject closes IPCP !\n",
888                fp->link->name);
889      fsm_Close(&fp->bundle->ncp.ipcp.fsm);
890    }
891    break;
892  case PROTO_MP:
893    if (fp->proto == PROTO_LCP) {
894      struct lcp *lcp = fsm2lcp(fp);
895
896      if (lcp->want_mrru && lcp->his_mrru) {
897        log_Printf(LogPHASE, "%s: MP protocol reject is fatal !\n",
898                  fp->link->name);
899        fsm_Close(fp);
900      }
901    }
902    break;
903  }
904  m_freem(bp);
905}
906
907static void
908FsmRecvEchoReq(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
909{
910  struct lcp *lcp = fsm2lcp(fp);
911  u_char *cp;
912  u_int32_t magic;
913
914  bp = m_pullup(bp);
915  m_settype(bp, MB_ECHOIN);
916
917  if (lcp && ntohs(lhp->length) - sizeof *lhp >= 4) {
918    cp = MBUF_CTOP(bp);
919    ua_ntohl(cp, &magic);
920    if (magic != lcp->his_magic) {
921      log_Printf(fp->LogLevel, "%s: RecvEchoReq: magic 0x%08lx is wrong,"
922                 " expecting 0x%08lx\n", fp->link->name, (u_long)magic,
923                 (u_long)lcp->his_magic);
924      /* XXX: We should send terminate request */
925    }
926    if (fp->state == ST_OPENED) {
927      ua_htonl(&lcp->want_magic, cp);		/* local magic */
928      fsm_Output(fp, CODE_ECHOREP, lhp->id, cp,
929                 ntohs(lhp->length) - sizeof *lhp, MB_ECHOOUT);
930    }
931  }
932  m_freem(bp);
933}
934
935static void
936FsmRecvEchoRep(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
937{
938  if (fsm2lcp(fp))
939    bp = lqr_RecvEcho(fp, bp);
940
941  m_freem(bp);
942}
943
944static void
945FsmRecvDiscReq(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
946{
947  m_freem(bp);
948}
949
950static void
951FsmRecvIdent(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
952{
953  u_int32_t magic;
954  u_short len;
955  u_char *cp;
956
957  len = ntohs(lhp->length) - sizeof *lhp;
958  if (len >= 4) {
959    bp = m_pullup(m_append(bp, "", 1));
960    cp = MBUF_CTOP(bp);
961    ua_ntohl(cp, &magic);
962    if (magic != fp->link->lcp.his_magic)
963      log_Printf(fp->LogLevel, "%s: RecvIdent: magic 0x%08lx is wrong,"
964                 " expecting 0x%08lx\n", fp->link->name, (u_long)magic,
965                 (u_long)fp->link->lcp.his_magic);
966    cp[len] = '\0';
967    lcp_RecvIdentification(&fp->link->lcp, cp + 4);
968  }
969  m_freem(bp);
970}
971
972static void
973FsmRecvTimeRemain(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
974{
975  m_freem(bp);
976}
977
978static void
979FsmRecvResetReq(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
980{
981  if ((*fp->fn->RecvResetReq)(fp)) {
982    /*
983     * All sendable compressed packets are queued in the first (lowest
984     * priority) modem output queue.... dump 'em to the priority queue
985     * so that they arrive at the peer before our ResetAck.
986     */
987    link_SequenceQueue(fp->link);
988    fsm_Output(fp, CODE_RESETACK, lhp->id, NULL, 0, MB_CCPOUT);
989  }
990  m_freem(bp);
991}
992
993static void
994FsmRecvResetAck(struct fsm *fp, struct fsmheader *lhp, struct mbuf *bp)
995{
996  (*fp->fn->RecvResetAck)(fp, lhp->id);
997  m_freem(bp);
998}
999
1000void
1001fsm_Input(struct fsm *fp, struct mbuf *bp)
1002{
1003  int len;
1004  struct fsmheader lh;
1005  const struct fsmcodedesc *codep;
1006
1007  len = m_length(bp);
1008  if (len < sizeof(struct fsmheader)) {
1009    m_freem(bp);
1010    return;
1011  }
1012  bp = mbuf_Read(bp, &lh, sizeof lh);
1013
1014  if (ntohs(lh.length) > len) {
1015    log_Printf(LogWARN, "%s: Oops: Got %d bytes but %d byte payload "
1016               "- dropped\n", fp->link->name, len, (int)ntohs(lh.length));
1017    m_freem(bp);
1018    return;
1019  }
1020
1021  if (lh.code < fp->min_code || lh.code > fp->max_code ||
1022      lh.code > sizeof FsmCodes / sizeof *FsmCodes) {
1023    /*
1024     * Use a private id.  This is really a response-type packet, but we
1025     * MUST send a unique id for each REQ....
1026     */
1027    static u_char id;
1028
1029    bp = m_prepend(bp, &lh, sizeof lh, 0);
1030    bp = m_pullup(bp);
1031    fsm_Output(fp, CODE_CODEREJ, id++, MBUF_CTOP(bp), bp->m_len, MB_UNKNOWN);
1032    m_freem(bp);
1033    return;
1034  }
1035
1036  codep = FsmCodes + lh.code - 1;
1037  if (lh.id != fp->reqid && codep->check_reqid &&
1038      Enabled(fp->bundle, OPT_IDCHECK)) {
1039    log_Printf(fp->LogLevel, "%s: Recv%s(%d), dropped (expected %d)\n",
1040	      fp->link->name, codep->name, lh.id, fp->reqid);
1041    return;
1042  }
1043
1044  log_Printf(fp->LogLevel, "%s: Recv%s(%d) state = %s\n",
1045	    fp->link->name, codep->name, lh.id, State2Nam(fp->state));
1046
1047  if (codep->inc_reqid && (lh.id == fp->reqid ||
1048      (!Enabled(fp->bundle, OPT_IDCHECK) && codep->check_reqid)))
1049    fp->reqid++;	/* That's the end of that ``exchange''.... */
1050
1051  (*codep->recv)(fp, &lh, bp);
1052}
1053
1054int
1055fsm_NullRecvResetReq(struct fsm *fp)
1056{
1057  log_Printf(fp->LogLevel, "%s: Oops - received unexpected reset req\n",
1058            fp->link->name);
1059  return 1;
1060}
1061
1062void
1063fsm_NullRecvResetAck(struct fsm *fp, u_char id)
1064{
1065  log_Printf(fp->LogLevel, "%s: Oops - received unexpected reset ack\n",
1066            fp->link->name);
1067}
1068
1069void
1070fsm_Reopen(struct fsm *fp)
1071{
1072  if (fp->state == ST_OPENED) {
1073    (*fp->fn->LayerDown)(fp);
1074    FsmInitRestartCounter(fp, FSM_REQ_TIMER);
1075    FsmSendConfigReq(fp);
1076    NewState(fp, ST_REQSENT);
1077    (*fp->parent->LayerDown)(fp->parent->object, fp);
1078  }
1079}
1080
1081void
1082fsm2initial(struct fsm *fp)
1083{
1084  timer_Stop(&fp->FsmTimer);
1085  timer_Stop(&fp->OpenTimer);
1086  timer_Stop(&fp->StoppedTimer);
1087  if (fp->state == ST_STOPPED)
1088    fsm_Close(fp);
1089  if (fp->state > ST_INITIAL)
1090    fsm_Down(fp);
1091  if (fp->state > ST_INITIAL)
1092    fsm_Close(fp);
1093}
1094