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