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