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