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