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