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