277a4abffc3d72e15529a7e319e9c9f1c001aa2b
[dragonfly.git] / usr.bin / tip / tip / tip.c
1 /*
2  * Copyright (c) 1983, 1993
3  *      The Regents of the University of California.  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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1983, 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)tip.c    8.1 (Berkeley) 6/6/93
35  * $FreeBSD: src/usr.bin/tip/tip/tip.c,v 1.12.2.2 2001/06/02 08:08:24 phk Exp $
36  */
37
38 /*
39         Forward declarations
40 */
41 void ttysetup (int speed);
42
43 /*
44  * tip - UNIX link to other systems
45  *  tip [-v] [-speed] system-name
46  * or
47  *  cu phone-number [-s speed] [-l line] [-a acu]
48  */
49
50 #include <err.h>
51 #include <errno.h>
52 #include <sys/types.h>
53 #include <libutil.h>
54 #include "tipconf.h"
55 #include "tip.h"
56 #include "pathnames.h"
57
58 /*
59  * Baud rate mapping table
60  */
61 #if !HAVE_TERMIOS
62 CONST int bauds[] = {
63         0, 50, 75, 110, 134, 150, 200, 300, 600,
64         1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200, -1
65 };
66 #endif
67
68 #if !HAVE_TERMIOS
69 int     disc = OTTYDISC;                /* tip normally runs this way */
70 #endif
71
72 void    intprompt();
73 void    timeout(int);
74 void    killchild();
75 void    cleanup();
76 void    tipdone();
77 char    *sname();
78 char    PNbuf[256];                     /* This limits the size of a number */
79
80 static void usage(void);
81 void setparity(char *);
82 void xpwrite(int, char *, int);
83 char escape(void);
84 void tipin(void);
85 int prompt(char *, char *, size_t);
86 void unraw(void);
87 void shell_uid(void);
88 void daemon_uid(void);
89 void user_uid(void);
90 int speed(int);
91
92 int
93 main(argc, argv)
94         char *argv[];
95 {
96         char *system = NULL;
97         int i;
98         char *p;
99         char sbuf[12];
100
101         gid = getgid();
102         egid = getegid();
103         uid = getuid();
104         euid = geteuid();
105
106 #if INCLUDE_CU_INTERFACE
107         if (equal(sname(argv[0]), "cu")) {
108                 cumode = 1;
109                 cumain(argc, argv);
110                 goto cucommon;
111         }
112 #endif /* INCLUDE_CU_INTERFACE */
113
114         if (argc > 4)
115                 usage();
116         if (!isatty(0))
117                 errx(1, "must be interactive");
118
119         for (; argc > 1; argv++, argc--) {
120                 if (argv[1][0] != '-')
121                         system = argv[1];
122                 else switch (argv[1][1]) {
123
124                 case 'v':
125                         vflag++;
126                         break;
127
128                 case '0': case '1': case '2': case '3': case '4':
129                 case '5': case '6': case '7': case '8': case '9':
130                         BR = atoi(&argv[1][1]);
131                         break;
132
133                 default:
134                         warnx("%s, unknown option", argv[1]);
135                         break;
136                 }
137         }
138
139         if (system == NULL)
140                 goto notnumber;
141         if (isalpha(*system))
142                 goto notnumber;
143         /*
144          * System name is really a phone number...
145          * Copy the number then stomp on the original (in case the number
146          *      is private, we don't want 'ps' or 'w' to find it).
147          */
148         if (strlen(system) > sizeof(PNbuf) - 1)
149                 errx(1, "phone number too long (max = %d bytes)", sizeof PNbuf - 1);
150         strncpy(PNbuf, system, sizeof(PNbuf) - 1);
151         for (p = system; *p; p++)
152                 *p = '\0';
153         PN = PNbuf;
154         (void)snprintf(sbuf, sizeof(sbuf), "tip%ld", BR);
155         system = sbuf;
156
157 notnumber:
158         (void)signal(SIGINT, cleanup);
159         (void)signal(SIGQUIT, cleanup);
160         (void)signal(SIGHUP, cleanup);
161         (void)signal(SIGTERM, cleanup);
162         (void)signal(SIGUSR1, tipdone);
163
164         if ((i = hunt(system)) == 0) {
165                 printf("all ports busy\n");
166                 exit(3);
167         }
168         if (i == -1) {
169                 printf("link down\n");
170                 (void)uu_unlock(uucplock);
171                 exit(3);
172         }
173         setbuf(stdout, NULL);
174         loginit();
175
176         /*
177          * Kludge, their's no easy way to get the initialization
178          *   in the right order, so force it here
179          */
180         if ((PH = getenv("PHONES")) == NULL)
181                 PH = _PATH_PHONES;
182         vinit();                                /* init variables */
183         setparity("even");                      /* set the parity table */
184         if ((i = speed(number(value(BAUDRATE)))) == 0) {
185                 printf("tip: bad baud rate %d\n", number(value(BAUDRATE)));
186                 (void)uu_unlock(uucplock);
187                 exit(3);
188         }
189
190         /*
191          * Now that we have the logfile and the ACU open
192          *  return to the real uid and gid.  These things will
193          *  be closed on exit.  Swap real and effective uid's
194          *  so we can get the original permissions back
195          *  for removing the uucp lock.
196          */
197         user_uid();
198
199         /*
200          * Hardwired connections require the
201          *  line speed set before they make any transmissions
202          *  (this is particularly true of things like a DF03-AC)
203          */
204         if (HW)
205                 ttysetup(i);
206         if ((p = connect())) {
207                 printf("\07%s\n[EOT]\n", p);
208                 daemon_uid();
209                 (void)uu_unlock(uucplock);
210                 exit(1);
211         }
212         if (!HW)
213                 ttysetup(i);
214 cucommon:
215         /*
216          * From here down the code is shared with
217          * the "cu" version of tip.
218          */
219
220 #if HAVE_TERMIOS
221         tcgetattr (0, &otermios);
222         ctermios = otermios;
223 #ifndef _POSIX_SOURCE
224         ctermios.c_iflag = (IMAXBEL|IXANY|ISTRIP|IXON|BRKINT);
225         ctermios.c_lflag = (PENDIN|IEXTEN|ISIG|ECHOCTL|ECHOE|ECHOKE);
226 #else
227         ctermios.c_iflag = (ISTRIP|IXON|BRKINT);
228         ctermios.c_lflag = (PENDIN|IEXTEN|ISIG|ECHOE);
229 #endif
230         ctermios.c_cflag = (CLOCAL|HUPCL|CREAD|CS8);
231         ctermios.c_cc[VINTR] =  ctermios.c_cc[VQUIT] = -1;
232         ctermios.c_cc[VSUSP] = ctermios.c_cc[VDSUSP] = ctermios.c_cc[VDISCARD] =
233                 ctermios.c_cc[VLNEXT] = -1;
234 #else /* HAVE_TERMIOS */
235         ioctl(0, TIOCGETP, (char *)&defarg);
236         ioctl(0, TIOCGETC, (char *)&defchars);
237         ioctl(0, TIOCGLTC, (char *)&deflchars);
238         ioctl(0, TIOCGETD, (char *)&odisc);
239         arg = defarg;
240         arg.sg_flags = ANYP | CBREAK;
241         tchars = defchars;
242         tchars.t_intrc = tchars.t_quitc = -1;
243         ltchars = deflchars;
244         ltchars.t_suspc = ltchars.t_dsuspc = ltchars.t_flushc
245                 = ltchars.t_lnextc = -1;
246 #endif /* HAVE_TERMIOS */
247         raw();
248
249         pipe(fildes); pipe(repdes);
250         (void)signal(SIGALRM, timeout);
251
252         /*
253          * Everything's set up now:
254          *      connection established (hardwired or dialup)
255          *      line conditioned (baud rate, mode, etc.)
256          *      internal data structures (variables)
257          * so, fork one process for local side and one for remote.
258          */
259         printf(cumode ? "Connected\r\n" : "\07connected\r\n");
260
261         if (LI != NULL && tiplink (LI, 0) != 0) {
262                 tipabort ("login failed");
263         }
264
265         if ((pid = fork()))
266                 tipin();
267         else
268                 tipout();
269         /*NOTREACHED*/
270 }
271
272 static void
273 usage()
274 {
275         fprintf(stderr, "usage: tip [-v] [-speed] [system-name]\n");
276         exit(1);
277 }
278
279 void
280 killchild()
281 {
282         if (pid != 0) {
283                 kill(pid, SIGTERM);
284                 pid = 0;
285         }
286 }
287
288 void
289 cleanup()
290 {
291
292         daemon_uid();
293         (void)uu_unlock(uucplock);
294 #if !HAVE_TERMIOS
295         if (odisc)
296                 ioctl(0, TIOCSETD, (char *)&odisc);
297 #endif
298         exit(0);
299 }
300
301 void
302 tipdone()
303 {
304         tipabort("Hangup.");
305 }
306 /*
307  * Muck with user ID's.  We are setuid to the owner of the lock
308  * directory when we start.  user_uid() reverses real and effective
309  * ID's after startup, to run with the user's permissions.
310  * daemon_uid() switches back to the privileged uid for unlocking.
311  * Finally, to avoid running a shell with the wrong real uid,
312  * shell_uid() sets real and effective uid's to the user's real ID.
313  */
314 static int uidswapped;
315
316 void
317 user_uid()
318 {
319         if (uidswapped == 0) {
320                 seteuid(uid);
321                 uidswapped = 1;
322         }
323 }
324
325 void
326 daemon_uid()
327 {
328         if (uidswapped) {
329                 seteuid(euid);
330                 uidswapped = 0;
331         }
332 }
333
334 void
335 shell_uid()
336 {
337         setegid(gid);
338         seteuid(uid);
339 }
340
341 /*
342  * put the controlling keyboard into raw mode
343  */
344 void
345 raw ()
346 {
347 #if HAVE_TERMIOS
348         tcsetattr (0, TCSANOW, &ctermios);
349 #else /* HAVE_TERMIOS */
350
351         ioctl(0, TIOCSETP, &arg);
352         ioctl(0, TIOCSETC, &tchars);
353         ioctl(0, TIOCSLTC, &ltchars);
354         ioctl(0, TIOCSETD, (char *)&disc);
355 #endif /* HAVE_TERMIOS */
356 }
357
358
359 /*
360  * return keyboard to normal mode
361  */
362 void
363 unraw()
364 {
365 #if HAVE_TERMIOS
366         tcsetattr (0, TCSANOW, &otermios);
367 #else /* HAVE_TERMIOS */
368
369         ioctl(0, TIOCSETD, (char *)&odisc);
370         ioctl(0, TIOCSETP, (char *)&defarg);
371         ioctl(0, TIOCSETC, (char *)&defchars);
372         ioctl(0, TIOCSLTC, (char *)&deflchars);
373 #endif /* HAVE_TERMIOS */
374 }
375
376 static  jmp_buf promptbuf;
377
378 /*
379  * Print string ``s'', then read a string
380  *  in from the terminal.  Handles signals & allows use of
381  *  normal erase and kill characters.
382  */
383 int
384 prompt(s, p, sz)
385         char *s;
386         char *p;
387         size_t sz;
388 {
389         char *b = p;
390         sig_t oint, oquit;
391
392         stoprompt = 0;
393         oint = signal(SIGINT, intprompt);
394         oquit = signal(SIGQUIT, SIG_IGN);
395         unraw();
396         printf("%s", s);
397         if (setjmp(promptbuf) == 0)
398                 while ((*p = getchar()) != EOF && *p != '\n' && --sz > 0)
399                         p++;
400         *p = '\0';
401
402         raw();
403         (void)signal(SIGINT, oint);
404         (void)signal(SIGQUIT, oquit);
405         return (stoprompt || p == b);
406 }
407
408 /*
409  * Interrupt service routine during prompting
410  */
411 void
412 intprompt()
413 {
414
415         (void)signal(SIGINT, SIG_IGN);
416         stoprompt = 1;
417         printf("\r\n");
418         longjmp(promptbuf, 1);
419 }
420
421 /*
422  * ****TIPIN   TIPIN****
423  */
424 void
425 tipin()
426 {
427         int i;
428         char gch, bol = 1;
429
430         atexit(killchild);
431
432         /*
433          * Kinda klugey here...
434          *   check for scripting being turned on from the .tiprc file,
435          *   but be careful about just using setscript(), as we may
436          *   send a SIGEMT before tipout has a chance to set up catching
437          *   it; so wait a second, then setscript()
438          */
439         if (boolean(value(SCRIPT))) {
440                 sleep(1);
441                 setscript();
442         }
443
444         while (1) {
445                 i = getchar();
446                 if (i == EOF)
447                         break;
448                 gch = i&0177;
449                 if ((gch == character(value(ESCAPE))) && bol) {
450                         if (!(gch = escape()))
451                                 continue;
452                 } else if (!cumode && gch == character(value(RAISECHAR))) {
453                         boolean(value(RAISE)) = !boolean(value(RAISE));
454                         continue;
455                 } else if (gch == '\r') {
456                         bol = 1;
457                         xpwrite(FD, &gch, 1);
458                         if (boolean(value(HALFDUPLEX)))
459                                 printf("\r\n");
460                         continue;
461                 } else if (!cumode && gch == character(value(FORCE))) {
462                         i = getchar();
463                         if (i == EOF)
464                                 break;
465                         gch = i & 0177;
466                 }
467                 bol = any(gch, value(EOL));
468                 if (boolean(value(RAISE)) && islower(gch))
469                         gch = toupper(gch);
470                 xpwrite(FD, &gch, 1);
471                 if (boolean(value(HALFDUPLEX)))
472                         printf("%c", gch);
473         }
474 }
475
476 extern esctable_t etable[];
477
478 /*
479  * Escape handler --
480  *  called on recognition of ``escapec'' at the beginning of a line
481  */
482 char
483 escape()
484 {
485         char gch;
486         esctable_t *p;
487         char c = character(value(ESCAPE));
488         int i;
489
490         i = getchar();
491         if (i == EOF)
492                 return 0;
493         gch = (i&0177);
494         for (p = etable; p->e_char; p++)
495                 if (p->e_char == gch) {
496                         if ((p->e_flags&PRIV) && uid)
497                                 continue;
498                         printf("%s", ctrl(c));
499                         (*p->e_func)(gch);
500                         return (0);
501                 }
502         /* ESCAPE ESCAPE forces ESCAPE */
503         if (c != gch)
504                 xpwrite(FD, &c, 1);
505         return (gch);
506 }
507
508 int
509 speed(n)
510         int n;
511 {
512 #if HAVE_TERMIOS
513         return (n);
514 #else
515         CONST int *p;
516
517         for (p = bauds; *p != -1;  p++)
518                 if (*p == n)
519                         return (p - bauds);
520         return (NULL);
521 #endif
522 }
523
524 int
525 any(c, p)
526         char c, *p;
527 {
528         while (p && *p)
529                 if (*p++ == c)
530                         return (1);
531         return (0);
532 }
533
534 int
535 size(s)
536         char    *s;
537 {
538         int i = 0;
539
540         while (s && *s++)
541                 i++;
542         return (i);
543 }
544
545 char *
546 interp(s)
547         char *s;
548 {
549         static char buf[256];
550         char *p = buf, c, *q;
551
552         while ((c = *s++)) {
553                 for (q = "\nn\rr\tt\ff\033E\bb"; *q; q++)
554                         if (*q++ == c) {
555                                 *p++ = '\\'; *p++ = *q;
556                                 goto next;
557                         }
558                 if (c < 040) {
559                         *p++ = '^'; *p++ = c + 'A'-1;
560                 } else if (c == 0177) {
561                         *p++ = '^'; *p++ = '?';
562                 } else
563                         *p++ = c;
564         next:
565                 ;
566         }
567         *p = '\0';
568         return (buf);
569 }
570
571 char *
572 ctrl(c)
573         char c;
574 {
575         static char s[3];
576
577         if (c < 040 || c == 0177) {
578                 s[0] = '^';
579                 s[1] = c == 0177 ? '?' : c+'A'-1;
580                 s[2] = '\0';
581         } else {
582                 s[0] = c;
583                 s[1] = '\0';
584         }
585         return (s);
586 }
587
588 /*
589  * Help command
590  */
591 void
592 help(c)
593         char c;
594 {
595         esctable_t *p;
596
597         printf("%c\r\n", c);
598         for (p = etable; p->e_char; p++) {
599                 if ((p->e_flags&PRIV) && uid)
600                         continue;
601                 printf("%2s", ctrl(character(value(ESCAPE))));
602                 printf("%-2s %c   %s\r\n", ctrl(p->e_char),
603                         p->e_flags&EXP ? '*': ' ', p->e_help);
604         }
605 }
606
607 /*
608  * Set up the "remote" tty's state
609  */
610 void
611 ttysetup (int speed)
612 {
613 #if HAVE_TERMIOS
614         struct termios termios;
615         tcgetattr (FD, &termios);
616         if (boolean(value(TAND)))
617                 termios.c_iflag = IXOFF;
618         else
619                 termios.c_iflag = 0;
620 #ifndef _POSIX_SOURCE
621         termios.c_lflag = (PENDIN|ECHOKE|ECHOE);
622 #else
623         termios.c_lflag = (PENDIN|ECHOE);
624 #endif
625         termios.c_cflag = (CLOCAL|HUPCL|CREAD|CS8);
626         termios.c_ispeed = termios.c_ospeed = speed;
627         tcsetattr (FD, TCSANOW, &termios);
628 #else /* HAVE_TERMIOS */
629         unsigned bits = LDECCTQ;
630
631         arg.sg_ispeed = arg.sg_ospeed = speed;
632         arg.sg_flags = RAW;
633         if (boolean(value(TAND)))
634                 arg.sg_flags |= TANDEM;
635         ioctl(FD, TIOCSETP, (char *)&arg);
636         ioctl(FD, TIOCLBIS, (char *)&bits);
637 #endif /* HAVE_TERMIOS */
638 }
639
640 /*
641  * Return "simple" name from a file name,
642  * strip leading directories.
643  */
644 char *
645 sname(s)
646         char *s;
647 {
648         char *p = s;
649
650         while (*s)
651                 if (*s++ == '/')
652                         p = s;
653         return (p);
654 }
655
656 static char partab[0200];
657 static int bits8;
658
659 /*
660  * Do a write to the remote machine with the correct parity.
661  * We are doing 8 bit wide output, so we just generate a character
662  * with the right parity and output it.
663  */
664 void
665 xpwrite(fd, buf, n)
666         int fd;
667         char *buf;
668         int n;
669 {
670         int i;
671         char *bp;
672
673         bp = buf;
674         if (bits8 == 0)
675                 for (i = 0; i < n; i++) {
676                         *bp = partab[(*bp) & 0177];
677                         bp++;
678                 }
679         if (write(fd, buf, n) < 0) {
680                 if (errno == EIO)
681                         tipabort("Lost carrier.");
682                 if (errno == ENODEV)
683                         tipabort("tty not available.");
684                 tipabort("Something wrong...");
685         }
686 }
687
688 /*
689  * Build a parity table with appropriate high-order bit.
690  */
691 void
692 setparity(defparity)
693         char *defparity;
694 {
695         int i, flip, clr, set;
696         char *parity;
697         extern char evenpartab[];
698
699         if (value(PARITY) == NULL)
700                 value(PARITY) = defparity;
701         parity = value(PARITY);
702         if (equal(parity, "none")) {
703                 bits8 = 1;
704                 return;
705         }
706         bits8 = 0;
707         flip = 0;
708         clr = 0377;
709         set = 0;
710         if (equal(parity, "odd"))
711                 flip = 0200;                    /* reverse bit 7 */
712         else if (equal(parity, "zero"))
713                 clr = 0177;                     /* turn off bit 7 */
714         else if (equal(parity, "one"))
715                 set = 0200;                     /* turn on bit 7 */
716         else if (!equal(parity, "even")) {
717                 (void) fprintf(stderr, "%s: unknown parity value\r\n", parity);
718                 (void) fflush(stderr);
719         }
720         for (i = 0; i < 0200; i++)
721                 partab[i] = (evenpartab[i] ^ flip) | (set & clr);
722 }