#include <stdio.h>

main()
{
  char *c, *d;
  FILE *fp;
  char *l;
  char buf[BUFSIZ];
  char comment[BUFSIZ];
  char user[BUFSIZ];
  char command[100];
  char file[100];

  sprintf(file, "/tmp/form.%d", getpid());
  fp = fopen(file, "w");

  l = (char *) getenv("CONTENT_LENGTH");
  fprintf(fp, "To: web-request@mit.edu\nSubject: www comment\nReply-To:web-request@mit.edu\n------------------------------------------------------------\n\n");

  fgets(buf, atoi(l)+1 < sizeof(buf) ? atoi(l)+1 : sizeof(buf), stdin);
  c = buf;
  while(*c)
    {
      if(strncasecmp(c, "comments=", 9) == 0)
	{
	  d = c + 9;
	  c = d;
	  while(*d && (*d != '&'))
	    ++d;
	  *d = '\0';
	  if(*d)
	    ++d;
	  strcpy(comment, c);
	  c = d;
	}

      if(strncasecmp(c, "username=", 9) == 0)
	{
	  d = c + 9;
	  c = d;
	  while(*d && (*d != '&'))
	    ++d;
	  *d = '\0';
	  if(*d)
	    ++d;
	  strcpy(user, c);
	  c = d;
	}
      ++c;
    }
  
  if(*user)
    {
      formats(fp, user);
      fprintf(fp, " says: \n\n", user);
    }
  else
    fprintf(fp, "an anonymous user says: \n\n");

  formats(fp, comment);
  fprintf(fp, "\n\n------------------------------------------------------------\n");
  fclose(fp);

  if(*comment)
    {
      sprintf(command, "/usr/lib/sendmail web-request@mit.edu < %s", file);
      system(command);
      
      fprintf(stdout, "HTTP/1.0 200 OK\nContent-type: text/plain\n\n<TITLE>Thanks</TITLE>\n<H1>Thank You</H1><P>\nThank you for your comments. Have a nice day. <P>\nTo return to the top level MIT home page, click <A HREF=\"http://web.mit.edu/afs/net/admin/www/root/index.html\">here</A>.\n");
    }
  else
    fprintf(stdout, "HTTP/1.0 200 OK\nContent-type: text/plain\n\n<TITLE>Thanks</TITLE>\n<H1>Thank You</H1><P>\nThank you for your attempt at making a comment. Since you didn't type anything, nothing was sent. We hope you have better luck next time. To return to the top level MIT home page, click <A HREF=\"http://web.mit.edu/afs/net/admin/www/root/index.html\">here</A>.\n");

  unlink(file);
  exit(0);
}
  

formats(fp, s)
     FILE *fp;
     char *s;
{
  char buf[10];
  int n;

  while (*s)
    {
      if(*s == '+')
	{
	  fputc(' ', fp);
	  ++s;
	  continue;
	}
      if(*s == '%')
	{
	  ++s;
	  sprintf(buf, "0x%c%c", s[0], s[1]);
	  n = strtol(buf, NULL, 16) & 0xff;
	  fputc(n, fp);
	  s +=2;
	  continue;
	}
      if(*s == '!')
	{
	  fprintf(fp, " !");
	  ++s;
	  continue;
	}
      fputc(*s, fp);
      ++s;
    }
}
     
