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