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