libevent源码分析:http-server例子
http-server例子是libevent提供的一个简单web服务器,实现了对静态网页的处理功能。
/*
* gcc -g -o http-server http-server.c -levent
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h> #include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/keyvalq_struct.h> #include <netinet/in.h>
#include <arpa/inet.h> char uri_root[]; static const struct table_entry {
const char *extension;
const char *content_type;
} content_type_table[] = {
{ "txt", "text/plain" },
{ "c", "text/plain" },
{ "h", "text/plain" },
{ "html", "text/html" },
{ "htm", "text/html" },
{ "css", "text/css" },
{ "gif", "image/gif" },
{ "jpg", "image/jpg" },
{ "jpeg", "image/jpeg" },
{ "png", "image/png" },
{ "pdf", "application/pdf" },
{ "ps", "application/postscript" },
{ NULL, NULL },
}; /* Try to guess a good content-type for 'path' */
const char* guess_content_type(const char *path)
{
const char *last_period, *extension;
const struct table_entry *ent;
last_period = strrchr(path, '.');
if (!last_period || strchr(last_period, '/'))
{
goto not_found;
} extension = last_period + ;
for (ent = &content_type_table[]; ent->extension; ++ent)
{
if (!evutil_ascii_strcasecmp(ent->extension, extension))
{
return ent->content_type;
}
} not_found:
return "application/misc";
} /* Callbase used for the /dump URI, and for every non-get request:
** dumps all information to stdout and gives base a trivial 200 ok */
void dump_request_cb(struct evhttp_request *req, void *arg)
{
const char *cmdtype;
struct evkeyvalq *headers;
struct evkeyval *header;
struct evbuffer *buf; switch (evhttp_request_get_command(req))
{
case EVHTTP_REQ_GET:
cmdtype = "GET";
break;
case EVHTTP_REQ_POST:
cmdtype = "POST";
break;
case EVHTTP_REQ_HEAD:
cmdtype = "HEAD";
break;
case EVHTTP_REQ_PUT:
cmdtype = "PUT";
break;
case EVHTTP_REQ_DELETE:
cmdtype = "DELETE";
break;
case EVHTTP_REQ_OPTIONS:
cmdtype = "OPTIONS";
break;
case EVHTTP_REQ_TRACE:
cmdtype = "TRACE";
break;
case EVHTTP_REQ_CONNECT:
break;
case EVHTTP_REQ_PATCH:
cmdtype = "PATCH";
break;
default:
cmdtype = "unknown";
break;
} printf("Received a %s request for %s\nHeader:\n", cmdtype, evhttp_request_get_uri(req)); headers = evhttp_request_get_input_headers(req);
for (header = headers->tqh_first; header; header = header->next.tqe_next)
{
printf(" %s: %s\n", header->key, header->value);
} buf = evhttp_request_get_input_buffer(req);
puts("Input data: <<<<");
while (evbuffer_get_length(buf))
{
int n;
char cbuf[];
n = evbuffer_remove(buf, cbuf, sizeof(cbuf));
if (n > )
{
(void)fwrite(cbuf, , n, stdout);
}
}
puts(">>>"); evhttp_send_reply(req, , "ok", NULL);
} /* This callback gets invoked when we get and http request than doesn't match
* any other callback. Like any evhttp server callback, it has a simple job:
* it must eventually call evhttp_send_error() or evhttp_send_reply().
*/
void send_document_cb(struct evhttp_request *req, void *arg)
{
struct evbuffer *evb = NULL;
const char *docroot = arg;
const char *uri = evhttp_request_get_uri(req);
struct evhttp_uri *decoded = NULL;
const char *path;
char *decoded_path;
char *whole_path = NULL;
size_t len;
int fd = -;
struct stat st; if (evhttp_request_get_command(req) != EVHTTP_REQ_GET)
{
dump_request_cb(req, arg);
return;
} printf("Got a GET request for <%s>\n", uri); /* Decode the URI */
decoded = evhttp_uri_parse(uri);
if (!decoded)
{
printf("It's not a good URI, Sneding BADREQUEST\n");
evhttp_send_error(req, HTTP_BADREQUEST, );
return;
} /* Let's see what path the user asked for. */
path = evhttp_uri_get_path(decoded);
if (!path)
{
path = "/";
} /* We need to decode it, to see what path the user really wanted */
decoded_path = evhttp_uridecode(path, , NULL);
if (decoded_path == NULL)
{
goto err;
} /* Don't allow any ".."'s in the path, to avoid exposing stuff outside
* of the docroot. This test is both overzealous and underzealous:
* it forbids aceptable paths like "/this/one..here", but it doesn't
* do anything to prevent symlink following. */
if (strstr(decoded_path, ".."))
{
goto err;
} len = strlen(decoded_path) + strlen(docroot) + ;
if (!(whole_path = malloc(len)))
{
perror("malloc");
goto err;
}
evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path); if (stat(whole_path, &st) < )
{
goto err;
} /* This holds the content we're sending */
evb = evbuffer_new(); if (S_ISDIR(st.st_mode))
{
/* If it's a directory, read the comments and make a little index page */
DIR *d;
struct dirent *ent;
const char *trailing_slash = ""; if (!strlen(path) || path[strlen(path) - ] != '/')
{
trailing_slash = "/";
} if (!(d = opendir(whole_path)))
{
goto err;
} evbuffer_add_printf(evb,
"<!DOCTYPE html>\n"
"<html>\n "
" <head>\n"
" <meta charset='utf-8'>\n"
" <title>%s</title>\n"
" <base href='%s%s'>\n"
" </head>\n"
" <body>\n"
" <h1>%s</h1>\n"
" <ul>\n",
decoded_path, /* xxx html-escape this. */
path, /* xxx html-escape this? */
trailing_slash,
decoded_path /* xx html-escape this */
); while ((ent = readdir(d)))
{
const char *name = ent->d_name;
evbuffer_add_printf(evb,
" <li><a href=\"%s\">%s</a>\n", name, name);
} evbuffer_add_printf(evb, "</ul></body></html>\n");
closedir(d);
evhttp_add_header(evhttp_request_get_output_headers(req),
"Content-Type", "text/html");
}
else
{
/* Otherwise it's a file; and it to the buffer to get send via sendfile */
const char *type = guess_content_type(decoded_path);
if ((fd = open(whole_path, O_RDONLY)) < )
{
perror("open");
goto err;
} if (fstat(fd, &st) < )
{
/* Make sure the length still matches, now that we opened the file :/ */
perror("fstat");
goto err;
}
evhttp_add_header(evhttp_request_get_output_headers(req),
"Content-Type", type);
evbuffer_add_file(evb, fd, , st.st_size);
} evhttp_send_reply(req, , "OK", evb);
goto done; err:
evhttp_send_error(req, , "Document was not found");
if (fd >= )
{
close(fd);
} done:
if (decoded)
{
evhttp_uri_free(decoded);
} if (decoded_path)
{
free(decoded_path);
} if (whole_path)
{
free(whole_path);
} if (evb)
{
evbuffer_free(evb);
}
} void syntax(void)
{
fprintf(stdout, "Syntax: http-server <docroot>\n");
} int main(int argc, char **argv)
{
struct event_base *base;
struct evhttp *http;
struct evhttp_bound_socket *handle;
int port = ; if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
{
printf("signal error, errno[%d], error[%s]", errno, strerror(errno));
return -;
} if (argc < )
{
syntax();
return -;
} base = event_base_new();
if (!base)
{
printf("Couldn't create an event_base:exiting\n");
return -;
} /* Create a new http oject to handle request */
http = evhttp_new(base);
if (!http)
{
printf("Couldn't create evhttp.Exiting\n");
return -;
} /* The /dump URI will dump all requests to stdout and say 200 ok */
evhttp_set_cb(http, "/dump", dump_request_cb, NULL); /* We want to accept arbitrary requests, so we need to set a "generic" cb
* We can also add callbacks for specific paths */
evhttp_set_gencb(http, send_document_cb, argv[]); /* Now we teel the evhttp what port to listen on */
handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
if (!handle)
{
printf("Couldn't bind to port[%d], exiting\n", port);
return -;
} {
/* Extract and display the address we're listening on. */
struct sockaddr_storage ss;
evutil_socket_t fd;
ev_socklen_t socklen = sizeof(ss);
char addrbuf[];
void *inaddr;
const char *addr;
int got_port = -;
fd = evhttp_bound_socket_get_fd(handle);
memset(&ss, , sizeof(ss));
if (getsockname(fd, (struct sockaddr *)&ss, &socklen))
{
perror("getsockname() failed");
return -;
} if (ss.ss_family == AF_INET)
{
got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
}
else if (ss.ss_family == AF_INET6)
{
got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
}
else
{
printf("Weird address family\n");
return ;
} addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf, sizeof(addrbuf));
if (addr)
{
printf("Listening on %s:%d\n", addr, got_port);
evutil_snprintf(uri_root, sizeof(uri_root), "http://%s:%d", addr, got_port);
}
else
{
printf("evutil_inet_ntop failed\n");
return -;
}
}
event_base_dispatch(base); return ;
}
下面就通过分析这个例子来理解evhttp对象的使用与实现:
1、首先介绍一个这段代码里面的几个函数及其作用:
1)guess_content_type:传入请求的路径,返回文件类型(根据请求资源的后缀名返回响应的MIME类型)
2)dump_requese_cb:这个函数是当uri为/dump时的回调,操作是打印全部的请求信息。
3)send_document_cb:这个函数是通用uri的回调函数,就是将请求的资源发送给客户端(浏览器)。
4)syntax:打印用法的函数
5)main:主函数
2、调用event_base_new函数得到一个event base对象。
3、调用evhttp_new函数得到一个evhttp对象。
4、调用evhttp_set_cb、evthttp_set_gencb设置回调函数和通用回调函数。
5、调用evhttp_bind_socket_with_handle函数设置监听端口。
6、打印监听端口信息。
7、调用event_base_dispatch进入事件循环。
这里使用了一个新的类evhttp,这个也是对基本函数更高层次的封装,方便编写http相关的程序,关于这个类会在后面详细的分析,这里略过。
到这里就分析完http-server了,可以发现使用libevent提供的函数来编写一个http-server服务器是多么的简单。
libevent源码分析:http-server例子的更多相关文章
- libevent源码分析:hello-world例子
hello-world是libevent自带的一个例子,这个例子的作用是启动后监听一个端口,对于所有通过这个端口连接上服务器的程序发送一段字符:hello-world,然后关闭连接. /* * gcc ...
- libevent源码分析:signal-test例子
signal-test是libevent自带的一个例子,展示了libevent对于信号事件的处理方法. #include <sys/types.h> #include <event2 ...
- libevent源码分析:time-test例子
time-test例子是libevent自带的一个例子,通过libevent提供的定时事件来实现,间隔固定时间打印的功能. /* * gcc -g -o time-test time-test.c - ...
- 【转】libevent源码分析
libevent源码分析 转自:http://www.cnblogs.com/hustcat/archive/2010/08/31/1814022.html 这两天没事,看了一下Memcached和l ...
- Libevent源码分析 (1) hello-world
Libevent源码分析 (1) hello-world ⑨月份接触了久闻大名的libevent,当时想读读源码,可是由于事情比较多一直没有时间,现在手头的东西基本告一段落了,我准备读读libeven ...
- Apache Kafka源码分析 – Broker Server
1. Kafka.scala 在Kafka的main入口中startup KafkaServerStartable, 而KafkaServerStartable这是对KafkaServer的封装 1: ...
- Kafka源码分析(三) - Server端 - 消息存储
系列文章目录 https://zhuanlan.zhihu.com/p/367683572 目录 系列文章目录 一. 业务模型 1.1 概念梳理 1.2 文件分析 1.2.1 数据目录 1.2.2 . ...
- kafka源码分析之一server启动分析
0. 关键概念 关键概念 Concepts Function Topic 用于划分Message的逻辑概念,一个Topic可以分布在多个Broker上. Partition 是Kafka中横向扩展和一 ...
- Libevent源码分析系列【转】
转自:https://www.cnblogs.com/zxiner/p/6919021.html 1.使用libevent库 源码那么多,该怎么分析从哪分析呢?一个好的方法就是先用起来,会用了 ...
随机推荐
- 分析器错误消息: 未能加载类型“Automation.Web.MvcApplication”。
常见原因1 : 可能是自己手动修改了项目 ==>属性==>生成的输出路径 ,导致版本不兼容 常见员因2 : Global的 命名空间 与 项目的命名空间 不一致 常见原因3 : 查看 ...
- C# 测试服务器连接 Ping
.aspx页: 一个textbox(txtIP)输入服务器地址,一个button(Btn_ok)点击测试,一个listbox(lboxContent)显示测试信息 .aspx.cs页: using S ...
- LeetCode Verify Preorder Sequence in Binary Search Tree
原题链接在这里:https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/ 题目: Given an a ...
- java8 学习系列--NIO学习笔记
近期有点时间,决定学习下java8相关的内容: 当然了不止java8中新增的功能点,整个JDK都需要自己研究的,不过这是个漫长的过程吧,以自己的惰性来看: 不过开发中不是有时候讲究模块化开发么,那么我 ...
- Javascript模板引擎:Hogan
hogan.js是一个开源前端模板引擎,无逻辑的设计,简单好用,性能也不错. 使用 引入hogan.js,下载链接:http://www.bootcdn.cn/hogan.js/,然后通过hogan. ...
- js 简易的分页器插件
1.自己引入jquery插件,我的demo是引入的自己本地的query <!DOCTYPE html> <html> <head> <meta charset ...
- leetcode bugfree note
463. Island Perimeterhttps://leetcode.com/problems/island-perimeter/就是逐一遍历所有的cell,用分离的cell总的的边数减去重叠的 ...
- JAVA NIO系列(二) Channel解读
Channel就是一个通道,用于传输数据,两端分别是缓冲区和实体(文件或者套接字),通道的特点(也是NIO的特点):通道中的数据总是要先读到一个缓冲区,或者总是要从一个缓冲区中读入. Channel的 ...
- 反编译android的apk
将要反编译的APK后缀名改为.rar或 .zip,并解压 得到其中的classes.dex文件(它就是java文件编译再通过dx工具打包而成的),将获取到的classes.dex放到之前解压出来的 ...
- java代码打包成jar以及转换为exe
教你如何把java代码打包成jar文件以及转换为exe可执行文件 1.背景: 学习java时,教材中关于如题问题,只有一小节说明,而且要自己写麻烦的配置文件,最终结果却只能转换为jar文件.实在是心有 ...