/*
 * Code illustrating buffer overflow attack
 *
 */
#include <stdio.h>

/* gets(char *s)
 * reads line from stdin into s, assuming
 * there the array starting at s is long
 * enough to hold a single line
 * dangerous function; use fgets instead
 */
char *gets(char *s) {
  int c;
  char *p = s;
  while ((c = getchar()) != '\n' && c != EOF)
    *p++ = c;
  *p = '\0';
  if (c == EOF)
    return NULL;
  return s;
}

/* echo()
 * Reads a line from stdin into buf and
 * writes it to stdout out
 * Long inputs will lead to segmentation fault
 * due to buffer overflow overwriting return address
 *
 * Compiling with gcc -O2 on lab machines
 * will lead to a seg fault with input longer than 12 bytes
 */
void echo() {
  char buf[4];			/* too small; for illustration only */
  gets(buf);			/* also should check return code */
  puts(buf);
}

/*
 * Better, but still not recommended implementation
 * See RIO package to go with textbook (CS:APP)
 */
void echosafe() {
  char buf[4];			/* too small; for illustration only */
  fgets(buf, 4, stdin);		/* should check for NULL */
  fputs(buf, stdout);
}

int main () {
  while (1)
    echo();
  return 0;
}
