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