datalink.c revision 37360
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.15 1998/06/30 23:04:14 brian Exp $
27 */
28
29#include <sys/types.h>
30#include <netinet/in.h>
31#include <netinet/in_systm.h>
32#include <netinet/ip.h>
33#include <sys/un.h>
34
35#include <ctype.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <sys/uio.h>
40#include <termios.h>
41
42#include "mbuf.h"
43#include "log.h"
44#include "defs.h"
45#include "timer.h"
46#include "fsm.h"
47#include "lcp.h"
48#include "descriptor.h"
49#include "lqr.h"
50#include "hdlc.h"
51#include "async.h"
52#include "throughput.h"
53#include "ccp.h"
54#include "link.h"
55#include "physical.h"
56#include "iplist.h"
57#include "slcompress.h"
58#include "ipcp.h"
59#include "filter.h"
60#include "mp.h"
61#include "bundle.h"
62#include "chat.h"
63#include "auth.h"
64#include "modem.h"
65#include "prompt.h"
66#include "lcpproto.h"
67#include "pap.h"
68#include "chap.h"
69#include "command.h"
70#include "datalink.h"
71
72static void datalink_LoginDone(struct datalink *);
73static void datalink_NewState(struct datalink *, int);
74
75static void
76datalink_OpenTimeout(void *v)
77{
78  struct datalink *dl = (struct datalink *)v;
79
80  timer_Stop(&dl->dial_timer);
81  if (dl->state == DATALINK_OPENING)
82    log_Printf(LogPHASE, "%s: Redial timer expired.\n", dl->name);
83}
84
85static void
86datalink_StartDialTimer(struct datalink *dl, int Timeout)
87{
88  timer_Stop(&dl->dial_timer);
89
90  if (Timeout) {
91    if (Timeout > 0)
92      dl->dial_timer.load = Timeout * SECTICKS;
93    else
94      dl->dial_timer.load = (random() % DIAL_TIMEOUT) * SECTICKS;
95    dl->dial_timer.func = datalink_OpenTimeout;
96    dl->dial_timer.name = "dial";
97    dl->dial_timer.arg = dl;
98    timer_Start(&dl->dial_timer);
99    if (dl->state == DATALINK_OPENING)
100      log_Printf(LogPHASE, "%s: Enter pause (%d) for redialing.\n",
101                dl->name, Timeout);
102  }
103}
104
105static void
106datalink_HangupDone(struct datalink *dl)
107{
108  if (dl->physical->type == PHYS_DEDICATED && !dl->bundle->CleaningUp &&
109      physical_GetFD(dl->physical) != -1) {
110    /* Don't close our modem if the link is dedicated */
111    datalink_LoginDone(dl);
112    return;
113  }
114
115  modem_Close(dl->physical);
116  dl->phone.chosen = "N/A";
117
118  if (dl->bundle->CleaningUp ||
119      (dl->physical->type == PHYS_DIRECT) ||
120      ((!dl->dial_tries || (dl->dial_tries < 0 && !dl->reconnect_tries)) &&
121       !(dl->physical->type & (PHYS_DDIAL|PHYS_DEDICATED)))) {
122    datalink_NewState(dl, DATALINK_CLOSED);
123    dl->dial_tries = -1;
124    dl->reconnect_tries = 0;
125    bundle_LinkClosed(dl->bundle, dl);
126    if (!dl->bundle->CleaningUp)
127      datalink_StartDialTimer(dl, dl->cfg.dial.timeout);
128  } else {
129    datalink_NewState(dl, DATALINK_OPENING);
130    if (dl->dial_tries < 0) {
131      datalink_StartDialTimer(dl, dl->cfg.reconnect.timeout);
132      dl->dial_tries = dl->cfg.dial.max;
133      dl->reconnect_tries--;
134    } else {
135      if (dl->phone.next == NULL)
136        datalink_StartDialTimer(dl, dl->cfg.dial.timeout);
137      else
138        datalink_StartDialTimer(dl, dl->cfg.dial.next_timeout);
139    }
140  }
141}
142
143static const char *
144datalink_ChoosePhoneNumber(struct datalink *dl)
145{
146  char *phone;
147
148  if (dl->phone.alt == NULL) {
149    if (dl->phone.next == NULL) {
150      strncpy(dl->phone.list, dl->cfg.phone.list, sizeof dl->phone.list - 1);
151      dl->phone.list[sizeof dl->phone.list - 1] = '\0';
152      dl->phone.next = dl->phone.list;
153    }
154    dl->phone.alt = strsep(&dl->phone.next, ":");
155  }
156  phone = strsep(&dl->phone.alt, "|");
157  dl->phone.chosen = *phone ? phone : "[NONE]";
158  if (*phone)
159    log_Printf(LogPHASE, "Phone: %s\n", phone);
160  return phone;
161}
162
163static void
164datalink_LoginDone(struct datalink *dl)
165{
166  if (!dl->script.packetmode) {
167    dl->dial_tries = -1;
168    datalink_NewState(dl, DATALINK_READY);
169  } else if (modem_Raw(dl->physical, dl->bundle) < 0) {
170    dl->dial_tries = 0;
171    log_Printf(LogWARN, "datalink_LoginDone: Not connected.\n");
172    if (dl->script.run) {
173      datalink_NewState(dl, DATALINK_HANGUP);
174      modem_Offline(dl->physical);
175      chat_Init(&dl->chat, dl->physical, dl->cfg.script.hangup, 1, NULL);
176    } else {
177      timer_Stop(&dl->physical->Timer);
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);	/* Is this required ? */
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    timer_Stop(&dl->physical->Timer);
407    datalink_NewState(dl, DATALINK_READY);
408  } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP) {
409    modem_Offline(dl->physical);
410    if (dl->script.run && dl->state != DATALINK_OPENING) {
411      datalink_NewState(dl, DATALINK_HANGUP);
412      chat_Init(&dl->chat, dl->physical, dl->cfg.script.hangup, 1, NULL);
413    } else
414      datalink_HangupDone(dl);
415  }
416}
417
418static void
419datalink_LayerStart(void *v, struct fsm *fp)
420{
421  /* The given FSM is about to start up ! */
422  struct datalink *dl = (struct datalink *)v;
423
424  if (fp->proto == PROTO_LCP)
425    (*dl->parent->LayerStart)(dl->parent->object, fp);
426}
427
428static void
429datalink_LayerUp(void *v, struct fsm *fp)
430{
431  /* The given fsm is now up */
432  struct datalink *dl = (struct datalink *)v;
433
434  if (fp->proto == PROTO_LCP) {
435    datalink_GotAuthname(dl, "", 0);
436    dl->physical->link.lcp.auth_ineed = dl->physical->link.lcp.want_auth;
437    dl->physical->link.lcp.auth_iwait = dl->physical->link.lcp.his_auth;
438    if (dl->physical->link.lcp.his_auth || dl->physical->link.lcp.want_auth) {
439      if (bundle_Phase(dl->bundle) == PHASE_ESTABLISH)
440        bundle_NewPhase(dl->bundle, PHASE_AUTHENTICATE);
441      log_Printf(LogPHASE, "%s: his = %s, mine = %s\n", dl->name,
442                Auth2Nam(dl->physical->link.lcp.his_auth),
443                Auth2Nam(dl->physical->link.lcp.want_auth));
444      if (dl->physical->link.lcp.his_auth == PROTO_PAP)
445        auth_StartChallenge(&dl->pap, dl->physical, pap_SendChallenge);
446      if (dl->physical->link.lcp.want_auth == PROTO_CHAP)
447        auth_StartChallenge(&dl->chap.auth, dl->physical, chap_SendChallenge);
448    } else
449      datalink_AuthOk(dl);
450  }
451}
452
453void
454datalink_GotAuthname(struct datalink *dl, const char *name, int len)
455{
456  if (len >= sizeof dl->peer.authname)
457    len = sizeof dl->peer.authname - 1;
458  strncpy(dl->peer.authname, name, len);
459  dl->peer.authname[len] = '\0';
460}
461
462void
463datalink_AuthOk(struct datalink *dl)
464{
465  int ccpok = ccp_SetOpenMode(&dl->physical->link.ccp);
466
467  if (dl->physical->link.lcp.want_mrru && dl->physical->link.lcp.his_mrru) {
468    /* we've authenticated in multilink mode ! */
469    switch (mp_Up(&dl->bundle->ncp.mp, dl)) {
470      case MP_LINKSENT:
471        /* We've handed the link off to another ppp (well, we will soon) ! */
472        return;
473      case MP_UP:
474        /* First link in the bundle */
475        auth_Select(dl->bundle, dl->peer.authname, dl->physical);
476        /* fall through */
477      case MP_ADDED:
478        /* We're in multilink mode ! */
479        dl->physical->link.ccp.fsm.open_mode = OPEN_PASSIVE;	/* override */
480        break;
481      case MP_FAILED:
482        datalink_AuthNotOk(dl);
483        return;
484    }
485  } else if (bundle_Phase(dl->bundle) == PHASE_NETWORK) {
486    log_Printf(LogPHASE, "%s: Already in NETWORK phase\n", dl->name);
487    datalink_NewState(dl, DATALINK_OPEN);
488    (*dl->parent->LayerUp)(dl->parent->object, &dl->physical->link.lcp.fsm);
489    return;
490  } else {
491    dl->bundle->ncp.mp.peer = dl->peer;
492    ipcp_SetLink(&dl->bundle->ncp.ipcp, &dl->physical->link);
493    auth_Select(dl->bundle, dl->peer.authname, dl->physical);
494  }
495
496  if (ccpok) {
497    fsm_Up(&dl->physical->link.ccp.fsm);
498    fsm_Open(&dl->physical->link.ccp.fsm);
499  }
500  datalink_NewState(dl, DATALINK_OPEN);
501  bundle_NewPhase(dl->bundle, PHASE_NETWORK);
502  (*dl->parent->LayerUp)(dl->parent->object, &dl->physical->link.lcp.fsm);
503}
504
505void
506datalink_AuthNotOk(struct datalink *dl)
507{
508  datalink_NewState(dl, DATALINK_LCP);
509  fsm_Close(&dl->physical->link.lcp.fsm);
510}
511
512static void
513datalink_LayerDown(void *v, struct fsm *fp)
514{
515  /* The given FSM has been told to come down */
516  struct datalink *dl = (struct datalink *)v;
517
518  if (fp->proto == PROTO_LCP) {
519    switch (dl->state) {
520      case DATALINK_OPEN:
521        peerid_Init(&dl->peer);
522        fsm2initial(&dl->physical->link.ccp.fsm);
523        datalink_NewState(dl, DATALINK_LCP);  /* before parent TLD */
524        (*dl->parent->LayerDown)(dl->parent->object, fp);
525        /* fall through */
526
527      case DATALINK_AUTH:
528        timer_Stop(&dl->pap.authtimer);
529        timer_Stop(&dl->chap.auth.authtimer);
530    }
531    datalink_NewState(dl, DATALINK_LCP);
532  }
533}
534
535static void
536datalink_LayerFinish(void *v, struct fsm *fp)
537{
538  /* The given fsm is now down */
539  struct datalink *dl = (struct datalink *)v;
540
541  if (fp->proto == PROTO_LCP) {
542    fsm2initial(fp);
543    (*dl->parent->LayerFinish)(dl->parent->object, fp);
544    datalink_ComeDown(dl, CLOSE_NORMAL);
545  } else if (fp->state == ST_CLOSED && fp->open_mode == OPEN_PASSIVE)
546    fsm_Open(fp);		/* CCP goes to ST_STOPPED */
547}
548
549struct datalink *
550datalink_Create(const char *name, struct bundle *bundle, int type)
551{
552  struct datalink *dl;
553
554  dl = (struct datalink *)malloc(sizeof(struct datalink));
555  if (dl == NULL)
556    return dl;
557
558  dl->desc.type = DATALINK_DESCRIPTOR;
559  dl->desc.UpdateSet = datalink_UpdateSet;
560  dl->desc.IsSet = datalink_IsSet;
561  dl->desc.Read = datalink_Read;
562  dl->desc.Write = datalink_Write;
563
564  dl->state = DATALINK_CLOSED;
565
566  *dl->cfg.script.dial = '\0';
567  *dl->cfg.script.login = '\0';
568  *dl->cfg.script.hangup = '\0';
569  *dl->cfg.phone.list = '\0';
570  *dl->phone.list = '\0';
571  dl->phone.next = NULL;
572  dl->phone.alt = NULL;
573  dl->phone.chosen = "N/A";
574  dl->stayonline = 0;
575  dl->script.run = 1;
576  dl->script.packetmode = 1;
577  mp_linkInit(&dl->mp);
578
579  dl->bundle = bundle;
580  dl->next = NULL;
581
582  memset(&dl->dial_timer, '\0', sizeof dl->dial_timer);
583
584  dl->dial_tries = 0;
585  dl->cfg.dial.max = 1;
586  dl->cfg.dial.next_timeout = DIAL_NEXT_TIMEOUT;
587  dl->cfg.dial.timeout = DIAL_TIMEOUT;
588
589  dl->reconnect_tries = 0;
590  dl->cfg.reconnect.max = 0;
591  dl->cfg.reconnect.timeout = RECONNECT_TIMEOUT;
592
593  dl->name = strdup(name);
594  peerid_Init(&dl->peer);
595  dl->parent = &bundle->fsm;
596  dl->fsmp.LayerStart = datalink_LayerStart;
597  dl->fsmp.LayerUp = datalink_LayerUp;
598  dl->fsmp.LayerDown = datalink_LayerDown;
599  dl->fsmp.LayerFinish = datalink_LayerFinish;
600  dl->fsmp.object = dl;
601
602  auth_Init(&dl->pap);
603  auth_Init(&dl->chap.auth);
604
605  if ((dl->physical = modem_Create(dl, type)) == NULL) {
606    free(dl->name);
607    free(dl);
608    return NULL;
609  }
610  chat_Init(&dl->chat, dl->physical, NULL, 1, NULL);
611
612  log_Printf(LogPHASE, "%s: Created in %s state\n",
613             dl->name, datalink_State(dl));
614
615  return dl;
616}
617
618struct datalink *
619datalink_Clone(struct datalink *odl, const char *name)
620{
621  struct datalink *dl;
622
623  dl = (struct datalink *)malloc(sizeof(struct datalink));
624  if (dl == NULL)
625    return dl;
626
627  dl->desc.type = DATALINK_DESCRIPTOR;
628  dl->desc.UpdateSet = datalink_UpdateSet;
629  dl->desc.IsSet = datalink_IsSet;
630  dl->desc.Read = datalink_Read;
631  dl->desc.Write = datalink_Write;
632
633  dl->state = DATALINK_CLOSED;
634
635  memcpy(&dl->cfg, &odl->cfg, sizeof dl->cfg);
636  mp_linkInit(&dl->mp);
637  *dl->phone.list = '\0';
638  dl->phone.next = NULL;
639  dl->phone.alt = NULL;
640  dl->phone.chosen = "N/A";
641  dl->bundle = odl->bundle;
642  dl->next = NULL;
643  memset(&dl->dial_timer, '\0', sizeof dl->dial_timer);
644  dl->dial_tries = 0;
645  dl->reconnect_tries = 0;
646  dl->name = strdup(name);
647  peerid_Init(&dl->peer);
648  dl->parent = odl->parent;
649  memcpy(&dl->fsmp, &odl->fsmp, sizeof dl->fsmp);
650  dl->fsmp.object = dl;
651  auth_Init(&dl->pap);
652  dl->pap.cfg.fsmretry = odl->pap.cfg.fsmretry;
653
654  auth_Init(&dl->chap.auth);
655  dl->chap.auth.cfg.fsmretry = odl->chap.auth.cfg.fsmretry;
656
657  if ((dl->physical = modem_Create(dl, PHYS_INTERACTIVE)) == NULL) {
658    free(dl->name);
659    free(dl);
660    return NULL;
661  }
662  memcpy(&dl->physical->cfg, &odl->physical->cfg, sizeof dl->physical->cfg);
663  memcpy(&dl->physical->link.lcp.cfg, &odl->physical->link.lcp.cfg,
664         sizeof dl->physical->link.lcp.cfg);
665  memcpy(&dl->physical->link.ccp.cfg, &odl->physical->link.ccp.cfg,
666         sizeof dl->physical->link.ccp.cfg);
667  memcpy(&dl->physical->async.cfg, &odl->physical->async.cfg,
668         sizeof dl->physical->async.cfg);
669
670  chat_Init(&dl->chat, dl->physical, NULL, 1, NULL);
671
672  log_Printf(LogPHASE, "%s: Cloned in %s state\n",
673             dl->name, datalink_State(dl));
674
675  return dl;
676}
677
678struct datalink *
679datalink_Destroy(struct datalink *dl)
680{
681  struct datalink *result;
682
683  if (dl->state != DATALINK_CLOSED) {
684    log_Printf(LogERROR, "Oops, destroying a datalink in state %s\n",
685              datalink_State(dl));
686    switch (dl->state) {
687      case DATALINK_HANGUP:
688      case DATALINK_DIAL:
689      case DATALINK_LOGIN:
690        chat_Destroy(&dl->chat);	/* Gotta blat the timers ! */
691        break;
692    }
693  }
694
695  result = dl->next;
696  modem_Destroy(dl->physical);
697  free(dl->name);
698  free(dl);
699
700  return result;
701}
702
703void
704datalink_Up(struct datalink *dl, int runscripts, int packetmode)
705{
706  if (dl->physical->type & (PHYS_DIRECT|PHYS_DEDICATED))
707    /* Ignore scripts */
708    runscripts = 0;
709
710  switch (dl->state) {
711    case DATALINK_CLOSED:
712      if (bundle_Phase(dl->bundle) == PHASE_DEAD ||
713          bundle_Phase(dl->bundle) == PHASE_TERMINATE)
714        bundle_NewPhase(dl->bundle, PHASE_ESTABLISH);
715      datalink_NewState(dl, DATALINK_OPENING);
716      dl->reconnect_tries =
717        dl->physical->type == PHYS_DIRECT ? 0 : dl->cfg.reconnect.max;
718      dl->dial_tries = dl->cfg.dial.max;
719      dl->script.run = runscripts;
720      dl->script.packetmode = packetmode;
721      break;
722
723    case DATALINK_OPENING:
724      if (!dl->script.run && runscripts)
725        dl->script.run = 1;
726      /* fall through */
727
728    case DATALINK_DIAL:
729    case DATALINK_LOGIN:
730    case DATALINK_READY:
731      if (!dl->script.packetmode && packetmode) {
732        dl->script.packetmode = 1;
733        if (dl->state == DATALINK_READY)
734          datalink_LoginDone(dl);
735      }
736      break;
737  }
738}
739
740void
741datalink_Close(struct datalink *dl, int how)
742{
743  /* Please close */
744  switch (dl->state) {
745    case DATALINK_OPEN:
746      peerid_Init(&dl->peer);
747      fsm2initial(&dl->physical->link.ccp.fsm);
748      /* fall through */
749
750    case DATALINK_AUTH:
751    case DATALINK_LCP:
752      fsm_Close(&dl->physical->link.lcp.fsm);
753      if (how != CLOSE_NORMAL) {
754        dl->dial_tries = -1;
755        dl->reconnect_tries = 0;
756        if (how == CLOSE_LCP)
757          dl->stayonline = 1;
758      }
759      break;
760
761    default:
762      datalink_ComeDown(dl, how);
763  }
764}
765
766void
767datalink_Down(struct datalink *dl, int how)
768{
769  /* Carrier is lost */
770  switch (dl->state) {
771    case DATALINK_OPEN:
772      peerid_Init(&dl->peer);
773      fsm2initial(&dl->physical->link.ccp.fsm);
774      /* fall through */
775
776    case DATALINK_AUTH:
777    case DATALINK_LCP:
778      fsm2initial(&dl->physical->link.lcp.fsm);
779      /* fall through */
780
781    default:
782      datalink_ComeDown(dl, how);
783  }
784}
785
786void
787datalink_StayDown(struct datalink *dl)
788{
789  dl->reconnect_tries = 0;
790}
791
792void
793datalink_DontHangup(struct datalink *dl)
794{
795  if (dl->state >= DATALINK_LCP)
796    dl->stayonline = 1;
797}
798
799int
800datalink_Show(struct cmdargs const *arg)
801{
802  prompt_Printf(arg->prompt, "Name: %s\n", arg->cx->name);
803  prompt_Printf(arg->prompt, " State:            %s\n",
804                datalink_State(arg->cx));
805  prompt_Printf(arg->prompt, " CHAP Encryption:  %s\n",
806                arg->cx->chap.using_MSChap ? "MSChap" : "MD5" );
807  prompt_Printf(arg->prompt, " Peer name:        ");
808  if (*arg->cx->peer.authname)
809    prompt_Printf(arg->prompt, "%s\n", arg->cx->peer.authname);
810  else if (arg->cx->state == DATALINK_OPEN)
811    prompt_Printf(arg->prompt, "None requested\n");
812  else
813    prompt_Printf(arg->prompt, "N/A\n");
814  prompt_Printf(arg->prompt, " Discriminator:    %s\n",
815                mp_Enddisc(arg->cx->peer.enddisc.class,
816                           arg->cx->peer.enddisc.address,
817                           arg->cx->peer.enddisc.len));
818
819  prompt_Printf(arg->prompt, "\nDefaults:\n");
820  prompt_Printf(arg->prompt, " Phone List:       %s\n",
821                arg->cx->cfg.phone.list);
822  if (arg->cx->cfg.dial.max)
823    prompt_Printf(arg->prompt, " Dial tries:       %d, delay ",
824                  arg->cx->cfg.dial.max);
825  else
826    prompt_Printf(arg->prompt, " Dial tries:       infinite, delay ");
827  if (arg->cx->cfg.dial.next_timeout > 0)
828    prompt_Printf(arg->prompt, "%ds/", arg->cx->cfg.dial.next_timeout);
829  else
830    prompt_Printf(arg->prompt, "random/");
831  if (arg->cx->cfg.dial.timeout > 0)
832    prompt_Printf(arg->prompt, "%ds\n", arg->cx->cfg.dial.timeout);
833  else
834    prompt_Printf(arg->prompt, "random\n");
835  prompt_Printf(arg->prompt, " Reconnect tries:  %d, delay ",
836                arg->cx->cfg.reconnect.max);
837  if (arg->cx->cfg.reconnect.timeout > 0)
838    prompt_Printf(arg->prompt, "%ds\n", arg->cx->cfg.reconnect.timeout);
839  else
840    prompt_Printf(arg->prompt, "random\n");
841  prompt_Printf(arg->prompt, " Dial Script:      %s\n",
842                arg->cx->cfg.script.dial);
843  prompt_Printf(arg->prompt, " Login Script:     %s\n",
844                arg->cx->cfg.script.login);
845  prompt_Printf(arg->prompt, " Hangup Script:    %s\n",
846                arg->cx->cfg.script.hangup);
847  return 0;
848}
849
850int
851datalink_SetReconnect(struct cmdargs const *arg)
852{
853  if (arg->argc == arg->argn+2) {
854    arg->cx->cfg.reconnect.timeout = atoi(arg->argv[arg->argn]);
855    arg->cx->cfg.reconnect.max = atoi(arg->argv[arg->argn+1]);
856    return 0;
857  }
858  return -1;
859}
860
861int
862datalink_SetRedial(struct cmdargs const *arg)
863{
864  int timeout;
865  int tries;
866  char *dot;
867
868  if (arg->argc == arg->argn+1 || arg->argc == arg->argn+2) {
869    if (strncasecmp(arg->argv[arg->argn], "random", 6) == 0 &&
870	(arg->argv[arg->argn][6] == '\0' || arg->argv[arg->argn][6] == '.')) {
871      arg->cx->cfg.dial.timeout = -1;
872      randinit();
873    } else {
874      timeout = atoi(arg->argv[arg->argn]);
875
876      if (timeout >= 0)
877	arg->cx->cfg.dial.timeout = timeout;
878      else {
879	log_Printf(LogWARN, "Invalid redial timeout\n");
880	return -1;
881      }
882    }
883
884    dot = strchr(arg->argv[arg->argn], '.');
885    if (dot) {
886      if (strcasecmp(++dot, "random") == 0) {
887	arg->cx->cfg.dial.next_timeout = -1;
888	randinit();
889      } else {
890	timeout = atoi(dot);
891	if (timeout >= 0)
892	  arg->cx->cfg.dial.next_timeout = timeout;
893	else {
894	  log_Printf(LogWARN, "Invalid next redial timeout\n");
895	  return -1;
896	}
897      }
898    } else
899      /* Default next timeout */
900      arg->cx->cfg.dial.next_timeout = DIAL_NEXT_TIMEOUT;
901
902    if (arg->argc == arg->argn+2) {
903      tries = atoi(arg->argv[arg->argn+1]);
904
905      if (tries >= 0) {
906	arg->cx->cfg.dial.max = tries;
907      } else {
908	log_Printf(LogWARN, "Invalid retry value\n");
909	return 1;
910      }
911    }
912    return 0;
913  }
914  return -1;
915}
916
917static const char *states[] = {
918  "closed",
919  "opening",
920  "hangup",
921  "dial",
922  "login",
923  "ready",
924  "lcp",
925  "auth",
926  "open"
927};
928
929const char *
930datalink_State(struct datalink *dl)
931{
932  if (dl->state < 0 || dl->state >= sizeof states / sizeof states[0])
933    return "unknown";
934  return states[dl->state];
935}
936
937static void
938datalink_NewState(struct datalink *dl, int state)
939{
940  if (state != dl->state) {
941    if (state >= 0 && state < sizeof states / sizeof states[0]) {
942      log_Printf(LogPHASE, "%s: %s -> %s\n", dl->name, datalink_State(dl),
943                 states[state]);
944      dl->state = state;
945    } else
946      log_Printf(LogERROR, "%s: Can't enter state %d !\n", dl->name, state);
947  }
948}
949
950struct datalink *
951iov2datalink(struct bundle *bundle, struct iovec *iov, int *niov, int maxiov,
952             int fd)
953{
954  struct datalink *dl, *cdl;
955  u_int retry;
956  char *oname;
957
958  dl = (struct datalink *)iov[(*niov)++].iov_base;
959  dl->name = iov[*niov].iov_base;
960
961  if (dl->name[DATALINK_MAXNAME-1]) {
962    dl->name[DATALINK_MAXNAME-1] = '\0';
963    if (strlen(dl->name) == DATALINK_MAXNAME - 1)
964      log_Printf(LogWARN, "Datalink name truncated to \"%s\"\n", dl->name);
965  }
966
967  /* Make sure the name is unique ! */
968  oname = NULL;
969  do {
970    for (cdl = bundle->links; cdl; cdl = cdl->next)
971      if (!strcasecmp(dl->name, cdl->name)) {
972        if (oname)
973          free(datalink_NextName(dl));
974        else
975          oname = datalink_NextName(dl);
976        break;	/* Keep renaming 'till we have no conflicts */
977      }
978  } while (cdl);
979
980  if (oname) {
981    log_Printf(LogPHASE, "Rename link %s to %s\n", oname, dl->name);
982    free(oname);
983  } else {
984    dl->name = strdup(dl->name);
985    free(iov[*niov].iov_base);
986  }
987  (*niov)++;
988
989  dl->desc.type = DATALINK_DESCRIPTOR;
990  dl->desc.UpdateSet = datalink_UpdateSet;
991  dl->desc.IsSet = datalink_IsSet;
992  dl->desc.Read = datalink_Read;
993  dl->desc.Write = datalink_Write;
994
995  mp_linkInit(&dl->mp);
996  *dl->phone.list = '\0';
997  dl->phone.next = NULL;
998  dl->phone.alt = NULL;
999  dl->phone.chosen = "N/A";
1000
1001  dl->bundle = bundle;
1002  dl->next = NULL;
1003  memset(&dl->dial_timer, '\0', sizeof dl->dial_timer);
1004  dl->dial_tries = 0;
1005  dl->reconnect_tries = 0;
1006  dl->parent = &bundle->fsm;
1007  dl->fsmp.LayerStart = datalink_LayerStart;
1008  dl->fsmp.LayerUp = datalink_LayerUp;
1009  dl->fsmp.LayerDown = datalink_LayerDown;
1010  dl->fsmp.LayerFinish = datalink_LayerFinish;
1011  dl->fsmp.object = dl;
1012
1013  retry = dl->pap.cfg.fsmretry;
1014  auth_Init(&dl->pap);
1015  dl->pap.cfg.fsmretry = retry;
1016
1017  retry = dl->chap.auth.cfg.fsmretry;
1018  auth_Init(&dl->chap.auth);
1019  dl->chap.auth.cfg.fsmretry = retry;
1020
1021  dl->physical = iov2modem(dl, iov, niov, maxiov, fd);
1022
1023  if (!dl->physical) {
1024    free(dl->name);
1025    free(dl);
1026    dl = NULL;
1027  } else {
1028    chat_Init(&dl->chat, dl->physical, NULL, 1, NULL);
1029
1030    log_Printf(LogPHASE, "%s: Transferred in %s state\n",
1031              dl->name, datalink_State(dl));
1032  }
1033
1034  return dl;
1035}
1036
1037int
1038datalink2iov(struct datalink *dl, struct iovec *iov, int *niov, int maxiov,
1039             pid_t newpid)
1040{
1041  /* If `dl' is NULL, we're allocating before a Fromiov() */
1042  int link_fd;
1043
1044  if (dl) {
1045    timer_Stop(&dl->dial_timer);
1046    timer_Stop(&dl->pap.authtimer);
1047    timer_Stop(&dl->chap.auth.authtimer);
1048  }
1049
1050  if (*niov >= maxiov - 1) {
1051    log_Printf(LogERROR, "Toiov: No room for datalink !\n");
1052    if (dl) {
1053      free(dl->name);
1054      free(dl);
1055    }
1056    return -1;
1057  }
1058
1059  iov[*niov].iov_base = dl ? dl : malloc(sizeof *dl);
1060  iov[(*niov)++].iov_len = sizeof *dl;
1061  iov[*niov].iov_base =
1062    dl ? realloc(dl->name, DATALINK_MAXNAME) : malloc(DATALINK_MAXNAME);
1063  iov[(*niov)++].iov_len = DATALINK_MAXNAME;
1064
1065  link_fd = modem2iov(dl ? dl->physical : NULL, iov, niov, maxiov, newpid);
1066
1067  if (link_fd == -1 && dl) {
1068    free(dl->name);
1069    free(dl);
1070  }
1071
1072  return link_fd;
1073}
1074
1075void
1076datalink_Rename(struct datalink *dl, const char *name)
1077{
1078  free(dl->name);
1079  dl->physical->link.name = dl->name = strdup(name);
1080}
1081
1082char *
1083datalink_NextName(struct datalink *dl)
1084{
1085  int f, n;
1086  char *name, *oname;
1087
1088  n = strlen(dl->name);
1089  name = (char *)malloc(n+3);
1090  for (f = n - 1; f >= 0; f--)
1091    if (!isdigit(dl->name[f]))
1092      break;
1093  n = sprintf(name, "%.*s-", dl->name[f] == '-' ? f : f + 1, dl->name);
1094  sprintf(name + n, "%d", atoi(dl->name + f + 1) + 1);
1095  oname = dl->name;
1096  dl->name = name;
1097  /* our physical link name isn't updated (it probably isn't created yet) */
1098  return oname;
1099}
1100
1101int
1102datalink_SetMode(struct datalink *dl, int mode)
1103{
1104  if (!physical_SetMode(dl->physical, mode))
1105    return 0;
1106  if (dl->physical->type & (PHYS_DIRECT|PHYS_DEDICATED))
1107    dl->script.run = 0;
1108  if (dl->physical->type == PHYS_DIRECT)
1109    dl->reconnect_tries = 0;
1110  if (mode & (PHYS_DDIAL|PHYS_BACKGROUND) && dl->state <= DATALINK_READY)
1111    datalink_Up(dl, 1, 1);
1112  return 1;
1113}
1114