0

I'm programming a simple web server in C. The HTTP message the server generates is stored in a buffer and sent (via send()) as follows:

Scenario 1:

"200 OK\nContent-Type: text/html\nContent-Length: " + resource size in bytes + "\r\n\n"

where the resource size in bytes is converted to a char array using snprintf and then concatenated into the string.

Scenario 2:

"HTTP1.1 404 Not Found\r\nContent-Length: 0\r\n\n"

Scenario 3:

"HTTP1.1 405 Method Not Allowed\r\nAllow: GET, HEAD\r\n"

These are the headers, they are sent beforehand. The message body is sent afterwards as follows:

   char resource[length];
   int numRead;
   while ( (numRead= read(filefd, resource, length)) > 0 ) 
       send(client, resource, length, 0);

When I use wireshark, it doesn't recognize it as an HTTP response. When I use firefox, the web page continues loading until I shut down the server, at which point it displays the HTTP response instead of a webpage (index.html):

image

Do I have to encode the message before sending? Or is there something wrong with my message format?

0thcall
  • 5
  • 2

1 Answers1

0

There are many errors here which suggest that you just made up your own version of HTTP instead of reading the standard. Please refer to the standard for all the details if you want to implement HTTP. In short:

"200 OK\nContent-Type: text/html\nContent-Length: " + resource size in bytes + "\r\n\n"

It should be HTTP/1.1 200 OK... and not just 200 OK.... All line ends must be \r\n and not \n and there must be a single \r\n at the end of the HTTP header.

"HTTP1.1 404 Not Found\r\nContent-Length: 0\r\n\n"
"HTTP1.1 405 Method Not Allowed\r\nAllow: GET, HEAD\r\n"

It should be HTTP/1.1 not HTTP1.1. And then all the other problems.

Again, if you really want to implement your own HTTP stack then study the standard. It is far more complex than you might think. Just because HTTP is a text based protocol does not mean that it is simple nor that any text is a correct HTTP message. Additionally implementations are tolerant in different ways, so just because it works with one client (i.e. browser) does not mean it is correct and that it will work with a different client too.

Community
  • 1
  • 1
Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
  • Thank you. I have taken your remarks in mind. I adjusted all the CRLFs according to standard and changed it to HTTP/1.1. The browser now loads the web page just fine. However, wireshark is still not capturing the HTTP request/response :( I'm using the loopback IP 127.0.0.1 to access the webpage, wireshark doesn't show ANY packets from/to 127.0.0.1. What could be the problem? – 0thcall Sep 23 '20 at 10:11
  • @0thcall: Regarding Wireshark: This is a completely different problem and should thus be its own question where you provide the necessary details of what exactly you are doing. – Steffen Ullrich Sep 23 '20 at 10:35