xref: /freebsd/usr.sbin/ppp/datalink.c (revision 6fd05b64b5b65dd4ba9b86482a0634a5f0b96c29)
1 /*-
2  * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/param.h>
30 #include <netinet/in.h>
31 #include <netinet/in_systm.h>
32 #include <netinet/ip.h>
33 #include <sys/socket.h>
34 #include <sys/un.h>
35 
36 #include <ctype.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/uio.h>
42 #include <termios.h>
43 
44 #include "layer.h"
45 #include "mbuf.h"
46 #include "log.h"
47 #include "defs.h"
48 #include "timer.h"
49 #include "fsm.h"
50 #include "descriptor.h"
51 #include "lqr.h"
52 #include "hdlc.h"
53 #include "lcp.h"
54 #include "async.h"
55 #include "throughput.h"
56 #include "ccp.h"
57 #include "link.h"
58 #include "physical.h"
59 #include "iplist.h"
60 #include "slcompress.h"
61 #include "ncpaddr.h"
62 #include "ipcp.h"
63 #include "filter.h"
64 #include "mp.h"
65 #ifndef NORADIUS
66 #include "radius.h"
67 #endif
68 #include "ipv6cp.h"
69 #include "ncp.h"
70 #include "bundle.h"
71 #include "chat.h"
72 #include "auth.h"
73 #include "prompt.h"
74 #include "proto.h"
75 #include "pap.h"
76 #include "chap.h"
77 #include "command.h"
78 #include "cbcp.h"
79 #include "datalink.h"
80 
81 static void datalink_LoginDone(struct datalink *);
82 static void datalink_NewState(struct datalink *, int);
83 
84 static void
85 datalink_OpenTimeout(void *v)
86 {
87   struct datalink *dl = (struct datalink *)v;
88 
89   timer_Stop(&dl->dial.timer);
90   if (dl->state == DATALINK_OPENING)
91     log_Printf(LogCHAT, "%s: Redial timer expired.\n", dl->name);
92 }
93 
94 static int
95 datalink_StartDialTimer(struct datalink *dl, int Timeout)
96 {
97   int result = Timeout;
98 
99   timer_Stop(&dl->dial.timer);
100   if (Timeout < 0)
101     result = (random() % DIAL_TIMEOUT) + 1;
102   dl->dial.timer.load = result ? result * SECTICKS : 1;
103   dl->dial.timer.func = datalink_OpenTimeout;
104   dl->dial.timer.name = "dial";
105   dl->dial.timer.arg = dl;
106   timer_Start(&dl->dial.timer);
107   if (dl->state == DATALINK_OPENING)
108     log_Printf(LogPHASE, "%s: Enter pause (%d) for redialing.\n",
109                dl->name, result);
110   return result;
111 }
112 
113 static void
114 datalink_HangupDone(struct datalink *dl)
115 {
116   if (dl->physical->type == PHYS_DEDICATED && !dl->bundle->CleaningUp &&
117       dl->physical->fd != -1) {
118     /* Don't close our device if the link is dedicated */
119     datalink_LoginDone(dl);
120     return;
121   }
122 
123   chat_Finish(&dl->chat);
124   physical_Close(dl->physical);
125   dl->phone.chosen = "N/A";
126 
127   if (dl->cbcp.required) {
128     log_Printf(LogPHASE, "Call peer back on %s\n", dl->cbcp.fsm.phone);
129     dl->cfg.callback.opmask = 0;
130     strncpy(dl->cfg.phone.list, dl->cbcp.fsm.phone,
131             sizeof dl->cfg.phone.list - 1);
132     dl->cfg.phone.list[sizeof dl->cfg.phone.list - 1] = '\0';
133     dl->phone.alt = dl->phone.next = NULL;
134     dl->reconnect_tries = dl->cfg.reconnect.max;
135     dl->dial.tries = dl->cfg.dial.max;
136     dl->dial.incs = 0;
137     dl->script.run = 1;
138     dl->script.packetmode = 1;
139     if (!physical_SetMode(dl->physical, PHYS_BACKGROUND))
140       log_Printf(LogERROR, "Oops - can't change mode to BACKGROUND (gulp) !\n");
141     bundle_LinksRemoved(dl->bundle);
142     /* if dial.timeout is < 0 (random), we don't override fsm.delay */
143     if (dl->cbcp.fsm.delay < dl->cfg.dial.timeout)
144       dl->cbcp.fsm.delay = dl->cfg.dial.timeout;
145     datalink_StartDialTimer(dl, dl->cbcp.fsm.delay);
146     cbcp_Down(&dl->cbcp);
147     datalink_NewState(dl, DATALINK_OPENING);
148     if (bundle_Phase(dl->bundle) == PHASE_DEAD ||
149         bundle_Phase(dl->bundle) == PHASE_TERMINATE)
150       bundle_NewPhase(dl->bundle, PHASE_ESTABLISH);
151   } else if (dl->bundle->CleaningUp ||
152       (dl->physical->type == PHYS_DIRECT) ||
153       ((!dl->dial.tries || (dl->dial.tries < 0 && !dl->reconnect_tries)) &&
154        !(dl->physical->type & (PHYS_DDIAL|PHYS_DEDICATED)))) {
155     datalink_NewState(dl, DATALINK_CLOSED);
156     dl->dial.tries = -1;
157     dl->dial.incs = 0;
158     dl->reconnect_tries = 0;
159     bundle_LinkClosed(dl->bundle, dl);
160     if (!dl->bundle->CleaningUp &&
161         !(dl->physical->type & (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)))
162       datalink_StartDialTimer(dl, datalink_GetDialTimeout(dl));
163   } else {
164     datalink_NewState(dl, DATALINK_OPENING);
165     if (bundle_Phase(dl->bundle) == PHASE_DEAD ||
166         bundle_Phase(dl->bundle) == PHASE_TERMINATE)
167       bundle_NewPhase(dl->bundle, PHASE_ESTABLISH);
168     if (dl->dial.tries < 0) {
169       datalink_StartDialTimer(dl, dl->cfg.reconnect.timeout);
170       dl->dial.tries = dl->cfg.dial.max;
171       dl->dial.incs = 0;
172       dl->reconnect_tries--;
173       log_Printf(LogCHAT, "%s: Reconnect try %d of %d\n",
174                  dl->name, dl->cfg.reconnect.max - dl->reconnect_tries,
175                  dl->cfg.reconnect.max);
176       bundle_Notify(dl->bundle, EX_RECONNECT);
177     } else {
178       if (dl->phone.next == NULL)
179         datalink_StartDialTimer(dl, datalink_GetDialTimeout(dl));
180       else
181         datalink_StartDialTimer(dl, dl->cfg.dial.next_timeout);
182       bundle_Notify(dl->bundle, EX_REDIAL);
183     }
184   }
185 }
186 
187 const char *
188 datalink_ChoosePhoneNumber(struct datalink *dl)
189 {
190   char *phone;
191 
192   if (dl->phone.alt == NULL) {
193     if (dl->phone.next == NULL) {
194       strncpy(dl->phone.list, dl->cfg.phone.list, sizeof dl->phone.list - 1);
195       dl->phone.list[sizeof dl->phone.list - 1] = '\0';
196       if (*dl->phone.list == '\0')
197         return "";
198       dl->phone.next = dl->phone.list;
199     }
200     dl->phone.alt = strsep(&dl->phone.next, ":");
201   }
202   phone = strsep(&dl->phone.alt, "|");
203   dl->phone.chosen = *phone ? phone : "[NONE]";
204   if (*phone)
205     log_Printf(LogCHAT, "Phone: %s\n", phone);
206   return phone;
207 }
208 
209 static void
210 datalink_LoginDone(struct datalink *dl)
211 {
212   chat_Finish(&dl->chat);
213 
214   if (!dl->script.packetmode) {
215     dl->dial.tries = -1;
216     dl->dial.incs = 0;
217     datalink_NewState(dl, DATALINK_READY);
218   } else if (!physical_Raw(dl->physical)) {
219     dl->dial.tries = 0;
220     log_Printf(LogWARN, "datalink_LoginDone: Not connected.\n");
221     if (dl->script.run) {
222       datalink_NewState(dl, DATALINK_LOGOUT);
223       if (!chat_Setup(&dl->chat, dl->cfg.script.logout, NULL))
224         log_Printf(LogWARN, "Invalid logout script\n");
225     } else {
226       physical_StopDeviceTimer(dl->physical);
227       if (dl->physical->type == PHYS_DEDICATED)
228         /* force a redial timeout */
229         physical_Close(dl->physical);
230       datalink_HangupDone(dl);
231     }
232   } else {
233     dl->dial.tries = -1;
234     dl->dial.incs = 0;
235 
236     hdlc_Init(&dl->physical->hdlc, &dl->physical->link.lcp);
237     async_Setup(&dl->physical->async);
238 
239     lcp_Setup(&dl->physical->link.lcp, dl->state == DATALINK_READY ?
240               0 : dl->physical->link.lcp.cfg.openmode);
241     ccp_Setup(&dl->physical->link.ccp);
242 
243     datalink_NewState(dl, DATALINK_LCP);
244     fsm_Up(&dl->physical->link.lcp.fsm);
245     fsm_Open(&dl->physical->link.lcp.fsm);
246   }
247 }
248 
249 static int
250 datalink_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e,
251                    int *n)
252 {
253   struct datalink *dl = descriptor2datalink(d);
254   int result;
255 
256   result = 0;
257   switch (dl->state) {
258     case DATALINK_CLOSED:
259       if ((dl->physical->type & (PHYS_DIRECT|PHYS_DEDICATED|PHYS_BACKGROUND|
260                                  PHYS_FOREGROUND|PHYS_DDIAL)) &&
261           !dl->bundle->CleaningUp)
262         /*
263          * Our first time in - DEDICATED & DDIAL never come down, and
264          * DIRECT, FOREGROUND & BACKGROUND get deleted when they enter
265          * DATALINK_CLOSED.  Go to DATALINK_OPENING via datalink_Up()
266          * and fall through.
267          */
268         datalink_Up(dl, 1, 1);
269       else
270         break;
271       /* FALLTHROUGH */
272 
273     case DATALINK_OPENING:
274       if (dl->dial.timer.state != TIMER_RUNNING) {
275         if (--dl->dial.tries < 0)
276           dl->dial.tries = 0;
277         if (physical_Open(dl->physical, dl->bundle) >= 0) {
278           log_WritePrompts(dl, "%s: Entering terminal mode on %s\r\n"
279                            "Type `~?' for help\r\n", dl->name,
280                            dl->physical->name.full);
281           if (dl->script.run) {
282             datalink_NewState(dl, DATALINK_DIAL);
283             if (!chat_Setup(&dl->chat, dl->cfg.script.dial,
284                             *dl->cfg.script.dial ?
285                             datalink_ChoosePhoneNumber(dl) : ""))
286               log_Printf(LogWARN, "Invalid dial script\n");
287             if (!(dl->physical->type & (PHYS_DDIAL|PHYS_DEDICATED)) &&
288                 dl->cfg.dial.max)
289               log_Printf(LogCHAT, "%s: Dial attempt %u of %d\n",
290                         dl->name, dl->cfg.dial.max - dl->dial.tries,
291                         dl->cfg.dial.max);
292           } else
293             datalink_NewState(dl, DATALINK_CARRIER);
294           return datalink_UpdateSet(d, r, w, e, n);
295         } else {
296           if (!(dl->physical->type & (PHYS_DDIAL|PHYS_DEDICATED)) &&
297               dl->cfg.dial.max)
298             log_Printf(LogCHAT, "Failed to open device (attempt %u of %d)\n",
299                        dl->cfg.dial.max - dl->dial.tries, dl->cfg.dial.max);
300           else
301             log_Printf(LogCHAT, "Failed to open device\n");
302 
303           if (dl->bundle->CleaningUp ||
304               (!(dl->physical->type & (PHYS_DDIAL|PHYS_DEDICATED)) &&
305                dl->cfg.dial.max && dl->dial.tries == 0)) {
306             datalink_NewState(dl, DATALINK_CLOSED);
307             dl->reconnect_tries = 0;
308             dl->dial.tries = -1;
309             log_WritePrompts(dl, "Failed to open %s\n",
310                              dl->physical->name.full);
311             bundle_LinkClosed(dl->bundle, dl);
312           }
313           if (!dl->bundle->CleaningUp) {
314             int timeout;
315 
316             timeout = datalink_StartDialTimer(dl, datalink_GetDialTimeout(dl));
317             bundle_Notify(dl->bundle, EX_REDIAL);
318             log_WritePrompts(dl, "Failed to open %s, pause %d seconds\n",
319                              dl->physical->name.full, timeout);
320           }
321         }
322       }
323       break;
324 
325     case DATALINK_CARRIER:
326       /* Wait for carrier on the device */
327       switch (physical_AwaitCarrier(dl->physical)) {
328         case CARRIER_PENDING:
329           log_Printf(LogDEBUG, "Waiting for carrier\n");
330           return 0;	/* A device timer is running to wake us up again */
331 
332         case CARRIER_OK:
333           if (dl->script.run) {
334             datalink_NewState(dl, DATALINK_LOGIN);
335             if (!chat_Setup(&dl->chat, dl->cfg.script.login, NULL))
336               log_Printf(LogWARN, "Invalid login script\n");
337           } else
338             datalink_LoginDone(dl);
339           return datalink_UpdateSet(d, r, w, e, n);
340 
341         case CARRIER_LOST:
342           physical_Offline(dl->physical);	/* Is this required ? */
343           if (dl->script.run) {
344             datalink_NewState(dl, DATALINK_HANGUP);
345             if (!chat_Setup(&dl->chat, dl->cfg.script.hangup, NULL))
346               log_Printf(LogWARN, "Invalid hangup script\n");
347             return datalink_UpdateSet(d, r, w, e, n);
348           } else {
349             datalink_HangupDone(dl);
350             return 0;	/* Maybe bundle_CleanDatalinks() has something to do */
351           }
352       }
353 
354     case DATALINK_HANGUP:
355     case DATALINK_DIAL:
356     case DATALINK_LOGOUT:
357     case DATALINK_LOGIN:
358       result = descriptor_UpdateSet(&dl->chat.desc, r, w, e, n);
359       switch (dl->chat.state) {
360         case CHAT_DONE:
361           /* script succeeded */
362           switch(dl->state) {
363             case DATALINK_HANGUP:
364               datalink_HangupDone(dl);
365               break;
366             case DATALINK_DIAL:
367               datalink_NewState(dl, DATALINK_CARRIER);
368               return datalink_UpdateSet(d, r, w, e, n);
369             case DATALINK_LOGOUT:
370               datalink_NewState(dl, DATALINK_HANGUP);
371               physical_Offline(dl->physical);
372               if (!chat_Setup(&dl->chat, dl->cfg.script.hangup, NULL))
373                 log_Printf(LogWARN, "Invalid hangup script\n");
374               return datalink_UpdateSet(d, r, w, e, n);
375             case DATALINK_LOGIN:
376               dl->phone.alt = NULL;
377               datalink_LoginDone(dl);
378               return datalink_UpdateSet(d, r, w, e, n);
379           }
380           break;
381         case CHAT_FAILED:
382           /* Going down - script failed */
383           log_Printf(LogWARN, "Chat script failed\n");
384           switch(dl->state) {
385             case DATALINK_HANGUP:
386               datalink_HangupDone(dl);
387               break;
388             case DATALINK_DIAL:
389             case DATALINK_LOGOUT:
390             case DATALINK_LOGIN:
391               datalink_NewState(dl, DATALINK_HANGUP);
392               physical_Offline(dl->physical);
393               if (!chat_Setup(&dl->chat, dl->cfg.script.hangup, NULL))
394                 log_Printf(LogWARN, "Invalid hangup script\n");
395               return datalink_UpdateSet(d, r, w, e, n);
396           }
397           break;
398       }
399       break;
400 
401     case DATALINK_READY:
402     case DATALINK_LCP:
403     case DATALINK_AUTH:
404     case DATALINK_CBCP:
405     case DATALINK_OPEN:
406       result = descriptor_UpdateSet(&dl->chap.desc, r, w, e, n) +
407                descriptor_UpdateSet(&dl->physical->desc, r, w, e, n);
408       break;
409   }
410   return result;
411 }
412 
413 int
414 datalink_RemoveFromSet(struct datalink *dl, fd_set *r, fd_set *w, fd_set *e)
415 {
416   return physical_RemoveFromSet(dl->physical, r, w, e);
417 }
418 
419 static int
420 datalink_IsSet(struct fdescriptor *d, const fd_set *fdset)
421 {
422   struct datalink *dl = descriptor2datalink(d);
423 
424   switch (dl->state) {
425     case DATALINK_CLOSED:
426     case DATALINK_OPENING:
427       break;
428 
429     case DATALINK_HANGUP:
430     case DATALINK_DIAL:
431     case DATALINK_LOGOUT:
432     case DATALINK_LOGIN:
433       return descriptor_IsSet(&dl->chat.desc, fdset);
434 
435     case DATALINK_READY:
436     case DATALINK_LCP:
437     case DATALINK_AUTH:
438     case DATALINK_CBCP:
439     case DATALINK_OPEN:
440       return descriptor_IsSet(&dl->chap.desc, fdset) ? 1 :
441              descriptor_IsSet(&dl->physical->desc, fdset);
442   }
443   return 0;
444 }
445 
446 static void
447 datalink_Read(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset)
448 {
449   struct datalink *dl = descriptor2datalink(d);
450 
451   switch (dl->state) {
452     case DATALINK_CLOSED:
453     case DATALINK_OPENING:
454       break;
455 
456     case DATALINK_HANGUP:
457     case DATALINK_DIAL:
458     case DATALINK_LOGOUT:
459     case DATALINK_LOGIN:
460       descriptor_Read(&dl->chat.desc, bundle, fdset);
461       break;
462 
463     case DATALINK_READY:
464     case DATALINK_LCP:
465     case DATALINK_AUTH:
466     case DATALINK_CBCP:
467     case DATALINK_OPEN:
468       if (descriptor_IsSet(&dl->chap.desc, fdset))
469         descriptor_Read(&dl->chap.desc, bundle, fdset);
470       if (descriptor_IsSet(&dl->physical->desc, fdset))
471         descriptor_Read(&dl->physical->desc, bundle, fdset);
472       break;
473   }
474 }
475 
476 static int
477 datalink_Write(struct fdescriptor *d, struct bundle *bundle,
478                const fd_set *fdset)
479 {
480   struct datalink *dl = descriptor2datalink(d);
481   int result = 0;
482 
483   switch (dl->state) {
484     case DATALINK_CLOSED:
485     case DATALINK_OPENING:
486       break;
487 
488     case DATALINK_HANGUP:
489     case DATALINK_DIAL:
490     case DATALINK_LOGOUT:
491     case DATALINK_LOGIN:
492       if ((result = descriptor_Write(&dl->chat.desc, bundle, fdset)) == -1) {
493         datalink_ComeDown(dl, CLOSE_NORMAL);
494         result = 0;
495       }
496       break;
497 
498     case DATALINK_READY:
499     case DATALINK_LCP:
500     case DATALINK_AUTH:
501     case DATALINK_CBCP:
502     case DATALINK_OPEN:
503       if (descriptor_IsSet(&dl->chap.desc, fdset))
504         switch (descriptor_Write(&dl->chap.desc, bundle, fdset)) {
505         case -1:
506           datalink_ComeDown(dl, CLOSE_NORMAL);
507           break;
508         case 1:
509           result++;
510         }
511       if (descriptor_IsSet(&dl->physical->desc, fdset))
512         switch (descriptor_Write(&dl->physical->desc, bundle, fdset)) {
513         case -1:
514           datalink_ComeDown(dl, CLOSE_NORMAL);
515           break;
516         case 1:
517           result++;
518         }
519       break;
520   }
521 
522   return result;
523 }
524 
525 void
526 datalink_ComeDown(struct datalink *dl, int how)
527 {
528   int stayonline;
529 
530   if (how == CLOSE_LCP)
531     datalink_DontHangup(dl);
532   else if (how == CLOSE_STAYDOWN)
533     datalink_StayDown(dl);
534 
535   stayonline = dl->stayonline;
536   dl->stayonline = 0;
537 
538   if (dl->state >= DATALINK_READY && stayonline) {
539     physical_StopDeviceTimer(dl->physical);
540     datalink_NewState(dl, DATALINK_READY);
541   } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP) {
542     physical_Offline(dl->physical);
543     if (dl->script.run && dl->state != DATALINK_OPENING) {
544       if (dl->state == DATALINK_LOGOUT) {
545         datalink_NewState(dl, DATALINK_HANGUP);
546         if (!chat_Setup(&dl->chat, dl->cfg.script.hangup, NULL))
547           log_Printf(LogWARN, "Invalid hangup script\n");
548       } else {
549         datalink_NewState(dl, DATALINK_LOGOUT);
550         if (!chat_Setup(&dl->chat, dl->cfg.script.logout, NULL))
551           log_Printf(LogWARN, "Invalid logout script\n");
552       }
553     } else
554       datalink_HangupDone(dl);
555   }
556 }
557 
558 static void
559 datalink_LayerStart(void *v, struct fsm *fp)
560 {
561   /* The given FSM is about to start up ! */
562   struct datalink *dl = (struct datalink *)v;
563 
564   if (fp->proto == PROTO_LCP)
565     (*dl->parent->LayerStart)(dl->parent->object, fp);
566 }
567 
568 static void
569 datalink_LayerUp(void *v, struct fsm *fp)
570 {
571   /* The given fsm is now up */
572   struct datalink *dl = (struct datalink *)v;
573   struct lcp *lcp = &dl->physical->link.lcp;
574 
575   if (fp->proto == PROTO_LCP) {
576     datalink_GotAuthname(dl, "");
577     lcp->auth_ineed = lcp->want_auth;
578     lcp->auth_iwait = lcp->his_auth;
579     if (lcp->his_auth || lcp->want_auth) {
580       if (bundle_Phase(dl->bundle) != PHASE_NETWORK)
581         bundle_NewPhase(dl->bundle, PHASE_AUTHENTICATE);
582       log_Printf(LogPHASE, "%s: his = %s, mine = %s\n", dl->name,
583                 Auth2Nam(lcp->his_auth, lcp->his_authtype),
584                 Auth2Nam(lcp->want_auth, lcp->want_authtype));
585       if (lcp->his_auth == PROTO_PAP)
586         auth_StartReq(&dl->pap);
587       if (lcp->want_auth == PROTO_CHAP)
588         auth_StartReq(&dl->chap.auth);
589     } else
590       datalink_AuthOk(dl);
591   } else if (fp->proto == PROTO_CCP)
592     (*dl->parent->LayerUp)(dl->parent->object, &dl->physical->link.ccp.fsm);
593 }
594 
595 static void
596 datalink_AuthReInit(struct datalink *dl)
597 {
598   auth_StopTimer(&dl->pap);
599   auth_StopTimer(&dl->chap.auth);
600   chap_ReInit(&dl->chap);
601 }
602 
603 void
604 datalink_GotAuthname(struct datalink *dl, const char *name)
605 {
606   strncpy(dl->peer.authname, name, sizeof dl->peer.authname - 1);
607   dl->peer.authname[sizeof dl->peer.authname - 1] = '\0';
608 }
609 
610 void
611 datalink_NCPUp(struct datalink *dl)
612 {
613   int ccpok = ccp_SetOpenMode(&dl->physical->link.ccp);
614 
615   if (dl->physical->link.lcp.want_mrru && dl->physical->link.lcp.his_mrru) {
616     /* we've authenticated in multilink mode ! */
617     switch (mp_Up(&dl->bundle->ncp.mp, dl)) {
618       case MP_LINKSENT:
619         /* We've handed the link off to another ppp (well, we will soon) ! */
620         return;
621       case MP_UP:
622         /* First link in the bundle */
623         auth_Select(dl->bundle, dl->peer.authname);
624         bundle_CalculateBandwidth(dl->bundle);
625         /* FALLTHROUGH */
626       case MP_ADDED:
627         /* We're in multilink mode ! */
628         dl->physical->link.ccp.fsm.open_mode = OPEN_PASSIVE;	/* override */
629         bundle_CalculateBandwidth(dl->bundle);
630         break;
631       case MP_FAILED:
632         datalink_AuthNotOk(dl);
633         return;
634     }
635   } else if (bundle_Phase(dl->bundle) == PHASE_NETWORK) {
636     log_Printf(LogPHASE, "%s: Already in NETWORK phase\n", dl->name);
637     datalink_NewState(dl, DATALINK_OPEN);
638     bundle_CalculateBandwidth(dl->bundle);
639     (*dl->parent->LayerUp)(dl->parent->object, &dl->physical->link.lcp.fsm);
640     return;
641   } else {
642     dl->bundle->ncp.mp.peer = dl->peer;
643     ncp_SetLink(&dl->bundle->ncp, &dl->physical->link);
644     auth_Select(dl->bundle, dl->peer.authname);
645   }
646 
647   if (ccpok) {
648     fsm_Up(&dl->physical->link.ccp.fsm);
649     fsm_Open(&dl->physical->link.ccp.fsm);
650   }
651   datalink_NewState(dl, DATALINK_OPEN);
652   bundle_NewPhase(dl->bundle, PHASE_NETWORK);
653   (*dl->parent->LayerUp)(dl->parent->object, &dl->physical->link.lcp.fsm);
654 }
655 
656 void
657 datalink_CBCPComplete(struct datalink *dl)
658 {
659   datalink_NewState(dl, DATALINK_LCP);
660   datalink_AuthReInit(dl);
661   fsm_Close(&dl->physical->link.lcp.fsm);
662 }
663 
664 void
665 datalink_CBCPFailed(struct datalink *dl)
666 {
667   cbcp_Down(&dl->cbcp);
668   datalink_CBCPComplete(dl);
669 }
670 
671 void
672 datalink_AuthOk(struct datalink *dl)
673 {
674   if ((dl->physical->link.lcp.his_callback.opmask &
675        CALLBACK_BIT(CALLBACK_CBCP) ||
676        dl->physical->link.lcp.want_callback.opmask &
677        CALLBACK_BIT(CALLBACK_CBCP)) &&
678       !(dl->physical->link.lcp.want_callback.opmask &
679         CALLBACK_BIT(CALLBACK_AUTH))) {
680     /* We must have agreed CBCP if AUTH isn't there any more */
681     datalink_NewState(dl, DATALINK_CBCP);
682     cbcp_Up(&dl->cbcp);
683   } else if (dl->physical->link.lcp.want_callback.opmask) {
684     /* It's not CBCP */
685     log_Printf(LogPHASE, "%s: Shutdown and await peer callback\n", dl->name);
686     datalink_NewState(dl, DATALINK_LCP);
687     datalink_AuthReInit(dl);
688     fsm_Close(&dl->physical->link.lcp.fsm);
689   } else
690     switch (dl->physical->link.lcp.his_callback.opmask) {
691       case 0:
692         datalink_NCPUp(dl);
693         break;
694 
695       case CALLBACK_BIT(CALLBACK_AUTH):
696         auth_SetPhoneList(dl->peer.authname, dl->cbcp.fsm.phone,
697                           sizeof dl->cbcp.fsm.phone);
698         if (*dl->cbcp.fsm.phone == '\0' || !strcmp(dl->cbcp.fsm.phone, "*")) {
699           log_Printf(LogPHASE, "%s: %s cannot be called back\n", dl->name,
700                      dl->peer.authname);
701           *dl->cbcp.fsm.phone = '\0';
702         } else {
703           char *ptr = strchr(dl->cbcp.fsm.phone, ',');
704           if (ptr)
705             *ptr = '\0';	/* Call back on the first number */
706           log_Printf(LogPHASE, "%s: Calling peer back on %s\n", dl->name,
707                      dl->cbcp.fsm.phone);
708           dl->cbcp.required = 1;
709         }
710         dl->cbcp.fsm.delay = 0;
711         datalink_NewState(dl, DATALINK_LCP);
712         datalink_AuthReInit(dl);
713         fsm_Close(&dl->physical->link.lcp.fsm);
714         break;
715 
716       case CALLBACK_BIT(CALLBACK_E164):
717         strncpy(dl->cbcp.fsm.phone, dl->physical->link.lcp.his_callback.msg,
718                 sizeof dl->cbcp.fsm.phone - 1);
719         dl->cbcp.fsm.phone[sizeof dl->cbcp.fsm.phone - 1] = '\0';
720         log_Printf(LogPHASE, "%s: Calling peer back on %s\n", dl->name,
721                    dl->cbcp.fsm.phone);
722         dl->cbcp.required = 1;
723         dl->cbcp.fsm.delay = 0;
724         datalink_NewState(dl, DATALINK_LCP);
725         datalink_AuthReInit(dl);
726         fsm_Close(&dl->physical->link.lcp.fsm);
727         break;
728 
729       default:
730         log_Printf(LogPHASE, "%s: Oops - Should have NAK'd peer callback !\n",
731                    dl->name);
732         datalink_NewState(dl, DATALINK_LCP);
733         datalink_AuthReInit(dl);
734         fsm_Close(&dl->physical->link.lcp.fsm);
735         break;
736     }
737 }
738 
739 void
740 datalink_AuthNotOk(struct datalink *dl)
741 {
742   datalink_NewState(dl, DATALINK_LCP);
743   datalink_AuthReInit(dl);
744   fsm_Close(&dl->physical->link.lcp.fsm);
745 }
746 
747 static void
748 datalink_LayerDown(void *v, struct fsm *fp)
749 {
750   /* The given FSM has been told to come down */
751   struct datalink *dl = (struct datalink *)v;
752 
753   if (fp->proto == PROTO_LCP) {
754     switch (dl->state) {
755       case DATALINK_OPEN:
756         peerid_Init(&dl->peer);
757         fsm2initial(&dl->physical->link.ccp.fsm);
758         datalink_NewState(dl, DATALINK_LCP);  /* before parent TLD */
759         (*dl->parent->LayerDown)(dl->parent->object, fp);
760         /* FALLTHROUGH (just in case) */
761 
762       case DATALINK_CBCP:
763         if (!dl->cbcp.required)
764           cbcp_Down(&dl->cbcp);
765         /* FALLTHROUGH (just in case) */
766 
767       case DATALINK_AUTH:
768         timer_Stop(&dl->pap.authtimer);
769         timer_Stop(&dl->chap.auth.authtimer);
770     }
771     datalink_NewState(dl, DATALINK_LCP);
772     datalink_AuthReInit(dl);
773   }
774 }
775 
776 static void
777 datalink_LayerFinish(void *v, struct fsm *fp)
778 {
779   /* The given fsm is now down */
780   struct datalink *dl = (struct datalink *)v;
781 
782   if (fp->proto == PROTO_LCP) {
783     fsm2initial(fp);
784     (*dl->parent->LayerFinish)(dl->parent->object, fp);
785     datalink_ComeDown(dl, CLOSE_NORMAL);
786   } else if (fp->state == ST_CLOSED && fp->open_mode == OPEN_PASSIVE)
787     fsm_Open(fp);		/* CCP goes to ST_STOPPED */
788 }
789 
790 struct datalink *
791 datalink_Create(const char *name, struct bundle *bundle, int type)
792 {
793   struct datalink *dl;
794 
795   dl = (struct datalink *)malloc(sizeof(struct datalink));
796   if (dl == NULL)
797     return dl;
798 
799   dl->desc.type = DATALINK_DESCRIPTOR;
800   dl->desc.UpdateSet = datalink_UpdateSet;
801   dl->desc.IsSet = datalink_IsSet;
802   dl->desc.Read = datalink_Read;
803   dl->desc.Write = datalink_Write;
804 
805   dl->state = DATALINK_CLOSED;
806 
807   *dl->cfg.script.dial = '\0';
808   *dl->cfg.script.login = '\0';
809   *dl->cfg.script.logout = '\0';
810   *dl->cfg.script.hangup = '\0';
811   *dl->cfg.phone.list = '\0';
812   *dl->phone.list = '\0';
813   dl->phone.next = NULL;
814   dl->phone.alt = NULL;
815   dl->phone.chosen = "N/A";
816   dl->stayonline = 0;
817   dl->script.run = 1;
818   dl->script.packetmode = 1;
819   mp_linkInit(&dl->mp);
820 
821   dl->bundle = bundle;
822   dl->next = NULL;
823 
824   memset(&dl->dial.timer, '\0', sizeof dl->dial.timer);
825 
826   dl->dial.tries = 0;
827   dl->cfg.dial.max = 1;
828   dl->cfg.dial.next_timeout = DIAL_NEXT_TIMEOUT;
829   dl->cfg.dial.timeout = DIAL_TIMEOUT;
830   dl->cfg.dial.inc = 0;
831   dl->cfg.dial.maxinc = 10;
832 
833   dl->reconnect_tries = 0;
834   dl->cfg.reconnect.max = 0;
835   dl->cfg.reconnect.timeout = RECONNECT_TIMEOUT;
836 
837   dl->cfg.callback.opmask = 0;
838   dl->cfg.cbcp.delay = 0;
839   *dl->cfg.cbcp.phone = '\0';
840   dl->cfg.cbcp.fsmretry = DEF_FSMRETRY;
841 
842   dl->name = strdup(name);
843   peerid_Init(&dl->peer);
844   dl->parent = &bundle->fsm;
845   dl->fsmp.LayerStart = datalink_LayerStart;
846   dl->fsmp.LayerUp = datalink_LayerUp;
847   dl->fsmp.LayerDown = datalink_LayerDown;
848   dl->fsmp.LayerFinish = datalink_LayerFinish;
849   dl->fsmp.object = dl;
850 
851   if ((dl->physical = physical_Create(dl, type)) == NULL) {
852     free(dl->name);
853     free(dl);
854     return NULL;
855   }
856 
857   pap_Init(&dl->pap, dl->physical);
858   chap_Init(&dl->chap, dl->physical);
859   cbcp_Init(&dl->cbcp, dl->physical);
860 
861   memset(&dl->chat, '\0', sizeof dl->chat);	/* Force buf{start,end} reset */
862   chat_Init(&dl->chat, dl->physical);
863 
864   log_Printf(LogPHASE, "%s: Created in %s state\n",
865              dl->name, datalink_State(dl));
866 
867   return dl;
868 }
869 
870 struct datalink *
871 datalink_Clone(struct datalink *odl, const char *name)
872 {
873   struct datalink *dl;
874 
875   dl = (struct datalink *)malloc(sizeof(struct datalink));
876   if (dl == NULL)
877     return dl;
878 
879   dl->desc.type = DATALINK_DESCRIPTOR;
880   dl->desc.UpdateSet = datalink_UpdateSet;
881   dl->desc.IsSet = datalink_IsSet;
882   dl->desc.Read = datalink_Read;
883   dl->desc.Write = datalink_Write;
884 
885   dl->state = DATALINK_CLOSED;
886 
887   memcpy(&dl->cfg, &odl->cfg, sizeof dl->cfg);
888   mp_linkInit(&dl->mp);
889   *dl->phone.list = '\0';
890   dl->phone.next = NULL;
891   dl->phone.alt = NULL;
892   dl->phone.chosen = "N/A";
893   dl->bundle = odl->bundle;
894   dl->next = NULL;
895   memset(&dl->dial.timer, '\0', sizeof dl->dial.timer);
896   dl->dial.tries = 0;
897   dl->reconnect_tries = 0;
898   dl->name = strdup(name);
899   peerid_Init(&dl->peer);
900   dl->parent = odl->parent;
901   memcpy(&dl->fsmp, &odl->fsmp, sizeof dl->fsmp);
902   dl->fsmp.object = dl;
903 
904   if ((dl->physical = physical_Create(dl, PHYS_INTERACTIVE)) == NULL) {
905     free(dl->name);
906     free(dl);
907     return NULL;
908   }
909   pap_Init(&dl->pap, dl->physical);
910   dl->pap.cfg = odl->pap.cfg;
911 
912   chap_Init(&dl->chap, dl->physical);
913   dl->chap.auth.cfg = odl->chap.auth.cfg;
914 
915   memcpy(&dl->physical->cfg, &odl->physical->cfg, sizeof dl->physical->cfg);
916   memcpy(&dl->physical->link.lcp.cfg, &odl->physical->link.lcp.cfg,
917          sizeof dl->physical->link.lcp.cfg);
918   memcpy(&dl->physical->link.ccp.cfg, &odl->physical->link.ccp.cfg,
919          sizeof dl->physical->link.ccp.cfg);
920   memcpy(&dl->physical->async.cfg, &odl->physical->async.cfg,
921          sizeof dl->physical->async.cfg);
922 
923   cbcp_Init(&dl->cbcp, dl->physical);
924 
925   memset(&dl->chat, '\0', sizeof dl->chat);	/* Force buf{start,end} reset */
926   chat_Init(&dl->chat, dl->physical);
927 
928   log_Printf(LogPHASE, "%s: Cloned in %s state\n",
929              dl->name, datalink_State(dl));
930 
931   return dl;
932 }
933 
934 struct datalink *
935 datalink_Destroy(struct datalink *dl)
936 {
937   struct datalink *result;
938 
939   if (dl->state != DATALINK_CLOSED) {
940     log_Printf(LogERROR, "Oops, destroying a datalink in state %s\n",
941               datalink_State(dl));
942     switch (dl->state) {
943       case DATALINK_HANGUP:
944       case DATALINK_DIAL:
945       case DATALINK_LOGIN:
946         chat_Finish(&dl->chat);		/* Gotta blat the timers ! */
947         break;
948     }
949   }
950 
951   chat_Destroy(&dl->chat);
952   timer_Stop(&dl->dial.timer);
953   result = dl->next;
954   physical_Destroy(dl->physical);
955   free(dl->name);
956   free(dl);
957 
958   return result;
959 }
960 
961 void
962 datalink_Up(struct datalink *dl, int runscripts, int packetmode)
963 {
964   if (!Enabled(dl->bundle, OPT_FORCE_SCRIPTS) &&
965       (dl->physical->type & (PHYS_DIRECT|PHYS_DEDICATED)))
966     /* Ignore scripts */
967     runscripts = 0;
968 
969   switch (dl->state) {
970     case DATALINK_CLOSED:
971       if (bundle_Phase(dl->bundle) == PHASE_DEAD ||
972           bundle_Phase(dl->bundle) == PHASE_TERMINATE)
973         bundle_NewPhase(dl->bundle, PHASE_ESTABLISH);
974       datalink_NewState(dl, DATALINK_OPENING);
975       dl->reconnect_tries =
976         dl->physical->type == PHYS_DIRECT ? 0 : dl->cfg.reconnect.max;
977       dl->dial.tries = dl->cfg.dial.max;
978       dl->script.run = runscripts;
979       dl->script.packetmode = packetmode;
980       break;
981 
982     case DATALINK_OPENING:
983       if (!dl->script.run && runscripts)
984         dl->script.run = 1;
985       /* FALLTHROUGH */
986 
987     case DATALINK_DIAL:
988     case DATALINK_LOGIN:
989     case DATALINK_READY:
990       if (!dl->script.packetmode && packetmode) {
991         dl->script.packetmode = 1;
992         if (dl->state == DATALINK_READY) {
993           dl->script.run = 0;
994           datalink_NewState(dl, DATALINK_CARRIER);
995         }
996       }
997       break;
998   }
999 }
1000 
1001 void
1002 datalink_Close(struct datalink *dl, int how)
1003 {
1004   /* Please close */
1005   switch (dl->state) {
1006     case DATALINK_OPEN:
1007       peerid_Init(&dl->peer);
1008       fsm2initial(&dl->physical->link.ccp.fsm);
1009       /* FALLTHROUGH */
1010 
1011     case DATALINK_CBCP:
1012     case DATALINK_AUTH:
1013     case DATALINK_LCP:
1014       datalink_AuthReInit(dl);
1015       if (how == CLOSE_LCP)
1016         datalink_DontHangup(dl);
1017       else if (how == CLOSE_STAYDOWN)
1018         datalink_StayDown(dl);
1019       fsm_Close(&dl->physical->link.lcp.fsm);
1020       break;
1021 
1022     default:
1023       datalink_ComeDown(dl, how);
1024   }
1025 }
1026 
1027 void
1028 datalink_Down(struct datalink *dl, int how)
1029 {
1030   /* Carrier is lost */
1031   switch (dl->state) {
1032     case DATALINK_OPEN:
1033       peerid_Init(&dl->peer);
1034       fsm2initial(&dl->physical->link.ccp.fsm);
1035       /* FALLTHROUGH */
1036 
1037     case DATALINK_CBCP:
1038     case DATALINK_AUTH:
1039     case DATALINK_LCP:
1040       fsm2initial(&dl->physical->link.lcp.fsm);
1041       if (dl->state == DATALINK_OPENING)
1042         return;			/* we're doing a callback... */
1043       /* FALLTHROUGH */
1044 
1045     default:
1046       datalink_ComeDown(dl, how);
1047   }
1048 }
1049 
1050 void
1051 datalink_StayDown(struct datalink *dl)
1052 {
1053   dl->dial.tries = -1;
1054   dl->reconnect_tries = 0;
1055   dl->stayonline = 0;
1056 }
1057 
1058 void
1059 datalink_DontHangup(struct datalink *dl)
1060 {
1061   dl->dial.tries = -1;
1062   dl->reconnect_tries = 0;
1063   dl->stayonline = dl->state >= DATALINK_LCP ? 1 : 0;
1064 }
1065 
1066 int
1067 datalink_Show(struct cmdargs const *arg)
1068 {
1069   prompt_Printf(arg->prompt, "Name: %s\n", arg->cx->name);
1070   prompt_Printf(arg->prompt, " State:              %s\n",
1071                 datalink_State(arg->cx));
1072   prompt_Printf(arg->prompt, " Peer name:          ");
1073   if (*arg->cx->peer.authname)
1074     prompt_Printf(arg->prompt, "%s\n", arg->cx->peer.authname);
1075   else if (arg->cx->state == DATALINK_OPEN)
1076     prompt_Printf(arg->prompt, "None requested\n");
1077   else
1078     prompt_Printf(arg->prompt, "N/A\n");
1079   prompt_Printf(arg->prompt, " Discriminator:      %s\n",
1080                 mp_Enddisc(arg->cx->peer.enddisc.class,
1081                            arg->cx->peer.enddisc.address,
1082                            arg->cx->peer.enddisc.len));
1083 
1084   prompt_Printf(arg->prompt, "\nDefaults:\n");
1085   prompt_Printf(arg->prompt, " Phone List:         %s\n",
1086                 arg->cx->cfg.phone.list);
1087   if (arg->cx->cfg.dial.max)
1088     prompt_Printf(arg->prompt, " Dial tries:         %d, delay ",
1089                   arg->cx->cfg.dial.max);
1090   else
1091     prompt_Printf(arg->prompt, " Dial tries:         infinite, delay ");
1092   if (arg->cx->cfg.dial.next_timeout >= 0)
1093     prompt_Printf(arg->prompt, "%ds/", arg->cx->cfg.dial.next_timeout);
1094   else
1095     prompt_Printf(arg->prompt, "random/");
1096   if (arg->cx->cfg.dial.timeout >= 0)
1097     prompt_Printf(arg->prompt, "%ds\n", arg->cx->cfg.dial.timeout);
1098   else
1099     prompt_Printf(arg->prompt, "random\n");
1100   prompt_Printf(arg->prompt, " Reconnect tries:    %d, delay ",
1101                 arg->cx->cfg.reconnect.max);
1102   if (arg->cx->cfg.reconnect.timeout > 0)
1103     prompt_Printf(arg->prompt, "%ds\n", arg->cx->cfg.reconnect.timeout);
1104   else
1105     prompt_Printf(arg->prompt, "random\n");
1106   prompt_Printf(arg->prompt, " Callback %s ", arg->cx->physical->type ==
1107                 PHYS_DIRECT ?  "accepted: " : "requested:");
1108   if (!arg->cx->cfg.callback.opmask)
1109     prompt_Printf(arg->prompt, "none\n");
1110   else {
1111     int comma = 0;
1112 
1113     if (arg->cx->cfg.callback.opmask & CALLBACK_BIT(CALLBACK_NONE)) {
1114       prompt_Printf(arg->prompt, "none");
1115       comma = 1;
1116     }
1117     if (arg->cx->cfg.callback.opmask & CALLBACK_BIT(CALLBACK_AUTH)) {
1118       prompt_Printf(arg->prompt, "%sauth", comma ? ", " : "");
1119       comma = 1;
1120     }
1121     if (arg->cx->cfg.callback.opmask & CALLBACK_BIT(CALLBACK_E164)) {
1122       prompt_Printf(arg->prompt, "%sE.164", comma ? ", " : "");
1123       if (arg->cx->physical->type != PHYS_DIRECT)
1124         prompt_Printf(arg->prompt, " (%s)", arg->cx->cfg.callback.msg);
1125       comma = 1;
1126     }
1127     if (arg->cx->cfg.callback.opmask & CALLBACK_BIT(CALLBACK_CBCP)) {
1128       prompt_Printf(arg->prompt, "%scbcp\n", comma ? ", " : "");
1129       prompt_Printf(arg->prompt, " CBCP:               delay: %ds\n",
1130                     arg->cx->cfg.cbcp.delay);
1131       prompt_Printf(arg->prompt, "                     phone: ");
1132       if (!strcmp(arg->cx->cfg.cbcp.phone, "*")) {
1133         if (arg->cx->physical->type & PHYS_DIRECT)
1134           prompt_Printf(arg->prompt, "Caller decides\n");
1135         else
1136           prompt_Printf(arg->prompt, "Dialback server decides\n");
1137       } else
1138         prompt_Printf(arg->prompt, "%s\n", arg->cx->cfg.cbcp.phone);
1139       prompt_Printf(arg->prompt, "                     timeout: %lds\n",
1140                     arg->cx->cfg.cbcp.fsmretry);
1141     } else
1142       prompt_Printf(arg->prompt, "\n");
1143   }
1144 
1145   prompt_Printf(arg->prompt, " Dial Script:        %s\n",
1146                 arg->cx->cfg.script.dial);
1147   prompt_Printf(arg->prompt, " Login Script:       %s\n",
1148                 arg->cx->cfg.script.login);
1149   prompt_Printf(arg->prompt, " Logout Script:      %s\n",
1150                 arg->cx->cfg.script.logout);
1151   prompt_Printf(arg->prompt, " Hangup Script:      %s\n",
1152                 arg->cx->cfg.script.hangup);
1153   return 0;
1154 }
1155 
1156 int
1157 datalink_SetReconnect(struct cmdargs const *arg)
1158 {
1159   if (arg->argc == arg->argn+2) {
1160     arg->cx->cfg.reconnect.timeout = atoi(arg->argv[arg->argn]);
1161     arg->cx->cfg.reconnect.max = atoi(arg->argv[arg->argn+1]);
1162     return 0;
1163   }
1164   return -1;
1165 }
1166 
1167 int
1168 datalink_SetRedial(struct cmdargs const *arg)
1169 {
1170   const char *sep, *osep;
1171   int timeout, inc, maxinc, tries;
1172 
1173   if (arg->argc == arg->argn+1 || arg->argc == arg->argn+2) {
1174     if (strncasecmp(arg->argv[arg->argn], "random", 6) == 0 &&
1175 	(arg->argv[arg->argn][6] == '\0' || arg->argv[arg->argn][6] == '.')) {
1176       arg->cx->cfg.dial.timeout = -1;
1177       randinit();
1178     } else {
1179       timeout = atoi(arg->argv[arg->argn]);
1180 
1181       if (timeout >= 0)
1182 	arg->cx->cfg.dial.timeout = timeout;
1183       else {
1184 	log_Printf(LogWARN, "Invalid redial timeout\n");
1185 	return -1;
1186       }
1187     }
1188 
1189     sep = strchr(arg->argv[arg->argn], '+');
1190     if (sep) {
1191       inc = atoi(++sep);
1192       osep = sep;
1193       if (inc >= 0)
1194         arg->cx->cfg.dial.inc = inc;
1195       else {
1196         log_Printf(LogWARN, "Invalid timeout increment\n");
1197         return -1;
1198       }
1199       sep = strchr(sep, '-');
1200       if (sep) {
1201         maxinc = atoi(++sep);
1202         if (maxinc >= 0)
1203           arg->cx->cfg.dial.maxinc = maxinc;
1204         else {
1205           log_Printf(LogWARN, "Invalid maximum timeout increments\n");
1206           return -1;
1207         }
1208       } else {
1209         /* Default timeout increment */
1210         arg->cx->cfg.dial.maxinc = 10;
1211         sep = osep;
1212       }
1213     } else {
1214       /* Default timeout increment & max increment */
1215       arg->cx->cfg.dial.inc = 0;
1216       arg->cx->cfg.dial.maxinc = 10;
1217       sep = arg->argv[arg->argn];
1218     }
1219 
1220     sep = strchr(sep, '.');
1221     if (sep) {
1222       if (strcasecmp(++sep, "random") == 0) {
1223 	arg->cx->cfg.dial.next_timeout = -1;
1224 	randinit();
1225       } else {
1226 	timeout = atoi(sep);
1227 	if (timeout >= 0)
1228 	  arg->cx->cfg.dial.next_timeout = timeout;
1229 	else {
1230 	  log_Printf(LogWARN, "Invalid next redial timeout\n");
1231 	  return -1;
1232 	}
1233       }
1234     } else
1235       /* Default next timeout */
1236       arg->cx->cfg.dial.next_timeout = DIAL_NEXT_TIMEOUT;
1237 
1238     if (arg->argc == arg->argn+2) {
1239       tries = atoi(arg->argv[arg->argn+1]);
1240 
1241       if (tries >= 0) {
1242 	arg->cx->cfg.dial.max = tries;
1243       } else {
1244 	log_Printf(LogWARN, "Invalid retry value\n");
1245 	return 1;
1246       }
1247     }
1248     return 0;
1249   }
1250 
1251   return -1;
1252 }
1253 
1254 static const char * const states[] = {
1255   "closed",
1256   "opening",
1257   "hangup",
1258   "dial",
1259   "carrier",
1260   "logout",
1261   "login",
1262   "ready",
1263   "lcp",
1264   "auth",
1265   "cbcp",
1266   "open"
1267 };
1268 
1269 const char *
1270 datalink_State(struct datalink *dl)
1271 {
1272   if (dl->state < 0 || dl->state >= sizeof states / sizeof states[0])
1273     return "unknown";
1274   return states[dl->state];
1275 }
1276 
1277 static void
1278 datalink_NewState(struct datalink *dl, int state)
1279 {
1280   if (state != dl->state) {
1281     if (state >= 0 && state < sizeof states / sizeof states[0]) {
1282       log_Printf(LogPHASE, "%s: %s -> %s\n", dl->name, datalink_State(dl),
1283                  states[state]);
1284       dl->state = state;
1285     } else
1286       log_Printf(LogERROR, "%s: Can't enter state %d !\n", dl->name, state);
1287   }
1288 }
1289 
1290 struct datalink *
1291 iov2datalink(struct bundle *bundle, struct iovec *iov, int *niov, int maxiov,
1292              int fd, int *auxfd, int *nauxfd)
1293 {
1294   struct datalink *dl, *cdl;
1295   struct fsm_retry copy;
1296   char *oname;
1297 
1298   dl = (struct datalink *)iov[(*niov)++].iov_base;
1299   dl->name = iov[*niov].iov_base;
1300 
1301   if (dl->name[DATALINK_MAXNAME-1]) {
1302     dl->name[DATALINK_MAXNAME-1] = '\0';
1303     if (strlen(dl->name) == DATALINK_MAXNAME - 1)
1304       log_Printf(LogWARN, "Datalink name truncated to \"%s\"\n", dl->name);
1305   }
1306 
1307   /* Make sure the name is unique ! */
1308   oname = NULL;
1309   do {
1310     for (cdl = bundle->links; cdl; cdl = cdl->next)
1311       if (!strcasecmp(dl->name, cdl->name)) {
1312         if (oname)
1313           free(datalink_NextName(dl));
1314         else
1315           oname = datalink_NextName(dl);
1316         break;	/* Keep renaming 'till we have no conflicts */
1317       }
1318   } while (cdl);
1319 
1320   if (oname) {
1321     log_Printf(LogPHASE, "Rename link %s to %s\n", oname, dl->name);
1322     free(oname);
1323   } else {
1324     dl->name = strdup(dl->name);
1325     free(iov[*niov].iov_base);
1326   }
1327   (*niov)++;
1328 
1329   dl->desc.type = DATALINK_DESCRIPTOR;
1330   dl->desc.UpdateSet = datalink_UpdateSet;
1331   dl->desc.IsSet = datalink_IsSet;
1332   dl->desc.Read = datalink_Read;
1333   dl->desc.Write = datalink_Write;
1334 
1335   mp_linkInit(&dl->mp);
1336   *dl->phone.list = '\0';
1337   dl->phone.next = NULL;
1338   dl->phone.alt = NULL;
1339   dl->phone.chosen = "N/A";
1340 
1341   dl->bundle = bundle;
1342   dl->next = NULL;
1343   memset(&dl->dial.timer, '\0', sizeof dl->dial.timer);
1344   dl->dial.tries = 0;
1345   dl->reconnect_tries = 0;
1346   dl->parent = &bundle->fsm;
1347   dl->fsmp.LayerStart = datalink_LayerStart;
1348   dl->fsmp.LayerUp = datalink_LayerUp;
1349   dl->fsmp.LayerDown = datalink_LayerDown;
1350   dl->fsmp.LayerFinish = datalink_LayerFinish;
1351   dl->fsmp.object = dl;
1352 
1353   dl->physical = iov2physical(dl, iov, niov, maxiov, fd, auxfd, nauxfd);
1354 
1355   if (!dl->physical) {
1356     free(dl->name);
1357     free(dl);
1358     dl = NULL;
1359   } else {
1360     copy = dl->pap.cfg.fsm;
1361     pap_Init(&dl->pap, dl->physical);
1362     dl->pap.cfg.fsm = copy;
1363 
1364     copy = dl->chap.auth.cfg.fsm;
1365     chap_Init(&dl->chap, dl->physical);
1366     dl->chap.auth.cfg.fsm = copy;
1367 
1368     cbcp_Init(&dl->cbcp, dl->physical);
1369 
1370     memset(&dl->chat, '\0', sizeof dl->chat);	/* Force buf{start,end} reset */
1371     chat_Init(&dl->chat, dl->physical);
1372 
1373     log_Printf(LogPHASE, "%s: Transferred in %s state\n",
1374               dl->name, datalink_State(dl));
1375   }
1376 
1377   return dl;
1378 }
1379 
1380 int
1381 datalink2iov(struct datalink *dl, struct iovec *iov, int *niov, int maxiov,
1382              int *auxfd, int *nauxfd)
1383 {
1384   /* If `dl' is NULL, we're allocating before a Fromiov() */
1385   int link_fd;
1386 
1387   if (dl) {
1388     timer_Stop(&dl->dial.timer);
1389     /* The following is purely for the sake of paranoia */
1390     cbcp_Down(&dl->cbcp);
1391     timer_Stop(&dl->pap.authtimer);
1392     timer_Stop(&dl->chap.auth.authtimer);
1393   }
1394 
1395   if (*niov >= maxiov - 1) {
1396     log_Printf(LogERROR, "Toiov: No room for datalink !\n");
1397     if (dl) {
1398       free(dl->name);
1399       free(dl);
1400     }
1401     return -1;
1402   }
1403 
1404   iov[*niov].iov_base = (void *)dl;
1405   iov[(*niov)++].iov_len = sizeof *dl;
1406   iov[*niov].iov_base = dl ? realloc(dl->name, DATALINK_MAXNAME) : NULL;
1407   iov[(*niov)++].iov_len = DATALINK_MAXNAME;
1408 
1409   link_fd = physical2iov(dl ? dl->physical : NULL, iov, niov, maxiov, auxfd,
1410                          nauxfd);
1411 
1412   if (link_fd == -1 && dl) {
1413     free(dl->name);
1414     free(dl);
1415   }
1416 
1417   return link_fd;
1418 }
1419 
1420 void
1421 datalink_Rename(struct datalink *dl, const char *name)
1422 {
1423   free(dl->name);
1424   dl->physical->link.name = dl->name = strdup(name);
1425 }
1426 
1427 char *
1428 datalink_NextName(struct datalink *dl)
1429 {
1430   int f, n;
1431   char *name, *oname;
1432 
1433   n = strlen(dl->name);
1434   name = (char *)malloc(n+3);
1435   for (f = n - 1; f >= 0; f--)
1436     if (!isdigit(dl->name[f]))
1437       break;
1438   n = sprintf(name, "%.*s-", dl->name[f] == '-' ? f : f + 1, dl->name);
1439   sprintf(name + n, "%d", atoi(dl->name + f + 1) + 1);
1440   oname = dl->name;
1441   dl->name = name;
1442   /* our physical link name isn't updated (it probably isn't created yet) */
1443   return oname;
1444 }
1445 
1446 int
1447 datalink_SetMode(struct datalink *dl, int mode)
1448 {
1449   if (!physical_SetMode(dl->physical, mode))
1450     return 0;
1451   if (dl->physical->type & (PHYS_DIRECT|PHYS_DEDICATED))
1452     dl->script.run = 0;
1453   if (dl->physical->type == PHYS_DIRECT)
1454     dl->reconnect_tries = 0;
1455   if (mode & (PHYS_DDIAL|PHYS_BACKGROUND|PHYS_FOREGROUND) &&
1456       dl->state <= DATALINK_READY)
1457     datalink_Up(dl, 1, 1);
1458   return 1;
1459 }
1460 
1461 int
1462 datalink_GetDialTimeout(struct datalink *dl)
1463 {
1464   int result = dl->cfg.dial.timeout + dl->dial.incs * dl->cfg.dial.inc;
1465 
1466   if (dl->dial.incs < dl->cfg.dial.maxinc)
1467     dl->dial.incs++;
1468 
1469   return result;
1470 }
1471