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