Initial import from FreeBSD RELENG_4:
[dragonfly.git] / usr.bin / rlogin / rlogin.c
1 /*
2  * Copyright (c) 1983, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 2002 Networks Associates Technology, Inc.
5  * All rights reserved.
6  *
7  * Portions of this software were developed for the FreeBSD Project by
8  * ThinkSec AS and NAI Labs, the Security Research Division of Network
9  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
10  * ("CBOSS"), as part of the DARPA CHATS research program.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *      This product includes software developed by the University of
23  *      California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40
41 #ifndef lint
42 static const char copyright[] =
43 "@(#) Copyright (c) 1983, 1990, 1993\n\
44         The Regents of the University of California.  All rights reserved.\n";
45 #endif /* not lint */
46
47 #ifndef lint
48 static const char sccsid[] = "@(#)rlogin.c      8.1 (Berkeley) 6/6/93";
49 static const char rcsid[] =
50   "$FreeBSD: src/usr.bin/rlogin/rlogin.c,v 1.24.2.2 2002/07/19 18:03:41 ru Exp $";
51 #endif /* not lint */
52
53 /*
54  * rlogin - remote login
55  */
56 #include <sys/param.h>
57 #include <sys/socket.h>
58 #include <sys/time.h>
59 #include <sys/resource.h>
60 #include <sys/wait.h>
61
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/tcp.h>
66
67 #include <err.h>
68 #include <errno.h>
69 #include <fcntl.h>
70 #include <libutil.h>
71 #include <netdb.h>
72 #include <paths.h>
73 #include <pwd.h>
74 #include <setjmp.h>
75 #include <sgtty.h>
76 #include <signal.h>
77 #include <stdio.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <unistd.h>
81 #include <err.h>
82
83 #ifdef KERBEROS
84 #include <openssl/des.h>
85 #include <krb.h>
86
87 #include "krb.h"
88
89 CREDENTIALS cred;
90 Key_schedule schedule;
91 int use_kerberos = 1, doencrypt;
92 char dst_realm_buf[REALM_SZ], *dest_realm = NULL;
93 #endif
94
95 #ifndef TIOCPKT_WINDOW
96 #define TIOCPKT_WINDOW  0x80
97 #endif
98
99 /* concession to Sun */
100 #ifndef SIGUSR1
101 #define SIGUSR1 30
102 #endif
103
104 int eight, litout, rem;
105 int family = PF_UNSPEC;
106
107 int noescape;
108 u_char escapechar = '~';
109
110 char *speeds[] = {
111         "0", "50", "75", "110", "134", "150", "200", "300", "600", "1200",
112         "1800", "2400", "4800", "9600", "19200", "38400", "57600", "115200"
113 #define MAX_SPEED_LENGTH        (sizeof("115200") - 1)
114 };
115
116 #ifdef OLDSUN
117 struct winsize {
118         unsigned short ws_row, ws_col;
119         unsigned short ws_xpixel, ws_ypixel;
120 };
121 #else
122 #define get_window_size(fd, wp) ioctl(fd, TIOCGWINSZ, wp)
123 #endif
124 struct  winsize winsize;
125
126 void            catch_child __P((int));
127 void            copytochild __P((int));
128 void            doit __P((long)) __dead2;
129 void            done __P((int)) __dead2;
130 void            echo __P((char));
131 u_int           getescape __P((char *));
132 void            lostpeer __P((int));
133 void            mode __P((int));
134 void            msg __P((char *));
135 void            oob __P((int));
136 int             reader __P((int));
137 void            sendwindow __P((void));
138 void            setsignal __P((int));
139 void            sigwinch __P((int));
140 void            stop __P((char));
141 void            usage __P((void)) __dead2;
142 void            writer __P((void));
143 void            writeroob __P((int));
144
145 #ifdef OLDSUN
146 int             get_window_size __P((int, struct winsize *));
147 #endif
148
149 int
150 main(argc, argv)
151         int argc;
152         char *argv[];
153 {
154         struct passwd *pw;
155         struct servent *sp;
156         struct sgttyb ttyb;
157         long omask;
158         int argoff, ch, dflag, Dflag, one, uid;
159         char *host, *localname, *p, *user, term[1024];
160 #ifdef KERBEROS
161         char *k;
162 #endif
163         struct sockaddr_storage ss;
164         int sslen;
165
166         argoff = dflag = Dflag = 0;
167         one = 1;
168         host = localname = user = NULL;
169
170         if ((p = rindex(argv[0], '/')))
171                 ++p;
172         else
173                 p = argv[0];
174
175         if (strcmp(p, "rlogin"))
176                 host = p;
177
178         /* handle "rlogin host flags" */
179         if (!host && argc > 2 && argv[1][0] != '-') {
180                 host = argv[1];
181                 argoff = 1;
182         }
183
184 #ifdef KERBEROS
185 #define OPTIONS "468DEKLde:i:k:l:x"
186 #else
187 #define OPTIONS "468DEKLde:i:l:"
188 #endif
189         while ((ch = getopt(argc - argoff, argv + argoff, OPTIONS)) != -1)
190                 switch(ch) {
191                 case '4':
192                         family = PF_INET;
193                         break;
194
195                 case '6':
196                         family = PF_INET6;
197                         break;
198
199                 case '8':
200                         eight = 1;
201                         break;
202                 case 'D':
203                         Dflag = 1;
204                         break;
205                 case 'E':
206                         noescape = 1;
207                         break;
208                 case 'K':
209 #ifdef KERBEROS
210                         use_kerberos = 0;
211 #endif
212                         break;
213                 case 'L':
214                         litout = 1;
215                         break;
216                 case 'd':
217                         dflag = 1;
218                         break;
219                 case 'e':
220                         noescape = 0;
221                         escapechar = getescape(optarg);
222                         break;
223                 case 'i':
224                         if (getuid() != 0)
225                                 errx(1, "-i user: permission denied");
226                         localname = optarg;
227                         break;
228 #ifdef KERBEROS
229                 case 'k':
230                         dest_realm = dst_realm_buf;
231                         (void)strncpy(dest_realm, optarg, REALM_SZ);
232                         break;
233 #endif
234                 case 'l':
235                         user = optarg;
236                         break;
237 #ifdef CRYPT
238 #ifdef KERBEROS
239                 case 'x':
240                         doencrypt = 1;
241                         break;
242 #endif
243 #endif
244                 case '?':
245                 default:
246                         usage();
247                 }
248         optind += argoff;
249
250         /* if haven't gotten a host yet, do so */
251         if (!host && !(host = argv[optind++]))
252                 usage();
253
254         if (argv[optind])
255                 usage();
256
257         if (!(pw = getpwuid(uid = getuid())))
258                 errx(1, "unknown user id");
259         if (!user)
260                 user = pw->pw_name;
261         if (!localname)
262                 localname = pw->pw_name;
263
264         sp = NULL;
265 #ifdef KERBEROS
266         k = auth_getval("auth_list");
267         if (k && !strstr(k, "kerberos"))
268             use_kerberos = 0;
269         if (use_kerberos) {
270                 sp = getservbyname((doencrypt ? "eklogin" : "klogin"), "tcp");
271                 if (sp == NULL) {
272                         use_kerberos = 0;
273                         warn("can't get entry for %s/tcp service",
274                             doencrypt ? "eklogin" : "klogin");
275                 }
276         }
277 #endif
278         if (sp == NULL)
279                 sp = getservbyname("login", "tcp");
280         if (sp == NULL)
281                 errx(1, "login/tcp: unknown service");
282
283 #define MAX_TERM_LENGTH (sizeof(term) - 1 - MAX_SPEED_LENGTH - 1)
284
285         (void)strncpy(term, (p = getenv("TERM")) ? p : "network",
286                       MAX_TERM_LENGTH);
287         term[MAX_TERM_LENGTH] = '\0';
288         if (ioctl(0, TIOCGETP, &ttyb) == 0) {
289                 (void)strcat(term, "/");
290                 (void)strcat(term, speeds[(int)ttyb.sg_ospeed]);
291         }
292
293         (void)get_window_size(0, &winsize);
294
295         (void)signal(SIGPIPE, lostpeer);
296         /* will use SIGUSR1 for window size hack, so hold it off */
297         omask = sigblock(sigmask(SIGURG) | sigmask(SIGUSR1));
298         /*
299          * We set SIGURG and SIGUSR1 below so that an
300          * incoming signal will be held pending rather than being
301          * discarded. Note that these routines will be ready to get
302          * a signal by the time that they are unblocked below.
303          */
304         (void)signal(SIGURG, copytochild);
305         (void)signal(SIGUSR1, writeroob);
306
307 #ifdef KERBEROS
308         if (use_kerberos) {
309                 setuid(getuid());
310                 rem = KSUCCESS;
311                 errno = 0;
312                 if (dest_realm == NULL)
313                         dest_realm = krb_realmofhost(host);
314
315 #ifdef CRYPT
316                 if (doencrypt) {
317                         rem = krcmd_mutual(&host, sp->s_port, user, term, 0,
318                             dest_realm, &cred, schedule);
319                         des_set_key(&cred.session, schedule);
320                 } else
321 #endif /* CRYPT */
322                         rem = krcmd(&host, sp->s_port, user, term, 0,
323                             dest_realm);
324                 if (rem < 0) {
325                         int i;
326                         char **newargv;
327
328                         sp = getservbyname("login", "tcp");
329                         if (sp == NULL)
330                                 errx(1, "unknown service login/tcp");
331                         if (errno == ECONNREFUSED)
332                                 warn("remote host doesn't support Kerberos");
333                         if (errno == ENOENT)
334                                 warn("can't provide Kerberos auth data");
335                         newargv = malloc((argc + 2) * sizeof(*newargv));
336                         if (newargv == NULL)
337                                 err(1, "malloc");
338                         newargv[0] = argv[0];
339                         newargv[1] = "-K";
340                         for(i = 1; i < argc; ++i)
341                         newargv[i + 1] = argv[i];
342                         newargv[argc + 1] = NULL;
343                         execv(_PATH_RLOGIN, newargv);
344                 }
345         } else {
346 #ifdef CRYPT
347                 if (doencrypt)
348                         errx(1, "the -x flag requires Kerberos authentication");
349 #endif /* CRYPT */
350                 rem = rcmd_af(&host, sp->s_port, localname, user, term, 0,
351                               family);
352         }
353 #else
354         rem = rcmd_af(&host, sp->s_port, localname, user, term, 0, family);
355 #endif /* KERBEROS */
356
357         if (rem < 0)
358                 exit(1);
359
360         if (dflag &&
361             setsockopt(rem, SOL_SOCKET, SO_DEBUG, &one, sizeof(one)) < 0)
362                 warn("setsockopt");
363         if (Dflag &&
364             setsockopt(rem, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) < 0)
365                 warn("setsockopt NODELAY (ignored)");
366
367         sslen = sizeof(ss);
368         one = IPTOS_LOWDELAY;
369         if (getsockname(rem, (struct sockaddr *)&ss, &sslen) == 0 &&
370             ss.ss_family == AF_INET) {
371                 if (setsockopt(rem, IPPROTO_IP, IP_TOS, (char *)&one,
372                                sizeof(int)) < 0)
373                         warn("setsockopt TOS (ignored)");
374         } else
375                 if (ss.ss_family == AF_INET)
376                         warn("setsockopt getsockname failed");
377
378         (void)setuid(uid);
379         doit(omask);
380         /*NOTREACHED*/
381 }
382
383 int child, defflags, deflflags, tabflag;
384 char deferase, defkill;
385 struct tchars deftc;
386 struct ltchars defltc;
387 struct tchars notc = { -1, -1, -1, -1, -1, -1 };
388 struct ltchars noltc = { -1, -1, -1, -1, -1, -1 };
389
390 void
391 doit(omask)
392         long omask;
393 {
394         struct sgttyb sb;
395
396         (void)ioctl(0, TIOCGETP, (char *)&sb);
397         defflags = sb.sg_flags;
398         tabflag = defflags & TBDELAY;
399         defflags &= ECHO | CRMOD;
400         deferase = sb.sg_erase;
401         defkill = sb.sg_kill;
402         (void)ioctl(0, TIOCLGET, &deflflags);
403         (void)ioctl(0, TIOCGETC, &deftc);
404         notc.t_startc = deftc.t_startc;
405         notc.t_stopc = deftc.t_stopc;
406         (void)ioctl(0, TIOCGLTC, &defltc);
407         (void)signal(SIGINT, SIG_IGN);
408         setsignal(SIGHUP);
409         setsignal(SIGQUIT);
410         child = fork();
411         if (child == -1) {
412                 warn("fork");
413                 done(1);
414         }
415         if (child == 0) {
416                 mode(1);
417                 if (reader(omask) == 0) {
418                         msg("connection closed.");
419                         exit(0);
420                 }
421                 sleep(1);
422                 msg("\007connection closed.");
423                 exit(1);
424         }
425
426         /*
427          * We may still own the socket, and may have a pending SIGURG (or might
428          * receive one soon) that we really want to send to the reader.  When
429          * one of these comes in, the trap copytochild simply copies such
430          * signals to the child. We can now unblock SIGURG and SIGUSR1
431          * that were set above.
432          */
433         (void)sigsetmask(omask);
434         (void)signal(SIGCHLD, catch_child);
435         writer();
436         msg("closed connection.");
437         done(0);
438 }
439
440 /* trap a signal, unless it is being ignored. */
441 void
442 setsignal(sig)
443         int sig;
444 {
445         int omask = sigblock(sigmask(sig));
446
447         if (signal(sig, exit) == SIG_IGN)
448                 (void)signal(sig, SIG_IGN);
449         (void)sigsetmask(omask);
450 }
451
452 void
453 done(status)
454         int status;
455 {
456         int w, wstatus;
457
458         mode(0);
459         if (child > 0) {
460                 /* make sure catch_child does not snap it up */
461                 (void)signal(SIGCHLD, SIG_DFL);
462                 if (kill(child, SIGKILL) >= 0)
463                         while ((w = wait(&wstatus)) > 0 && w != child);
464         }
465         exit(status);
466 }
467
468 int dosigwinch;
469
470 /*
471  * This is called when the reader process gets the out-of-band (urgent)
472  * request to turn on the window-changing protocol.
473  */
474 void
475 writeroob(signo)
476         int signo;
477 {
478         if (dosigwinch == 0) {
479                 sendwindow();
480                 (void)signal(SIGWINCH, sigwinch);
481         }
482         dosigwinch = 1;
483 }
484
485 void
486 catch_child(signo)
487         int signo;
488 {
489         union wait status;
490         int pid;
491
492         for (;;) {
493                 pid = wait3((int *)&status, WNOHANG|WUNTRACED, NULL);
494                 if (pid == 0)
495                         return;
496                 /* if the child (reader) dies, just quit */
497                 if (pid < 0 || (pid == child && !WIFSTOPPED(status)))
498                         done((int)(status.w_termsig | status.w_retcode));
499         }
500         /* NOTREACHED */
501 }
502
503 /*
504  * writer: write to remote: 0 -> line.
505  * ~.                           terminate
506  * ~^Z                          suspend rlogin process.
507  * ~<delayed-suspend char>      suspend rlogin process, but leave reader alone.
508  */
509 void
510 writer()
511 {
512         register int bol, local, n;
513         char c;
514
515         bol = 1;                        /* beginning of line */
516         local = 0;
517         for (;;) {
518                 n = read(STDIN_FILENO, &c, 1);
519                 if (n <= 0) {
520                         if (n < 0 && errno == EINTR)
521                                 continue;
522                         break;
523                 }
524                 /*
525                  * If we're at the beginning of the line and recognize a
526                  * command character, then we echo locally.  Otherwise,
527                  * characters are echo'd remotely.  If the command character
528                  * is doubled, this acts as a force and local echo is
529                  * suppressed.
530                  */
531                 if (bol) {
532                         bol = 0;
533                         if (!noescape && c == escapechar) {
534                                 local = 1;
535                                 continue;
536                         }
537                 } else if (local) {
538                         local = 0;
539                         if (c == '.' || c == deftc.t_eofc) {
540                                 echo(c);
541                                 break;
542                         }
543                         if (c == defltc.t_suspc || c == defltc.t_dsuspc) {
544                                 bol = 1;
545                                 echo(c);
546                                 stop(c);
547                                 continue;
548                         }
549                         if (c != escapechar)
550 #ifdef CRYPT
551 #ifdef KERBEROS
552                                 if (doencrypt)
553                                         (void)des_enc_write(rem,
554                                             (char *)&escapechar, 1,
555                                                 schedule, &cred.session);
556                                 else
557 #endif
558 #endif
559                                         (void)write(rem, &escapechar, 1);
560                 }
561
562 #ifdef CRYPT
563 #ifdef KERBEROS
564                 if (doencrypt) {
565                         if (des_enc_write(rem, &c, 1, schedule, &cred.session) == 0) {
566                                 msg("line gone");
567                                 break;
568                         }
569                 } else
570 #endif
571 #endif
572                         if (write(rem, &c, 1) == 0) {
573                                 msg("line gone");
574                                 break;
575                         }
576                 bol = c == defkill || c == deftc.t_eofc ||
577                     c == deftc.t_intrc || c == defltc.t_suspc ||
578                     c == '\r' || c == '\n';
579         }
580 }
581
582 void
583 #if __STDC__
584 echo(register char c)
585 #else
586 echo(c)
587         register char c;
588 #endif
589 {
590         register char *p;
591         char buf[8];
592
593         p = buf;
594         c &= 0177;
595         *p++ = escapechar;
596         if (c < ' ') {
597                 *p++ = '^';
598                 *p++ = c + '@';
599         } else if (c == 0177) {
600                 *p++ = '^';
601                 *p++ = '?';
602         } else
603                 *p++ = c;
604         *p++ = '\r';
605         *p++ = '\n';
606         (void)write(STDOUT_FILENO, buf, p - buf);
607 }
608
609 void
610 #if __STDC__
611 stop(char cmdc)
612 #else
613 stop(cmdc)
614         char cmdc;
615 #endif
616 {
617         mode(0);
618         (void)signal(SIGCHLD, SIG_IGN);
619         (void)kill(cmdc == defltc.t_suspc ? 0 : getpid(), SIGTSTP);
620         (void)signal(SIGCHLD, catch_child);
621         mode(1);
622         sigwinch(0);                    /* check for size changes */
623 }
624
625 void
626 sigwinch(signo)
627         int signo;
628 {
629         struct winsize ws;
630
631         if (dosigwinch && get_window_size(0, &ws) == 0 &&
632             bcmp(&ws, &winsize, sizeof(ws))) {
633                 winsize = ws;
634                 sendwindow();
635         }
636 }
637
638 /*
639  * Send the window size to the server via the magic escape
640  */
641 void
642 sendwindow()
643 {
644         struct winsize *wp;
645         char obuf[4 + sizeof (struct winsize)];
646
647         wp = (struct winsize *)(obuf+4);
648         obuf[0] = 0377;
649         obuf[1] = 0377;
650         obuf[2] = 's';
651         obuf[3] = 's';
652         wp->ws_row = htons(winsize.ws_row);
653         wp->ws_col = htons(winsize.ws_col);
654         wp->ws_xpixel = htons(winsize.ws_xpixel);
655         wp->ws_ypixel = htons(winsize.ws_ypixel);
656
657 #ifdef CRYPT
658 #ifdef KERBEROS
659         if(doencrypt)
660                 (void)des_enc_write(rem, obuf, sizeof(obuf),
661                         schedule, &cred.session);
662         else
663 #endif
664 #endif
665                 (void)write(rem, obuf, sizeof(obuf));
666 }
667
668 /*
669  * reader: read from remote: line -> 1
670  */
671 #define READING 1
672 #define WRITING 2
673
674 jmp_buf rcvtop;
675 int ppid, rcvcnt, rcvstate;
676 char rcvbuf[8 * 1024];
677
678 void
679 oob(signo)
680         int signo;
681 {
682         struct sgttyb sb;
683         int atmark, n, out, rcvd;
684         char waste[BUFSIZ], mark;
685
686         out = O_RDWR;
687         rcvd = 0;
688         while (recv(rem, &mark, 1, MSG_OOB) < 0) {
689                 switch (errno) {
690                 case EWOULDBLOCK:
691                         /*
692                          * Urgent data not here yet.  It may not be possible
693                          * to send it yet if we are blocked for output and
694                          * our input buffer is full.
695                          */
696                         if (rcvcnt < sizeof(rcvbuf)) {
697                                 n = read(rem, rcvbuf + rcvcnt,
698                                     sizeof(rcvbuf) - rcvcnt);
699                                 if (n <= 0)
700                                         return;
701                                 rcvd += n;
702                         } else {
703                                 n = read(rem, waste, sizeof(waste));
704                                 if (n <= 0)
705                                         return;
706                         }
707                         continue;
708                 default:
709                         return;
710                 }
711         }
712         if (mark & TIOCPKT_WINDOW) {
713                 /* Let server know about window size changes */
714                 (void)kill(ppid, SIGUSR1);
715         }
716         if (!eight && (mark & TIOCPKT_NOSTOP)) {
717                 (void)ioctl(0, TIOCGETP, (char *)&sb);
718                 sb.sg_flags &= ~CBREAK;
719                 sb.sg_flags |= RAW;
720                 (void)ioctl(0, TIOCSETN, (char *)&sb);
721                 notc.t_stopc = -1;
722                 notc.t_startc = -1;
723                 (void)ioctl(0, TIOCSETC, (char *)&notc);
724         }
725         if (!eight && (mark & TIOCPKT_DOSTOP)) {
726                 (void)ioctl(0, TIOCGETP, (char *)&sb);
727                 sb.sg_flags &= ~RAW;
728                 sb.sg_flags |= CBREAK;
729                 (void)ioctl(0, TIOCSETN, (char *)&sb);
730                 notc.t_stopc = deftc.t_stopc;
731                 notc.t_startc = deftc.t_startc;
732                 (void)ioctl(0, TIOCSETC, (char *)&notc);
733         }
734         if (mark & TIOCPKT_FLUSHWRITE) {
735                 (void)ioctl(1, TIOCFLUSH, (char *)&out);
736                 for (;;) {
737                         if (ioctl(rem, SIOCATMARK, &atmark) < 0) {
738                                 warn("ioctl");
739                                 break;
740                         }
741                         if (atmark)
742                                 break;
743                         n = read(rem, waste, sizeof (waste));
744                         if (n <= 0)
745                                 break;
746                 }
747                 /*
748                  * Don't want any pending data to be output, so clear the recv
749                  * buffer.  If we were hanging on a write when interrupted,
750                  * don't want it to restart.  If we were reading, restart
751                  * anyway.
752                  */
753                 rcvcnt = 0;
754                 longjmp(rcvtop, 1);
755         }
756
757         /* oob does not do FLUSHREAD (alas!) */
758
759         /*
760          * If we filled the receive buffer while a read was pending, longjmp
761          * to the top to restart appropriately.  Don't abort a pending write,
762          * however, or we won't know how much was written.
763          */
764         if (rcvd && rcvstate == READING)
765                 longjmp(rcvtop, 1);
766 }
767
768 /* reader: read from remote: line -> 1 */
769 int
770 reader(omask)
771         int omask;
772 {
773         int pid, n, remaining;
774         char *bufp;
775
776 #if BSD >= 43 || defined(SUNOS4)
777         pid = getpid();         /* modern systems use positives for pid */
778 #else
779         pid = -getpid();        /* old broken systems use negatives */
780 #endif
781         (void)signal(SIGTTOU, SIG_IGN);
782         (void)signal(SIGURG, oob);
783         ppid = getppid();
784         (void)fcntl(rem, F_SETOWN, pid);
785         (void)setjmp(rcvtop);
786         (void)sigsetmask(omask);
787         bufp = rcvbuf;
788         for (;;) {
789                 while ((remaining = rcvcnt - (bufp - rcvbuf)) > 0) {
790                         rcvstate = WRITING;
791                         n = write(STDOUT_FILENO, bufp, remaining);
792                         if (n < 0) {
793                                 if (errno != EINTR)
794                                         return (-1);
795                                 continue;
796                         }
797                         bufp += n;
798                 }
799                 bufp = rcvbuf;
800                 rcvcnt = 0;
801                 rcvstate = READING;
802
803 #ifdef CRYPT
804 #ifdef KERBEROS
805                 if (doencrypt)
806                         rcvcnt = des_enc_read(rem, rcvbuf, sizeof(rcvbuf),
807                                 schedule, &cred.session);
808                 else
809 #endif
810 #endif
811                         rcvcnt = read(rem, rcvbuf, sizeof (rcvbuf));
812                 if (rcvcnt == 0)
813                         return (0);
814                 if (rcvcnt < 0) {
815                         if (errno == EINTR)
816                                 continue;
817                         warn("read");
818                         return (-1);
819                 }
820         }
821 }
822
823 void
824 mode(f)
825         int f;
826 {
827         struct ltchars *ltc;
828         struct sgttyb sb;
829         struct tchars *tc;
830         int lflags;
831
832         (void)ioctl(0, TIOCGETP, (char *)&sb);
833         (void)ioctl(0, TIOCLGET, (char *)&lflags);
834         switch(f) {
835         case 0:
836                 sb.sg_flags &= ~(CBREAK|RAW|TBDELAY);
837                 sb.sg_flags |= defflags|tabflag;
838                 tc = &deftc;
839                 ltc = &defltc;
840                 sb.sg_kill = defkill;
841                 sb.sg_erase = deferase;
842                 lflags = deflflags;
843                 break;
844         case 1:
845                 sb.sg_flags |= (eight ? RAW : CBREAK);
846                 sb.sg_flags &= ~defflags;
847                 /* preserve tab delays, but turn off XTABS */
848                 if ((sb.sg_flags & TBDELAY) == XTABS)
849                         sb.sg_flags &= ~TBDELAY;
850                 tc = &notc;
851                 ltc = &noltc;
852                 sb.sg_kill = sb.sg_erase = -1;
853                 if (litout)
854                         lflags |= LLITOUT;
855                 break;
856         default:
857                 return;
858         }
859         (void)ioctl(0, TIOCSLTC, (char *)ltc);
860         (void)ioctl(0, TIOCSETC, (char *)tc);
861         (void)ioctl(0, TIOCSETN, (char *)&sb);
862         (void)ioctl(0, TIOCLSET, (char *)&lflags);
863 }
864
865 void
866 lostpeer(signo)
867         int signo;
868 {
869         (void)signal(SIGPIPE, SIG_IGN);
870         msg("\007connection closed.");
871         done(1);
872 }
873
874 /* copy SIGURGs to the child process. */
875 void
876 copytochild(signo)
877         int signo;
878 {
879         (void)kill(child, SIGURG);
880 }
881
882 void
883 msg(str)
884         char *str;
885 {
886         (void)fprintf(stderr, "rlogin: %s\r\n", str);
887 }
888
889 void
890 usage()
891 {
892         (void)fprintf(stderr,
893         "usage: rlogin [-46%s]%s[-e char] [-i localname] [-l username] host\n",
894 #ifdef KERBEROS
895 #ifdef CRYPT
896             "8DEKLdx", " [-k realm] ");
897 #else
898             "8DEKLd", " [-k realm] ");
899 #endif
900 #else
901             "8DEKLd", " ");
902 #endif
903         exit(1);
904 }
905
906 /*
907  * The following routine provides compatibility (such as it is) between older
908  * Suns and others.  Suns have only a `ttysize', so we convert it to a winsize.
909  */
910 #ifdef OLDSUN
911 int
912 get_window_size(fd, wp)
913         int fd;
914         struct winsize *wp;
915 {
916         struct ttysize ts;
917         int error;
918
919         if ((error = ioctl(0, TIOCGSIZE, &ts)) != 0)
920                 return (error);
921         wp->ws_row = ts.ts_lines;
922         wp->ws_col = ts.ts_cols;
923         wp->ws_xpixel = 0;
924         wp->ws_ypixel = 0;
925         return (0);
926 }
927 #endif
928
929 u_int
930 getescape(p)
931         register char *p;
932 {
933         long val;
934         int len;
935
936         if ((len = strlen(p)) == 1)     /* use any single char, including '\' */
937                 return ((u_int)*p);
938                                         /* otherwise, \nnn */
939         if (*p == '\\' && len >= 2 && len <= 4) {
940                 val = strtol(++p, NULL, 8);
941                 for (;;) {
942                         if (!*++p)
943                                 return ((u_int)val);
944                         if (*p < '0' || *p > '8')
945                                 break;
946                 }
947         }
948         msg("illegal option value -- e");
949         usage();
950         /* NOTREACHED */
951 }