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