Home | History | Annotate | Line # | Download | only in rlogin
rlogin.c revision 1.19
      1 /*	$NetBSD: rlogin.c,v 1.19 1997/06/28 23:43:38 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.19 1997/06/28 23:43:38 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, *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 			sp = getservbyname("login", "tcp");
    354 			goto try_connect;
    355 		}
    356 
    357 		strncpy(dest_realm, cp, REALM_SZ);
    358 
    359 		rem = kcmd(&sock, &host, sp->s_port, name, user,
    360 			   term, 0, &ticket, "rcmd", dest_realm,
    361 			   &cred, schedule, &msg_data, &local, &foreign,
    362 			   authopts);
    363 
    364 		if (rem != KSUCCESS) {
    365 			switch(rem) {
    366 
    367 				case KDC_PR_UNKNOWN:
    368 					warnx("Host %s not registered for %s",
    369 				       	      host, "Kerberos rlogin service");
    370 					use_kerberos = 0;
    371 					sp = getservbyname("login", "tcp");
    372 					goto try_connect;
    373 				case NO_TKT_FIL:
    374 					if (through_once++) {
    375 						use_kerberos = 0;
    376 						sp = getservbyname("login", "tcp");
    377 						goto try_connect;
    378 					}
    379 #ifdef notyet
    380 				krb_get_pw_in_tkt(user, krb_realm, "krbtgt",
    381 						  krb_realm,
    382 					          DEFAULT_TKT_LIFE/5, 0);
    383 				goto try_connect;
    384 #endif
    385 			default:
    386 				warnx("Kerberos rcmd failed: %s",
    387 				      (rem == -1) ? "rcmd protocol failure" :
    388 				      krb_err_txt[rem]);
    389 				use_kerberos = 0;
    390 				sp = getservbyname("login", "tcp");
    391 				goto try_connect;
    392 			}
    393 		}
    394 		rem = sock;
    395 		if (doencrypt)
    396 			krem = kstream_create_rlogin_from_fd(rem, &schedule,
    397 							     &cred.session);
    398 		else
    399 			krem = kstream_create_from_fd(rem, 0, 0);
    400 			kstream_set_buffer_mode(krem, 0);
    401 	} else {
    402 #ifdef CRYPT
    403 		if (doencrypt)
    404 			errx(1, "the -x flag requires Kerberos authentication.");
    405 #endif /* CRYPT */
    406 		rem = rcmd(&host, sp->s_port, name, user, term, 0);
    407 		if (rem < 0)
    408 			exit(1);
    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 				if (use_kerberos) {
    654 					(void)kstream_write(krem,
    655 				    	(char *)&escapechar, 1);
    656 				}
    657 				else
    658 #endif
    659 				(void)write(rem, &escapechar, 1);
    660 		}
    661 
    662 #ifdef KERBEROS
    663 		if (use_kerberos) {
    664 			if (kstream_write(krem, &c, 1) == 0) {
    665 					msg("line gone");
    666 					break;
    667 			}
    668 		}
    669 		else
    670 #endif
    671 			if (write(rem, &c, 1) == 0) {
    672 				msg("line gone");
    673 				break;
    674 			}
    675 
    676 		bol = CCEQ(deftty.c_cc[VKILL], c) ||
    677 		    CCEQ(deftty.c_cc[VEOF], c) ||
    678 		    CCEQ(deftty.c_cc[VINTR], c) ||
    679 		    CCEQ(deftty.c_cc[VSUSP], c) ||
    680 		    c == '\r' || c == '\n';
    681 	}
    682 }
    683 
    684 void
    685 #if __STDC__
    686 echo(register char c)
    687 #else
    688 echo(c)
    689 	register char c;
    690 #endif
    691 {
    692 	register char *p;
    693 	char buf[8];
    694 
    695 	p = buf;
    696 	c &= 0177;
    697 	*p++ = escapechar;
    698 	if (c < ' ') {
    699 		*p++ = '^';
    700 		*p++ = c + '@';
    701 	} else if (c == 0177) {
    702 		*p++ = '^';
    703 		*p++ = '?';
    704 	} else
    705 		*p++ = c;
    706 	*p++ = '\r';
    707 	*p++ = '\n';
    708 	(void)write(STDOUT_FILENO, buf, p - buf);
    709 }
    710 
    711 void
    712 stop(all)
    713 	int all;
    714 {
    715 	struct sigaction sa;
    716 
    717 	mode(0);
    718 	sigemptyset(&sa.sa_mask);
    719 	sa.sa_handler = SIG_IGN;
    720 	sa.sa_flags = SA_RESTART;
    721 	(void)sigaction(SIGCHLD, &sa, (struct sigaction *) 0);
    722 	(void)kill(all ? 0 : getpid(), SIGTSTP);
    723 	sa.sa_handler = catch_child;
    724 	(void)sigaction(SIGCHLD, &sa, (struct sigaction *) 0);
    725 	mode(1);
    726 	sigwinch(0);			/* check for size changes */
    727 }
    728 
    729 void
    730 sigwinch(signo)
    731 	int signo;
    732 {
    733 	struct winsize ws;
    734 
    735 	if (dosigwinch && get_window_size(0, &ws) == 0 &&
    736 	    memcmp(&ws, &winsize, sizeof(ws))) {
    737 		winsize = ws;
    738 		sendwindow();
    739 	}
    740 }
    741 
    742 /*
    743  * Send the window size to the server via the magic escape
    744  */
    745 void
    746 sendwindow()
    747 {
    748 	struct winsize *wp;
    749 	char obuf[4 + sizeof (struct winsize)];
    750 
    751 	wp = (struct winsize *)(obuf+4);
    752 	obuf[0] = 0377;
    753 	obuf[1] = 0377;
    754 	obuf[2] = 's';
    755 	obuf[3] = 's';
    756 	wp->ws_row = htons(winsize.ws_row);
    757 	wp->ws_col = htons(winsize.ws_col);
    758 	wp->ws_xpixel = htons(winsize.ws_xpixel);
    759 	wp->ws_ypixel = htons(winsize.ws_ypixel);
    760 
    761 #ifdef KERBEROS
    762 		if (use_kerberos)
    763 			(void)kstream_write(krem, obuf, sizeof(obuf));
    764 		else
    765 #endif
    766 		(void)write(rem, obuf, sizeof(obuf));
    767 }
    768 
    769 /*
    770  * reader: read from remote: line -> 1
    771  */
    772 #define	READING	1
    773 #define	WRITING	2
    774 
    775 jmp_buf rcvtop;
    776 pid_t ppid;
    777 int rcvcnt, rcvstate;
    778 char rcvbuf[8 * 1024];
    779 
    780 void
    781 oob(signo)
    782 	int signo;
    783 {
    784 	struct termios tty;
    785 	int atmark, n, rcvd;
    786 	char waste[BUFSIZ], mark;
    787 
    788 	rcvd = 0;
    789 	while (recv(rem, &mark, 1, MSG_OOB) < 0) {
    790 		switch (errno) {
    791 		case EWOULDBLOCK:
    792 			/*
    793 			 * Urgent data not here yet.  It may not be possible
    794 			 * to send it yet if we are blocked for output and
    795 			 * our input buffer is full.
    796 			 */
    797 			if (rcvcnt < sizeof(rcvbuf)) {
    798 				n = read(rem, rcvbuf + rcvcnt,
    799 				    sizeof(rcvbuf) - rcvcnt);
    800 				if (n <= 0)
    801 					return;
    802 				rcvd += n;
    803 			} else {
    804 				n = read(rem, waste, sizeof(waste));
    805 				if (n <= 0)
    806 					return;
    807 			}
    808 			continue;
    809 		default:
    810 			return;
    811 		}
    812 	}
    813 	if (mark & TIOCPKT_WINDOW) {
    814 		/* Let server know about window size changes */
    815 		(void)kill(ppid, SIGUSR1);
    816 	}
    817 	if (!eight && (mark & TIOCPKT_NOSTOP)) {
    818 		(void)tcgetattr(0, &tty);
    819 		tty.c_iflag &= ~IXON;
    820 		(void)tcsetattr(0, TCSANOW, &tty);
    821 	}
    822 	if (!eight && (mark & TIOCPKT_DOSTOP)) {
    823 		(void)tcgetattr(0, &tty);
    824 		tty.c_iflag |= (deftty.c_iflag & IXON);
    825 		(void)tcsetattr(0, TCSANOW, &tty);
    826 	}
    827 	if (mark & TIOCPKT_FLUSHWRITE) {
    828 		(void)tcflush(1, TCIOFLUSH);
    829 		for (;;) {
    830 			if (ioctl(rem, SIOCATMARK, &atmark) < 0) {
    831 				warn("ioctl SIOCATMARK (ignored)");
    832 				break;
    833 			}
    834 			if (atmark)
    835 				break;
    836 			n = read(rem, waste, sizeof (waste));
    837 			if (n <= 0)
    838 				break;
    839 		}
    840 		/*
    841 		 * Don't want any pending data to be output, so clear the recv
    842 		 * buffer.  If we were hanging on a write when interrupted,
    843 		 * don't want it to restart.  If we were reading, restart
    844 		 * anyway.
    845 		 */
    846 		rcvcnt = 0;
    847 		longjmp(rcvtop, 1);
    848 	}
    849 
    850 	/* oob does not do FLUSHREAD (alas!) */
    851 
    852 	/*
    853 	 * If we filled the receive buffer while a read was pending, longjmp
    854 	 * to the top to restart appropriately.  Don't abort a pending write,
    855 	 * however, or we won't know how much was written.
    856 	 */
    857 	if (rcvd && rcvstate == READING)
    858 		longjmp(rcvtop, 1);
    859 }
    860 
    861 /* reader: read from remote: line -> 1 */
    862 int
    863 reader(smask)
    864 	sigset_t *smask;
    865 {
    866 	pid_t pid;
    867 	int n, remaining;
    868 	char *bufp;
    869 	struct sigaction sa;
    870 
    871 #if BSD >= 43 || defined(SUNOS4)
    872 	pid = getpid();		/* modern systems use positives for pid */
    873 #else
    874 	pid = -getpid();	/* old broken systems use negatives */
    875 #endif
    876 	sigemptyset(&sa.sa_mask);
    877 	sa.sa_flags = SA_RESTART;
    878 	sa.sa_handler = SIG_IGN;
    879 	(void)sigaction(SIGTTOU, &sa, (struct sigaction *) 0);
    880 	sa.sa_handler = oob;
    881 	(void)sigaction(SIGURG, &sa, (struct sigaction *) 0);
    882 	ppid = getppid();
    883 	(void)fcntl(rem, F_SETOWN, pid);
    884 	(void)setjmp(rcvtop);
    885 	(void)sigprocmask(SIG_SETMASK, smask, (sigset_t *) 0);
    886 	bufp = rcvbuf;
    887 	for (;;) {
    888 		while ((remaining = rcvcnt - (bufp - rcvbuf)) > 0) {
    889 			rcvstate = WRITING;
    890 			n = write(STDOUT_FILENO, bufp, remaining);
    891 			if (n < 0) {
    892 				if (errno != EINTR)
    893 					return (-1);
    894 				continue;
    895 			}
    896 			bufp += n;
    897 		}
    898 		bufp = rcvbuf;
    899 		rcvcnt = 0;
    900 		rcvstate = READING;
    901 
    902 #ifdef KERBEROS
    903 			if (use_kerberos)
    904 				rcvcnt = kstream_read(krem, rcvbuf, sizeof(rcvbuf));
    905 			else
    906 #endif
    907 			rcvcnt = read(rem, rcvbuf, sizeof (rcvbuf));
    908 
    909 		if (rcvcnt == 0)
    910 			return (0);
    911 		if (rcvcnt < 0) {
    912 			if (errno == EINTR)
    913 				continue;
    914 			warn("read");
    915 			return (-1);
    916 		}
    917 	}
    918 }
    919 
    920 void
    921 mode(f)
    922 	int f;
    923 {
    924 	struct termios tty;
    925 
    926 	switch (f) {
    927 	case 0:
    928 		(void)tcsetattr(0, TCSANOW, &deftty);
    929 		break;
    930 	case 1:
    931 		(void)tcgetattr(0, &deftty);
    932 		tty = deftty;
    933 		/* This is loosely derived from sys/compat/tty_compat.c. */
    934 		tty.c_lflag &= ~(ECHO|ICANON|ISIG|IEXTEN);
    935 		tty.c_iflag &= ~ICRNL;
    936 		tty.c_oflag &= ~OPOST;
    937 		tty.c_cc[VMIN] = 1;
    938 		tty.c_cc[VTIME] = 0;
    939 		if (eight) {
    940 			tty.c_iflag &= IXOFF;
    941 			tty.c_cflag &= ~(CSIZE|PARENB);
    942 			tty.c_cflag |= CS8;
    943 		}
    944 		(void)tcsetattr(0, TCSANOW, &tty);
    945 		break;
    946 
    947 	default:
    948 		return;
    949 	}
    950 }
    951 
    952 void
    953 lostpeer(signo)
    954 	int signo;
    955 {
    956 	struct sigaction sa;
    957 	sa.sa_flags = SA_RESTART;
    958 	sa.sa_handler = SIG_IGN;
    959 	(void)sigaction(SIGPIPE, &sa, (struct sigaction *)0);
    960 	msg("\aconnection closed.");
    961 	done(1);
    962 }
    963 
    964 /* copy SIGURGs to the child process. */
    965 void
    966 copytochild(signo)
    967 	int signo;
    968 {
    969 
    970 	(void)kill(child, SIGURG);
    971 }
    972 
    973 void
    974 msg(str)
    975 	char *str;
    976 {
    977 
    978 	(void)fprintf(stderr, "rlogin: %s\r\n", str);
    979 }
    980 
    981 #ifdef KERBEROS
    982 /* VARARGS */
    983 void
    984 #if __STDC__
    985 warning(const char *fmt, ...)
    986 #else
    987 warning(fmt, va_alist)
    988 	char *fmt;
    989 	va_dcl
    990 #endif
    991 {
    992 	va_list ap;
    993 
    994 	(void)fprintf(stderr, "rlogin: warning, using standard rlogin: ");
    995 #ifdef __STDC__
    996 	va_start(ap, fmt);
    997 #else
    998 	va_start(ap);
    999 #endif
   1000 	vfprintf(stderr, fmt, ap);
   1001 	va_end(ap);
   1002 	(void)fprintf(stderr, ".\n");
   1003 }
   1004 #endif
   1005 
   1006 __dead void
   1007 usage()
   1008 {
   1009 	(void)fprintf(stderr,
   1010 	    "usage: rlogin [ -%s]%s[-e char] [ -l username ] [username@]host\n",
   1011 #ifdef KERBEROS
   1012 #ifdef CRYPT
   1013 	    "8EKLx", " [-k realm] ");
   1014 #else
   1015 	    "8EKL", " [-k realm] ");
   1016 #endif
   1017 #else
   1018 	    "8EL", " ");
   1019 #endif
   1020 	exit(1);
   1021 }
   1022 
   1023 /*
   1024  * The following routine provides compatibility (such as it is) between older
   1025  * Suns and others.  Suns have only a `ttysize', so we convert it to a winsize.
   1026  */
   1027 #ifdef OLDSUN
   1028 int
   1029 get_window_size(fd, wp)
   1030 	int fd;
   1031 	struct winsize *wp;
   1032 {
   1033 	struct ttysize ts;
   1034 	int error;
   1035 
   1036 	if ((error = ioctl(0, TIOCGSIZE, &ts)) != 0)
   1037 		return (error);
   1038 	wp->ws_row = ts.ts_lines;
   1039 	wp->ws_col = ts.ts_cols;
   1040 	wp->ws_xpixel = 0;
   1041 	wp->ws_ypixel = 0;
   1042 	return (0);
   1043 }
   1044 #endif
   1045 
   1046 u_int
   1047 getescape(p)
   1048 	register char *p;
   1049 {
   1050 	long val;
   1051 	int len;
   1052 
   1053 	if ((len = strlen(p)) == 1)	/* use any single char, including '\' */
   1054 		return ((u_int)*p);
   1055 					/* otherwise, \nnn */
   1056 	if (*p == '\\' && len >= 2 && len <= 4) {
   1057 		val = strtol(++p, NULL, 8);
   1058 		for (;;) {
   1059 			if (!*++p)
   1060 				return ((u_int)val);
   1061 			if (*p < '0' || *p > '8')
   1062 				break;
   1063 		}
   1064 	}
   1065 	msg("illegal option value -- e");
   1066 	usage();
   1067 	/* NOTREACHED */
   1068 }
   1069