tinyhttpd的使用与源码分析

  本着学习的目的下载到了tinnyhttpd的源码,首先阅读了一下readme文档,以下是tinnyhttpd的readme的大概意思:
  1. 这个软件是 J. David Blackstone1999年写的,根据从http://www.gnu.org/获得的
  2. GNU通用公共许可证被允许修改和分发。
  3. 如果你使用这个软件或者测试这个代码,我将会非常感激,并想知道关于这件事情,
  4. 可以联系我jdavidb@sourceforge.net
  5. 这个软件并不能保证生产质量。没有提供任何形式的保证,甚至是某种目的的
  6. 默认的保证。如果你在你的计算机系统中使用这个软件造成了损坏,我不会负责的。
  7. 我写这个web服务器是在1999年的时候因为我的网络课程的一次作业。
  8. 我们被告知在一个最小型的服务器提供网页服务,以及告诉我们如果我们做了额
  9. 外的任务将会得到额外的学分。Perl向我展示了一些UNIX功能(学习了sockers以及fork),
  10. 同时O'Reilly的关于UNIX系统与CGIPerl写一个web客户端的书籍让我意识到我可以轻易
  11. 的制作一个web服务器来提供CGI功能。
  12. 现在如果你是一个apache核心团体的成员,你或许一点儿印象都没有,但是我的教授被搞定了。
  13. 测试color.cgi脚本例程然后输入"chartreuse.",让我看起来比较聪明一些。
  14. Apache不会,但是我希望这个程序对于那些对http/socket编程感兴趣的人是一个好的教学工具,
  15. 就像UNIX系统调用一样。(这里有关于使用pipe,环境变量,forks等等)
  16. 一件最后的事情:如果你看到了我的web服务器或者(你是心不在焉的吗?)使用它,我都会非常高兴的知道这件事。
  17. 请给我发email。我或许不会真正的去更新程序,但是我想知道知道我帮助你学习了一些东西;
  18. 快乐的黑客
  19. J. David Blackstone

    其源代码网上资源很多,可以搜一下就可以找到下载链接,在拿到代码执行Makefile的时候可能会遇到-lsocket找不到,可以在Makefile里面讲这个库的引用直接删去即可。编译通过之后,将htdoc下面的color.cgi添加一个可执行权限,然后执行httpd可以拿到一个端口号,然后可以使用浏览器通过输入ip进行访问,例如我的访问方式如下:10.95.4.211:12345   其中12345代表端口号。

    一共500多行代码,其实在技巧上并没有多少让人眼前一亮的感觉,不如阅读cJSON源码的时候那种时刻都会感觉到闪光点存在。但是从整体上来看在结构上有许多可以去学习和借鉴的地方:
    服务端socket建立之后,便阻塞等待客户端来连接,每来一个连接就创建一个线程去处理这个连接。处理流程上,根据收到的请求方式来决定给客户端反馈的方式。有直接返回请求的文件,有执行cgi脚本产生的内容。其中解析数据的时候需要一些http协议相关的协议知识,另外就是在执行cgi的时候通过管道的重映射方式,将程序的输入和输出与cgi脚本的输入输出联系起来。对于整个网页的访问流程会有一些学习,比如说,发起一个网页访问的时候,其实就是向web服务器发起一个资源请求,web服务器接收到这个请求之后会根据携带的目录或者资源标识去找到请求的资源并发送到客户端。执行cgi脚本,其实也是将cgi脚本处理后所输出的内容发送给了客户端。
    对于cgi脚本没有接触过,html文本也就有一点点儿概念,所以就没有自己再做一下改编版的例程了。读一下理解了原理也是很好的。
    在读源码的时候有一些注释就顺道加上了,还有一些根据英文内容做了一下自己的理解。源码如下:
