xref: /freebsd/usr.sbin/ppp/tty.c (revision 817420dc8eac7df799c78f5309b75092b7f7cd40)
1 /*-
2  * Copyright (c) 1999 Brian Somers <brian@Awfulhak.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
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 <stdlib.h>
38 #include <string.h>
39 #include <sysexits.h>
40 #include <sys/uio.h>
41 #include <termios.h>
42 #include <unistd.h>
43 
44 #include "layer.h"
45 #include "defs.h"
46 #include "mbuf.h"
47 #include "log.h"
48 #include "timer.h"
49 #include "lqr.h"
50 #include "hdlc.h"
51 #include "throughput.h"
52 #include "fsm.h"
53 #include "lcp.h"
54 #include "ccp.h"
55 #include "link.h"
56 #include "async.h"
57 #include "descriptor.h"
58 #include "physical.h"
59 #include "mp.h"
60 #include "chat.h"
61 #include "auth.h"
62 #include "chap.h"
63 #include "cbcp.h"
64 #include "datalink.h"
65 #include "main.h"
66 #include "tty.h"
67 
68 #if defined(__mac68k__) || defined(__macppc__)
69 #undef	CRTS_IFLOW
70 #undef	CCTS_OFLOW
71 #define	CRTS_IFLOW	CDTRCTS
72 #define	CCTS_OFLOW	CDTRCTS
73 #endif
74 
75 #define	Online(dev)	((dev)->mbits & TIOCM_CD)
76 
77 struct ttydevice {
78   struct device dev;		/* What struct physical knows about */
79   struct pppTimer Timer;	/* CD checks */
80   int mbits;			/* Current DCD status */
81   int carrier_seconds;		/* seconds before CD is *required* */
82   struct termios ios;		/* To be able to reset from raw mode */
83 };
84 
85 #define device2tty(d) ((d)->type == TTY_DEVICE ? (struct ttydevice *)d : NULL)
86 
87 int
88 tty_DeviceSize(void)
89 {
90   return sizeof(struct ttydevice);
91 }
92 
93 /*
94  * tty_Timeout() watches the DCD signal and mentions it if it's status
95  * changes.
96  */
97 static void
98 tty_Timeout(void *data)
99 {
100   struct physical *p = data;
101   struct ttydevice *dev = device2tty(p->handler);
102   int ombits, change;
103 
104   timer_Stop(&dev->Timer);
105   dev->Timer.load = SECTICKS;		/* Once a second please */
106   timer_Start(&dev->Timer);
107   ombits = dev->mbits;
108 
109   if (p->fd >= 0) {
110     if (ioctl(p->fd, TIOCMGET, &dev->mbits) < 0) {
111       /* we must be a pty ? */
112       if (p->cfg.cd.necessity != CD_DEFAULT)
113         log_Printf(LogWARN, "%s: Carrier ioctl not supported, "
114                    "using ``set cd off''\n", p->link.name);
115       timer_Stop(&dev->Timer);
116       dev->mbits = TIOCM_CD;
117       return;
118     }
119   } else
120     dev->mbits = 0;
121 
122   if (ombits == -1) {
123     /* First time looking for carrier */
124     if (Online(dev))
125       log_Printf(LogPHASE, "%s: %s: CD detected\n", p->link.name, p->name.full);
126     else if (++dev->carrier_seconds >= dev->dev.cd.delay) {
127       if (dev->dev.cd.necessity == CD_REQUIRED)
128         log_Printf(LogPHASE, "%s: %s: Required CD not detected\n",
129                    p->link.name, p->name.full);
130       else {
131         log_Printf(LogPHASE, "%s: %s doesn't support CD\n",
132                    p->link.name, p->name.full);
133         dev->mbits = TIOCM_CD;		/* Dodgy null-modem cable ? */
134       }
135       timer_Stop(&dev->Timer);
136       /* tty_AwaitCarrier() will notice */
137     } else {
138       /* Keep waiting */
139       log_Printf(LogDEBUG, "%s: %s: Still no carrier (%d/%d)\n",
140                  p->link.name, p->name.full, dev->carrier_seconds,
141                  dev->dev.cd.delay);
142       dev->mbits = -1;
143     }
144   } else {
145     change = ombits ^ dev->mbits;
146     if (change & TIOCM_CD) {
147       if (dev->mbits & TIOCM_CD)
148         log_Printf(LogDEBUG, "%s: offline -> online\n", p->link.name);
149       else {
150         log_Printf(LogDEBUG, "%s: online -> offline\n", p->link.name);
151         log_Printf(LogPHASE, "%s: Carrier lost\n", p->link.name);
152         datalink_Down(p->dl, CLOSE_NORMAL);
153         timer_Stop(&dev->Timer);
154       }
155     } else
156       log_Printf(LogDEBUG, "%s: Still %sline\n", p->link.name,
157                  Online(dev) ? "on" : "off");
158   }
159 }
160 
161 static void
162 tty_StartTimer(struct physical *p)
163 {
164   struct ttydevice *dev = device2tty(p->handler);
165 
166   timer_Stop(&dev->Timer);
167   dev->Timer.load = SECTICKS;
168   dev->Timer.func = tty_Timeout;
169   dev->Timer.name = "tty CD";
170   dev->Timer.arg = p;
171   log_Printf(LogDEBUG, "%s: Using tty_Timeout [%p]\n",
172              p->link.name, tty_Timeout);
173   timer_Start(&dev->Timer);
174 }
175 
176 static int
177 tty_AwaitCarrier(struct physical *p)
178 {
179   struct ttydevice *dev = device2tty(p->handler);
180 
181   if (dev->dev.cd.necessity == CD_NOTREQUIRED || physical_IsSync(p))
182     return CARRIER_OK;
183 
184   if (dev->mbits == -1) {
185     if (dev->Timer.state == TIMER_STOPPED) {
186       dev->carrier_seconds = 0;
187       tty_StartTimer(p);
188     }
189     return CARRIER_PENDING;			/* Not yet ! */
190   }
191 
192   return Online(dev) ? CARRIER_OK : CARRIER_LOST;
193 }
194 
195 static int
196 tty_Raw(struct physical *p)
197 {
198   struct ttydevice *dev = device2tty(p->handler);
199   struct termios ios;
200   int oldflag;
201 
202   log_Printf(LogDEBUG, "%s: Entering tty_Raw\n", p->link.name);
203 
204   if (p->type != PHYS_DIRECT && p->fd >= 0 && !Online(dev))
205     log_Printf(LogDEBUG, "%s: Raw: descriptor = %d, mbits = %x\n",
206               p->link.name, p->fd, dev->mbits);
207 
208   if (!physical_IsSync(p)) {
209     tcgetattr(p->fd, &ios);
210     cfmakeraw(&ios);
211     if (p->cfg.rts_cts)
212       ios.c_cflag |= CLOCAL | CCTS_OFLOW | CRTS_IFLOW;
213     else
214       ios.c_cflag |= CLOCAL;
215 
216     if (p->type != PHYS_DEDICATED)
217       ios.c_cflag |= HUPCL;
218 
219     if (tcsetattr(p->fd, TCSANOW, &ios) == -1)
220       log_Printf(LogWARN, "%s: tcsetattr: Failed configuring device\n",
221                  p->link.name);
222   }
223 
224   oldflag = fcntl(p->fd, F_GETFL, 0);
225   if (oldflag < 0)
226     return 0;
227   fcntl(p->fd, F_SETFL, oldflag | O_NONBLOCK);
228 
229   return 1;
230 }
231 
232 static void
233 tty_Offline(struct physical *p)
234 {
235   struct ttydevice *dev = device2tty(p->handler);
236 
237   if (p->fd >= 0) {
238     timer_Stop(&dev->Timer);
239     dev->mbits &= ~TIOCM_DTR;	/* XXX: Hmm, what's this supposed to do ? */
240     if (Online(dev)) {
241       struct termios tio;
242 
243       tcgetattr(p->fd, &tio);
244       if (cfsetspeed(&tio, B0) == -1 || tcsetattr(p->fd, TCSANOW, &tio) == -1)
245         log_Printf(LogWARN, "%s: Unable to set physical to speed 0\n",
246                    p->link.name);
247     }
248   }
249 }
250 
251 static void
252 tty_Cooked(struct physical *p)
253 {
254   struct ttydevice *dev = device2tty(p->handler);
255   int oldflag;
256 
257   tty_Offline(p);	/* In case of emergency close()s */
258 
259   tcflush(p->fd, TCIOFLUSH);
260 
261   if (!physical_IsSync(p) && tcsetattr(p->fd, TCSAFLUSH, &dev->ios) == -1)
262     log_Printf(LogWARN, "%s: tcsetattr: Unable to restore device settings\n",
263                p->link.name);
264 
265   if ((oldflag = fcntl(p->fd, F_GETFL, 0)) != -1)
266     fcntl(p->fd, F_SETFL, oldflag & ~O_NONBLOCK);
267 }
268 
269 static void
270 tty_StopTimer(struct physical *p)
271 {
272   struct ttydevice *dev = device2tty(p->handler);
273 
274   timer_Stop(&dev->Timer);
275 }
276 
277 static void
278 tty_Free(struct physical *p)
279 {
280   struct ttydevice *dev = device2tty(p->handler);
281 
282   tty_Offline(p);	/* In case of emergency close()s */
283   free(dev);
284 }
285 
286 static int
287 tty_Speed(struct physical *p)
288 {
289   struct termios ios;
290 
291   if (tcgetattr(p->fd, &ios) == -1)
292     return 0;
293 
294   return SpeedToInt(cfgetispeed(&ios));
295 }
296 
297 static const char *
298 tty_OpenInfo(struct physical *p)
299 {
300   struct ttydevice *dev = device2tty(p->handler);
301   static char buf[13];
302 
303   if (Online(dev))
304     strcpy(buf, "with");
305   else
306     strcpy(buf, "no");
307   strcat(buf, " carrier");
308 
309   return buf;
310 }
311 
312 static void
313 tty_device2iov(struct device *d, struct iovec *iov, int *niov,
314                int maxiov, int *auxfd, int *nauxfd)
315 {
316   struct ttydevice *dev = device2tty(d);
317   int sz = physical_MaxDeviceSize();
318 
319   iov[*niov].iov_base = realloc(d, sz);
320   if (iov[*niov].iov_base == NULL) {
321     log_Printf(LogALERT, "Failed to allocate memory: %d\n", sz);
322     AbortProgram(EX_OSERR);
323   }
324   iov[*niov].iov_len = sz;
325   (*niov)++;
326 
327   if (dev->Timer.state != TIMER_STOPPED) {
328     timer_Stop(&dev->Timer);
329     dev->Timer.state = TIMER_RUNNING;
330   }
331 }
332 
333 static struct device basettydevice = {
334   TTY_DEVICE,
335   "tty",
336   { CD_VARIABLE, DEF_TTYCDDELAY },
337   tty_AwaitCarrier,
338   NULL,
339   tty_Raw,
340   tty_Offline,
341   tty_Cooked,
342   tty_StopTimer,
343   tty_Free,
344   NULL,
345   NULL,
346   tty_device2iov,
347   tty_Speed,
348   tty_OpenInfo
349 };
350 
351 struct device *
352 tty_iov2device(int type, struct physical *p, struct iovec *iov, int *niov,
353                int maxiov, int *auxfd, int *nauxfd)
354 {
355   if (type == TTY_DEVICE) {
356     struct ttydevice *dev = (struct ttydevice *)iov[(*niov)++].iov_base;
357 
358     dev = realloc(dev, sizeof *dev);	/* Reduce to the correct size */
359     if (dev == NULL) {
360       log_Printf(LogALERT, "Failed to allocate memory: %d\n",
361                  (int)(sizeof *dev));
362       AbortProgram(EX_OSERR);
363     }
364 
365     /* Refresh function pointers etc */
366     memcpy(&dev->dev, &basettydevice, sizeof dev->dev);
367 
368     physical_SetupStack(p, dev->dev.name, PHYSICAL_NOFORCE);
369     if (dev->Timer.state != TIMER_STOPPED) {
370       dev->Timer.state = TIMER_STOPPED;
371       p->handler = &dev->dev;		/* For the benefit of StartTimer */
372       tty_StartTimer(p);
373     }
374     return &dev->dev;
375   }
376 
377   return NULL;
378 }
379 
380 struct device *
381 tty_Create(struct physical *p)
382 {
383   struct ttydevice *dev;
384   struct termios ios;
385   int oldflag;
386 
387   if (p->fd < 0 || !isatty(p->fd))
388     /* Don't want this */
389     return NULL;
390 
391   if (*p->name.full == '\0') {
392     physical_SetDevice(p, ttyname(p->fd));
393     log_Printf(LogDEBUG, "%s: Input is a tty (%s)\n",
394                p->link.name, p->name.full);
395   } else
396     log_Printf(LogDEBUG, "%s: Opened %s\n", p->link.name, p->name.full);
397 
398   /* We're gonna return a ttydevice (unless something goes horribly wrong) */
399 
400   if ((dev = malloc(sizeof *dev)) == NULL) {
401     /* Complete failure - parent doesn't continue trying to ``create'' */
402     close(p->fd);
403     p->fd = -1;
404     return NULL;
405   }
406 
407   memcpy(&dev->dev, &basettydevice, sizeof dev->dev);
408   memset(&dev->Timer, '\0', sizeof dev->Timer);
409   dev->mbits = -1;
410   tcgetattr(p->fd, &ios);
411   dev->ios = ios;
412 
413   if (p->cfg.cd.necessity != CD_DEFAULT)
414     /* Any override is ok for the tty device */
415     dev->dev.cd = p->cfg.cd;
416 
417   log_Printf(LogDEBUG, "%s: tty_Create: physical (get): fd = %d,"
418              " iflag = %lx, oflag = %lx, cflag = %lx\n", p->link.name, p->fd,
419              (u_long)ios.c_iflag, (u_long)ios.c_oflag, (u_long)ios.c_cflag);
420 
421   cfmakeraw(&ios);
422   if (p->cfg.rts_cts)
423     ios.c_cflag |= CLOCAL | CCTS_OFLOW | CRTS_IFLOW;
424   else {
425     ios.c_cflag |= CLOCAL;
426     ios.c_iflag |= IXOFF;
427   }
428   ios.c_iflag |= IXON;
429   if (p->type != PHYS_DEDICATED)
430     ios.c_cflag |= HUPCL;
431 
432   if (p->type != PHYS_DIRECT) {
433       /* Change tty speed when we're not in -direct mode */
434       ios.c_cflag &= ~(CSIZE | PARODD | PARENB);
435       ios.c_cflag |= p->cfg.parity;
436       if (cfsetspeed(&ios, IntToSpeed(p->cfg.speed)) == -1)
437 	log_Printf(LogWARN, "%s: %s: Unable to set speed to %d\n",
438 		  p->link.name, p->name.full, p->cfg.speed);
439   }
440 
441   if (tcsetattr(p->fd, TCSADRAIN, &ios) == -1) {
442     log_Printf(LogWARN, "%s: tcsetattr: Failed configuring device\n",
443                p->link.name);
444     if (p->type != PHYS_DIRECT && p->cfg.speed > 115200)
445       log_Printf(LogWARN, "%.*s             Perhaps the speed is unsupported\n",
446                  (int)strlen(p->link.name), "");
447   }
448 
449   log_Printf(LogDEBUG, "%s: physical (put): iflag = %lx, oflag = %lx, "
450             "cflag = %lx\n", p->link.name, (u_long)ios.c_iflag,
451             (u_long)ios.c_oflag, (u_long)ios.c_cflag);
452 
453   oldflag = fcntl(p->fd, F_GETFL, 0);
454   if (oldflag < 0) {
455     /* Complete failure - parent doesn't continue trying to ``create'' */
456 
457     log_Printf(LogWARN, "%s: Open: Cannot get physical flags: %s\n",
458                p->link.name, strerror(errno));
459     tty_Cooked(p);
460     close(p->fd);
461     p->fd = -1;
462     free(dev);
463     return NULL;
464   } else
465     fcntl(p->fd, F_SETFL, oldflag & ~O_NONBLOCK);
466 
467   physical_SetupStack(p, dev->dev.name, PHYSICAL_NOFORCE);
468 
469   return &dev->dev;
470 }
471