title: Parse HTTP Request Line In C
body: <p>This is the problem that will never end. The task is to parse a request line in a web server -- of indeterminate length -- in C. I pulled the following off of the web as an example with which to work. </p>
  
  <pre><code>GET /path/script.cgi?field1=value1&amp;field2=value2 HTTP/1.1
  </code></pre>
  
  <p>I must extract the absolute path: <code>/path/script.cgi</code> and the query: <code>?field1=value1&amp;field2=value2</code>. I'm told the following functions hold the key: <code>strchr</code>, <code>strcpy</code>, <code>strncmp</code>, <code>strncpy</code>, and/or <code>strstr</code>.</p>
  
  <p>Here's what has happened so far: I've learned that using functions like <code>strchr</code> and <code>strstr</code> will absolutely allow me to truncate the request line at certain points, but will never allow me to get rid of portions of the request line I do not want, and it doesn't matter how I layer them. </p>
  
  <p>For example, here's some code that get's me close to isolating the query, but I can't eliminate the http version. </p>
  
  <pre><code>bool parse(const char* line)
  {
      // request line w/o method
      const char ch = '/';
      char* lineptr = strchr(line, ch);
  
      // request line w/ query and HTTP version
      char ch_1 = '?';
      char* lineptr_1 = strchr(lineptr, ch_1);
  
      // request line w/o query
      char ch_2 = ' ';
      char* lineptr_2 = strchr(lineptr_1, ch_2);
  
      printf("%s\n", lineptr_2);
  
      if (lineptr_2 != NULL)
          return true;
      else
          return false;
  }
  </code></pre>
  
  <p>Needless to say, I have a similar issue trying to isolate the absolute path (I can ditch the method, but not the ? or anything thereafter), and I see no occasion on which I can use the functions that require me to know <em>a priori</em> how many chars I'd like to copy from one location (usually an array) to another because, when this is run in real time, I will have no clue what the request line will look like in advance. If someone sees something that I am missing and could point me in the right direction, I would be most grateful!</p>