xref: /freebsd/usr.sbin/ppp/datalink.c (revision 6780ab54325a71e7e70112b11657973edde8655e)
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 (dl->physical->type & (PHYS_DIRECT|PHYS_DEDICATED))
965     /* Ignore scripts */
966     runscripts = 0;
967 
968   switch (dl->state) {
969     case DATALINK_CLOSED:
970       if (bundle_Phase(dl->bundle) == PHASE_DEAD ||
971           bundle_Phase(dl->bundle) == PHASE_TERMINATE)
972         bundle_NewPhase(dl->bundle, PHASE_ESTABLISH);
973       datalink_NewState(dl, DATALINK_OPENING);
974       dl->reconnect_tries =
975         dl->physical->type == PHYS_DIRECT ? 0 : dl->cfg.reconnect.max;
976       dl->dial.tries = dl->cfg.dial.max;
977       dl->script.run = runscripts;
978       dl->script.packetmode = packetmode;
979       break;
980 
981     case DATALINK_OPENING:
982       if (!dl->script.run && runscripts)
983         dl->script.run = 1;
984       /* FALLTHROUGH */
985 
986     case DATALINK_DIAL:
987     case DATALINK_LOGIN:
988     case DATALINK_READY:
989       if (!dl->script.packetmode && packetmode) {
990         dl->script.packetmode = 1;
991         if (dl->state == DATALINK_READY) {
992           dl->script.run = 0;
993           datalink_NewState(dl, DATALINK_CARRIER);
994         }
995       }
996       break;
997   }
998 }
999 
1000 void
1001 datalink_Close(struct datalink *dl, int how)
1002 {
1003   /* Please close */
1004   switch (dl->state) {
1005     case DATALINK_OPEN:
1006       peerid_Init(&dl->peer);
1007       fsm2initial(&dl->physical->link.ccp.fsm);
1008       /* FALLTHROUGH */
1009 
1010     case DATALINK_CBCP:
1011     case DATALINK_AUTH:
1012     case DATALINK_LCP:
1013       datalink_AuthReInit(dl);
1014       if (how == CLOSE_LCP)
1015         datalink_DontHangup(dl);
1016       else if (how == CLOSE_STAYDOWN)
1017         datalink_StayDown(dl);
1018       fsm_Close(&dl->physical->link.lcp.fsm);
1019       break;
1020 
1021     default:
1022       datalink_ComeDown(dl, how);
1023   }
1024 }
1025 
1026 void
1027 datalink_Down(struct datalink *dl, int how)
1028 {
1029   /* Carrier is lost */
1030   switch (dl->state) {
1031     case DATALINK_OPEN:
1032       peerid_Init(&dl->peer);
1033       fsm2initial(&dl->physical->link.ccp.fsm);
1034       /* FALLTHROUGH */
1035 
1036     case DATALINK_CBCP:
1037     case DATALINK_AUTH:
1038     case DATALINK_LCP:
1039       fsm2initial(&dl->physical->link.lcp.fsm);
1040       if (dl->state == DATALINK_OPENING)
1041         return;			/* we're doing a callback... */
1042       /* FALLTHROUGH */
1043 
1044     default:
1045       datalink_ComeDown(dl, how);
1046   }
1047 }
1048 
1049 void
1050 datalink_StayDown(struct datalink *dl)
1051 {
1052   dl->dial.tries = -1;
1053   dl->reconnect_tries = 0;
1054   dl->stayonline = 0;
1055 }
1056 
1057 void
1058 datalink_DontHangup(struct datalink *dl)
1059 {
1060   dl->dial.tries = -1;
1061   dl->reconnect_tries = 0;
1062   dl->stayonline = dl->state >= DATALINK_LCP ? 1 : 0;
1063 }
1064 
1065 int
1066 datalink_Show(struct cmdargs const *arg)
1067 {
1068   prompt_Printf(arg->prompt, "Name: %s\n", arg->cx->name);
1069   prompt_Printf(arg->prompt, " State:              %s\n",
1070                 datalink_State(arg->cx));
1071   prompt_Printf(arg->prompt, " Peer name:          ");
1072   if (*arg->cx->peer.authname)
1073     prompt_Printf(arg->prompt, "%s\n", arg->cx->peer.authname);
1074   else if (arg->cx->state == DATALINK_OPEN)
1075     prompt_Printf(arg->prompt, "None requested\n");
1076   else
1077     prompt_Printf(arg->prompt, "N/A\n");
1078   prompt_Printf(arg->prompt, " Discriminator:      %s\n",
1079                 mp_Enddisc(arg->cx->peer.enddisc.class,
1080                            arg->cx->peer.enddisc.address,
1081                            arg->cx->peer.enddisc.len));
1082 
1083   prompt_Printf(arg->prompt, "\nDefaults:\n");
1084   prompt_Printf(arg->prompt, " Phone List:         %s\n",
1085                 arg->cx->cfg.phone.list);
1086   if (arg->cx->cfg.dial.max)
1087     prompt_Printf(arg->prompt, " Dial tries:         %d, delay ",
1088                   arg->cx->cfg.dial.max);
1089   else
1090     prompt_Printf(arg->prompt, " Dial tries:         infinite, delay ");
1091   if (arg->cx->cfg.dial.next_timeout >= 0)
1092     prompt_Printf(arg->prompt, "%ds/", arg->cx->cfg.dial.next_timeout);
1093   else
1094     prompt_Printf(arg->prompt, "random/");
1095   if (arg->cx->cfg.dial.timeout >= 0)
1096     prompt_Printf(arg->prompt, "%ds\n", arg->cx->cfg.dial.timeout);
1097   else
1098     prompt_Printf(arg->prompt, "random\n");
1099   prompt_Printf(arg->prompt, " Reconnect tries:    %d, delay ",
1100                 arg->cx->cfg.reconnect.max);
1101   if (arg->cx->cfg.reconnect.timeout > 0)
1102     prompt_Printf(arg->prompt, "%ds\n", arg->cx->cfg.reconnect.timeout);
1103   else
1104     prompt_Printf(arg->prompt, "random\n");
1105   prompt_Printf(arg->prompt, " Callback %s ", arg->cx->physical->type ==
1106                 PHYS_DIRECT ?  "accepted: " : "requested:");
1107   if (!arg->cx->cfg.callback.opmask)
1108     prompt_Printf(arg->prompt, "none\n");
1109   else {
1110     int comma = 0;
1111 
1112     if (arg->cx->cfg.callback.opmask & CALLBACK_BIT(CALLBACK_NONE)) {
1113       prompt_Printf(arg->prompt, "none");
1114       comma = 1;
1115     }
1116     if (arg->cx->cfg.callback.opmask & CALLBACK_BIT(CALLBACK_AUTH)) {
1117       prompt_Printf(arg->prompt, "%sauth", comma ? ", " : "");
1118       comma = 1;
1119     }
1120     if (arg->cx->cfg.callback.opmask & CALLBACK_BIT(CALLBACK_E164)) {
1121       prompt_Printf(arg->prompt, "%sE.164", comma ? ", " : "");
1122       if (arg->cx->physical->type != PHYS_DIRECT)
1123         prompt_Printf(arg->prompt, " (%s)", arg->cx->cfg.callback.msg);
1124       comma = 1;
1125     }
1126     if (arg->cx->cfg.callback.opmask & CALLBACK_BIT(CALLBACK_CBCP)) {
1127       prompt_Printf(arg->prompt, "%scbcp\n", comma ? ", " : "");
1128       prompt_Printf(arg->prompt, " CBCP:               delay: %ds\n",
1129                     arg->cx->cfg.cbcp.delay);
1130       prompt_Printf(arg->prompt, "                     phone: ");
1131       if (!strcmp(arg->cx->cfg.cbcp.phone, "*")) {
1132         if (arg->cx->physical->type & PHYS_DIRECT)
1133           prompt_Printf(arg->prompt, "Caller decides\n");
1134         else
1135           prompt_Printf(arg->prompt, "Dialback server decides\n");
1136       } else
1137         prompt_Printf(arg->prompt, "%s\n", arg->cx->cfg.cbcp.phone);
1138       prompt_Printf(arg->prompt, "                     timeout: %lds\n",
1139                     arg->cx->cfg.cbcp.fsmretry);
1140     } else
1141       prompt_Printf(arg->prompt, "\n");
1142   }
1143 
1144   prompt_Printf(arg->prompt, " Dial Script:        %s\n",
1145                 arg->cx->cfg.script.dial);
1146   prompt_Printf(arg->prompt, " Login Script:       %s\n",
1147                 arg->cx->cfg.script.login);
1148   prompt_Printf(arg->prompt, " Logout Script:      %s\n",
1149                 arg->cx->cfg.script.logout);
1150   prompt_Printf(arg->prompt, " Hangup Script:      %s\n",
1151                 arg->cx->cfg.script.hangup);
1152   return 0;
1153 }
1154 
1155 int
1156 datalink_SetReconnect(struct cmdargs const *arg)
1157 {
1158   if (arg->argc == arg->argn+2) {
1159     arg->cx->cfg.reconnect.timeout = atoi(arg->argv[arg->argn]);
1160     arg->cx->cfg.reconnect.max = atoi(arg->argv[arg->argn+1]);
1161     return 0;
1162   }
1163   return -1;
1164 }
1165 
1166 int
1167 datalink_SetRedial(struct cmdargs const *arg)
1168 {
1169   const char *sep, *osep;
1170   int timeout, inc, maxinc, tries;
1171 
1172   if (arg->argc == arg->argn+1 || arg->argc == arg->argn+2) {
1173     if (strncasecmp(arg->argv[arg->argn], "random", 6) == 0 &&
1174 	(arg->argv[arg->argn][6] == '\0' || arg->argv[arg->argn][6] == '.')) {
1175       arg->cx->cfg.dial.timeout = -1;
1176       randinit();
1177     } else {
1178       timeout = atoi(arg->argv[arg->argn]);
1179 
1180       if (timeout >= 0)
1181 	arg->cx->cfg.dial.timeout = timeout;
1182       else {
1183 	log_Printf(LogWARN, "Invalid redial timeout\n");
1184 	return -1;
1185       }
1186     }
1187 
1188     sep = strchr(arg->argv[arg->argn], '+');
1189     if (sep) {
1190       inc = atoi(++sep);
1191       osep = sep;
1192       if (inc >= 0)
1193         arg->cx->cfg.dial.inc = inc;
1194       else {
1195         log_Printf(LogWARN, "Invalid timeout increment\n");
1196         return -1;
1197       }
1198       sep = strchr(sep, '-');
1199       if (sep) {
1200         maxinc = atoi(++sep);
1201         if (maxinc >= 0)
1202           arg->cx->cfg.dial.maxinc = maxinc;
1203         else {
1204           log_Printf(LogWARN, "Invalid maximum timeout increments\n");
1205           return -1;
1206         }
1207       } else {
1208         /* Default timeout increment */
1209         arg->cx->cfg.dial.maxinc = 10;
1210         sep = osep;
1211       }
1212     } else {
1213       /* Default timeout increment & max increment */
1214       arg->cx->cfg.dial.inc = 0;
1215       arg->cx->cfg.dial.maxinc = 10;
1216       sep = arg->argv[arg->argn];
1217     }
1218 
1219     sep = strchr(sep, '.');
1220     if (sep) {
1221       if (strcasecmp(++sep, "random") == 0) {
1222 	arg->cx->cfg.dial.next_timeout = -1;
1223 	randinit();
1224       } else {
1225 	timeout = atoi(sep);
1226 	if (timeout >= 0)
1227 	  arg->cx->cfg.dial.next_timeout = timeout;
1228 	else {
1229 	  log_Printf(LogWARN, "Invalid next redial timeout\n");
1230 	  return -1;
1231 	}
1232       }
1233     } else
1234       /* Default next timeout */
1235       arg->cx->cfg.dial.next_timeout = DIAL_NEXT_TIMEOUT;
1236 
1237     if (arg->argc == arg->argn+2) {
1238       tries = atoi(arg->argv[arg->argn+1]);
1239 
1240       if (tries >= 0) {
1241 	arg->cx->cfg.dial.max = tries;
1242       } else {
1243 	log_Printf(LogWARN, "Invalid retry value\n");
1244 	return 1;
1245       }
1246     }
1247     return 0;
1248   }
1249 
1250   return -1;
1251 }
1252 
1253 static const char * const states[] = {
1254   "closed",
1255   "opening",
1256   "hangup",
1257   "dial",
1258   "carrier",
1259   "logout",
1260   "login",
1261   "ready",
1262   "lcp",
1263   "auth",
1264   "cbcp",
1265   "open"
1266 };
1267 
1268 const char *
1269 datalink_State(struct datalink *dl)
1270 {
1271   if (dl->state < 0 || dl->state >= sizeof states / sizeof states[0])
1272     return "unknown";
1273   return states[dl->state];
1274 }
1275 
1276 static void
1277 datalink_NewState(struct datalink *dl, int state)
1278 {
1279   if (state != dl->state) {
1280     if (state >= 0 && state < sizeof states / sizeof states[0]) {
1281       log_Printf(LogPHASE, "%s: %s -> %s\n", dl->name, datalink_State(dl),
1282                  states[state]);
1283       dl->state = state;
1284     } else
1285       log_Printf(LogERROR, "%s: Can't enter state %d !\n", dl->name, state);
1286   }
1287 }
1288 
1289 struct datalink *
1290 iov2datalink(struct bundle *bundle, struct iovec *iov, int *niov, int maxiov,
1291              int fd, int *auxfd, int *nauxfd)
1292 {
1293   struct datalink *dl, *cdl;
1294   struct fsm_retry copy;
1295   char *oname;
1296 
1297   dl = (struct datalink *)iov[(*niov)++].iov_base;
1298   dl->name = iov[*niov].iov_base;
1299 
1300   if (dl->name[DATALINK_MAXNAME-1]) {
1301     dl->name[DATALINK_MAXNAME-1] = '\0';
1302     if (strlen(dl->name) == DATALINK_MAXNAME - 1)
1303       log_Printf(LogWARN, "Datalink name truncated to \"%s\"\n", dl->name);
1304   }
1305 
1306   /* Make sure the name is unique ! */
1307   oname = NULL;
1308   do {
1309     for (cdl = bundle->links; cdl; cdl = cdl->next)
1310       if (!strcasecmp(dl->name, cdl->name)) {
1311         if (oname)
1312           free(datalink_NextName(dl));
1313         else
1314           oname = datalink_NextName(dl);
1315         break;	/* Keep renaming 'till we have no conflicts */
1316       }
1317   } while (cdl);
1318 
1319   if (oname) {
1320     log_Printf(LogPHASE, "Rename link %s to %s\n", oname, dl->name);
1321     free(oname);
1322   } else {
1323     dl->name = strdup(dl->name);
1324     free(iov[*niov].iov_base);
1325   }
1326   (*niov)++;
1327 
1328   dl->desc.type = DATALINK_DESCRIPTOR;
1329   dl->desc.UpdateSet = datalink_UpdateSet;
1330   dl->desc.IsSet = datalink_IsSet;
1331   dl->desc.Read = datalink_Read;
1332   dl->desc.Write = datalink_Write;
1333 
1334   mp_linkInit(&dl->mp);
1335   *dl->phone.list = '\0';
1336   dl->phone.next = NULL;
1337   dl->phone.alt = NULL;
1338   dl->phone.chosen = "N/A";
1339 
1340   dl->bundle = bundle;
1341   dl->next = NULL;
1342   memset(&dl->dial.timer, '\0', sizeof dl->dial.timer);
1343   dl->dial.tries = 0;
1344   dl->reconnect_tries = 0;
1345   dl->parent = &bundle->fsm;
1346   dl->fsmp.LayerStart = datalink_LayerStart;
1347   dl->fsmp.LayerUp = datalink_LayerUp;
1348   dl->fsmp.LayerDown = datalink_LayerDown;
1349   dl->fsmp.LayerFinish = datalink_LayerFinish;
1350   dl->fsmp.object = dl;
1351 
1352   dl->physical = iov2physical(dl, iov, niov, maxiov, fd, auxfd, nauxfd);
1353 
1354   if (!dl->physical) {
1355     free(dl->name);
1356     free(dl);
1357     dl = NULL;
1358   } else {
1359     copy = dl->pap.cfg.fsm;
1360     pap_Init(&dl->pap, dl->physical);
1361     dl->pap.cfg.fsm = copy;
1362 
1363     copy = dl->chap.auth.cfg.fsm;
1364     chap_Init(&dl->chap, dl->physical);
1365     dl->chap.auth.cfg.fsm = copy;
1366 
1367     cbcp_Init(&dl->cbcp, dl->physical);
1368 
1369     memset(&dl->chat, '\0', sizeof dl->chat);	/* Force buf{start,end} reset */
1370     chat_Init(&dl->chat, dl->physical);
1371 
1372     log_Printf(LogPHASE, "%s: Transferred in %s state\n",
1373               dl->name, datalink_State(dl));
1374   }
1375 
1376   return dl;
1377 }
1378 
1379 int
1380 datalink2iov(struct datalink *dl, struct iovec *iov, int *niov, int maxiov,
1381              int *auxfd, int *nauxfd)
1382 {
1383   /* If `dl' is NULL, we're allocating before a Fromiov() */
1384   int link_fd;
1385 
1386   if (dl) {
1387     timer_Stop(&dl->dial.timer);
1388     /* The following is purely for the sake of paranoia */
1389     cbcp_Down(&dl->cbcp);
1390     timer_Stop(&dl->pap.authtimer);
1391     timer_Stop(&dl->chap.auth.authtimer);
1392   }
1393 
1394   if (*niov >= maxiov - 1) {
1395     log_Printf(LogERROR, "Toiov: No room for datalink !\n");
1396     if (dl) {
1397       free(dl->name);
1398       free(dl);
1399     }
1400     return -1;
1401   }
1402 
1403   iov[*niov].iov_base = (void *)dl;
1404   iov[(*niov)++].iov_len = sizeof *dl;
1405   iov[*niov].iov_base = dl ? realloc(dl->name, DATALINK_MAXNAME) : NULL;
1406   iov[(*niov)++].iov_len = DATALINK_MAXNAME;
1407 
1408   link_fd = physical2iov(dl ? dl->physical : NULL, iov, niov, maxiov, auxfd,
1409                          nauxfd);
1410 
1411   if (link_fd == -1 && dl) {
1412     free(dl->name);
1413     free(dl);
1414   }
1415 
1416   return link_fd;
1417 }
1418 
1419 void
1420 datalink_Rename(struct datalink *dl, const char *name)
1421 {
1422   free(dl->name);
1423   dl->physical->link.name = dl->name = strdup(name);
1424 }
1425 
1426 char *
1427 datalink_NextName(struct datalink *dl)
1428 {
1429   int f, n;
1430   char *name, *oname;
1431 
1432   n = strlen(dl->name);
1433   name = (char *)malloc(n+3);
1434   for (f = n - 1; f >= 0; f--)
1435     if (!isdigit(dl->name[f]))
1436       break;
1437   n = sprintf(name, "%.*s-", dl->name[f] == '-' ? f : f + 1, dl->name);
1438   sprintf(name + n, "%d", atoi(dl->name + f + 1) + 1);
1439   oname = dl->name;
1440   dl->name = name;
1441   /* our physical link name isn't updated (it probably isn't created yet) */
1442   return oname;
1443 }
1444 
1445 int
1446 datalink_SetMode(struct datalink *dl, int mode)
1447 {
1448   if (!physical_SetMode(dl->physical, mode))
1449     return 0;
1450   if (dl->physical->type & (PHYS_DIRECT|PHYS_DEDICATED))
1451     dl->script.run = 0;
1452   if (dl->physical->type == PHYS_DIRECT)
1453     dl->reconnect_tries = 0;
1454   if (mode & (PHYS_DDIAL|PHYS_BACKGROUND|PHYS_FOREGROUND) &&
1455       dl->state <= DATALINK_READY)
1456     datalink_Up(dl, 1, 1);
1457   return 1;
1458 }
1459 
1460 int
1461 datalink_GetDialTimeout(struct datalink *dl)
1462 {
1463   int result = dl->cfg.dial.timeout + dl->dial.incs * dl->cfg.dial.inc;
1464 
1465   if (dl->dial.incs < dl->cfg.dial.maxinc)
1466     dl->dial.incs++;
1467 
1468   return result;
1469 }
1470