单线程,同步阻塞的socket。去掉了cgi的功能,只处理静态文件请求,改了accept_request中的几处bug。
/* J. David's webserver */
/* This is a simple webserver.
* Created November 1999 by J. David Blackstone.
* CSE 4344 (Network concepts), Prof. Zeigler
* University of Texas at Arlington
*/
/* This program compiles for Sparc Solaris 2.6.
* To compile for Linux:
* 1) Comment out the #include <pthread.h> line.
* 2) Comment out the line that defines the variable newthread.
* 3) Comment out the two lines that run pthread_create().
* 4) Uncomment the line that runs accept_request().
* 5) Remove -lsocket from the Makefile.
*/
#include <WinSock2.h>
#include <stdio.h>
#include <sys/types.h>
#include <ctype.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#pragma warning(disable : 4267)
#define ISspace(x) isspace((int)(x))
#define SERVER_STRING "Server: bdsoftmgr httpd/0.1.0\r\n"
void accept_request(SOCKET);
void bad_request(int);
void cat(SOCKET, FILE *);
void cannot_execute(int);
void error_die(const char *);
void execute_cgi(int, const char *, const char *, const char *);
int get_line(SOCKET, char *, int);
void headers(SOCKET, const char *);
void not_found(SOCKET);
void serve_file(SOCKET, const char *);
SOCKET startup(u_short *);
void unimplemented(SOCKET);
void discardheaders(SOCKET);
/**********************************************************************/
/* A request has caused a call to accept() on the server port to
* return. Process the request appropriately.
* Parameters: the socket connected to the client */
/**********************************************************************/
void accept_request(SOCKET client)
{
char buf[1024];
int numchars;
char method[255];
char url[255];
char path[512];
size_t i, j;
struct stat st;
char *query_string = NULL;
numchars = get_line(client, buf, sizeof(buf));
i = 0; j = 0;
while (j < numchars && !ISspace(buf[j]) && (i < sizeof(method) - 1))
{
method[i] = buf[j];
i++; j++;
}
method[i] = '\0';
if (_stricmp(method, "GET") != 0) // 只处理GET请求
{
if (numchars > 0)
discardheaders(client);
unimplemented(client);
closesocket(client);
return;
}
i = 0;
while (ISspace(buf[j]) && (j < sizeof(buf)))
j++;
while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)))
{
url[i] = buf[j];
i++; j++;
}
url[i] = '\0';
if (_stricmp(method, "GET") == 0)
{
query_string = url;
while ((*query_string != '?') && (*q