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