Home | History | Annotate | Line # | Download | only in rlogin
rlogin.c revision 1.24
      1 /*	$NetBSD: rlogin.c,v 1.24 2000/01/31 14:19:35 itojun Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1983, 1990, 1993
      5  *	The Regents of the University of California.  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  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __COPYRIGHT("@(#) Copyright (c) 1983, 1990, 1993\n\
     39 	The Regents of the University of California.  All rights reserved.\n");
     40 #endif /* not lint */
     41 
     42 #ifndef lint
     43 #if 0
     44 static char sccsid[] = "@(#)rlogin.c	8.4 (Berkeley) 4/29/95";
     45 #else
     46 __RCSID("$NetBSD: rlogin.c,v 1.24 2000/01/31 14:19:35 itojun Exp $");
     47 #endif
     48 #endif /* not lint */
     49 
     50 /*
     51  * rlogin - remote login
     52  */
     53 #include <sys/param.h>
     54 #include <sys/ioctl.h>
     55 #include <sys/socket.h>
     56 #include <sys/time.h>
     57 #include <sys/resource.h>
     58 #include <sys/wait.h>
     59 #include <sys/ioctl.h>
     60 
     61 #include <netinet/in.h>
     62 #include <netinet/in_systm.h>
     63 #include <netinet/ip.h>
     64 
     65 #include <err.h>
     66 #include <errno.h>
     67 #include <fcntl.h>
     68 #include <netdb.h>
     69 #include <pwd.h>
     70 #include <setjmp.h>
     71 #include <termios.h>
     72 #include <signal.h>
     73 #include <stdio.h>
     74 #include <stdlib.h>
     75 #include <string.h>
     76 #include <unistd.h>
     77 
     78 #ifdef __STDC__
     79 #include <stdarg.h>
     80 #else
     81 #include <varargs.h>
     82 #endif
     83 
     84 #ifdef KERBEROS
     85 #include <kerberosIV/des.h>
     86 #include <kerberosIV/krb.h>
     87 #include <kerberosIV/kstream.h>
     88 
     89 #include "krb.h"
     90 
     91 CREDENTIALS cred;
     92 Key_schedule schedule;
     93 MSG_DAT msg_data;
     94 struct sockaddr_in local, foreign;
     95 int use_kerberos = 1, doencrypt;
     96 kstream krem;
     97 #endif
     98 
     99 #ifndef TIOCPKT_WINDOW
    100 #define	TIOCPKT_WINDOW	0x80
    101 #endif
    102 
    103 /* concession to Sun */
    104 #ifndef SIGUSR1
    105 #define	SIGUSR1	30
    106 #endif
    107 
    108 #ifndef CCEQ
    109 #define CCEQ(val, c)	(c == val ? val != _POSIX_VDISABLE : 0)
    110 #endif
    111 
    112 int eight, rem;
    113 struct termios deftty;
    114 
    115 int noescape;
    116 u_char escapechar = '~';
    117 
    118 #ifdef OLDSUN
    119 struct winsize {
    120 	unsigned short ws_row, ws_col;
    121 	unsigned short ws_xpixel, ws_ypixel;
    122 };
    123 #else
    124 #define	get_window_size(fd, wp)	ioctl(fd, TIOCGWINSZ, wp)
    125 #endif
    126 struct	winsize winsize;
    127 
    128 void		catch_child __P((int));
    129 void		copytochild __P((int));
    130 void		doit __P((sigset_t *));
    131 void		done __P((int));
    132 void		echo __P((int));
    133 u_int		getescape __P((char *));
    134 void		lostpeer __P((int));
    135 int		main __P((int, char **));
    136 void		mode __P((int));
    137 void		msg __P((char *));
    138 void		oob __P((int));
    139 int		reader __P((sigset_t *));
    140 void		sendwindow __P((void));
    141 void		setsignal __P((int));
    142 int		speed __P((int));
    143 void		sigwinch __P((int));
    144 void		stop __P((int));
    145 void		usage __P((void));
    146 void		writer __P((void));
    147 void		writeroob __P((int));
    148 
    149 #ifdef	KERBEROS
    150 void		warning __P((const char *, ...));
    151 #endif
    152 #ifdef OLDSUN
    153 int		get_window_size __P((int, struct winsize *));
    154 #endif
    155 
    156 extern char *__progname;
    157 
    158 int
    159 main(argc, argv)
    160 	int argc;
    161 	char *argv[];
    162 {
    163 	struct passwd *pw;
    164 	struct servent *sp;
    165 	struct termios tty;
    166 	sigset_t smask;
    167 	int argoff, ch, dflag, one, uid;
    168 	int i, len, len2;
    169 	char *host, *p, *user, *name, term[1024] = "network";
    170 	speed_t ospeed;
    171 	struct sigaction sa;
    172 	struct rlimit rlim;
    173 #ifdef KERBEROS
    174 	KTEXT_ST ticket;
    175 	int sock;
    176 	long authopts;
    177 	int through_once = 0;
    178 	extern int _kstream_des_debug_OOB;
    179 	char *dest_realm = NULL;
    180 #endif
    181 
    182 	argoff = dflag = 0;
    183 	one = 1;
    184 	host = user = NULL;
    185 
    186 	if (strcmp(__progname, "rlogin") != 0)
    187 		host = __progname;
    188 
    189 	/* handle "rlogin host flags" */
    190 	if (!host && argc > 2 && argv[1][0] != '-') {
    191 		host = argv[1];
    192 		argoff = 1;
    193 	}
    194 
    195 #ifdef KERBEROS
    196 #define	OPTIONS	"8EKLde:k:l:x"
    197 #else
    198 #define	OPTIONS	"8EKLde:l:"
    199 #endif
    200 	while ((ch = getopt(argc - argoff, argv + argoff, OPTIONS)) != -1)
    201 		switch(ch) {
    202 		case '8':
    203 			eight = 1;
    204 			break;
    205 		case 'E':
    206 			noescape = 1;
    207 			break;
    208 #ifdef KERBEROS
    209 		case 'K':
    210 			use_kerberos = 0;
    211 			break;
    212 #endif
    213 		case 'd':
    214 #ifdef KERBEROS
    215 			_kstream_des_debug_OOB = 1;
    216 #endif
    217 			dflag = 1;
    218 			break;
    219 		case 'e':
    220 			noescape = 0;
    221 			escapechar = getescape(optarg);
    222 			break;
    223 #ifdef KERBEROS
    224 		case 'k':
    225 			dest_realm = optarg;
    226 			break;
    227 #endif
    228 		case 'l':
    229 			user = optarg;
    230 			break;
    231 #ifdef CRYPT
    232 #ifdef KERBEROS
    233 		case 'x':
    234 			doencrypt = 1;
    235 			break;
    236 #endif
    237 #endif
    238 		case '?':
    239 		default:
    240 			usage();
    241 		}
    242 	optind += argoff;
    243 	argc -= optind;
    244 	argv += optind;
    245 
    246 	/* if haven't gotten a host yet, do so */
    247 	if (!host && !(host = *argv++))
    248 		usage();
    249 
    250 	if (*argv)
    251 		usage();
    252 
    253 	if (!(pw = getpwuid(uid = getuid())))
    254 		errx(1, "unknown user id.");
    255 	/* Accept user1@host format, though "-l user2" overrides user1 */
    256 	p = strchr(host, '@');
    257 	if (p) {
    258 		*p = '\0';
    259 		if (!user && p > host)
    260 			user = host;
    261 		host = p + 1;
    262 		if (*host == '\0')
    263 			usage();
    264 	}
    265 	if ((name = strdup(pw->pw_name)) == NULL)
    266 		err(1, "malloc");
    267 	if (!user)
    268 		user = name;
    269 
    270 #ifdef KERBEROS
    271 	sp = NULL;
    272 	if (use_kerberos) {
    273 		sp = getservbyname((doencrypt ? "eklogin" : "klogin"), "tcp");
    274 		if (sp == NULL) {
    275 			use_kerberos = 0;
    276 			warning("can't get entry for %s/tcp service",
    277 			    doencrypt ? "eklogin" : "klogin");
    278 		}
    279 	}
    280 	if (sp == NULL)
    281 #endif
    282 		sp = getservbyname("login", "tcp");
    283 	if (sp == NULL)
    284 		errx(1, "login/tcp: unknown service.");
    285 
    286 	if ((p = getenv("TERM")) != NULL) {
    287 		(void)strncpy(term, p, sizeof(term) - 1);
    288 		term[sizeof(term) - 1] = '\0';
    289 	}
    290 	len = strlen(term);
    291 	if (len < (sizeof(term) - 1) && tcgetattr(0, &tty) == 0) {
    292 		/* start at 2 to include the / */
    293 		for (ospeed = i = cfgetospeed(&tty), len2 = 2; i > 9; len2++)
    294 			i /= 10;
    295 
    296 		if (len + len2 < sizeof(term))
    297 			(void)snprintf(term + len, len2 + 1, "/%d", ospeed);
    298 	}
    299 
    300 	(void)get_window_size(0, &winsize);
    301 
    302 	sigemptyset(&sa.sa_mask);
    303 	sa.sa_flags = SA_RESTART;
    304 	sa.sa_handler = lostpeer;
    305 	(void)sigaction(SIGPIPE, &sa, (struct sigaction *)0);
    306 	/* will use SIGUSR1 for window size hack, so hold it off */
    307 	sigemptyset(&smask);
    308 	sigaddset(&smask, SIGURG);
    309 	sigaddset(&smask, SIGUSR1);
    310 	(void)sigprocmask(SIG_SETMASK, &smask, &smask);
    311 	/*
    312 	 * We set SIGURG and SIGUSR1 below so that an
    313 	 * incoming signal will be held pending rather than being
    314 	 * discarded. Note that these routines will be ready to get
    315 	 * a signal by the time that they are unblocked below.;
    316 	 */
    317 	sa.sa_handler = copytochild;
    318 	(void)sigaction(SIGURG, &sa, (struct sigaction *) 0);
    319 	sa.sa_handler = writeroob;
    320 	(void)sigaction(SIGUSR1, &sa, (struct sigaction *) 0);
    321 
    322 	/* don't dump core */
    323 	rlim.rlim_cur = rlim.rlim_max = 0;
    324 	if (setrlimit(RLIMIT_CORE, &rlim) < 0)
    325 		warn("setrlimit");
    326 
    327 #ifdef KERBEROS
    328 try_connect:
    329 	if (use_kerberos) {
    330 		struct hostent *hp;
    331 
    332 		/* Fully qualify hostname (needed for krb_realmofhost). */
    333 		hp = gethostbyname(host);
    334 		if (hp != NULL && !(host = strdup(hp->h_name)))
    335 			errx(1, "%s", strerror(ENOMEM));
    336 
    337 		rem = KSUCCESS;
    338 		errno = 0;
    339 #ifdef CRYPT
    340 		if (doencrypt)
    341 			authopts = KOPT_DO_MUTUAL;
    342 		else
    343 #endif /* CRYPT */
    344 			authopts = 0L;
    345 
    346 		if (dest_realm == NULL) {
    347 			/* default this now, once. */
    348 			if (!(dest_realm = krb_realmofhost (host))) {
    349 				warnx("Unknown realm for host %s.", host);
    350 				use_kerberos = 0;
    351 				sp = getservbyname("login", "tcp");
    352 				goto try_connect;
    353 			}
    354 		}
    355 
    356 		rem = kcmd(&sock, &host, sp->s_port, name, user,
    357 			   term, 0, &ticket, "rcmd", dest_realm,
    358 			   &cred, schedule, &msg_data, &local, &foreign,
    359 			   authopts);
    360 
    361 		if (rem != KSUCCESS) {
    362 			switch(rem) {
    363 
    364 				case KDC_PR_UNKNOWN:
    365 					warnx("Host %s not registered for %s",
    366 				       	      host, "Kerberos rlogin service");
    367 					use_kerberos = 0;
    368 					sp = getservbyname("login", "tcp");
    369 					goto try_connect;
    370 				case NO_TKT_FIL:
    371 					if (through_once++) {
    372 						use_kerberos = 0;
    373 						sp = getservbyname("login", "tcp");
    374 						goto try_connect;
    375 					}
    376 #ifdef notyet
    377 				krb_get_pw_in_tkt(user, krb_realm, "krbtgt",
    378 						  krb_realm,
    379 					          DEFAULT_TKT_LIFE/5, 0);
    380 				goto try_connect;
    381 #endif
    382 			default:
    383 				warnx("Kerberos rcmd failed: %s",
    384 				      (rem == -1) ? "rcmd protocol failure" :
    385 				      krb_err_txt[rem]);
    386 				use_kerberos = 0;
    387 				sp = getservbyname("login", "tcp");
    388 				goto try_connect;
    389 			}
    390 		}
    391 		rem = sock;
    392 		if (doencrypt)
    393 			krem = kstream_create_rlogin_from_fd(rem, &schedule,
    394 							     &cred.session);
    395 		else
    396 			krem = kstream_create_from_fd(rem, 0, 0);
    397 			kstream_set_buffer_mode(krem, 0);
    398 	} else {
    399 #ifdef CRYPT
    400 		if (doencrypt)
    401 			errx(1, "the -x flag requires Kerberos authentication.");
    402 #endif /* CRYPT */
    403 		rem = rcmd_af(&host, sp->s_port, name, user, term, 0,
    404 		    PF_UNSPEC);
    405 		if (rem < 0)
    406 			exit(1);
    407 	}
    408 #else
    409 	rem = rcmd_af(&host, sp->s_port, name, user, term, 0, PF_UNSPEC);
    410 
    411 #endif /* KERBEROS */
    412 
    413 	if (rem < 0)
    414 		exit(1);
    415 
    416 	if (dflag &&
    417 	    setsockopt(rem, SOL_SOCKET, SO_DEBUG, &one, sizeof(one)) < 0)
    418 		warn("setsockopt DEBUG (ignored)");
    419     {
    420 	struct sockaddr_storage ss;
    421 	int sslen;
    422 	sslen = sizeof(ss);
    423 	if (getsockname(rem, (struct sockaddr *)&ss, &sslen) == 0
    424 	 && ((struct sockaddr *)&ss)->sa_family == AF_INET) {
    425 		one = IPTOS_LOWDELAY;
    426 		if (setsockopt(rem, IPPROTO_IP, IP_TOS, (char *)&one,
    427 				sizeof(int)) < 0) {
    428 			warn("setsockopt TOS (ignored)");
    429 		}
    430 	}
    431     }
    432 
    433 	(void)setuid(uid);
    434 	doit(&smask);
    435 	/*NOTREACHED*/
    436 	return (0);
    437 }
    438 
    439 int
    440 speed(fd)
    441 	int fd;
    442 {
    443 	struct termios tt;
    444 
    445 	(void)tcgetattr(fd, &tt);
    446 
    447 	return ((int)cfgetispeed(&tt));
    448 }
    449 
    450 pid_t child;
    451 struct termios deftt;
    452 struct termios nott;
    453 
    454 void
    455 doit(smask)
    456 	sigset_t *smask;
    457 {
    458 	int i;
    459 	struct sigaction sa;
    460 
    461 	for (i = 0; i < NCCS; i++)
    462 		nott.c_cc[i] = _POSIX_VDISABLE;
    463 	tcgetattr(0, &deftt);
    464 	nott.c_cc[VSTART] = deftt.c_cc[VSTART];
    465 	nott.c_cc[VSTOP] = deftt.c_cc[VSTOP];
    466 	sigemptyset(&sa.sa_mask);
    467 	sa.sa_flags = SA_RESTART;
    468 	sa.sa_handler = SIG_IGN;
    469 	(void)sigaction(SIGINT, &sa, (struct sigaction *) 0);
    470 	setsignal(SIGHUP);
    471 	setsignal(SIGQUIT);
    472 	mode(1);
    473 	child = fork();
    474 	if (child == -1) {
    475 		warn("fork");
    476 		done(1);
    477 	}
    478 	if (child == 0) {
    479 		mode(1);
    480 		if (reader(smask) == 0) {
    481 			msg("connection closed.");
    482 			exit(0);
    483 		}
    484 		sleep(1);
    485 		msg("\aconnection closed.");
    486 		exit(1);
    487 	}
    488 
    489 	/*
    490 	 * We may still own the socket, and may have a pending SIGURG (or might
    491 	 * receive one soon) that we really want to send to the reader.  When
    492 	 * one of these comes in, the trap copytochild simply copies such
    493 	 * signals to the child. We can now unblock SIGURG and SIGUSR1
    494 	 * that were set above.
    495 	 */
    496 	(void)sigprocmask(SIG_SETMASK, smask, (sigset_t *) 0);
    497 	sa.sa_handler = catch_child;
    498 	(void)sigaction(SIGCHLD, &sa, (struct sigaction *) 0);
    499 	writer();
    500 	msg("closed connection.");
    501 	done(0);
    502 }
    503 
    504 /* trap a signal, unless it is being ignored. */
    505 void
    506 setsignal(sig)
    507 	int sig;
    508 {
    509 	struct sigaction sa;
    510 	sigset_t sigs;
    511 
    512 	sigemptyset(&sigs);
    513 	sigaddset(&sigs, sig);
    514 	sigprocmask(SIG_BLOCK, &sigs, &sigs);
    515 
    516 	sigemptyset(&sa.sa_mask);
    517 	sa.sa_handler = exit;
    518 	sa.sa_flags = SA_RESTART;
    519 	(void)sigaction(sig, &sa, &sa);
    520 	if (sa.sa_handler == SIG_IGN)
    521 		(void)sigaction(sig, &sa, (struct sigaction *) 0);
    522 
    523 	(void)sigprocmask(SIG_SETMASK, &sigs, (sigset_t *) 0);
    524 }
    525 
    526 void
    527 done(status)
    528 	int status;
    529 {
    530 	pid_t w;
    531 	int wstatus;
    532 	struct sigaction sa;
    533 
    534 	mode(0);
    535 	if (child > 0) {
    536 		/* make sure catch_child does not snap it up */
    537 		sigemptyset(&sa.sa_mask);
    538 		sa.sa_handler = SIG_DFL;
    539 		sa.sa_flags = 0;
    540 		(void)sigaction(SIGCHLD, &sa, (struct sigaction *) 0);
    541 		if (kill(child, SIGKILL) >= 0)
    542 			while ((w = wait(&wstatus)) > 0 && w != child)
    543 				continue;
    544 	}
    545 	exit(status);
    546 }
    547 
    548 int dosigwinch;
    549 
    550 /*
    551  * This is called when the reader process gets the out-of-band (urgent)
    552  * request to turn on the window-changing protocol.
    553  */
    554 void
    555 writeroob(signo)
    556 	int signo;
    557 {
    558 	struct sigaction sa;
    559 
    560 	if (dosigwinch == 0) {
    561 		sendwindow();
    562 		sigemptyset(&sa.sa_mask);
    563 		sa.sa_handler = sigwinch;
    564 		sa.sa_flags = SA_RESTART;
    565 		(void)sigaction(SIGWINCH, &sa, (struct sigaction *) 0);
    566 	}
    567 	dosigwinch = 1;
    568 }
    569 
    570 void
    571 catch_child(signo)
    572 	int signo;
    573 {
    574 	int status;
    575 	pid_t pid;
    576 
    577 	for (;;) {
    578 		pid = waitpid(-1, &status, WNOHANG|WUNTRACED);
    579 		if (pid == 0)
    580 			return;
    581 		/* if the child (reader) dies, just quit */
    582 		if (pid < 0 || (pid == child && !WIFSTOPPED(status)))
    583 			done(WEXITSTATUS(status) | WTERMSIG(status));
    584 	}
    585 	/* NOTREACHED */
    586 }
    587 
    588 /*
    589  * writer: write to remote: 0 -> line.
    590  * ~.				terminate
    591  * ~^Z				suspend rlogin process.
    592  * ~<delayed-suspend char>	suspend rlogin process, but leave reader alone.
    593  */
    594 void
    595 writer()
    596 {
    597 	int bol, local, n;
    598 	char c;
    599 
    600 	bol = 1;			/* beginning of line */
    601 	local = 0;
    602 	for (;;) {
    603 		n = read(STDIN_FILENO, &c, 1);
    604 		if (n <= 0) {
    605 			if (n < 0 && errno == EINTR)
    606 				continue;
    607 			break;
    608 		}
    609 		/*
    610 		 * If we're at the beginning of the line and recognize a
    611 		 * command character, then we echo locally.  Otherwise,
    612 		 * characters are echo'd remotely.  If the command character
    613 		 * is doubled, this acts as a force and local echo is
    614 		 * suppressed.
    615 		 */
    616 		if (bol) {
    617 			bol = 0;
    618 			if (!noescape && c == escapechar) {
    619 				local = 1;
    620 				continue;
    621 			}
    622 		} else if (local) {
    623 			local = 0;
    624 			if (c == '.' || CCEQ(deftty.c_cc[VEOF], c)) {
    625 				echo((int)c);
    626 				break;
    627 			}
    628 			if (CCEQ(deftty.c_cc[VSUSP], c)) {
    629 				bol = 1;
    630 				echo((int)c);
    631 				stop(1);
    632 				continue;
    633 			}
    634 			if (CCEQ(deftty.c_cc[VDSUSP], c)) {
    635 				bol = 1;
    636 				echo((int)c);
    637 				stop(0);
    638 				continue;
    639 			}
    640 			if (c != escapechar) {
    641 #ifdef KERBEROS
    642 				if (use_kerberos)
    643 					(void)kstream_write(krem,
    644 					    (char *)&escapechar, 1);
    645 				else
    646 #endif
    647 					(void)write(rem, &escapechar, 1);
    648 			}
    649 		}
    650 
    651 #ifdef KERBEROS
    652 		if (use_kerberos) {
    653 			if (kstream_write(krem, &c, 1) == 0) {
    654 					msg("line gone");
    655 					break;
    656 			}
    657 		}
    658 		else
    659 #endif
    660 			if (write(rem, &c, 1) == 0) {
    661 				msg("line gone");
    662 				break;
    663 			}
    664 
    665 		bol = CCEQ(deftty.c_cc[VKILL], c) ||
    666 		    CCEQ(deftty.c_cc[VEOF], c) ||
    667 		    CCEQ(deftty.c_cc[VINTR], c) ||
    668 		    CCEQ(deftty.c_cc[VSUSP], c) ||
    669 		    c == '\r' || c == '\n';
    670 	}
    671 }
    672 
    673 void
    674 echo(i)
    675 	int i;
    676 {
    677 	char c = (char)i;
    678 	char *p;
    679 	char buf[8];
    680 
    681 	p = buf;
    682 	c &= 0177;
    683 	*p++ = escapechar;
    684 	if (c < ' ') {
    685 		*p++ = '^';
    686 		*p++ = c + '@';
    687 	} else if (c == 0177) {
    688 		*p++ = '^';
    689 		*p++ = '?';
    690 	} else
    691 		*p++ = c;
    692 	*p++ = '\r';
    693 	*p++ = '\n';
    694 	(void)write(STDOUT_FILENO, buf, p - buf);
    695 }
    696 
    697 void
    698 stop(all)
    699 	int all;
    700 {
    701 	struct sigaction sa;
    702 
    703 	mode(0);
    704 	sigemptyset(&sa.sa_mask);
    705 	sa.sa_handler = SIG_IGN;
    706 	sa.sa_flags = SA_RESTART;
    707 	(void)sigaction(SIGCHLD, &sa, (struct sigaction *) 0);
    708 	(void)kill(all ? 0 : getpid(), SIGTSTP);
    709 	sa.sa_handler = catch_child;
    710 	(void)sigaction(SIGCHLD, &sa, (struct sigaction *) 0);
    711 	mode(1);
    712 	sigwinch(0);			/* check for size changes */
    713 }
    714 
    715 void
    716 sigwinch(signo)
    717 	int signo;
    718 {
    719 	struct winsize ws;
    720 
    721 	if (dosigwinch && get_window_size(0, &ws) == 0 &&
    722 	    memcmp(&ws, &winsize, sizeof(ws))) {
    723 		winsize = ws;
    724 		sendwindow();
    725 	}
    726 }
    727 
    728 /*
    729  * Send the window size to the server via the magic escape
    730  */
    731 void
    732 sendwindow()
    733 {
    734 	struct winsize *wp;
    735 	char obuf[4 + sizeof (struct winsize)];
    736 
    737 	wp = (struct winsize *)(obuf+4);
    738 	obuf[0] = 0377;
    739 	obuf[1] = 0377;
    740 	obuf[2] = 's';
    741 	obuf[3] = 's';
    742 	wp->ws_row = htons(winsize.ws_row);
    743 	wp->ws_col = htons(winsize.ws_col);
    744 	wp->ws_xpixel = htons(winsize.ws_xpixel);
    745 	wp->ws_ypixel = htons(winsize.ws_ypixel);
    746 
    747 #ifdef KERBEROS
    748 		if (use_kerberos)
    749 			(void)kstream_write(krem, obuf, sizeof(obuf));
    750 		else
    751 #endif
    752 		(void)write(rem, obuf, sizeof(obuf));
    753 }
    754 
    755 /*
    756  * reader: read from remote: line -> 1
    757  */
    758 #define	READING	1
    759 #define	WRITING	2
    760 
    761 jmp_buf rcvtop;
    762 pid_t ppid;
    763 int rcvcnt, rcvstate;
    764 char rcvbuf[8 * 1024];
    765 
    766 void
    767 oob(signo)
    768 	int signo;
    769 {
    770 	struct termios tty;
    771 	int atmark, n, rcvd;
    772 	char waste[BUFSIZ], mark;
    773 
    774 	rcvd = 0;
    775 	while (recv(rem, &mark, 1, MSG_OOB) < 0) {
    776 		switch (errno) {
    777 		case EWOULDBLOCK:
    778 			/*
    779 			 * Urgent data not here yet.  It may not be possible
    780 			 * to send it yet if we are blocked for output and
    781 			 * our input buffer is full.
    782 			 */
    783 			if (rcvcnt < sizeof(rcvbuf)) {
    784 				n = read(rem, rcvbuf + rcvcnt,
    785 				    sizeof(rcvbuf) - rcvcnt);
    786 				if (n <= 0)
    787 					return;
    788 				rcvd += n;
    789 			} else {
    790 				n = read(rem, waste, sizeof(waste));
    791 				if (n <= 0)
    792 					return;
    793 			}
    794 			continue;
    795 		default:
    796 			return;
    797 		}
    798 	}
    799 	if (mark & TIOCPKT_WINDOW) {
    800 		/* Let server know about window size changes */
    801 		(void)kill(ppid, SIGUSR1);
    802 	}
    803 	if (!eight && (mark & TIOCPKT_NOSTOP)) {
    804 		(void)tcgetattr(0, &tty);
    805 		tty.c_iflag &= ~IXON;
    806 		(void)tcsetattr(0, TCSANOW, &tty);
    807 	}
    808 	if (!eight && (mark & TIOCPKT_DOSTOP)) {
    809 		(void)tcgetattr(0, &tty);
    810 		tty.c_iflag |= (deftty.c_iflag & IXON);
    811 		(void)tcsetattr(0, TCSANOW, &tty);
    812 	}
    813 	if (mark & TIOCPKT_FLUSHWRITE) {
    814 		(void)tcflush(1, TCIOFLUSH);
    815 		for (;;) {
    816 			if (ioctl(rem, SIOCATMARK, &atmark) < 0) {
    817 				warn("ioctl SIOCATMARK (ignored)");
    818 				break;
    819 			}
    820 			if (atmark)
    821 				break;
    822 			n = read(rem, waste, sizeof (waste));
    823 			if (n <= 0)
    824 				break;
    825 		}
    826 		/*
    827 		 * Don't want any pending data to be output, so clear the recv
    828 		 * buffer.  If we were hanging on a write when interrupted,
    829 		 * don't want it to restart.  If we were reading, restart
    830 		 * anyway.
    831 		 */
    832 		rcvcnt = 0;
    833 		longjmp(rcvtop, 1);
    834 	}
    835 
    836 	/* oob does not do FLUSHREAD (alas!) */
    837 
    838 	/*
    839 	 * If we filled the receive buffer while a read was pending, longjmp
    840 	 * to the top to restart appropriately.  Don't abort a pending write,
    841 	 * however, or we won't know how much was written.
    842 	 */
    843 	if (rcvd && rcvstate == READING)
    844 		longjmp(rcvtop, 1);
    845 }
    846 
    847 /* reader: read from remote: line -> 1 */
    848 int
    849 reader(smask)
    850 	sigset_t *smask;
    851 {
    852 	pid_t pid;
    853 	int n, remaining;
    854 	char *bufp;
    855 	struct sigaction sa;
    856 
    857 	pid = getpid();		/* modern systems use positives for pid */
    858 	sigemptyset(&sa.sa_mask);
    859 	sa.sa_flags = SA_RESTART;
    860 	sa.sa_handler = SIG_IGN;
    861 	(void)sigaction(SIGTTOU, &sa, (struct sigaction *) 0);
    862 	sa.sa_handler = oob;
    863 	(void)sigaction(SIGURG, &sa, (struct sigaction *) 0);
    864 	ppid = getppid();
    865 	(void)fcntl(rem, F_SETOWN, pid);
    866 	(void)setjmp(rcvtop);
    867 	(void)sigprocmask(SIG_SETMASK, smask, (sigset_t *) 0);
    868 	bufp = rcvbuf;
    869 	for (;;) {
    870 		while ((remaining = rcvcnt - (bufp - rcvbuf)) > 0) {
    871 			rcvstate = WRITING;
    872 			n = write(STDOUT_FILENO, bufp, remaining);
    873 			if (n < 0) {
    874 				if (errno != EINTR)
    875 					return (-1);
    876 				continue;
    877 			}
    878 			bufp += n;
    879 		}
    880 		bufp = rcvbuf;
    881 		rcvcnt = 0;
    882 		rcvstate = READING;
    883 
    884 #ifdef KERBEROS
    885 			if (use_kerberos)
    886 				rcvcnt = kstream_read(krem, rcvbuf, sizeof(rcvbuf));
    887 			else
    888 #endif
    889 			rcvcnt = read(rem, rcvbuf, sizeof (rcvbuf));
    890 
    891 		if (rcvcnt == 0)
    892 			return (0);
    893 		if (rcvcnt < 0) {
    894 			if (errno == EINTR)
    895 				continue;
    896 			warn("read");
    897 			return (-1);
    898 		}
    899 	}
    900 }
    901 
    902 void
    903 mode(f)
    904 	int f;
    905 {
    906 	struct termios tty;
    907 
    908 	switch (f) {
    909 	case 0:
    910 		(void)tcsetattr(0, TCSANOW, &deftty);
    911 		break;
    912 	case 1:
    913 		(void)tcgetattr(0, &deftty);
    914 		tty = deftty;
    915 		/* This is loosely derived from sys/compat/tty_compat.c. */
    916 		tty.c_lflag &= ~(ECHO|ICANON|ISIG|IEXTEN);
    917 		tty.c_iflag &= ~ICRNL;
    918 		tty.c_oflag &= ~OPOST;
    919 		tty.c_cc[VMIN] = 1;
    920 		tty.c_cc[VTIME] = 0;
    921 		if (eight) {
    922 			tty.c_iflag &= IXOFF;
    923 			tty.c_cflag &= ~(CSIZE|PARENB);
    924 			tty.c_cflag |= CS8;
    925 		}
    926 		(void)tcsetattr(0, TCSANOW, &tty);
    927 		break;
    928 
    929 	default:
    930 		return;
    931 	}
    932 }
    933 
    934 void
    935 lostpeer(signo)
    936 	int signo;
    937 {
    938 	struct sigaction sa;
    939 	sa.sa_flags = SA_RESTART;
    940 	sa.sa_handler = SIG_IGN;
    941 	(void)sigaction(SIGPIPE, &sa, (struct sigaction *)0);
    942 	msg("\aconnection closed.");
    943 	done(1);
    944 }
    945 
    946 /* copy SIGURGs to the child process. */
    947 void
    948 copytochild(signo)
    949 	int signo;
    950 {
    951 
    952 	(void)kill(child, SIGURG);
    953 }
    954 
    955 void
    956 msg(str)
    957 	char *str;
    958 {
    959 
    960 	(void)fprintf(stderr, "rlogin: %s\r\n", str);
    961 }
    962 
    963 #ifdef KERBEROS
    964 /* VARARGS */
    965 void
    966 #if __STDC__
    967 warning(const char *fmt, ...)
    968 #else
    969 warning(fmt, va_alist)
    970 	char *fmt;
    971 	va_dcl
    972 #endif
    973 {
    974 	va_list ap;
    975 
    976 	(void)fprintf(stderr, "rlogin: warning, using standard rlogin: ");
    977 #ifdef __STDC__
    978 	va_start(ap, fmt);
    979 #else
    980 	va_start(ap);
    981 #endif
    982 	vfprintf(stderr, fmt, ap);
    983 	va_end(ap);
    984 	(void)fprintf(stderr, ".\n");
    985 }
    986 #endif
    987 
    988 void
    989 usage()
    990 {
    991 	(void)fprintf(stderr,
    992 	    "usage: rlogin [ -%s]%s[-e char] [ -l username ] [username@]host\n",
    993 #ifdef KERBEROS
    994 #ifdef CRYPT
    995 	    "8EKLdx", " [-k realm] ");
    996 #else
    997 	    "8EKLd", " [-k realm] ");
    998 #endif
    999 #else
   1000 	    "8ELd", " ");
   1001 #endif
   1002 	exit(1);
   1003 }
   1004 
   1005 /*
   1006  * The following routine provides compatibility (such as it is) between older
   1007  * Suns and others.  Suns have only a `ttysize', so we convert it to a winsize.
   1008  */
   1009 #ifdef OLDSUN
   1010 int
   1011 get_window_size(fd, wp)
   1012 	int fd;
   1013 	struct winsize *wp;
   1014 {
   1015 	struct ttysize ts;
   1016 	int error;
   1017 
   1018 	if ((error = ioctl(0, TIOCGSIZE, &ts)) != 0)
   1019 		return (error);
   1020 	wp->ws_row = ts.ts_lines;
   1021 	wp->ws_col = ts.ts_cols;
   1022 	wp->ws_xpixel = 0;
   1023 	wp->ws_ypixel = 0;
   1024 	return (0);
   1025 }
   1026 #endif
   1027 
   1028 u_int
   1029 getescape(p)
   1030 	char *p;
   1031 {
   1032 	long val;
   1033 	int len;
   1034 
   1035 	if ((len = strlen(p)) == 1)	/* use any single char, including '\' */
   1036 		return ((u_int)*p);
   1037 					/* otherwise, \nnn */
   1038 	if (*p == '\\' && len >= 2 && len <= 4) {
   1039 		val = strtol(++p, NULL, 8);
   1040 		for (;;) {
   1041 			if (!*++p)
   1042 				return ((u_int)val);
   1043 			if (*p < '0' || *p > '8')
   1044 				break;
   1045 		}
   1046 	}
   1047 	msg("illegal option value -- e");
   1048 	usage();
   1049 	/* NOTREACHED */
   1050 	return (0);
   1051 }
   1052