tinnyhttpd.c
  1. /* 程序是在 Sparc Solaris 2.6.上编译的
  2. * 如果要在Linux上编译:
  3. * 1) 注释 #include <pthread.h> line.
  4. * 2) 注释掉定义的newthread变量.
  5. * 3) 注释掉pthread_create().
  6. * 4) 取消注释accept_request().
  7. * 5) 从Makefile移除 -lsocket
  8. */
  9. #include <stdio.h>
  10. #include <sys/socket.h>
  11. #include <sys/types.h>
  12. #include <netinet/in.h>
  13. #include <arpa/inet.h>
  14. #include <unistd.h>
  15. #include <ctype.h>
  16. #include <strings.h>
  17. #include <string.h>
  18. #include <sys/stat.h>
  19. #include <pthread.h>
  20. #include <sys/wait.h>
  21. #include <stdlib.h>
  22. #define ISspace(x) isspace((int)(x))
  23. #define SERVER_STRING "Server: jdbhttpd/0.1.0\r\n"
  24. void accept_request(int);
  25. void bad_request(int);
  26. void cat(int, FILE *);
  27. void cannot_execute(int);
  28. void error_die(const char *);
  29. void execute_cgi(int, const char *, const char *, const char *);
  30. int get_line(int, char *, int);
  31. void headers(int, const char *);
  32. void not_found(int);
  33. void serve_file(int, const char *);
  34. int startup(u_short *);
  35. void unimplemented(int);
  36. /**********************************************************************/
  37. /* 一个请求是的accept调用返回。合适的处理这个请求
  38. * 参数: 连接到服务器的socket
  39. /**********************************************************************/
  40. void accept_request(int client)
  41. {
  42. char buf[1024];
  43. int numchars;
  44. char method[255];
  45. char url[255];
  46. char path[512];
  47. size_t i, j;
  48. struct stat st;
  49. int cgi = 0; /* 为真时,服务器确定是一个cgi程序*/
  50. char *query_string = NULL;
  51. //获取一行
  52. numchars = get_line(client, buf, sizeof(buf));
  53. i = 0; j = 0;//将读到的一行内容的行为备份到method中
  54. while (!ISspace(buf[j]) && (i < sizeof(method) - 1))
  55. {//读取直到空行
  56. method[i] = buf[j];
  57. i++; j++;
  58. }
  59. method[i] = '\0';//结束字符
  60. //如果不"GET"或者"POST"请求,那么就不做处理
  61. if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
  62. {
  63. unimplemented(client);
  64. return;
  65. }
  66. //如果是post请求,那么置一个标志位
  67. if (strcasecmp(method, "POST") == 0)
  68. cgi = 1;
  69. //在这里获取url
  70. i = 0;
  71. while (ISspace(buf[j]) && (j < sizeof(buf)))
  72. j++;
  73. while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)))
  74. {
  75. url[i] = buf[j];
  76. i++; j++;
  77. }
  78. url[i] = '\0';
  79. if (strcasecmp(method, "GET") == 0)
  80. {
  81. query_string = url;
  82. while ((*query_string != '?') && (*query_string != '\0'))
  83. query_string++;
  84. if (*query_string == '?')
  85. {
  86. cgi = 1;
  87. *query_string = '\0';
  88. query_string++;
  89. }
  90. }
  91. //拼接资源目录
  92. sprintf(path, "htdocs%s", url);
  93. if (path[strlen(path) - 1] == '/')
  94. strcat(path, "index.html");//如果没有url目录那么就是访问主页
  95. if (stat(path, &st) == -1)
  96. {
  97. while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
  98. numchars = get_line(client, buf, sizeof(buf));
  99. not_found(client);
  100. }
  101. else
  102. {
  103. if ((st.st_mode & S_IFMT) == S_IFDIR)
  104. strcat(path, "/index.html");//拼接目录
  105. if ((st.st_mode & S_IXUSR) ||
  106. (st.st_mode & S_IXGRP) ||
  107. (st.st_mode & S_IXOTH) )
  108. cgi = 1;
  109. if (!cgi)//根据cgi的标志位选择如何进行返回
  110. serve_file(client, path);
  111. else
  112. execute_cgi(client, path, method, query_string);
  113. }
  114. close(client);
  115. }
  116. /**********************************************************************/
  117. /* 通知客户端请求造成了一个错误
  118. /**********************************************************************/
  119. void bad_request(int client)
  120. {
  121. char buf[1024];
  122. //拼接字符串发送出去
  123. sprintf(buf, "HTTP/1.0 400 BAD REQUEST\r\n");
  124. send(client, buf, sizeof(buf), 0);
  125. sprintf(buf, "Content-type: text/html\r\n");
  126. send(client, buf, sizeof(buf), 0);
  127. sprintf(buf, "\r\n");
  128. send(client, buf, sizeof(buf), 0);
  129. sprintf(buf, "<P>Your browser sent a bad request, ");
  130. send(client, buf, sizeof(buf), 0);
  131. sprintf(buf, "such as a POST without a Content-Length.\r\n");
  132. send(client, buf, sizeof(buf), 0);
  133. }
  134. /**********************************************************************/
  135. /* Put the entire contents of a file out on a socket. This function
  136. * is named after the UNIX "cat" command, because it might have been
  137. * easier just to do something like pipe, fork, and exec("cat").
  138. * Parameters: the client socket descriptor
  139. * FILE pointer for the file to cat */
  140. /**********************************************************************/
  141. /**********************************************************************/
  142. /* 通过sockt将整个文件发送出去. 这个命令一个nuix的cat命令命名,因为它
  143. * 或许比较容易的去做管道所做的事情,比如fork 然后执行cat
  144. /**********************************************************************/
  145. void cat(int client, FILE *resource)
  146. {
  147. char buf[1024];
  148. fgets(buf, sizeof(buf), resource);
  149. while (!feof(resource))
  150. {//将源文件发送出去
  151. send(client, buf, strlen(buf), 0);
  152. fgets(buf, sizeof(buf), resource);
  153. }
  154. }
  155. /**********************************************************************/
  156. /* 通知客户端cgi文件无法被执行
  157. /**********************************************************************/
  158. void cannot_execute(int client)
  159. {
  160. char buf[1024];
  161. //组装字符串发出去
  162. sprintf(buf, "HTTP/1.0 500 Internal Server Error\r\n");
  163. send(client, buf, strlen(buf), 0);
  164. sprintf(buf, "Content-type: text/html\r\n");
  165. send(client, buf, strlen(buf), 0);
  166. sprintf(buf, "\r\n");
  167. send(client, buf, strlen(buf), 0);
  168. sprintf(buf, "<P>Error prohibited CGI execution.\r\n");
  169. send(client, buf, strlen(buf), 0);
  170. }
  171. /**********************************************************************/
  172. /* 使用perror()打印错误信息 (适用于系统错误; 依赖于代表系统调用错误的errorno)
  173. * 使程序退出执行 */
  174. /**********************************************************************/
  175. void error_die(const char *sc)
  176. {
  177. perror(sc);
  178. exit(1);
  179. }
  180. /**********************************************************************/
  181. /* 执行一个cgi脚本,需要恰当的设置环境变量
  182. /**********************************************************************/
  183. void execute_cgi(int client, const char *path,
  184. const char *method, const char *query_string)
  185. {
  186. char buf[1024];
  187. int cgi_output[2];
  188. int cgi_input[2];
  189. pid_t pid;
  190. int status;
  191. int i;
  192. char c;
  193. int numchars = 1;
  194. int content_length = -1;
  195. buf[0] = 'A'; buf[1] = '\0';
  196. if (strcasecmp(method, "GET") == 0)
  197. while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
  198. numchars = get_line(client, buf, sizeof(buf));
  199. else /* POST */
  200. {//获取执行cgi相关的信息
  201. numchars = get_line(client, buf, sizeof(buf));
  202. while ((numchars > 0) && strcmp("\n", buf))
  203. {
  204. buf[15] = '\0';
  205. if (strcasecmp(buf, "Content-Length:") == 0)
  206. content_length = atoi(&(buf[16]));
  207. numchars = get_line(client, buf, sizeof(buf));
  208. }
  209. if (content_length == -1) {
  210. bad_request(client);
  211. return;
  212. }
  213. }
  214. sprintf(buf, "HTTP/1.0 200 OK\r\n");
  215. send(client, buf, strlen(buf), 0);
  216. if (pipe(cgi_output) < 0) {
  217. cannot_execute(client);
  218. return;
  219. }
  220. if (pipe(cgi_input) < 0) {
  221. cannot_execute(client);
  222. return;
  223. }
  224. if ( (pid = fork()) < 0 ) {
  225. cannot_execute(client);
  226. return;
  227. }
  228. if (pid == 0) /* child: CGI script */
  229. {
  230. char meth_env[255];
  231. char query_env[255];
  232. char length_env[255];
  233. //子进程中设置环境变量,重映射标准输入输出为打开的管道
  234. dup2(cgi_output[1], 1);
  235. dup2(cgi_input[0], 0);
  236. close(cgi_output[0]);
  237. close(cgi_input[1]);
  238. sprintf(meth_env, "REQUEST_METHOD=%s", method);
  239. putenv(meth_env);
  240. if (strcasecmp(method, "GET") == 0) {
  241. sprintf(query_env, "QUERY_STRING=%s", query_string);
  242. putenv(query_env);
  243. }
  244. else { /* POST */
  245. sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
  246. putenv(length_env);
  247. }
  248. execl(path, path, NULL);//设置好了环境变量之后就执行cgi脚本
  249. exit(0);
  250. }
  251. else
  252. { /* parent */
  253. close(cgi_output[1]);
  254. close(cgi_input[0]);
  255. if (strcasecmp(method, "POST") == 0)
  256. for (i = 0; i < content_length; i++)
  257. {//将接受到的参数写入管道其实就是为了给cgi脚本传参数
  258. recv(client, &c, 1, 0);
  259. write(cgi_input[1], &c, 1);
  260. }
  261. while (read(cgi_output[0], &c, 1) > 0)
  262. send(client, &c, 1, 0);//接受cgi脚本的输出
  263. close(cgi_output[0]);
  264. close(cgi_input[1]);
  265. waitpid(pid, &status, 0);
  266. }
  267. }
  268. /**********************************************************************/
  269. /* 从socket中获取一行, 不论这一行是以一个换行符\n还是\r或者是\r\n。遇到'\0'
  270. * 时结束读取内容。如果在完成读取之前没有换行提示,那么这个字符串就以'\0'结尾
  271. * 如果上述的三个行结束标记被读取到,那么这个字符串的最后一个字符是回车换行符
  272. * 字符串会以'\0'结尾
  273. * 参数: socket 套接字
  274. * buf 保存信息的缓存区
  275. * size 缓冲区的大小
  276. * 返回: 保存的字节数,不含'\0'
  277. /**********************************************************************/
  278. int get_line(int sock, char *buf, int size)
  279. {
  280. int i = 0;
  281. char c = '\0';
  282. int n;
  283. //寻找'\n'直到超出缓冲区大小
  284. while ((i < size - 1) && (c != '\n'))
  285. {//接收一个字符
  286. n = recv(sock, &c, 1, 0);
  287. // printf("%02X\n", c);
  288. if (n > 0)
  289. {
  290. if (c == '\r')
  291. {//处理\r\n的情况,再取一个直接进行判断一次
  292. n = recv(sock, &c, 1, MSG_PEEK);
  293. /* DEBUG printf("%02X\n", c); */
  294. if ((n > 0) && (c == '\n'))
  295. recv(sock, &c, 1, 0);//如果是那么就把这个字符读出来
  296. else
  297. c = '\n';//否则就将\r变成\n
  298. }
  299. buf[i] = c;//放到缓存中
  300. i++;
  301. }
  302. else
  303. c = '\n';//没有接收到数据,那么就认为接收到'\n'触发退出条件
  304. }
  305. buf[i] = '\0';//将'\0'填充到末尾
  306. return(i);//返回字节数
  307. }
  308. /**********************************************************************/
  309. /* Return the informational HTTP headers about a file. */
  310. /* Parameters: the socket to print the headers on
  311. * the name of the file */
  312. /**********************************************************************/
  313. /**********************************************************************/
  314. /* 返回一个关于文件信息的HTTP头. */
  315. /**********************************************************************/
  316. void headers(int client, const char *filename)
  317. {
  318. char buf[1024];
  319. (void)filename; /* could use filename to determine file type */
  320. //组装字符串发送出去
  321. strcpy(buf, "HTTP/1.0 200 OK\r\n");
  322. send(client, buf, strlen(buf), 0);
  323. strcpy(buf, SERVER_STRING);
  324. send(client, buf, strlen(buf), 0);
  325. sprintf(buf, "Content-Type: text/html\r\n");
  326. send(client, buf, strlen(buf), 0);
  327. strcpy(buf, "\r\n");
  328. send(client, buf, strlen(buf), 0);
  329. }
  330. /**********************************************************************/
  331. /* 给出一个404错误 */
  332. /**********************************************************************/
  333. void not_found(int client)
  334. {
  335. char buf[1024];
  336. //组装发送
  337. sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n");
  338. send(client, buf, strlen(buf), 0);
  339. sprintf(buf, SERVER_STRING);
  340. send(client, buf, strlen(buf), 0);
  341. sprintf(buf, "Content-Type: text/html\r\n");
  342. send(client, buf, strlen(buf), 0);
  343. sprintf(buf, "\r\n");
  344. send(client, buf, strlen(buf), 0);
  345. sprintf(buf, "<HTML><TITLE>Not Found</TITLE>\r\n");
  346. send(client, buf, strlen(buf), 0);
  347. sprintf(buf, "<BODY><P>The server could not fulfill\r\n");
  348. send(client, buf, strlen(buf), 0);
  349. sprintf(buf, "your request because the resource specified\r\n");
  350. send(client, buf, strlen(buf), 0);
  351. sprintf(buf, "is unavailable or nonexistent.\r\n");
  352. send(client, buf, strlen(buf), 0);
  353. sprintf(buf, "</BODY></HTML>\r\n");
  354. send(client, buf, strlen(buf), 0);
  355. }
  356. /**********************************************************************/
  357. /* 发送一个规则文件到客户端. 使用headers, 上报错误如果发生错误
  358. /**********************************************************************/
  359. void serve_file(int client, const char *filename)
  360. {
  361. FILE *resource = NULL;
  362. int numchars = 1;
  363. char buf[1024];
  364. buf[0] = 'A'; buf[1] = '\0';
  365. while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
  366. numchars = get_line(client, buf, sizeof(buf));
  367. //打开文件
  368. resource = fopen(filename, "r");
  369. if (resource == NULL)
  370. not_found(client);
  371. else
  372. {//组织头部
  373. headers(client, filename);
  374. cat(client, resource);//传输文件到客户端
  375. }
  376. fclose(resource);
  377. }
  378. /**********************************************************************
  379. * 这个函数在一个指定的端口上启动一个监听web连接的处理。如果*port==0,那么
  380. * 就动态的申请一个端口号然后修改*port的值
  381. * 参数: 指向待连接端口号值的指针
  382. * 返回: socket
  383. **********************************************************************/
  384. int startup(u_short *port)
  385. {
  386. int httpd = 0;
  387. struct sockaddr_in name;
  388. //建立socket
  389. httpd = socket(PF_INET, SOCK_STREAM, 0);
  390. if (httpd == -1)
  391. error_die("socket");
  392. memset(&name, 0, sizeof(name));
  393. //为绑定做准备后进行绑定
  394. name.sin_family = AF_INET;
  395. name.sin_port = htons(*port);
  396. name.sin_addr.s_addr = htonl(INADDR_ANY);
  397. if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)
  398. error_die("bind");
  399. if (*port == 0) /* if dynamically allocating a port */
  400. {//如果port传入的原值为0 ,那么动态的端口号进行回填
  401. int namelen = sizeof(name);
  402. //用于获取一个套接字的名字。它用于一个已捆绑或已连接套接字s,本地地址将被返回
  403. if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1)
  404. error_die("getsockname");
  405. *port = ntohs(name.sin_port);//回填
  406. }
  407. if (listen(httpd, 5) < 0)
  408. error_die("listen");
  409. return(httpd);
  410. }
  411. /**********************************************************************/
  412. /* 通知客户端,请求方法还不支持
  413. * 参数: 客户端socket */
  414. /**********************************************************************/
  415. void unimplemented(int client)
  416. {
  417. char buf[1024];
  418. //组装一个xml说明文件进行返回到client
  419. sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n");
  420. send(client, buf, strlen(buf), 0);
  421. sprintf(buf, SERVER_STRING);
  422. send(client, buf, strlen(buf), 0);
  423. sprintf(buf, "Content-Type: text/html\r\n");
  424. send(client, buf, strlen(buf), 0);
  425. sprintf(buf, "\r\n");
  426. send(client, buf, strlen(buf), 0);
  427. sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n");
  428. send(client, buf, strlen(buf), 0);
  429. sprintf(buf, "</TITLE></HEAD>\r\n");
  430. send(client, buf, strlen(buf), 0);
  431. sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n");
  432. send(client, buf, strlen(buf), 0);
  433. sprintf(buf, "</BODY></HTML>\r\n");
  434. send(client, buf, strlen(buf), 0);
  435. }
  436. /**********************************************************************/
  437. int main(void)
  438. {
  439. int server_sock = -1;
  440. u_short port = 0;
  441. int client_sock = -1;
  442. struct sockaddr_in client_name;
  443. int client_name_len = sizeof(client_name);
  444. pthread_t newthread;
  445. //打开服务器socket等待连接
  446. server_sock = startup(&port);
  447. printf("httpd running on port %d\n", port);
  448. while (1)
  449. {
  450. //等待连接
  451. client_sock = accept(server_sock, (struct sockaddr *)&client_name, &client_name_len);
  452. if (client_sock == -1)
  453. error_die("accept");//如果连接失败那么就打印下错误然后退出
  454. //连接成功则为这次连接创建一个线程进行处理
  455. if (pthread_create(&newthread , NULL, accept_request, client_sock) != 0)
  456. perror("pthread_create");
  457. }
  458. close(server_sock);
  459. return(0);
  460. }







附件列表

     

    posted on 2017-08-28 11:31  cfzhang  阅读(694)  评论(0编辑  收藏  举报

    导航