通过添加 fseek(file, 0, 0) 一旦完成响应来解决。
我正在编写一个非常简单的 http 服务器,它将用 HTTP 响应回复任何 GET 请求。响应内容将在程序启动时传递给程序,例如
$./server test1.html 999
该命令将打开监听 999 端口,如果有任何 GET 请求,服务器将发送“http headers”+“test1.html 的内容”给请求的客户端。
fork() 部分不能正常工作,我第一次可以得到正确的响应,但是之后,新客户端将不会从服务器收到任何东西(cookie 和缓存被清除)。
我调试了,程序会 fprintf() 正确的内容,问题是“客户端不会收到它们”。
下面是我的代码,有一个名为 get_mime_type() 的函数,你可以忽略它并将 mime 设置为“text/html”或任何你想要的。
有什么提示吗?
顺便说一句,我也想避免使用多个进程来处理多个连接,关于实现单进程、单线程 http 服务器的任何想法?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#include <dirent.h>
#include <time.h>
#include <unistd.h>
#define BACKLOG 1024
#define RFC1123FMT "%a, %d %b %Y %H:%M:%S GMT"
#define DEBUG 1
/**
* Get the mime type of a file
*
* Pre-Condition: 1. mime-types.tsv is in current directory, and it is correct
* 2. file exists and all right
*/
char *get_mime_type(char *filename) {
// Get extension
char *ext; // file extension
if ((ext = strrchr(filename, '.')) == NULL) {
fprintf(stderr, "Error: Cannot get the extension of \"%s\".\n", filename);
exit(1);
}
ext += sizeof(char); // get rid of the `.'
// Read in mime-types.tsv and try to get the mime-type regarding to current file's extension
// No detailed error-checking according to pre-condition
FILE *mime_file;
mime_file = fopen("mime-types.tsv", "r");
int BUF_MAX = 1024;
char *buffer = (char *)malloc(sizeof(char) * BUF_MAX);
char *mime;
fgets(buffer, BUF_MAX, mime_file);
int linum = atoi(buffer);
while (linum-- > 0) {
fgets(buffer, BUF_MAX, mime_file);
if ((strncasecmp(buffer, ext, strlen(ext))) == 0) {
buffer[strlen(buffer) - 1] = '\0';
mime = buffer;
while (*mime != ' ') {
mime += sizeof(char);
}
mime += sizeof(char);
free(buffer); // TODO: is this all right?
fclose(mime_file);
return mime;
}
}
free(buffer);
fclose(mime_file);
return NULL;
}
void sigchld_handler(int s)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
/**
* Get sockaddr, IPv4 or IPv6:
*/
void *get_in_addr(struct sockaddr *sig_action)
{
if (sig_action->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sig_action)->sin_addr);
}
return &(((struct sockaddr_in6*)sig_action)->sin6_addr);
}
/**
* Open a socket and listen to it, send information once got requests
*/
int run_server(char *filename, char *port) {
// open file and get its information
FILE *file;
struct stat statbuf;
if (stat(filename, &statbuf) < 0) {
fprintf(stderr, "Error: Unable to open \"%s\".\n", filename);
exit(1);
}
if (S_ISDIR(statbuf.st_mode)) {
fprintf(stderr, "Error: %s is a directory, expected a file.\n", filename);
exit(1);
}
if ((file = fopen(filename, "r")) == NULL) {
fprintf(stderr, "Error: Unable to open \"%s\".\n", filename);
exit(1);
}
char *mime = get_mime_type(filename);
if (mime == NULL) {
fprintf(stderr, "Error: the type of \"%s\" cannot be recognised.\n", filename);
exit(1);
}
int file_len = S_ISREG(statbuf.st_mode) ? statbuf.st_size : -1;
time_t mtime = statbuf.st_mtime; // last modified time, used in header
// init sock
int server_fd, client_fd;
struct addrinfo hints, *server_info, *p_server_info;
struct sockaddr_storage client_addr;
socklen_t sock_in_size;
struct sigaction sig_action;
int yes = 1;
char client_ip[INET6_ADDRSTRLEN];
int return_value; // store return value of getaddrinfo
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((return_value = getaddrinfo(NULL, port, &hints, &server_info)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(return_value));
return 1;
}
// TODO ? free hints? free p_server_info
// bind
for (p_server_info = server_info; p_server_info != NULL; p_server_info = p_server_info->ai_next) {
if ((server_fd = socket(p_server_info->ai_family, p_server_info->ai_socktype,
p_server_info->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (bind(server_fd, p_server_info->ai_addr, p_server_info->ai_addrlen) == -1) {
close(server_fd);
perror("server: bind");
continue;
}
break;
}
if (p_server_info == NULL) { // not bind
fprintf(stderr, "server: failed to bind\n");
return 2;
}
freeaddrinfo(server_info);
// listen
if (listen(server_fd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
// reap dead processes
sig_action.sa_handler = sigchld_handler;
sigemptyset(&sig_action.sa_mask);
sig_action.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sig_action, NULL) == -1) {
perror("sigaction");
exit(1);
}
printf("server: waiting for connections...\n");
while (1) {
sock_in_size = sizeof(client_addr);
client_fd = accept(server_fd, (struct sockaddr *) &client_addr, &sock_in_size);
if (client_fd == -1) {
perror("accept");
continue;
}
inet_ntop(client_addr.ss_family,
get_in_addr((struct sockaddr *)&client_addr),
client_ip, sizeof(client_ip));
printf("server: got connection from %s\n", client_ip);
if (!fork()) { // child process
close(server_fd);
FILE* response = fdopen(client_fd, "a+"); // response file
// response header
time_t now;
char timebuf[128];
now = time(NULL);
strftime(timebuf, sizeof(timebuf), RFC1123FMT, gmtime(&now));
fprintf(response, "HTTP/1.1 200 OK\r\n");
fprintf(response, "Server: server\r\n");
fprintf(response, "Date: %s\r\n", timebuf);
strftime(timebuf, sizeof(timebuf), RFC1123FMT, gmtime(&mtime));
fprintf(response, "Last-Modified: %s\r\n", timebuf);
fprintf(response, "Content-Type: %s\r\n", mime);
fprintf(response, "Content-Length: %d\r\n", file_len);
fprintf(response, "Connection: close\r\n");
fprintf(response, "\r\n");
// response content
char buf[1024];
int n;
while ((n = fread(buf, 1, sizeof(buf), file)) > 0) {
fwrite(buf, 1, n, response);
}
fclose(response);
fclose(file);
close(client_fd);
exit(0);
}
}
fclose(file);
close(server_fd);
return 0;
}
int main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "Usage: $server filename port\n");
exit(1);
}
char *filename = argv[1];
char *port = argv[2];
return run_server(filename, port);
}