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