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