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