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