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