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