physical.c revision 98243
1/*
2 * Written by Eivind Eklund <eivind@yes.no>
3 *    for Yes Interactive
4 *
5 * Copyright (C) 1998, Yes Interactive.  All rights reserved.
6 *
7 * Redistribution and use in any form is permitted.  Redistribution in
8 * source form should include the above copyright and this set of
9 * conditions, because large sections american law seems to have been
10 * created by a bunch of jerks on drugs that are now illegal, forcing
11 * me to include this copyright-stuff instead of placing this in the
12 * public domain.  The name of of 'Yes Interactive' or 'Eivind Eklund'
13 * may not be used to endorse or promote products derived from this
14 * software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18 *
19 * $FreeBSD: head/usr.sbin/ppp/physical.c 98243 2002-06-15 08:03:30Z brian $
20 *
21 */
22
23#include <sys/param.h>
24#include <netinet/in.h>
25#include <netinet/in_systm.h>
26#include <netinet/ip.h>
27#include <sys/socket.h>
28#include <sys/un.h>
29
30#include <errno.h>
31#include <fcntl.h>
32#include <paths.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <string.h>
36#include <sys/tty.h>	/* TIOCOUTQ */
37#include <sys/uio.h>
38#include <time.h>
39#include <unistd.h>
40#include <utmp.h>
41#if defined(__OpenBSD__) || defined(__NetBSD__)
42#include <sys/ioctl.h>
43#include <util.h>
44#else
45#include <libutil.h>
46#endif
47
48#include "layer.h"
49#ifndef NONAT
50#include "nat_cmd.h"
51#endif
52#include "proto.h"
53#include "acf.h"
54#include "vjcomp.h"
55#include "defs.h"
56#include "command.h"
57#include "mbuf.h"
58#include "log.h"
59#include "id.h"
60#include "timer.h"
61#include "fsm.h"
62#include "lqr.h"
63#include "hdlc.h"
64#include "lcp.h"
65#include "throughput.h"
66#include "sync.h"
67#include "async.h"
68#include "iplist.h"
69#include "slcompress.h"
70#include "ncpaddr.h"
71#include "ipcp.h"
72#include "filter.h"
73#include "descriptor.h"
74#include "ccp.h"
75#include "link.h"
76#include "physical.h"
77#include "mp.h"
78#ifndef NORADIUS
79#include "radius.h"
80#endif
81#include "ipv6cp.h"
82#include "ncp.h"
83#include "bundle.h"
84#include "prompt.h"
85#include "chat.h"
86#include "auth.h"
87#include "chap.h"
88#include "cbcp.h"
89#include "datalink.h"
90#include "tcp.h"
91#include "udp.h"
92#include "exec.h"
93#include "tty.h"
94#ifndef NOI4B
95#include "i4b.h"
96#endif
97#ifndef NONETGRAPH
98#include "ether.h"
99#include "netgraph.h"
100#endif
101#ifndef NOATM
102#include "atm.h"
103#endif
104#include "tcpmss.h"
105
106#define PPPOTCPLINE "ppp"
107
108static int physical_DescriptorWrite(struct fdescriptor *, struct bundle *,
109                                    const fd_set *);
110
111static int
112physical_DeviceSize(void)
113{
114  return sizeof(struct device);
115}
116
117struct {
118  struct device *(*create)(struct physical *);
119  struct device *(*iov2device)(int, struct physical *, struct iovec *,
120                               int *, int, int *, int *);
121  int (*DeviceSize)(void);
122} devices[] = {
123#ifndef NOI4B
124  /*
125   * This must come before ``tty'' so that the probe routine is
126   * able to identify it as a more specific type of terminal device.
127   */
128  { i4b_Create, i4b_iov2device, i4b_DeviceSize },
129#endif
130  { tty_Create, tty_iov2device, tty_DeviceSize },
131#ifndef NONETGRAPH
132  /*
133   * This must come before ``udp'' so that the probe routine is
134   * able to identify it as a more specific type of SOCK_DGRAM.
135   */
136  { ether_Create, ether_iov2device, ether_DeviceSize },
137#ifdef EXPERIMENTAL_NETGRAPH
138  { ng_Create, ng_iov2device, ng_DeviceSize },
139#endif
140#endif
141#ifndef NOATM
142  /* Ditto for ATM devices */
143  { atm_Create, atm_iov2device, atm_DeviceSize },
144#endif
145  { tcp_Create, tcp_iov2device, tcp_DeviceSize },
146  { udp_Create, udp_iov2device, udp_DeviceSize },
147  { exec_Create, exec_iov2device, exec_DeviceSize }
148};
149
150#define NDEVICES (sizeof devices / sizeof devices[0])
151
152static int
153physical_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e,
154                   int *n)
155{
156  return physical_doUpdateSet(d, r, w, e, n, 0);
157}
158
159void
160physical_SetDescriptor(struct physical *p)
161{
162  p->desc.type = PHYSICAL_DESCRIPTOR;
163  p->desc.UpdateSet = physical_UpdateSet;
164  p->desc.IsSet = physical_IsSet;
165  p->desc.Read = physical_DescriptorRead;
166  p->desc.Write = physical_DescriptorWrite;
167}
168
169struct physical *
170physical_Create(struct datalink *dl, int type)
171{
172  struct physical *p;
173
174  p = (struct physical *)malloc(sizeof(struct physical));
175  if (!p)
176    return NULL;
177
178  p->link.type = PHYSICAL_LINK;
179  p->link.name = dl->name;
180  p->link.len = sizeof *p;
181
182  /* The sample period is fixed - see physical2iov() & iov2physical() */
183  throughput_init(&p->link.stats.total, SAMPLE_PERIOD);
184  p->link.stats.parent = dl->bundle->ncp.mp.active ?
185    &dl->bundle->ncp.mp.link.stats.total : NULL;
186  p->link.stats.gather = 1;
187
188  memset(p->link.Queue, '\0', sizeof p->link.Queue);
189  memset(p->link.proto_in, '\0', sizeof p->link.proto_in);
190  memset(p->link.proto_out, '\0', sizeof p->link.proto_out);
191  link_EmptyStack(&p->link);
192
193  p->handler = NULL;
194  physical_SetDescriptor(p);
195  p->type = type;
196
197  hdlc_Init(&p->hdlc, &p->link.lcp);
198  async_Init(&p->async);
199
200  p->fd = -1;
201  p->out = NULL;
202  p->connect_count = 0;
203  p->dl = dl;
204  p->input.sz = 0;
205  *p->name.full = '\0';
206  p->name.base = p->name.full;
207
208  p->Utmp = 0;
209  p->session_owner = (pid_t)-1;
210
211  p->cfg.rts_cts = MODEM_CTSRTS;
212  p->cfg.speed = MODEM_SPEED;
213  p->cfg.parity = CS8;
214  memcpy(p->cfg.devlist, MODEM_LIST, sizeof MODEM_LIST);
215  p->cfg.ndev = NMODEMS;
216  p->cfg.cd.necessity = CD_DEFAULT;
217  p->cfg.cd.delay = 0;		/* reconfigured or device specific default */
218
219  lcp_Init(&p->link.lcp, dl->bundle, &p->link, &dl->fsmp);
220  ccp_Init(&p->link.ccp, dl->bundle, &p->link, &dl->fsmp);
221
222  return p;
223}
224
225static const struct parity {
226  const char *name;
227  const char *name1;
228  int set;
229} validparity[] = {
230  { "even", "P_EVEN", CS7 | PARENB },
231  { "odd", "P_ODD", CS7 | PARENB | PARODD },
232  { "none", "P_ZERO", CS8 },
233  { NULL, 0 },
234};
235
236static int
237GetParityValue(const char *str)
238{
239  const struct parity *pp;
240
241  for (pp = validparity; pp->name; pp++) {
242    if (strcasecmp(pp->name, str) == 0 ||
243	strcasecmp(pp->name1, str) == 0) {
244      return pp->set;
245    }
246  }
247  return (-1);
248}
249
250int
251physical_SetParity(struct physical *p, const char *str)
252{
253  struct termios rstio;
254  int val;
255
256  val = GetParityValue(str);
257  if (val > 0) {
258    p->cfg.parity = val;
259    if (p->fd >= 0) {
260      tcgetattr(p->fd, &rstio);
261      rstio.c_cflag &= ~(CSIZE | PARODD | PARENB);
262      rstio.c_cflag |= val;
263      tcsetattr(p->fd, TCSADRAIN, &rstio);
264    }
265    return 0;
266  }
267  log_Printf(LogWARN, "%s: %s: Invalid parity\n", p->link.name, str);
268  return -1;
269}
270
271int
272physical_GetSpeed(struct physical *p)
273{
274  if (p->handler && p->handler->speed)
275    return (*p->handler->speed)(p);
276
277  return 0;
278}
279
280int
281physical_SetSpeed(struct physical *p, int speed)
282{
283  if (IntToSpeed(speed) != B0) {
284      p->cfg.speed = speed;
285      return 1;
286  }
287
288  return 0;
289}
290
291int
292physical_Raw(struct physical *p)
293{
294  if (p->handler && p->handler->raw)
295    return (*p->handler->raw)(p);
296
297  return 1;
298}
299
300void
301physical_Offline(struct physical *p)
302{
303  if (p->handler && p->handler->offline)
304    (*p->handler->offline)(p);
305  log_Printf(LogPHASE, "%s: Disconnected!\n", p->link.name);
306}
307
308static int
309physical_Lock(struct physical *p)
310{
311  int res;
312
313  if (*p->name.full == '/' && p->type != PHYS_DIRECT &&
314      (res = ID0uu_lock(p->name.base)) != UU_LOCK_OK) {
315    if (res == UU_LOCK_INUSE)
316      log_Printf(LogPHASE, "%s: %s is in use\n", p->link.name, p->name.full);
317    else
318      log_Printf(LogPHASE, "%s: %s is in use: uu_lock: %s\n",
319                 p->link.name, p->name.full, uu_lockerr(res));
320    return 0;
321  }
322
323  return 1;
324}
325
326static void
327physical_Unlock(struct physical *p)
328{
329  if (*p->name.full == '/' && p->type != PHYS_DIRECT &&
330      ID0uu_unlock(p->name.base) == -1)
331    log_Printf(LogALERT, "%s: Can't uu_unlock %s\n", p->link.name,
332               p->name.base);
333}
334
335void
336physical_Close(struct physical *p)
337{
338  int newsid;
339  char fn[PATH_MAX];
340
341  if (p->fd < 0)
342    return;
343
344  log_Printf(LogDEBUG, "%s: Close\n", p->link.name);
345
346  if (p->handler && p->handler->cooked)
347    (*p->handler->cooked)(p);
348
349  physical_StopDeviceTimer(p);
350  if (p->Utmp) {
351    if (p->handler && (p->handler->type == TCP_DEVICE ||
352                       p->handler->type == UDP_DEVICE))
353      /* Careful - we logged in on line ``ppp'' with IP as our host */
354      ID0logout(PPPOTCPLINE, 1);
355    else
356      ID0logout(p->name.base, 0);
357    p->Utmp = 0;
358  }
359  newsid = tcgetpgrp(p->fd) == getpgrp();
360  close(p->fd);
361  p->fd = -1;
362  log_SetTtyCommandMode(p->dl);
363
364  throughput_stop(&p->link.stats.total);
365  throughput_log(&p->link.stats.total, LogPHASE, p->link.name);
366
367  if (p->session_owner != (pid_t)-1) {
368    log_Printf(LogPHASE, "%s: HUPing %ld\n", p->link.name,
369               (long)p->session_owner);
370    ID0kill(p->session_owner, SIGHUP);
371    p->session_owner = (pid_t)-1;
372  }
373
374  if (newsid)
375    bundle_setsid(p->dl->bundle, 0);
376
377  if (*p->name.full == '/') {
378    snprintf(fn, sizeof fn, "%s%s.if", _PATH_VARRUN, p->name.base);
379#ifndef RELEASE_CRUNCH
380    if (ID0unlink(fn) == -1)
381      log_Printf(LogALERT, "%s: Can't remove %s: %s\n",
382                 p->link.name, fn, strerror(errno));
383#else
384    ID0unlink(fn);
385#endif
386  }
387  physical_Unlock(p);
388  if (p->handler && p->handler->destroy)
389    (*p->handler->destroy)(p);
390  p->handler = NULL;
391  p->name.base = p->name.full;
392  *p->name.full = '\0';
393}
394
395void
396physical_Destroy(struct physical *p)
397{
398  physical_Close(p);
399  throughput_destroy(&p->link.stats.total);
400  free(p);
401}
402
403static int
404physical_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle,
405                         const fd_set *fdset)
406{
407  struct physical *p = descriptor2physical(d);
408  int nw, result = 0;
409
410  if (p->out == NULL)
411    p->out = link_Dequeue(&p->link);
412
413  if (p->out) {
414    nw = physical_Write(p, MBUF_CTOP(p->out), p->out->m_len);
415    log_Printf(LogDEBUG, "%s: DescriptorWrite: wrote %d(%lu) to %d\n",
416               p->link.name, nw, (unsigned long)p->out->m_len, p->fd);
417    if (nw > 0) {
418      p->out->m_len -= nw;
419      p->out->m_offset += nw;
420      if (p->out->m_len == 0)
421	p->out = m_free(p->out);
422      result = 1;
423    } else if (nw < 0) {
424      if (errno == EAGAIN)
425        result = 1;
426      else if (errno != ENOBUFS) {
427	log_Printf(LogPHASE, "%s: write (%d): %s\n", p->link.name,
428                   p->fd, strerror(errno));
429        datalink_Down(p->dl, CLOSE_NORMAL);
430      }
431    }
432    /* else we shouldn't really have been called !  select() is broken ! */
433  }
434
435  return result;
436}
437
438int
439physical_ShowStatus(struct cmdargs const *arg)
440{
441  struct physical *p = arg->cx->physical;
442  struct cd *cd;
443  const char *dev;
444  int n;
445
446  prompt_Printf(arg->prompt, "Name: %s\n", p->link.name);
447  prompt_Printf(arg->prompt, " State:           ");
448  if (p->fd < 0)
449    prompt_Printf(arg->prompt, "closed\n");
450  else if (p->handler && p->handler->openinfo)
451    prompt_Printf(arg->prompt, "open (%s)\n", (*p->handler->openinfo)(p));
452  else
453    prompt_Printf(arg->prompt, "open\n");
454
455  prompt_Printf(arg->prompt, " Device:          %s",
456                *p->name.full ?  p->name.full :
457                p->type == PHYS_DIRECT ? "unknown" : "N/A");
458  if (p->session_owner != (pid_t)-1)
459    prompt_Printf(arg->prompt, " (session owner: %ld)", (long)p->session_owner);
460
461  prompt_Printf(arg->prompt, "\n Link Type:       %s\n", mode2Nam(p->type));
462  prompt_Printf(arg->prompt, " Connect Count:   %d\n", p->connect_count);
463#ifdef TIOCOUTQ
464  if (p->fd >= 0 && ioctl(p->fd, TIOCOUTQ, &n) >= 0)
465      prompt_Printf(arg->prompt, " Physical outq:   %d\n", n);
466#endif
467
468  prompt_Printf(arg->prompt, " Queued Packets:  %lu\n",
469                (u_long)link_QueueLen(&p->link));
470  prompt_Printf(arg->prompt, " Phone Number:    %s\n", arg->cx->phone.chosen);
471
472  prompt_Printf(arg->prompt, "\nDefaults:\n");
473
474  prompt_Printf(arg->prompt, " Device List:     ");
475  dev = p->cfg.devlist;
476  for (n = 0; n < p->cfg.ndev; n++) {
477    if (n)
478      prompt_Printf(arg->prompt, ", ");
479    prompt_Printf(arg->prompt, "\"%s\"", dev);
480    dev += strlen(dev) + 1;
481  }
482
483  prompt_Printf(arg->prompt, "\n Characteristics: ");
484  if (physical_IsSync(arg->cx->physical))
485    prompt_Printf(arg->prompt, "sync");
486  else
487    prompt_Printf(arg->prompt, "%dbps", p->cfg.speed);
488
489  switch (p->cfg.parity & CSIZE) {
490  case CS7:
491    prompt_Printf(arg->prompt, ", cs7");
492    break;
493  case CS8:
494    prompt_Printf(arg->prompt, ", cs8");
495    break;
496  }
497  if (p->cfg.parity & PARENB) {
498    if (p->cfg.parity & PARODD)
499      prompt_Printf(arg->prompt, ", odd parity");
500    else
501      prompt_Printf(arg->prompt, ", even parity");
502  } else
503    prompt_Printf(arg->prompt, ", no parity");
504
505  prompt_Printf(arg->prompt, ", CTS/RTS %s\n", (p->cfg.rts_cts ? "on" : "off"));
506
507  prompt_Printf(arg->prompt, " CD check delay:  ");
508  cd = p->handler ? &p->handler->cd : &p->cfg.cd;
509  if (cd->necessity == CD_NOTREQUIRED)
510    prompt_Printf(arg->prompt, "no cd");
511  else if (p->cfg.cd.necessity == CD_DEFAULT) {
512    prompt_Printf(arg->prompt, "device specific");
513  } else {
514    prompt_Printf(arg->prompt, "%d second%s", p->cfg.cd.delay,
515                  p->cfg.cd.delay == 1 ? "" : "s");
516    if (p->cfg.cd.necessity == CD_REQUIRED)
517      prompt_Printf(arg->prompt, " (required!)");
518  }
519  prompt_Printf(arg->prompt, "\n\n");
520
521  throughput_disp(&p->link.stats.total, arg->prompt);
522
523  return 0;
524}
525
526void
527physical_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
528                     const fd_set *fdset)
529{
530  struct physical *p = descriptor2physical(d);
531  u_char *rbuff;
532  int n, found;
533
534  rbuff = p->input.buf + p->input.sz;
535
536  /* something to read */
537  n = physical_Read(p, rbuff, sizeof p->input.buf - p->input.sz);
538  log_Printf(LogDEBUG, "%s: DescriptorRead: read %d/%d from %d\n",
539             p->link.name, n, (int)(sizeof p->input.buf - p->input.sz), p->fd);
540  if (n <= 0) {
541    if (n < 0)
542      log_Printf(LogPHASE, "%s: read (%d): %s\n", p->link.name, p->fd,
543                 strerror(errno));
544    else
545      log_Printf(LogPHASE, "%s: read (%d): Got zero bytes\n",
546                 p->link.name, p->fd);
547    datalink_Down(p->dl, CLOSE_NORMAL);
548    return;
549  }
550
551  rbuff -= p->input.sz;
552  n += p->input.sz;
553
554  if (p->link.lcp.fsm.state <= ST_CLOSED) {
555    if (p->type != PHYS_DEDICATED) {
556      found = hdlc_Detect((u_char const **)&rbuff, n, physical_IsSync(p));
557      if (rbuff != p->input.buf)
558        log_WritePrompts(p->dl, "%.*s", (int)(rbuff - p->input.buf),
559                         p->input.buf);
560      p->input.sz = n - (rbuff - p->input.buf);
561
562      if (found) {
563        /* LCP packet is detected. Turn ourselves into packet mode */
564        log_Printf(LogPHASE, "%s: PPP packet detected, coming up\n",
565                   p->link.name);
566        log_SetTtyCommandMode(p->dl);
567        datalink_Up(p->dl, 0, 1);
568        link_PullPacket(&p->link, rbuff, p->input.sz, bundle);
569        p->input.sz = 0;
570      } else
571        bcopy(rbuff, p->input.buf, p->input.sz);
572    } else
573      /* In -dedicated mode, we just discard input until LCP is started */
574      p->input.sz = 0;
575  } else if (n > 0)
576    link_PullPacket(&p->link, rbuff, n, bundle);
577}
578
579struct physical *
580iov2physical(struct datalink *dl, struct iovec *iov, int *niov, int maxiov,
581             int fd, int *auxfd, int *nauxfd)
582{
583  struct physical *p;
584  int len, h, type;
585
586  p = (struct physical *)iov[(*niov)++].iov_base;
587  p->link.name = dl->name;
588  memset(p->link.Queue, '\0', sizeof p->link.Queue);
589
590  p->desc.UpdateSet = physical_UpdateSet;
591  p->desc.IsSet = physical_IsSet;
592  p->desc.Read = physical_DescriptorRead;
593  p->desc.Write = physical_DescriptorWrite;
594  p->type = PHYS_DIRECT;
595  p->dl = dl;
596  len = strlen(_PATH_DEV);
597  p->out = NULL;
598  p->connect_count = 1;
599
600  physical_SetDevice(p, p->name.full);
601
602  p->link.lcp.fsm.bundle = dl->bundle;
603  p->link.lcp.fsm.link = &p->link;
604  memset(&p->link.lcp.fsm.FsmTimer, '\0', sizeof p->link.lcp.fsm.FsmTimer);
605  memset(&p->link.lcp.fsm.OpenTimer, '\0', sizeof p->link.lcp.fsm.OpenTimer);
606  memset(&p->link.lcp.fsm.StoppedTimer, '\0',
607         sizeof p->link.lcp.fsm.StoppedTimer);
608  p->link.lcp.fsm.parent = &dl->fsmp;
609  lcp_SetupCallbacks(&p->link.lcp);
610
611  p->link.ccp.fsm.bundle = dl->bundle;
612  p->link.ccp.fsm.link = &p->link;
613  /* Our in.state & out.state are NULL (no link-level ccp yet) */
614  memset(&p->link.ccp.fsm.FsmTimer, '\0', sizeof p->link.ccp.fsm.FsmTimer);
615  memset(&p->link.ccp.fsm.OpenTimer, '\0', sizeof p->link.ccp.fsm.OpenTimer);
616  memset(&p->link.ccp.fsm.StoppedTimer, '\0',
617         sizeof p->link.ccp.fsm.StoppedTimer);
618  p->link.ccp.fsm.parent = &dl->fsmp;
619  ccp_SetupCallbacks(&p->link.ccp);
620
621  p->hdlc.lqm.owner = &p->link.lcp;
622  p->hdlc.ReportTimer.state = TIMER_STOPPED;
623  p->hdlc.lqm.timer.state = TIMER_STOPPED;
624
625  p->fd = fd;
626  p->link.stats.total.in.SampleOctets = (long long *)iov[(*niov)++].iov_base;
627  p->link.stats.total.out.SampleOctets = (long long *)iov[(*niov)++].iov_base;
628  p->link.stats.parent = dl->bundle->ncp.mp.active ?
629    &dl->bundle->ncp.mp.link.stats.total : NULL;
630  p->link.stats.gather = 1;
631
632  type = (long)p->handler;
633  p->handler = NULL;
634  for (h = 0; h < NDEVICES && p->handler == NULL; h++)
635    p->handler = (*devices[h].iov2device)(type, p, iov, niov, maxiov,
636                                          auxfd, nauxfd);
637  if (p->handler == NULL) {
638    log_Printf(LogPHASE, "%s: Unknown link type\n", p->link.name);
639    free(iov[(*niov)++].iov_base);
640    physical_SetupStack(p, "unknown", PHYSICAL_NOFORCE);
641  } else
642    log_Printf(LogPHASE, "%s: Device %s, link type is %s\n",
643               p->link.name, p->name.full, p->handler->name);
644
645  if (p->hdlc.lqm.method && p->hdlc.lqm.timer.load)
646    lqr_reStart(&p->link.lcp);
647  hdlc_StartTimer(&p->hdlc);
648
649  throughput_restart(&p->link.stats.total, "physical throughput",
650                     Enabled(dl->bundle, OPT_THROUGHPUT));
651
652  return p;
653}
654
655int
656physical_MaxDeviceSize()
657{
658  int biggest, sz, n;
659
660  biggest = sizeof(struct device);
661  for (sz = n = 0; n < NDEVICES; n++)
662    if (devices[n].DeviceSize) {
663      sz = (*devices[n].DeviceSize)();
664      if (biggest < sz)
665        biggest = sz;
666    }
667
668  return biggest;
669}
670
671int
672physical2iov(struct physical *p, struct iovec *iov, int *niov, int maxiov,
673             int *auxfd, int *nauxfd)
674{
675  struct device *h;
676  int sz;
677
678  h = NULL;
679  if (p) {
680    hdlc_StopTimer(&p->hdlc);
681    lqr_StopTimer(p);
682    timer_Stop(&p->link.lcp.fsm.FsmTimer);
683    timer_Stop(&p->link.ccp.fsm.FsmTimer);
684    timer_Stop(&p->link.lcp.fsm.OpenTimer);
685    timer_Stop(&p->link.ccp.fsm.OpenTimer);
686    timer_Stop(&p->link.lcp.fsm.StoppedTimer);
687    timer_Stop(&p->link.ccp.fsm.StoppedTimer);
688    if (p->handler) {
689      h = p->handler;
690      p->handler = (struct device *)(long)p->handler->type;
691    }
692
693    if (Enabled(p->dl->bundle, OPT_KEEPSESSION) ||
694        tcgetpgrp(p->fd) == getpgrp())
695      p->session_owner = getpid();      /* So I'll eventually get HUP'd */
696    else
697      p->session_owner = (pid_t)-1;
698    timer_Stop(&p->link.stats.total.Timer);
699  }
700
701  if (*niov + 2 >= maxiov) {
702    log_Printf(LogERROR, "physical2iov: No room for physical + throughput"
703               " + device !\n");
704    if (p)
705      free(p);
706    return -1;
707  }
708
709  iov[*niov].iov_base = (void *)p;
710  iov[*niov].iov_len = sizeof *p;
711  (*niov)++;
712
713  iov[*niov].iov_base = p ? (void *)p->link.stats.total.in.SampleOctets : NULL;
714  iov[*niov].iov_len = SAMPLE_PERIOD * sizeof(long long);
715  (*niov)++;
716  iov[*niov].iov_base = p ? (void *)p->link.stats.total.out.SampleOctets : NULL;
717  iov[*niov].iov_len = SAMPLE_PERIOD * sizeof(long long);
718  (*niov)++;
719
720  sz = physical_MaxDeviceSize();
721  if (p) {
722    if (h && h->device2iov)
723      (*h->device2iov)(h, iov, niov, maxiov, auxfd, nauxfd);
724    else {
725      iov[*niov].iov_base = malloc(sz);
726      if (h)
727        memcpy(iov[*niov].iov_base, h, sizeof *h);
728      iov[*niov].iov_len = sz;
729      (*niov)++;
730    }
731  } else {
732    iov[*niov].iov_base = NULL;
733    iov[*niov].iov_len = sz;
734    (*niov)++;
735  }
736
737  return p ? p->fd : 0;
738}
739
740const char *
741physical_LockedDevice(struct physical *p)
742{
743  if (p->fd >= 0 && *p->name.full == '/' && p->type != PHYS_DIRECT)
744    return p->name.base;
745
746  return NULL;
747}
748
749void
750physical_ChangedPid(struct physical *p, pid_t newpid)
751{
752  if (physical_LockedDevice(p)) {
753    int res;
754
755    if ((res = ID0uu_lock_txfr(p->name.base, newpid)) != UU_LOCK_OK)
756      log_Printf(LogPHASE, "uu_lock_txfr: %s\n", uu_lockerr(res));
757  }
758}
759
760int
761physical_IsSync(struct physical *p)
762{
763   return p->cfg.speed == 0;
764}
765
766u_short
767physical_DeviceMTU(struct physical *p)
768{
769  return p->handler ? p->handler->mtu : 0;
770}
771
772const char *physical_GetDevice(struct physical *p)
773{
774   return p->name.full;
775}
776
777void
778physical_SetDeviceList(struct physical *p, int argc, const char *const *argv)
779{
780  int f, pos;
781
782  p->cfg.devlist[sizeof p->cfg.devlist - 1] = '\0';
783  for (f = 0, pos = 0; f < argc && pos < sizeof p->cfg.devlist - 1; f++) {
784    if (pos)
785      p->cfg.devlist[pos++] = '\0';
786    strncpy(p->cfg.devlist + pos, argv[f], sizeof p->cfg.devlist - pos - 1);
787    pos += strlen(p->cfg.devlist + pos);
788  }
789  p->cfg.ndev = f;
790}
791
792void
793physical_SetSync(struct physical *p)
794{
795   p->cfg.speed = 0;
796}
797
798int
799physical_SetRtsCts(struct physical *p, int enable)
800{
801   p->cfg.rts_cts = enable ? 1 : 0;
802   return 1;
803}
804
805ssize_t
806physical_Read(struct physical *p, void *buf, size_t nbytes)
807{
808  ssize_t ret;
809
810  if (p->handler && p->handler->read)
811    ret = (*p->handler->read)(p, buf, nbytes);
812  else
813    ret = read(p->fd, buf, nbytes);
814
815  log_DumpBuff(LogPHYSICAL, "read", buf, ret);
816
817  return ret;
818}
819
820ssize_t
821physical_Write(struct physical *p, const void *buf, size_t nbytes)
822{
823  log_DumpBuff(LogPHYSICAL, "write", buf, nbytes);
824
825  if (p->handler && p->handler->write)
826    return (*p->handler->write)(p, buf, nbytes);
827
828  return write(p->fd, buf, nbytes);
829}
830
831int
832physical_doUpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e,
833                     int *n, int force)
834{
835  struct physical *p = descriptor2physical(d);
836  int sets;
837
838  sets = 0;
839  if (p->fd >= 0) {
840    if (r) {
841      FD_SET(p->fd, r);
842      log_Printf(LogTIMER, "%s: fdset(r) %d\n", p->link.name, p->fd);
843      sets++;
844    }
845    if (e) {
846      FD_SET(p->fd, e);
847      log_Printf(LogTIMER, "%s: fdset(e) %d\n", p->link.name, p->fd);
848      sets++;
849    }
850    if (w && (force || link_QueueLen(&p->link) || p->out)) {
851      FD_SET(p->fd, w);
852      log_Printf(LogTIMER, "%s: fdset(w) %d\n", p->link.name, p->fd);
853      sets++;
854    }
855    if (sets && *n < p->fd + 1)
856      *n = p->fd + 1;
857  }
858
859  return sets;
860}
861
862int
863physical_RemoveFromSet(struct physical *p, fd_set *r, fd_set *w, fd_set *e)
864{
865  if (p->handler && p->handler->removefromset)
866    return (*p->handler->removefromset)(p, r, w, e);
867  else {
868    int sets;
869
870    sets = 0;
871    if (p->fd >= 0) {
872      if (r && FD_ISSET(p->fd, r)) {
873        FD_CLR(p->fd, r);
874        log_Printf(LogTIMER, "%s: fdunset(r) %d\n", p->link.name, p->fd);
875        sets++;
876      }
877      if (e && FD_ISSET(p->fd, e)) {
878        FD_CLR(p->fd, e);
879        log_Printf(LogTIMER, "%s: fdunset(e) %d\n", p->link.name, p->fd);
880        sets++;
881      }
882      if (w && FD_ISSET(p->fd, w)) {
883        FD_CLR(p->fd, w);
884        log_Printf(LogTIMER, "%s: fdunset(w) %d\n", p->link.name, p->fd);
885        sets++;
886      }
887    }
888
889    return sets;
890  }
891}
892
893int
894physical_IsSet(struct fdescriptor *d, const fd_set *fdset)
895{
896  struct physical *p = descriptor2physical(d);
897  return p->fd >= 0 && FD_ISSET(p->fd, fdset);
898}
899
900void
901physical_Login(struct physical *p, const char *name)
902{
903  if (p->type == PHYS_DIRECT && *p->name.base && !p->Utmp) {
904    struct utmp ut;
905    const char *connstr;
906    char *colon;
907
908    memset(&ut, 0, sizeof ut);
909    time(&ut.ut_time);
910    strncpy(ut.ut_name, name, sizeof ut.ut_name);
911    if (p->handler && (p->handler->type == TCP_DEVICE ||
912                       p->handler->type == UDP_DEVICE)) {
913      strncpy(ut.ut_line, PPPOTCPLINE, sizeof ut.ut_line);
914      strncpy(ut.ut_host, p->name.base, sizeof ut.ut_host);
915      colon = memchr(ut.ut_host, ':', sizeof ut.ut_host);
916      if (colon)
917        *colon = '\0';
918    } else
919      strncpy(ut.ut_line, p->name.base, sizeof ut.ut_line);
920    if ((connstr = getenv("CONNECT")))
921      /* mgetty sets this to the connection speed */
922      strncpy(ut.ut_host, connstr, sizeof ut.ut_host);
923    ID0login(&ut);
924    p->Utmp = ut.ut_time;
925  }
926}
927
928int
929physical_SetMode(struct physical *p, int mode)
930{
931  if ((p->type & (PHYS_DIRECT|PHYS_DEDICATED) ||
932       mode & (PHYS_DIRECT|PHYS_DEDICATED)) &&
933      (!(p->type & PHYS_DIRECT) || !(mode & PHYS_BACKGROUND))) {
934    /* Note:  The -direct -> -background is for callback ! */
935    log_Printf(LogWARN, "%s: Cannot change mode %s to %s\n", p->link.name,
936               mode2Nam(p->type), mode2Nam(mode));
937    return 0;
938  }
939  p->type = mode;
940  return 1;
941}
942
943void
944physical_DeleteQueue(struct physical *p)
945{
946  if (p->out) {
947    m_freem(p->out);
948    p->out = NULL;
949  }
950  link_DeleteQueue(&p->link);
951}
952
953void
954physical_SetDevice(struct physical *p, const char *name)
955{
956  int len = strlen(_PATH_DEV);
957
958  if (name != p->name.full) {
959    strncpy(p->name.full, name, sizeof p->name.full - 1);
960    p->name.full[sizeof p->name.full - 1] = '\0';
961  }
962  p->name.base = *p->name.full == '!' ?  p->name.full + 1 :
963                 strncmp(p->name.full, _PATH_DEV, len) ?
964                 p->name.full : p->name.full + len;
965}
966
967static void
968physical_Found(struct physical *p)
969{
970  FILE *lockfile;
971  char fn[PATH_MAX];
972
973  if (*p->name.full == '/') {
974    snprintf(fn, sizeof fn, "%s%s.if", _PATH_VARRUN, p->name.base);
975    lockfile = ID0fopen(fn, "w");
976    if (lockfile != NULL) {
977      fprintf(lockfile, "%s%d\n", TUN_NAME, p->dl->bundle->unit);
978      fclose(lockfile);
979    }
980#ifndef RELEASE_CRUNCH
981    else
982      log_Printf(LogALERT, "%s: Can't create %s: %s\n",
983                 p->link.name, fn, strerror(errno));
984#endif
985  }
986
987  throughput_start(&p->link.stats.total, "physical throughput",
988                   Enabled(p->dl->bundle, OPT_THROUGHPUT));
989  p->connect_count++;
990  p->input.sz = 0;
991
992  log_Printf(LogPHASE, "%s: Connected!\n", p->link.name);
993}
994
995int
996physical_Open(struct physical *p, struct bundle *bundle)
997{
998  int devno, h, wasfd, err;
999  char *dev;
1000
1001  if (p->fd >= 0)
1002    log_Printf(LogDEBUG, "%s: Open: Modem is already open!\n", p->link.name);
1003    /* We're going back into "term" mode */
1004  else if (p->type == PHYS_DIRECT) {
1005    physical_SetDevice(p, "");
1006    p->fd = STDIN_FILENO;
1007    for (h = 0; h < NDEVICES && p->handler == NULL && p->fd >= 0; h++)
1008      p->handler = (*devices[h].create)(p);
1009    if (p->fd >= 0) {
1010      if (p->handler == NULL) {
1011        physical_SetupStack(p, "unknown", PHYSICAL_NOFORCE);
1012        log_Printf(LogDEBUG, "%s: stdin is unidentified\n", p->link.name);
1013      }
1014      physical_Found(p);
1015    }
1016  } else {
1017    dev = p->cfg.devlist;
1018    devno = 0;
1019    while (devno < p->cfg.ndev && p->fd < 0) {
1020      physical_SetDevice(p, dev);
1021      if (physical_Lock(p)) {
1022        err = 0;
1023
1024        if (*p->name.full == '/') {
1025          p->fd = ID0open(p->name.full, O_RDWR | O_NONBLOCK);
1026          if (p->fd < 0)
1027            err = errno;
1028        }
1029
1030        wasfd = p->fd;
1031        for (h = 0; h < NDEVICES && p->handler == NULL; h++)
1032          if ((p->handler = (*devices[h].create)(p)) == NULL && wasfd != p->fd)
1033            break;
1034
1035        if (p->fd < 0) {
1036          if (h == NDEVICES) {
1037            if (err)
1038	      log_Printf(LogWARN, "%s: %s: %s\n", p->link.name, p->name.full,
1039                         strerror(errno));
1040            else
1041	      log_Printf(LogWARN, "%s: Device (%s) must begin with a '/',"
1042                         " a '!' or contain at least one ':'\n", p->link.name,
1043                         p->name.full);
1044          }
1045          physical_Unlock(p);
1046        } else
1047          physical_Found(p);
1048      }
1049      dev += strlen(dev) + 1;
1050      devno++;
1051    }
1052  }
1053
1054  return p->fd;
1055}
1056
1057void
1058physical_SetupStack(struct physical *p, const char *who, int how)
1059{
1060  link_EmptyStack(&p->link);
1061  if (how == PHYSICAL_FORCE_SYNC || how == PHYSICAL_FORCE_SYNCNOACF ||
1062      (how == PHYSICAL_NOFORCE && physical_IsSync(p)))
1063    link_Stack(&p->link, &synclayer);
1064  else {
1065    link_Stack(&p->link, &asynclayer);
1066    link_Stack(&p->link, &hdlclayer);
1067  }
1068  if (how != PHYSICAL_FORCE_SYNCNOACF)
1069    link_Stack(&p->link, &acflayer);
1070  link_Stack(&p->link, &protolayer);
1071  link_Stack(&p->link, &lqrlayer);
1072  link_Stack(&p->link, &ccplayer);
1073  link_Stack(&p->link, &vjlayer);
1074  link_Stack(&p->link, &tcpmsslayer);
1075#ifndef NONAT
1076  link_Stack(&p->link, &natlayer);
1077#endif
1078  if (how == PHYSICAL_FORCE_ASYNC && physical_IsSync(p)) {
1079    log_Printf(LogWARN, "Sync device setting ignored for ``%s'' device\n", who);
1080    p->cfg.speed = MODEM_SPEED;
1081  } else if (how == PHYSICAL_FORCE_SYNC && !physical_IsSync(p)) {
1082    log_Printf(LogWARN, "Async device setting ignored for ``%s'' device\n",
1083               who);
1084    physical_SetSync(p);
1085  }
1086}
1087
1088void
1089physical_StopDeviceTimer(struct physical *p)
1090{
1091  if (p->handler && p->handler->stoptimer)
1092    (*p->handler->stoptimer)(p);
1093}
1094
1095int
1096physical_AwaitCarrier(struct physical *p)
1097{
1098  if (p->handler && p->handler->awaitcarrier)
1099    return (*p->handler->awaitcarrier)(p);
1100
1101  return CARRIER_OK;
1102}
1103
1104
1105void
1106physical_SetAsyncParams(struct physical *p, u_int32_t mymap, u_int32_t hismap)
1107{
1108  if (p->handler && p->handler->setasyncparams)
1109    return (*p->handler->setasyncparams)(p, mymap, hismap);
1110
1111  async_SetLinkParams(&p->async, mymap, hismap);
1112}
1113
1114int
1115physical_Slot(struct physical *p)
1116{
1117  if (p->handler && p->handler->slot)
1118    return (*p->handler->slot)(p);
1119
1120  return -1;
1121}
1122