xref: /freebsd/usr.sbin/ppp/tty.c (revision c91777f23a3b13649cdf303515ee45a04c788af3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1999 Brian Somers <brian@Awfulhak.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/un.h>
31 #if defined(__OpenBSD__) || defined(__NetBSD__)
32 #include <sys/ioctl.h>
33 #endif
34 
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <sysexits.h>
41 #include <sys/uio.h>
42 #include <termios.h>
43 #include <ttyent.h>
44 #include <unistd.h>
45 #ifndef NONETGRAPH
46 #include <netgraph.h>
47 #include <netgraph/ng_async.h>
48 #include <netgraph/ng_message.h>
49 #include <netgraph/ng_ppp.h>
50 #include <netgraph/ng_tty.h>
51 #endif
52 
53 #include "layer.h"
54 #include "defs.h"
55 #include "mbuf.h"
56 #include "log.h"
57 #include "timer.h"
58 #include "lqr.h"
59 #include "hdlc.h"
60 #include "throughput.h"
61 #include "fsm.h"
62 #include "lcp.h"
63 #include "ccp.h"
64 #include "link.h"
65 #include "async.h"
66 #include "descriptor.h"
67 #include "physical.h"
68 #include "mp.h"
69 #include "chat.h"
70 #include "auth.h"
71 #include "chap.h"
72 #include "cbcp.h"
73 #include "datalink.h"
74 #include "main.h"
75 #include "id.h"
76 #include "tty.h"
77 
78 #if defined(__mac68k__) || defined(__macppc__)
79 #undef	CRTS_IFLOW
80 #undef	CCTS_OFLOW
81 #define	CRTS_IFLOW	CDTRCTS
82 #define	CCTS_OFLOW	CDTRCTS
83 #endif
84 
85 #define	Online(dev)	((dev)->mbits & TIOCM_CD)
86 
87 struct ttydevice {
88   struct device dev;		/* What struct physical knows about */
89   struct pppTimer Timer;	/* CD checks */
90   int mbits;			/* Current DCD status */
91   int carrier_seconds;		/* seconds before CD is *required* */
92 #ifndef NONETGRAPH
93   struct {
94     unsigned speed;		/* Pre-line-discipline speed */
95     int fd;			/* Pre-line-discipline fd */
96     int disc;			/* Old line-discipline */
97   } real;
98   char hook[sizeof NG_ASYNC_HOOK_SYNC]; /* our ng_socket hook */
99   int cs;			/* A netgraph control socket (maybe) */
100 #endif
101   struct termios ios;		/* To be able to reset from raw mode */
102 };
103 
104 #define device2tty(d) ((d)->type == TTY_DEVICE ? (struct ttydevice *)d : NULL)
105 
106 unsigned
tty_DeviceSize(void)107 tty_DeviceSize(void)
108 {
109   return sizeof(struct ttydevice);
110 }
111 
112 /*
113  * tty_Timeout() watches the DCD signal and mentions it if it's status
114  * changes.
115  */
116 static void
tty_Timeout(void * data)117 tty_Timeout(void *data)
118 {
119   struct physical *p = data;
120   struct ttydevice *dev = device2tty(p->handler);
121   int ombits, change;
122 
123   timer_Stop(&dev->Timer);
124   dev->Timer.load = SECTICKS;		/* Once a second please */
125   timer_Start(&dev->Timer);
126   ombits = dev->mbits;
127 
128   if (p->fd >= 0) {
129     if (ioctl(p->fd, TIOCMGET, &dev->mbits) < 0) {
130       /* we must be a pty ? */
131       if (p->cfg.cd.necessity != CD_DEFAULT)
132         log_Printf(LogWARN, "%s: Carrier ioctl not supported, "
133                    "using ``set cd off''\n", p->link.name);
134       timer_Stop(&dev->Timer);
135       dev->mbits = TIOCM_CD;
136       return;
137     }
138   } else
139     dev->mbits = 0;
140 
141   if (ombits == -1) {
142     /* First time looking for carrier */
143     if (Online(dev))
144       log_Printf(LogPHASE, "%s: %s: CD detected\n", p->link.name, p->name.full);
145     else if (++dev->carrier_seconds >= dev->dev.cd.delay) {
146       if (dev->dev.cd.necessity == CD_REQUIRED)
147         log_Printf(LogPHASE, "%s: %s: Required CD not detected\n",
148                    p->link.name, p->name.full);
149       else {
150         log_Printf(LogPHASE, "%s: %s doesn't support CD\n",
151                    p->link.name, p->name.full);
152         dev->mbits = TIOCM_CD;		/* Dodgy null-modem cable ? */
153       }
154       timer_Stop(&dev->Timer);
155       /* tty_AwaitCarrier() will notice */
156     } else {
157       /* Keep waiting */
158       log_Printf(LogDEBUG, "%s: %s: Still no carrier (%d/%d)\n",
159                  p->link.name, p->name.full, dev->carrier_seconds,
160                  dev->dev.cd.delay);
161       dev->mbits = -1;
162     }
163   } else {
164     change = ombits ^ dev->mbits;
165     if (change & TIOCM_CD) {
166       if (dev->mbits & TIOCM_CD)
167         log_Printf(LogDEBUG, "%s: offline -> online\n", p->link.name);
168       else {
169         log_Printf(LogDEBUG, "%s: online -> offline\n", p->link.name);
170         log_Printf(LogPHASE, "%s: Carrier lost\n", p->link.name);
171         datalink_Down(p->dl, CLOSE_NORMAL);
172         timer_Stop(&dev->Timer);
173       }
174     } else
175       log_Printf(LogDEBUG, "%s: Still %sline\n", p->link.name,
176                  Online(dev) ? "on" : "off");
177   }
178 }
179 
180 static void
tty_StartTimer(struct physical * p)181 tty_StartTimer(struct physical *p)
182 {
183   struct ttydevice *dev = device2tty(p->handler);
184 
185   timer_Stop(&dev->Timer);
186   dev->Timer.load = SECTICKS;
187   dev->Timer.func = tty_Timeout;
188   dev->Timer.name = "tty CD";
189   dev->Timer.arg = p;
190   log_Printf(LogDEBUG, "%s: Using tty_Timeout\n", p->link.name);
191   timer_Start(&dev->Timer);
192 }
193 
194 static int
tty_AwaitCarrier(struct physical * p)195 tty_AwaitCarrier(struct physical *p)
196 {
197   struct ttydevice *dev = device2tty(p->handler);
198 
199   if (dev->dev.cd.necessity == CD_NOTREQUIRED || physical_IsSync(p))
200     return CARRIER_OK;
201 
202   if (dev->mbits == -1) {
203     if (dev->Timer.state == TIMER_STOPPED) {
204       dev->carrier_seconds = 0;
205       tty_StartTimer(p);
206     }
207     return CARRIER_PENDING;			/* Not yet ! */
208   }
209 
210   return Online(dev) ? CARRIER_OK : CARRIER_LOST;
211 }
212 
213 #ifdef NONETGRAPH
214 #define tty_SetAsyncParams	NULL
215 #define tty_Write		NULL
216 #define tty_Read		NULL
217 #else
218 
219 static int
isngtty(struct ttydevice * dev)220 isngtty(struct ttydevice *dev)
221 {
222   return dev->real.fd != -1;
223 }
224 
225 static void
tty_SetAsyncParams(struct physical * p,u_int32_t mymap,u_int32_t hismap)226 tty_SetAsyncParams(struct physical *p, u_int32_t mymap, u_int32_t hismap)
227 {
228   struct ttydevice *dev = device2tty(p->handler);
229   char asyncpath[NG_PATHSIZ];
230   struct ng_async_cfg cfg;
231 
232   if (isngtty(dev)) {
233     /* Configure the async converter node */
234 
235     snprintf(asyncpath, sizeof asyncpath, ".:%s", dev->hook);
236     memset(&cfg, 0, sizeof cfg);
237     cfg.enabled = 1;
238     cfg.accm = mymap | hismap;
239     cfg.amru = MAX_MTU;
240     cfg.smru = MAX_MRU;
241     log_Printf(LogDEBUG, "Configure async node at %s\n", asyncpath);
242     if (NgSendMsg(dev->cs, asyncpath, NGM_ASYNC_COOKIE,
243                   NGM_ASYNC_CMD_SET_CONFIG, &cfg, sizeof cfg) < 0)
244       log_Printf(LogWARN, "%s: Can't configure async node at %s\n",
245                  p->link.name, asyncpath);
246   } else
247     /* No netgraph node, just config the async layer */
248     async_SetLinkParams(&p->async, mymap, hismap);
249 }
250 
251 static int
LoadLineDiscipline(struct physical * p)252 LoadLineDiscipline(struct physical *p)
253 {
254   struct ttydevice *dev = device2tty(p->handler);
255   u_char rbuf[sizeof(struct ng_mesg) + sizeof(struct nodeinfo)];
256   struct ng_mesg *reply;
257   struct nodeinfo *info;
258   char ttypath[NG_NODESIZ];
259   struct ngm_mkpeer ngm;
260   struct ngm_connect ngc;
261   int ldisc, cs, ds, hot;
262   unsigned speed;
263 
264   /*
265    * Don't use the netgraph line discipline for now.  Using it works, but
266    * carrier cannot be detected via TIOCMGET and the device doesn't become
267    * selectable with 0 bytes to read when carrier is lost :(
268    */
269   return 0;
270 
271   reply = (struct ng_mesg *)rbuf;
272   info = (struct nodeinfo *)reply->data;
273 
274   loadmodules(LOAD_VERBOSLY, "netgraph", "ng_tty", "ng_async", "ng_socket",
275               NULL);
276 
277   /* Get the speed before loading the line discipline */
278   speed = physical_GetSpeed(p);
279 
280   if (ioctl(p->fd, TIOCGETD, &dev->real.disc) < 0) {
281     log_Printf(LogDEBUG, "%s: Couldn't get tty line discipline\n",
282                p->link.name);
283     return 0;
284   }
285   ldisc = NETGRAPHDISC;
286   if (ID0ioctl(p->fd, TIOCSETD, &ldisc) < 0) {
287     log_Printf(LogDEBUG, "%s: Couldn't set NETGRAPHDISC line discipline\n",
288                p->link.name);
289     return 0;
290   }
291 
292   /* Get the name of the tty node */
293   if (ioctl(p->fd, NGIOCGINFO, info) < 0) {
294     log_Printf(LogWARN, "%s: ioctl(NGIOCGINFO): %s\n", p->link.name,
295                strerror(errno));
296     ID0ioctl(p->fd, TIOCSETD, &dev->real.disc);
297     return 0;
298   }
299   snprintf(ttypath, sizeof ttypath, "%s:", info->name);
300 
301   /* Create a socket node for our endpoint (and to send messages via) */
302   if (ID0NgMkSockNode(NULL, &cs, &ds) == -1) {
303     log_Printf(LogWARN, "%s: NgMkSockNode: %s\n", p->link.name,
304                strerror(errno));
305     ID0ioctl(p->fd, TIOCSETD, &dev->real.disc);
306     return 0;
307   }
308 
309   /* Set the ``hot char'' on the TTY node */
310   hot = HDLC_SYN;
311   log_Printf(LogDEBUG, "%s: Set tty hotchar to 0x%02x\n", p->link.name, hot);
312   if (NgSendMsg(cs, ttypath, NGM_TTY_COOKIE,
313       NGM_TTY_SET_HOTCHAR, &hot, sizeof hot) < 0) {
314     log_Printf(LogWARN, "%s: Can't set hot char\n", p->link.name);
315     goto failed;
316   }
317 
318   /* Attach an async converter node */
319   snprintf(ngm.type, sizeof ngm.type, "%s", NG_ASYNC_NODE_TYPE);
320   snprintf(ngm.ourhook, sizeof ngm.ourhook, "%s", NG_TTY_HOOK);
321   snprintf(ngm.peerhook, sizeof ngm.peerhook, "%s", NG_ASYNC_HOOK_ASYNC);
322   log_Printf(LogDEBUG, "%s: Send mkpeer async:%s to %s:%s\n", p->link.name,
323              ngm.peerhook, ttypath, ngm.ourhook);
324   if (NgSendMsg(cs, ttypath, NGM_GENERIC_COOKIE,
325       NGM_MKPEER, &ngm, sizeof ngm) < 0) {
326     log_Printf(LogWARN, "%s: Can't create %s node\n", p->link.name,
327                NG_ASYNC_NODE_TYPE);
328     goto failed;
329   }
330 
331   /* Connect the async node to our socket */
332   snprintf(ngc.path, sizeof ngc.path, "%s%s", ttypath, NG_TTY_HOOK);
333   snprintf(ngc.peerhook, sizeof ngc.peerhook, "%s", NG_ASYNC_HOOK_SYNC);
334   memcpy(ngc.ourhook, ngc.peerhook, sizeof ngc.ourhook);
335   log_Printf(LogDEBUG, "%s: Send connect %s:%s to .:%s\n", p->link.name,
336              ngc.path, ngc.peerhook, ngc.ourhook);
337   if (NgSendMsg(cs, ".:", NGM_GENERIC_COOKIE, NGM_CONNECT,
338       &ngc, sizeof ngc) < 0) {
339     log_Printf(LogWARN, "%s: Can't connect .:%s -> %s.%s: %s\n",
340                p->link.name, ngc.ourhook, ngc.path, ngc.peerhook,
341                strerror(errno));
342     goto failed;
343   }
344 
345   /* Get the async node id */
346   if (NgSendMsg(cs, ngc.path, NGM_GENERIC_COOKIE, NGM_NODEINFO, NULL, 0) < 0) {
347     log_Printf(LogWARN, "%s: Can't request async node info at %s: %s\n",
348                p->link.name, ngc.path, strerror(errno));
349     goto failed;
350   }
351   if (NgRecvMsg(cs, reply, sizeof rbuf, NULL) < 0) {
352     log_Printf(LogWARN, "%s: Can't obtain async node info at %s: %s\n",
353                p->link.name, ngc.path, strerror(errno));
354     goto failed;
355   }
356 
357   /* All done, set up our device state */
358   snprintf(dev->hook, sizeof dev->hook, "%s", ngc.ourhook);
359   dev->cs = cs;
360   dev->real.fd = p->fd;
361   p->fd = ds;
362   dev->real.speed = speed;
363   physical_SetSync(p);
364 
365   tty_SetAsyncParams(p, 0xffffffff, 0xffffffff);
366   physical_SetupStack(p, dev->dev.name, PHYSICAL_NOFORCE);
367   log_Printf(LogPHASE, "%s: Loaded netgraph tty line discipline\n",
368              p->link.name);
369 
370   return 1;
371 
372 failed:
373   ID0ioctl(p->fd, TIOCSETD, &dev->real.disc);
374   close(ds);
375   close(cs);
376 
377   return 0;
378 }
379 
380 static void
UnloadLineDiscipline(struct physical * p)381 UnloadLineDiscipline(struct physical *p)
382 {
383   struct ttydevice *dev = device2tty(p->handler);
384 
385   if (isngtty(dev)) {
386     if (!physical_SetSpeed(p, dev->real.speed))
387       log_Printf(LogWARN, "Couldn't reset tty speed to %d\n", dev->real.speed);
388     dev->real.speed = 0;
389     close(p->fd);
390     p->fd = dev->real.fd;
391     dev->real.fd = -1;
392     close(dev->cs);
393     dev->cs = -1;
394     *dev->hook = '\0';
395     if (ID0ioctl(p->fd, TIOCSETD, &dev->real.disc) == 0) {
396       physical_SetupStack(p, dev->dev.name, PHYSICAL_NOFORCE);
397       log_Printf(LogPHASE, "%s: Unloaded netgraph tty line discipline\n",
398                  p->link.name);
399     } else
400       log_Printf(LogWARN, "%s: Failed to unload netgraph tty line discipline\n",
401                  p->link.name);
402   }
403 }
404 
405 static ssize_t
tty_Write(struct physical * p,const void * v,size_t n)406 tty_Write(struct physical *p, const void *v, size_t n)
407 {
408   struct ttydevice *dev = device2tty(p->handler);
409 
410   if (isngtty(dev))
411     return NgSendData(p->fd, dev->hook, v, n) == -1 ? -1 : (ssize_t)n;
412   else
413     return write(p->fd, v, n);
414 }
415 
416 static ssize_t
tty_Read(struct physical * p,void * v,size_t n)417 tty_Read(struct physical *p, void *v, size_t n)
418 {
419   struct ttydevice *dev = device2tty(p->handler);
420   char hook[sizeof NG_ASYNC_HOOK_SYNC];
421 
422   if (isngtty(dev))
423     return NgRecvData(p->fd, v, n, hook);
424   else
425     return read(p->fd, v, n);
426 }
427 
428 #endif /* NETGRAPH */
429 
430 static int
tty_Raw(struct physical * p)431 tty_Raw(struct physical *p)
432 {
433   struct ttydevice *dev = device2tty(p->handler);
434   struct termios ios;
435   int oldflag;
436 
437   log_Printf(LogDEBUG, "%s: Entering tty_Raw\n", p->link.name);
438 
439   if (p->type != PHYS_DIRECT && p->fd >= 0 && !Online(dev))
440     log_Printf(LogDEBUG, "%s: Raw: descriptor = %d, mbits = %x\n",
441               p->link.name, p->fd, dev->mbits);
442 
443   if (!physical_IsSync(p)) {
444 #ifndef NONETGRAPH
445     if (!LoadLineDiscipline(p))
446 #endif
447     {
448       tcgetattr(p->fd, &ios);
449       cfmakeraw(&ios);
450       if (p->cfg.rts_cts)
451         ios.c_cflag |= CLOCAL | CCTS_OFLOW | CRTS_IFLOW;
452       else
453         ios.c_cflag |= CLOCAL;
454 
455       if (p->type != PHYS_DEDICATED)
456         ios.c_cflag |= HUPCL;
457 
458       if (tcsetattr(p->fd, TCSANOW, &ios) == -1)
459         log_Printf(LogWARN, "%s: tcsetattr: Failed configuring device\n",
460                    p->link.name);
461     }
462   }
463 
464   oldflag = fcntl(p->fd, F_GETFL, 0);
465   if (oldflag < 0)
466     return 0;
467   fcntl(p->fd, F_SETFL, oldflag | O_NONBLOCK);
468 
469   return 1;
470 }
471 
472 static void
tty_Offline(struct physical * p)473 tty_Offline(struct physical *p)
474 {
475   struct ttydevice *dev = device2tty(p->handler);
476 
477   if (p->fd >= 0) {
478     timer_Stop(&dev->Timer);
479     dev->mbits &= ~TIOCM_DTR;	/* XXX: Hmm, what's this supposed to do ? */
480     if (Online(dev)) {
481       struct termios tio;
482 
483       tcgetattr(p->fd, &tio);
484       if (cfsetspeed(&tio, B0) == -1 || tcsetattr(p->fd, TCSANOW, &tio) == -1)
485         log_Printf(LogWARN, "%s: Unable to set physical to speed 0\n",
486                    p->link.name);
487     }
488   }
489 }
490 
491 static void
tty_Cooked(struct physical * p)492 tty_Cooked(struct physical *p)
493 {
494   struct ttydevice *dev = device2tty(p->handler);
495   int oldflag;
496 
497   tty_Offline(p);	/* In case of emergency close()s */
498 
499   tcflush(p->fd, TCIOFLUSH);
500 
501   if (!physical_IsSync(p) && tcsetattr(p->fd, TCSAFLUSH, &dev->ios) == -1)
502     log_Printf(LogWARN, "%s: tcsetattr: Unable to restore device settings\n",
503                p->link.name);
504 
505 #ifndef NONETGRAPH
506   UnloadLineDiscipline(p);
507 #endif
508 
509   if ((oldflag = fcntl(p->fd, F_GETFL, 0)) != -1)
510     fcntl(p->fd, F_SETFL, oldflag & ~O_NONBLOCK);
511 }
512 
513 static void
tty_StopTimer(struct physical * p)514 tty_StopTimer(struct physical *p)
515 {
516   struct ttydevice *dev = device2tty(p->handler);
517 
518   timer_Stop(&dev->Timer);
519 }
520 
521 static void
tty_Free(struct physical * p)522 tty_Free(struct physical *p)
523 {
524   struct ttydevice *dev = device2tty(p->handler);
525 
526   tty_Offline(p);	/* In case of emergency close()s */
527   free(dev);
528 }
529 
530 static unsigned
tty_Speed(struct physical * p)531 tty_Speed(struct physical *p)
532 {
533   struct termios ios;
534 
535   if (tcgetattr(p->fd, &ios) == -1)
536     return 0;
537 
538   return SpeedToUnsigned(cfgetispeed(&ios));
539 }
540 
541 static const char *
tty_OpenInfo(struct physical * p)542 tty_OpenInfo(struct physical *p)
543 {
544   struct ttydevice *dev = device2tty(p->handler);
545   static char buf[13];
546 
547   if (Online(dev))
548     strcpy(buf, "with");
549   else
550     strcpy(buf, "no");
551   strcat(buf, " carrier");
552 
553   return buf;
554 }
555 
556 static int
tty_Slot(struct physical * p)557 tty_Slot(struct physical *p)
558 {
559   struct ttyent *ttyp;
560   int slot;
561 
562   setttyent();
563   for (slot = 1; (ttyp = getttyent()); ++slot)
564     if (!strcmp(ttyp->ty_name, p->name.base)) {
565       endttyent();
566       return slot;
567     }
568 
569   endttyent();
570   return -1;
571 }
572 
573 static void
tty_device2iov(struct device * d,struct iovec * iov,int * niov,int maxiov __unused,int * auxfd,int * nauxfd)574 tty_device2iov(struct device *d, struct iovec *iov, int *niov,
575                int maxiov __unused,
576 #ifndef NONETGRAPH
577                int *auxfd, int *nauxfd
578 #else
579                int *auxfd __unused, int *nauxfd __unused
580 #endif
581                )
582 {
583   struct ttydevice *dev;
584   int sz = physical_MaxDeviceSize();
585 
586   iov[*niov].iov_base = d = realloc(d, sz);
587   if (d == NULL) {
588     log_Printf(LogALERT, "Failed to allocate memory: %d\n", sz);
589     AbortProgram(EX_OSERR);
590   }
591   iov[*niov].iov_len = sz;
592   (*niov)++;
593 
594   dev = device2tty(d);
595 
596 #ifndef NONETGRAPH
597   if (dev->cs >= 0) {
598     *auxfd = dev->cs;
599     (*nauxfd)++;
600   }
601 #endif
602 
603   if (dev->Timer.state != TIMER_STOPPED) {
604     timer_Stop(&dev->Timer);
605     dev->Timer.state = TIMER_RUNNING;
606   }
607 }
608 
609 static struct device basettydevice = {
610   TTY_DEVICE,
611   "tty",
612   0,
613   { CD_VARIABLE, DEF_TTYCDDELAY },
614   tty_AwaitCarrier,
615   NULL,
616   tty_Raw,
617   tty_Offline,
618   tty_Cooked,
619   tty_SetAsyncParams,
620   tty_StopTimer,
621   tty_Free,
622   tty_Read,
623   tty_Write,
624   tty_device2iov,
625   tty_Speed,
626   tty_OpenInfo,
627   tty_Slot
628 };
629 
630 struct device *
tty_iov2device(int type,struct physical * p,struct iovec * iov,int * niov,int maxiov __unused,int * auxfd,int * nauxfd)631 tty_iov2device(int type, struct physical *p, struct iovec *iov, int *niov,
632                int maxiov __unused,
633 #ifndef NONETGRAPH
634                int *auxfd, int *nauxfd
635 #else
636                int *auxfd __unused, int *nauxfd __unused
637 #endif
638                )
639 {
640   if (type == TTY_DEVICE) {
641     struct ttydevice *dev = (struct ttydevice *)iov[(*niov)++].iov_base;
642 
643     dev = realloc(dev, sizeof *dev);	/* Reduce to the correct size */
644     if (dev == NULL) {
645       log_Printf(LogALERT, "Failed to allocate memory: %d\n",
646                  (int)(sizeof *dev));
647       AbortProgram(EX_OSERR);
648     }
649 
650 #ifndef NONETGRAPH
651     if (*nauxfd) {
652       dev->cs = *auxfd;
653       (*nauxfd)--;
654     } else
655       dev->cs = -1;
656 #endif
657 
658     /* Refresh function pointers etc */
659     memcpy(&dev->dev, &basettydevice, sizeof dev->dev);
660 
661     physical_SetupStack(p, dev->dev.name, PHYSICAL_NOFORCE);
662     if (dev->Timer.state != TIMER_STOPPED) {
663       dev->Timer.state = TIMER_STOPPED;
664       p->handler = &dev->dev;		/* For the benefit of StartTimer */
665       tty_StartTimer(p);
666     }
667     return &dev->dev;
668   }
669 
670   return NULL;
671 }
672 
673 struct device *
tty_Create(struct physical * p)674 tty_Create(struct physical *p)
675 {
676   struct ttydevice *dev;
677   struct termios ios;
678   int oldflag;
679 
680   if (p->fd < 0 || !isatty(p->fd))
681     /* Don't want this */
682     return NULL;
683 
684   if (*p->name.full == '\0') {
685     physical_SetDevice(p, ttyname(p->fd));
686     log_Printf(LogDEBUG, "%s: Input is a tty (%s)\n",
687                p->link.name, p->name.full);
688   } else
689     log_Printf(LogDEBUG, "%s: Opened %s\n", p->link.name, p->name.full);
690 
691   /* We're gonna return a ttydevice (unless something goes horribly wrong) */
692 
693   if ((dev = malloc(sizeof *dev)) == NULL) {
694     /* Complete failure - parent doesn't continue trying to ``create'' */
695     close(p->fd);
696     p->fd = -1;
697     return NULL;
698   }
699 
700   memcpy(&dev->dev, &basettydevice, sizeof dev->dev);
701   memset(&dev->Timer, '\0', sizeof dev->Timer);
702   dev->mbits = -1;
703 #ifndef NONETGRAPH
704   dev->real.speed = 0;
705   dev->real.fd = -1;
706   dev->real.disc = -1;
707   *dev->hook = '\0';
708 #endif
709   tcgetattr(p->fd, &ios);
710   dev->ios = ios;
711 
712   if (p->cfg.cd.necessity != CD_DEFAULT)
713     /* Any override is ok for the tty device */
714     dev->dev.cd = p->cfg.cd;
715 
716   log_Printf(LogDEBUG, "%s: tty_Create: physical (get): fd = %d,"
717              " iflag = %lx, oflag = %lx, cflag = %lx\n", p->link.name, p->fd,
718              (u_long)ios.c_iflag, (u_long)ios.c_oflag, (u_long)ios.c_cflag);
719 
720   cfmakeraw(&ios);
721   if (p->cfg.rts_cts)
722     ios.c_cflag |= CLOCAL | CCTS_OFLOW | CRTS_IFLOW;
723   else {
724     ios.c_cflag |= CLOCAL;
725     ios.c_iflag |= IXOFF;
726   }
727   ios.c_iflag |= IXON;
728   if (p->type != PHYS_DEDICATED)
729     ios.c_cflag |= HUPCL;
730 
731   if (p->type != PHYS_DIRECT) {
732       /* Change tty speed when we're not in -direct mode */
733       ios.c_cflag &= ~(CSIZE | PARODD | PARENB);
734       ios.c_cflag |= p->cfg.parity;
735       if (cfsetspeed(&ios, UnsignedToSpeed(p->cfg.speed)) == -1)
736 	log_Printf(LogWARN, "%s: %s: Unable to set speed to %d\n",
737 		  p->link.name, p->name.full, p->cfg.speed);
738   }
739 
740   if (tcsetattr(p->fd, TCSADRAIN, &ios) == -1) {
741     log_Printf(LogWARN, "%s: tcsetattr: Failed configuring device\n",
742                p->link.name);
743     if (p->type != PHYS_DIRECT && p->cfg.speed > 115200)
744       log_Printf(LogWARN, "%.*s             Perhaps the speed is unsupported\n",
745                  (int)strlen(p->link.name), "");
746   }
747 
748   log_Printf(LogDEBUG, "%s: physical (put): iflag = %lx, oflag = %lx, "
749             "cflag = %lx\n", p->link.name, (u_long)ios.c_iflag,
750             (u_long)ios.c_oflag, (u_long)ios.c_cflag);
751 
752   oldflag = fcntl(p->fd, F_GETFL, 0);
753   if (oldflag < 0) {
754     /* Complete failure - parent doesn't continue trying to ``create'' */
755 
756     log_Printf(LogWARN, "%s: Open: Cannot get physical flags: %s\n",
757                p->link.name, strerror(errno));
758     tty_Cooked(p);
759     close(p->fd);
760     p->fd = -1;
761     free(dev);
762     return NULL;
763   } else
764     fcntl(p->fd, F_SETFL, oldflag & ~O_NONBLOCK);
765 
766   physical_SetupStack(p, dev->dev.name, PHYSICAL_NOFORCE);
767 
768   return &dev->dev;
769 }
770