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