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