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