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