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