tags:

views:

59

answers:

3

C file:

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

int main(int argc, char* argv[])
{
  FILE *ptr;
  char m[200];
  char *data = malloc(200);
  data=getenv("QUERY_STRING");
  sscanf(data,"%s", m);
  printf("%s", m);
  ptr=fopen("c:/test.txt", "w");
  fprintf(ptr, "%s", m);
  fclose(ptr);
  return 0;
}

//gcc -g print.c -o print.exe

HTML file:

<html>
  <body>
    <h2>CGI Server</h2>
    <p>
      <form action="http://localhost/cgi-bin/print.exe"&gt;
    <div><label>value: <input name="m" size="10"></label></div>
    <div><input type="submit" value="Run"></div>
      </form>
    </p>
  </body>
</html>

If the input into the webpage form is c:/data.txt then the result is: c%3A%2Fdata.txt

What happened? Why are the / and the : damaged in the output? it seems the problem is with QUERY_STRING because getenv("PATH") doesn't present this problem.

+3  A: 

The "problem" is due to URL-encoding. You'll need to URL-decode the value you get from QUERY_STRING.

LarsH
Like @nategoose said, the "damage" was done by the browser before your server ever received it. (Check the access logs and you'll see.)
LarsH
+1  A: 

The %3A type stuff is the HTTP hexadecimal encoding of characters which may be special. It is just like escaping the quote character in a C string. "\""

The PATH environmental variable has nothing to do with HTTP, so it is not effected. Your web server program is setting the QUERY_STRING to what the web browser sent, which has the % hex encoding in it.

nategoose
+2  A: 
  char *data = malloc(200);
  data=getenv("QUERY_STRING");

Memory leak here. You're allocating 200 bytes you'll never use or be able to free(). (Or not, for malloc() may fail and return NULL.)

  char m[200];
  sscanf(data,"%s", m);

This is a crude replacement for strcpy()/strncpy(). Results in a buffer overflow if the query string is more than 200 characters long. Also terminates as soon as it finds a whitespace, but that's not a problem becuase they've been turned to + or %20 during URL encoding.

  ptr=fopen("c:/test.txt", "w");
  fprintf(ptr, "%s", m);

fopen() may fail, resulting in a return value of NULL.

I suggest you review pointers and memory allocation, look up some string manipulation functions other than printf/scanf and also make a habit of checking for errors, i.e. coding defensively. Even in small, example-quality code.

aib