     /*
      * Stuff: program to stuff input into another terminal.
      *
      * This program bypasses the normal superuser check for stuffing chars
      * into other people's terminals.  All you need is write permission on
      * the user's terminal.
      */

     #include <sgtty.h>
     #include <stdio.h>

     main(argc, argv)
	 char **argv;
     {
	 register int fd;               /* file descriptor */
	 char ch;                       /* current character */
	 char name[100];                /* tty name */
	 struct sgttyb sb;              /* old and new tty flags */
	 struct sgttyb nsb;

	 if (argc < 2)
	   {
	  fprintf(stderr, "stuff ttyname\n");
	  exit(1);
	   }
	 argv++;
	 if (**argv == '/')
	   strcpy(name, *argv); /* build full name */
	 else
	   sprintf(name, "/dev/%s", *argv);
    
	 if (setpgrp(0, 0)) /* clear my process group */
	   {
	  perror("spgrp");
	  goto done;
	   }
    
	 if (open(name, 1) < 0) /* open tty, making it mine */
	   {
	  perror(name);
	  exit(1);
	   }
    
	 fd = open("/dev/tty", 2);              /* open read/write as tty */
    
	 if (fd < 0)
	   {
	  perror("/dev/tty");
	  exit(1);
	   }
    
	 ioctl(0, TIOCGETP, &sb); /* go to raw mode */
	 nsb = sb;
	 nsb.sg_flags |= RAW;
	 nsb.sg_flags &= ~ECHO;
	 ioctl(0, TIOCSETN, &nsb);
	 sigsetmask(-1); /* stop hangups */
	 printf("Connected.  Type ^B to exit\r\n");
	 while (1)
	   {
	  if (read(0, &ch, 1) <= 0) break;
	  if ((ch & 0x7f) == '\002') break;
	  if (ioctl(fd, TIOCSTI, &ch))  /* stuff char on "his" tty */
	    {
		perror("\r\nsti failed\r");
		goto done;
	    }
	  ch &= 0x7f; /* echo it for me */
	  if (ch < ' ')
	    {
		if ((ch == '\r') || (ch == '\n'))
		  {
		      write(1, "\r\n", 2);
		      continue;
		  }
		ch += '@';
		write(1, "^", 1);
		write(1, &ch, 1);
		continue;
	    }
	  if (ch == '\177') {
	      write(1, "^?", 2);
	      continue;
	  }
	  write(1, &ch, 1);
	   }

     done:      ioctl(0, TIOCSETN, &sb);                /* reset tty */
     }


