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