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