/*
 * ftelnetd - fake telnet daemon
 *
 * data_handling.c
 *
 * Wed Feb  7 15:02:56 CET 2007
 *
 * by Levent Kayan
 * levent[at]corehack.org
 * www.corehack.org
 */

#include "ftelnetd.h"
#include "ferror.h"

#include <stdio.h>
#include <stdlib.h>

unsigned char get_byte(int s) {
   /* get byte, ignore protocol shit; exit() on error/close */
   /* blame the mantrain master if this breaks. */
   unsigned char b;
   int ret, state;
#define GB_ST_WAITBYTE     0
#define GB_ST_WAITCOMMAND  1
#define GB_ST_WAITPARAM    2

   state = GB_ST_WAITBYTE;
   while (1) {
      if ( (ret = recv(s, &b, 1, 0)) < 0 ) {
         ERR_GEN;
      }
      if (ret == 0) {
         exit(EXIT_SUCCESS);
      }
      if (ret != 1) {
         ERR_GEN;
      }
      switch (state) {
       case GB_ST_WAITBYTE:
          if (b != 0xff) {
             return b;
          }
          state = GB_ST_WAITCOMMAND;
          break;
       case GB_ST_WAITCOMMAND:
          /* literal 0xff, no IAC */
          if (b == 0xff) {
             return 0xff;
          }
          if (b >= 0xfb) {
             state = GB_ST_WAITPARAM;
          }
          else {
             state = GB_ST_WAITBYTE;
          }
          break;
       case GB_ST_WAITPARAM:
          state = GB_ST_WAITBYTE;
          break;
       default:
          while (1) {
             printf("[-] You fucked up! Go and ride the mantrain, retard!\n");
          }
      }
   }
}

/* read up to len chars into *target, say "say" for every char
 * 0x00 keeps silent, 0xff echoes - yes, this is gh3y. */
void get_line(int s, char *target, unsigned int len, unsigned char say) {
   unsigned int read = 0;
   char b = 0;

   while (read < len) {
      target[read] = get_byte(s);
      if (target[read] == 0x0d) {
         target[read] = 0x00;
         /* 0-byte */
         (void) get_byte(s);
         return;
      }
      if (say) {
         b = (say == 0xff) ? target[read] : say;
         if (send(s , &b, 1, 0) != 1) {
            ERR_GEN;
         }
      }
      read++;
   }
   target[len - 1] = 0x00;
}

/* EOF */


syntax highlighted by Code2HTML, v. 0.9.1