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