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