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