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