最近决定找一些C语言的HTTP有关的开源代码进行学习,本着由简入繁的原则,首先从一个仅200多行的micro_httpd入手。
micro_httpd是一个极其轻量级的HTTP服务端程序,支持安全的..上级目录过滤、通用的MIME类型、目录列表、index.html、斜杠重定向等。它需要从inetd服务启动,因此代码里面基本没有套接字相关的东西。
在阅读的过程中,也发现了一些我觉得可以进行微调的地方并进行了修改。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include <dirent.h>
#include <unistd.h>
#define SERVER_NAME "micro_httpd"
#define SERVER_URL "http://www.acme.com/software/micro_httpd/"
#define PROTOCOL "HTTP/1.0"
#define RFC1123FMT "%a, %d %b %Y %H:%M:%S GMT"
typedef struct MIME_TYPE
{
const char *suffix;
const char *type;
} MIME_TYPE;
static const MIME_TYPE MIMES[] = {
{NULL, "text/plain; charset=UTF-8"}, // default type
{".html", "text/html; charset=UTF-8"},
{".htm", "text/html; charset=UTF-8"},
{".xhtml", "application/xhtml+xml; charset=UTF-8"},
{".xht", "application/xhtml+xml; charset=UTF-8"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"},
{".png", "image/png"},
{".css", "text/css"},
{".xml", "text/xml; charset=UTF-8"},
{".xsl", "text/xml; charset=UTF-8"},
{".au", "audio/basic"},
{".wav", "audio/wav"},
{".avi", "video/x-msvideo"},
{".mov", "video/quicktime"},
{".qt", "video/quicktime"},
{".mpeg", "video/mpeg"},
{".mpe", "video/mpeg"},
{".vrml", "model/vrml"},
{".wrl", "model/vrml"},
{".midi", "audio/midi"},
{".mid", "audio/midi"},
{".mp3", "audio/mpeg"},
{".ogg", "application/ogg"},
{".pac", "application/x-ns-proxy-autoconfig"}
};
static void send_headers(int status, char *title, char *extra_header, char *mime_type, off_t length, time_t mod);
static void send_error(int status, char *title, char *extra_header, char *text);
static char* get_mime_type(char* name);
static int hexit(char c);
static void strdecode(char* to, char* from);
static void strencode(char* to, size_t tosize, const char* from);
static void file_details(char* dir, char* name);
/* note:该HTT