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