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