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