physical.c revision 58028
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 58028 2000-03-14 01:46: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/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    ID0kill(p->session_owner, SIGHUP);
344    p->session_owner = (pid_t)-1;
345  }
346
347  if (newsid)
348    bundle_setsid(p->dl->bundle, 0);
349
350  if (*p->name.full == '/') {
351    snprintf(fn, sizeof fn, "%s%s.if", _PATH_VARRUN, p->name.base);
352#ifndef RELEASE_CRUNCH
353    if (ID0unlink(fn) == -1)
354      log_Printf(LogALERT, "%s: Can't remove %s: %s\n",
355                 p->link.name, fn, strerror(errno));
356#else
357    ID0unlink(fn);
358#endif
359  }
360  physical_Unlock(p);
361  if (p->handler && p->handler->destroy)
362    (*p->handler->destroy)(p);
363  p->handler = NULL;
364  p->name.base = p->name.full;
365  *p->name.full = '\0';
366}
367
368void
369physical_Destroy(struct physical *p)
370{
371  physical_Close(p);
372  throughput_destroy(&p->link.throughput);
373  free(p);
374}
375
376static int
377physical_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle,
378                         const fd_set *fdset)
379{
380  struct physical *p = descriptor2physical(d);
381  int nw, result = 0;
382
383  if (p->out == NULL)
384    p->out = link_Dequeue(&p->link);
385
386  if (p->out) {
387    nw = physical_Write(p, MBUF_CTOP(p->out), p->out->m_len);
388    log_Printf(LogDEBUG, "%s: DescriptorWrite: wrote %d(%d) to %d\n",
389               p->link.name, nw, p->out->m_len, p->fd);
390    if (nw > 0) {
391      p->out->m_len -= nw;
392      p->out->m_offset += nw;
393      if (p->out->m_len == 0)
394	p->out = m_free(p->out);
395      result = 1;
396    } else if (nw < 0) {
397      if (errno != EAGAIN) {
398	log_Printf(LogPHASE, "%s: write (%d): %s\n", p->link.name,
399                   p->fd, strerror(errno));
400        datalink_Down(p->dl, CLOSE_NORMAL);
401      }
402      result = 1;
403    }
404    /* else we shouldn't really have been called !  select() is broken ! */
405  }
406
407  return result;
408}
409
410int
411physical_ShowStatus(struct cmdargs const *arg)
412{
413  struct physical *p = arg->cx->physical;
414  struct cd *cd;
415  const char *dev;
416  int n;
417
418  prompt_Printf(arg->prompt, "Name: %s\n", p->link.name);
419  prompt_Printf(arg->prompt, " State:           ");
420  if (p->fd < 0)
421    prompt_Printf(arg->prompt, "closed\n");
422  else if (p->handler && p->handler->openinfo)
423    prompt_Printf(arg->prompt, "open (%s)\n", (*p->handler->openinfo)(p));
424  else
425    prompt_Printf(arg->prompt, "open\n");
426
427  prompt_Printf(arg->prompt, " Device:          %s",
428                *p->name.full ?  p->name.full :
429                p->type == PHYS_DIRECT ? "unknown" : "N/A");
430  if (p->session_owner != (pid_t)-1)
431    prompt_Printf(arg->prompt, " (session owner: %d)", (int)p->session_owner);
432
433  prompt_Printf(arg->prompt, "\n Link Type:       %s\n", mode2Nam(p->type));
434  prompt_Printf(arg->prompt, " Connect Count:   %d\n", p->connect_count);
435#ifdef TIOCOUTQ
436  if (p->fd >= 0 && ioctl(p->fd, TIOCOUTQ, &n) >= 0)
437      prompt_Printf(arg->prompt, " Physical outq:   %d\n", n);
438#endif
439
440  prompt_Printf(arg->prompt, " Queued Packets:  %lu\n",
441                (u_long)link_QueueLen(&p->link));
442  prompt_Printf(arg->prompt, " Phone Number:    %s\n", arg->cx->phone.chosen);
443
444  prompt_Printf(arg->prompt, "\nDefaults:\n");
445
446  prompt_Printf(arg->prompt, " Device List:     ");
447  dev = p->cfg.devlist;
448  for (n = 0; n < p->cfg.ndev; n++) {
449    if (n)
450      prompt_Printf(arg->prompt, ", ");
451    prompt_Printf(arg->prompt, "\"%s\"", dev);
452    dev += strlen(dev) + 1;
453  }
454
455  prompt_Printf(arg->prompt, "\n Characteristics: ");
456  if (physical_IsSync(arg->cx->physical))
457    prompt_Printf(arg->prompt, "sync");
458  else
459    prompt_Printf(arg->prompt, "%dbps", p->cfg.speed);
460
461  switch (p->cfg.parity & CSIZE) {
462  case CS7:
463    prompt_Printf(arg->prompt, ", cs7");
464    break;
465  case CS8:
466    prompt_Printf(arg->prompt, ", cs8");
467    break;
468  }
469  if (p->cfg.parity & PARENB) {
470    if (p->cfg.parity & PARODD)
471      prompt_Printf(arg->prompt, ", odd parity");
472    else
473      prompt_Printf(arg->prompt, ", even parity");
474  } else
475    prompt_Printf(arg->prompt, ", no parity");
476
477  prompt_Printf(arg->prompt, ", CTS/RTS %s\n", (p->cfg.rts_cts ? "on" : "off"));
478
479  prompt_Printf(arg->prompt, " CD check delay:  ");
480  cd = p->handler ? &p->handler->cd : &p->cfg.cd;
481  if (cd->necessity == CD_NOTREQUIRED)
482    prompt_Printf(arg->prompt, "no cd");
483  else if (p->cfg.cd.necessity == CD_DEFAULT) {
484    prompt_Printf(arg->prompt, "device specific");
485  } else {
486    prompt_Printf(arg->prompt, "%d second%s", p->cfg.cd.delay,
487                  p->cfg.cd.delay == 1 ? "" : "s");
488    if (p->cfg.cd.necessity == CD_REQUIRED)
489      prompt_Printf(arg->prompt, " (required!)");
490  }
491  prompt_Printf(arg->prompt, "\n\n");
492
493  throughput_disp(&p->link.throughput, arg->prompt);
494
495  return 0;
496}
497
498void
499physical_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
500                     const fd_set *fdset)
501{
502  struct physical *p = descriptor2physical(d);
503  u_char *rbuff;
504  int n, found;
505
506  rbuff = p->input.buf + p->input.sz;
507
508  /* something to read */
509  n = physical_Read(p, rbuff, sizeof p->input.buf - p->input.sz);
510  log_Printf(LogDEBUG, "%s: DescriptorRead: read %d/%d from %d\n",
511             p->link.name, n, (int)(sizeof p->input.buf - p->input.sz), p->fd);
512  if (n <= 0) {
513    if (n < 0)
514      log_Printf(LogPHASE, "%s: read (%d): %s\n", p->link.name, p->fd,
515                 strerror(errno));
516    else
517      log_Printf(LogPHASE, "%s: read (%d): Got zero bytes\n",
518                 p->link.name, p->fd);
519    datalink_Down(p->dl, CLOSE_NORMAL);
520    return;
521  }
522
523  rbuff -= p->input.sz;
524  n += p->input.sz;
525
526  if (p->link.lcp.fsm.state <= ST_CLOSED) {
527    if (p->type != PHYS_DEDICATED) {
528      found = hdlc_Detect((u_char const **)&rbuff, n, physical_IsSync(p));
529      if (rbuff != p->input.buf)
530        log_WritePrompts(p->dl, "%.*s", (int)(rbuff - p->input.buf),
531                         p->input.buf);
532      p->input.sz = n - (rbuff - p->input.buf);
533
534      if (found) {
535        /* LCP packet is detected. Turn ourselves into packet mode */
536        log_Printf(LogPHASE, "%s: PPP packet detected, coming up\n",
537                   p->link.name);
538        log_SetTtyCommandMode(p->dl);
539        datalink_Up(p->dl, 0, 1);
540        link_PullPacket(&p->link, rbuff, p->input.sz, bundle);
541        p->input.sz = 0;
542      } else
543        bcopy(rbuff, p->input.buf, p->input.sz);
544    } else
545      /* In -dedicated mode, we just discard input until LCP is started */
546      p->input.sz = 0;
547  } else if (n > 0)
548    link_PullPacket(&p->link, rbuff, n, bundle);
549}
550
551struct physical *
552iov2physical(struct datalink *dl, struct iovec *iov, int *niov, int maxiov,
553             int fd, int *auxfd, int *nauxfd)
554{
555  struct physical *p;
556  int len, h, type;
557
558  p = (struct physical *)iov[(*niov)++].iov_base;
559  p->link.name = dl->name;
560  memset(p->link.Queue, '\0', sizeof p->link.Queue);
561
562  p->desc.UpdateSet = physical_UpdateSet;
563  p->desc.IsSet = physical_IsSet;
564  p->desc.Read = physical_DescriptorRead;
565  p->desc.Write = physical_DescriptorWrite;
566  p->type = PHYS_DIRECT;
567  p->dl = dl;
568  len = strlen(_PATH_DEV);
569  p->out = NULL;
570  p->connect_count = 1;
571
572  physical_SetDevice(p, p->name.full);
573
574  p->link.lcp.fsm.bundle = dl->bundle;
575  p->link.lcp.fsm.link = &p->link;
576  memset(&p->link.lcp.fsm.FsmTimer, '\0', sizeof p->link.lcp.fsm.FsmTimer);
577  memset(&p->link.lcp.fsm.OpenTimer, '\0', sizeof p->link.lcp.fsm.OpenTimer);
578  memset(&p->link.lcp.fsm.StoppedTimer, '\0',
579         sizeof p->link.lcp.fsm.StoppedTimer);
580  p->link.lcp.fsm.parent = &dl->fsmp;
581  lcp_SetupCallbacks(&p->link.lcp);
582
583  p->link.ccp.fsm.bundle = dl->bundle;
584  p->link.ccp.fsm.link = &p->link;
585  /* Our in.state & out.state are NULL (no link-level ccp yet) */
586  memset(&p->link.ccp.fsm.FsmTimer, '\0', sizeof p->link.ccp.fsm.FsmTimer);
587  memset(&p->link.ccp.fsm.OpenTimer, '\0', sizeof p->link.ccp.fsm.OpenTimer);
588  memset(&p->link.ccp.fsm.StoppedTimer, '\0',
589         sizeof p->link.ccp.fsm.StoppedTimer);
590  p->link.ccp.fsm.parent = &dl->fsmp;
591  ccp_SetupCallbacks(&p->link.ccp);
592
593  p->hdlc.lqm.owner = &p->link.lcp;
594  p->hdlc.ReportTimer.state = TIMER_STOPPED;
595  p->hdlc.lqm.timer.state = TIMER_STOPPED;
596
597  p->fd = fd;
598  p->link.throughput.SampleOctets = (long long *)iov[(*niov)++].iov_base;
599
600  type = (long)p->handler;
601  p->handler = NULL;
602  for (h = 0; h < NDEVICES && p->handler == NULL; h++)
603    p->handler = (*devices[h].iov2device)(type, p, iov, niov, maxiov,
604                                          auxfd, nauxfd);
605  if (p->handler == NULL) {
606    log_Printf(LogPHASE, "%s: Unknown link type\n", p->link.name);
607    free(iov[(*niov)++].iov_base);
608    physical_SetupStack(p, "unknown", PHYSICAL_NOFORCE);
609  } else
610    log_Printf(LogPHASE, "%s: Device %s, link type is %s\n",
611               p->link.name, p->name.full, p->handler->name);
612
613  if (p->hdlc.lqm.method && p->hdlc.lqm.timer.load)
614    lqr_reStart(&p->link.lcp);
615  hdlc_StartTimer(&p->hdlc);
616
617  throughput_restart(&p->link.throughput, "physical throughput",
618                     Enabled(dl->bundle, OPT_THROUGHPUT));
619
620  return p;
621}
622
623int
624physical_MaxDeviceSize()
625{
626  int biggest, sz, n;
627
628  biggest = sizeof(struct device);
629  for (sz = n = 0; n < NDEVICES; n++)
630    if (devices[n].DeviceSize) {
631      sz = (*devices[n].DeviceSize)();
632      if (biggest < sz)
633        biggest = sz;
634    }
635
636  return biggest;
637}
638
639int
640physical2iov(struct physical *p, struct iovec *iov, int *niov, int maxiov,
641             int *auxfd, int *nauxfd)
642{
643  struct device *h;
644  int sz;
645
646  h = NULL;
647  if (p) {
648    hdlc_StopTimer(&p->hdlc);
649    lqr_StopTimer(p);
650    timer_Stop(&p->link.lcp.fsm.FsmTimer);
651    timer_Stop(&p->link.ccp.fsm.FsmTimer);
652    timer_Stop(&p->link.lcp.fsm.OpenTimer);
653    timer_Stop(&p->link.ccp.fsm.OpenTimer);
654    timer_Stop(&p->link.lcp.fsm.StoppedTimer);
655    timer_Stop(&p->link.ccp.fsm.StoppedTimer);
656    if (p->handler) {
657      h = p->handler;
658      p->handler = (struct device *)(long)p->handler->type;
659    }
660
661    if (Enabled(p->dl->bundle, OPT_KEEPSESSION) ||
662        tcgetpgrp(p->fd) == getpgrp())
663      p->session_owner = getpid();      /* So I'll eventually get HUP'd */
664    else
665      p->session_owner = (pid_t)-1;
666    timer_Stop(&p->link.throughput.Timer);
667  }
668
669  if (*niov + 2 >= maxiov) {
670    log_Printf(LogERROR, "physical2iov: No room for physical + throughput"
671               " + device !\n");
672    if (p)
673      free(p);
674    return -1;
675  }
676
677  iov[*niov].iov_base = (void *)p;
678  iov[*niov].iov_len = sizeof *p;
679  (*niov)++;
680
681  iov[*niov].iov_base = p ? (void *)p->link.throughput.SampleOctets : NULL;
682  iov[*niov].iov_len = SAMPLE_PERIOD * sizeof(long long);
683  (*niov)++;
684
685  sz = physical_MaxDeviceSize();
686  if (p) {
687    if (h && h->device2iov)
688      (*h->device2iov)(h, iov, niov, maxiov, auxfd, nauxfd);
689    else {
690      iov[*niov].iov_base = malloc(sz);
691      if (h)
692        memcpy(iov[*niov].iov_base, h, sizeof *h);
693      iov[*niov].iov_len = sz;
694      (*niov)++;
695    }
696  } else {
697    iov[*niov].iov_base = NULL;
698    iov[*niov].iov_len = sz;
699    (*niov)++;
700  }
701
702  return p ? p->fd : 0;
703}
704
705const char *
706physical_LockedDevice(struct physical *p)
707{
708  if (p->fd >= 0 && *p->name.full == '/' && p->type != PHYS_DIRECT)
709    return p->name.base;
710
711  return NULL;
712}
713
714void
715physical_ChangedPid(struct physical *p, pid_t newpid)
716{
717  if (physical_LockedDevice(p)) {
718    int res;
719
720    if ((res = ID0uu_lock_txfr(p->name.base, newpid)) != UU_LOCK_OK)
721      log_Printf(LogPHASE, "uu_lock_txfr: %s\n", uu_lockerr(res));
722  }
723}
724
725int
726physical_IsSync(struct physical *p)
727{
728   return p->cfg.speed == 0;
729}
730
731const char *physical_GetDevice(struct physical *p)
732{
733   return p->name.full;
734}
735
736void
737physical_SetDeviceList(struct physical *p, int argc, const char *const *argv)
738{
739  int f, pos;
740
741  p->cfg.devlist[sizeof p->cfg.devlist - 1] = '\0';
742  for (f = 0, pos = 0; f < argc && pos < sizeof p->cfg.devlist - 1; f++) {
743    if (pos)
744      p->cfg.devlist[pos++] = '\0';
745    strncpy(p->cfg.devlist + pos, argv[f], sizeof p->cfg.devlist - pos - 1);
746    pos += strlen(p->cfg.devlist + pos);
747  }
748  p->cfg.ndev = f;
749}
750
751void
752physical_SetSync(struct physical *p)
753{
754   p->cfg.speed = 0;
755}
756
757int
758physical_SetRtsCts(struct physical *p, int enable)
759{
760   p->cfg.rts_cts = enable ? 1 : 0;
761   return 1;
762}
763
764ssize_t
765physical_Read(struct physical *p, void *buf, size_t nbytes)
766{
767  ssize_t ret;
768
769  if (p->handler && p->handler->read)
770    ret = (*p->handler->read)(p, buf, nbytes);
771  else
772    ret = read(p->fd, buf, nbytes);
773
774  log_DumpBuff(LogPHYSICAL, "read", buf, ret);
775
776  return ret;
777}
778
779ssize_t
780physical_Write(struct physical *p, const void *buf, size_t nbytes)
781{
782  log_DumpBuff(LogPHYSICAL, "write", buf, nbytes);
783
784  if (p->handler && p->handler->write)
785    return (*p->handler->write)(p, buf, nbytes);
786
787  return write(p->fd, buf, nbytes);
788}
789
790int
791physical_doUpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e,
792                     int *n, int force)
793{
794  struct physical *p = descriptor2physical(d);
795  int sets;
796
797  sets = 0;
798  if (p->fd >= 0) {
799    if (r) {
800      FD_SET(p->fd, r);
801      log_Printf(LogTIMER, "%s: fdset(r) %d\n", p->link.name, p->fd);
802      sets++;
803    }
804    if (e) {
805      FD_SET(p->fd, e);
806      log_Printf(LogTIMER, "%s: fdset(e) %d\n", p->link.name, p->fd);
807      sets++;
808    }
809    if (w && (force || link_QueueLen(&p->link) || p->out)) {
810      FD_SET(p->fd, w);
811      log_Printf(LogTIMER, "%s: fdset(w) %d\n", p->link.name, p->fd);
812      sets++;
813    }
814    if (sets && *n < p->fd + 1)
815      *n = p->fd + 1;
816  }
817
818  return sets;
819}
820
821int
822physical_RemoveFromSet(struct physical *p, fd_set *r, fd_set *w, fd_set *e)
823{
824  if (p->handler && p->handler->removefromset)
825    return (*p->handler->removefromset)(p, r, w, e);
826  else {
827    int sets;
828
829    sets = 0;
830    if (p->fd >= 0) {
831      if (r && FD_ISSET(p->fd, r)) {
832        FD_CLR(p->fd, r);
833        log_Printf(LogTIMER, "%s: fdunset(r) %d\n", p->link.name, p->fd);
834        sets++;
835      }
836      if (e && FD_ISSET(p->fd, e)) {
837        FD_CLR(p->fd, e);
838        log_Printf(LogTIMER, "%s: fdunset(e) %d\n", p->link.name, p->fd);
839        sets++;
840      }
841      if (w && FD_ISSET(p->fd, w)) {
842        FD_CLR(p->fd, w);
843        log_Printf(LogTIMER, "%s: fdunset(w) %d\n", p->link.name, p->fd);
844        sets++;
845      }
846    }
847
848    return sets;
849  }
850}
851
852int
853physical_IsSet(struct fdescriptor *d, const fd_set *fdset)
854{
855  struct physical *p = descriptor2physical(d);
856  return p->fd >= 0 && FD_ISSET(p->fd, fdset);
857}
858
859void
860physical_Login(struct physical *p, const char *name)
861{
862  if (p->type == PHYS_DIRECT && *p->name.base && !p->Utmp) {
863    struct utmp ut;
864    const char *connstr;
865    char *colon;
866
867    memset(&ut, 0, sizeof ut);
868    time(&ut.ut_time);
869    strncpy(ut.ut_name, name, sizeof ut.ut_name);
870    if (p->handler && (p->handler->type == TCP_DEVICE ||
871                       p->handler->type == UDP_DEVICE)) {
872      strncpy(ut.ut_line, PPPOTCPLINE, sizeof ut.ut_line);
873      strncpy(ut.ut_host, p->name.base, sizeof ut.ut_host);
874      colon = memchr(ut.ut_host, ':', sizeof ut.ut_host);
875      if (colon)
876        *colon = '\0';
877    } else
878      strncpy(ut.ut_line, p->name.base, sizeof ut.ut_line);
879    if ((connstr = getenv("CONNECT")))
880      /* mgetty sets this to the connection speed */
881      strncpy(ut.ut_host, connstr, sizeof ut.ut_host);
882    ID0login(&ut);
883    p->Utmp = ut.ut_time;
884  }
885}
886
887int
888physical_SetMode(struct physical *p, int mode)
889{
890  if ((p->type & (PHYS_DIRECT|PHYS_DEDICATED) ||
891       mode & (PHYS_DIRECT|PHYS_DEDICATED)) &&
892      (!(p->type & PHYS_DIRECT) || !(mode & PHYS_BACKGROUND))) {
893    /* Note:  The -direct -> -background is for callback ! */
894    log_Printf(LogWARN, "%s: Cannot change mode %s to %s\n", p->link.name,
895               mode2Nam(p->type), mode2Nam(mode));
896    return 0;
897  }
898  p->type = mode;
899  return 1;
900}
901
902void
903physical_DeleteQueue(struct physical *p)
904{
905  if (p->out) {
906    m_freem(p->out);
907    p->out = NULL;
908  }
909  link_DeleteQueue(&p->link);
910}
911
912void
913physical_SetDevice(struct physical *p, const char *name)
914{
915  int len = strlen(_PATH_DEV);
916
917  if (name != p->name.full) {
918    strncpy(p->name.full, name, sizeof p->name.full - 1);
919    p->name.full[sizeof p->name.full - 1] = '\0';
920  }
921  p->name.base = *p->name.full == '!' ?  p->name.full + 1 :
922                 strncmp(p->name.full, _PATH_DEV, len) ?
923                 p->name.full : p->name.full + len;
924}
925
926static void
927physical_Found(struct physical *p)
928{
929  FILE *lockfile;
930  char fn[MAXPATHLEN];
931
932  if (*p->name.full == '/') {
933    snprintf(fn, sizeof fn, "%s%s.if", _PATH_VARRUN, p->name.base);
934    lockfile = ID0fopen(fn, "w");
935    if (lockfile != NULL) {
936      fprintf(lockfile, "%s%d\n", TUN_NAME, p->dl->bundle->unit);
937      fclose(lockfile);
938    }
939#ifndef RELEASE_CRUNCH
940    else
941      log_Printf(LogALERT, "%s: Can't create %s: %s\n",
942                 p->link.name, fn, strerror(errno));
943#endif
944  }
945
946  throughput_start(&p->link.throughput, "physical throughput",
947                   Enabled(p->dl->bundle, OPT_THROUGHPUT));
948  p->connect_count++;
949  p->input.sz = 0;
950
951  log_Printf(LogPHASE, "%s: Connected!\n", p->link.name);
952}
953
954int
955physical_Open(struct physical *p, struct bundle *bundle)
956{
957  int devno, h, wasfd, err;
958  char *dev;
959
960  if (p->fd >= 0)
961    log_Printf(LogDEBUG, "%s: Open: Modem is already open!\n", p->link.name);
962    /* We're going back into "term" mode */
963  else if (p->type == PHYS_DIRECT) {
964    physical_SetDevice(p, "");
965    p->fd = STDIN_FILENO;
966    for (h = 0; h < NDEVICES && p->handler == NULL && p->fd >= 0; h++)
967      p->handler = (*devices[h].create)(p);
968    if (p->fd >= 0) {
969      if (p->handler == NULL) {
970        physical_SetupStack(p, "unknown", PHYSICAL_NOFORCE);
971        log_Printf(LogDEBUG, "%s: stdin is unidentified\n", p->link.name);
972      }
973      physical_Found(p);
974    }
975  } else {
976    dev = p->cfg.devlist;
977    devno = 0;
978    while (devno < p->cfg.ndev && p->fd < 0) {
979      physical_SetDevice(p, dev);
980      if (physical_Lock(p)) {
981        err = 0;
982
983        if (*p->name.full == '/') {
984          p->fd = ID0open(p->name.full, O_RDWR | O_NONBLOCK);
985          if (p->fd < 0)
986            err = errno;
987        }
988
989        wasfd = p->fd;
990        for (h = 0; h < NDEVICES && p->handler == NULL; h++)
991          if ((p->handler = (*devices[h].create)(p)) == NULL && wasfd != p->fd)
992            break;
993
994        if (p->fd < 0) {
995          if (h == NDEVICES) {
996            if (err)
997	      log_Printf(LogWARN, "%s: %s: %s\n", p->link.name, p->name.full,
998                         strerror(errno));
999            else
1000	      log_Printf(LogWARN, "%s: Device (%s) must begin with a '/',"
1001                         " a '!' or contain at least one ':'\n", p->link.name,
1002                         p->name.full);
1003          }
1004          physical_Unlock(p);
1005        } else
1006          physical_Found(p);
1007      }
1008      dev += strlen(dev) + 1;
1009      devno++;
1010    }
1011  }
1012
1013  return p->fd;
1014}
1015
1016void
1017physical_SetupStack(struct physical *p, const char *who, int how)
1018{
1019  link_EmptyStack(&p->link);
1020  if (how == PHYSICAL_FORCE_SYNC || how == PHYSICAL_FORCE_SYNCNOACF ||
1021      (how == PHYSICAL_NOFORCE && physical_IsSync(p)))
1022    link_Stack(&p->link, &synclayer);
1023  else {
1024    link_Stack(&p->link, &asynclayer);
1025    link_Stack(&p->link, &hdlclayer);
1026  }
1027  if (how != PHYSICAL_FORCE_SYNCNOACF)
1028    link_Stack(&p->link, &acflayer);
1029  link_Stack(&p->link, &protolayer);
1030  link_Stack(&p->link, &lqrlayer);
1031  link_Stack(&p->link, &ccplayer);
1032  link_Stack(&p->link, &vjlayer);
1033#ifndef NONAT
1034  link_Stack(&p->link, &natlayer);
1035#endif
1036  if (how == PHYSICAL_FORCE_ASYNC && physical_IsSync(p)) {
1037    log_Printf(LogWARN, "Sync device setting ignored for ``%s'' device\n", who);
1038    p->cfg.speed = MODEM_SPEED;
1039  } else if (how == PHYSICAL_FORCE_SYNC && !physical_IsSync(p)) {
1040    log_Printf(LogWARN, "Async device setting ignored for ``%s'' device\n",
1041               who);
1042    physical_SetSync(p);
1043  }
1044}
1045
1046void
1047physical_StopDeviceTimer(struct physical *p)
1048{
1049  if (p->handler && p->handler->stoptimer)
1050    (*p->handler->stoptimer)(p);
1051}
1052
1053int
1054physical_AwaitCarrier(struct physical *p)
1055{
1056  if (p->handler && p->handler->awaitcarrier)
1057    return (*p->handler->awaitcarrier)(p);
1058
1059  return CARRIER_OK;
1060}
1061