Cryptography Reference
In-Depth Information
There are three problems with this function:
It keeps reallocating its internal buffer essentially forever. A rogue client
could take advantage of this, send a malformed request with no CRLF's
and crash the server.
It reads one byte at a time from the socket. Each call to recv actually
invokes a system call, which slows things down quite a bit. For optimal
effi ciency, you should read a buffer of text, extract a line from it, and store
the remainder for the next invocation.
Its use of static variables makes it non-thread-safe.
You can ignore these shortcomings, though. This implementation is good
enough for your requirements, which is to have a server to which you can add
SSL support.
To wrap up the web server, implement the functions build_success_response
and build_error_response shown in Listing 1-21.
Listing 1-21: “webserver.c” build responses
static void build_success_response( int connection )
{
char buf[ 255 ];
sprintf( buf, “HTTP/1.1 200 Success\r\nConnection: Close\r\n\
Content-Type:text/html\r\n\
\r\n<html><head><title>Test Page</title></head><body>Nothing here</body></html>\
\r\n” );
// Technically, this should account for short writes.
if ( send( connection, buf, strlen( buf ), 0 ) < strlen( buf ) )
{
perror( “Trying to respond” );
}
}
static void build_error_response( int connection, int error_code )
{
char buf[ 255 ];
sprintf( buf, “HTTP/1.1 %d Error Occurred\r\n\r\n”, error_code );
// Technically, this should account for short writes.
if ( send( connection, buf, strlen( buf ), 0 ) < strlen( buf ) )
{
perror( “Trying to respond” );
}
}
 
Search WWH ::




Custom Search