httpstub.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /* A simple http server for performance test.
  2. Copyright (C) 2013 Sun, Junyi <[email protected]> */
  3. #include <sys/time.h>
  4. #include <sys/types.h>
  5. #include <ctype.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <stdarg.h>
  9. #include <string.h>
  10. #include <getopt.h>
  11. #include <unistd.h>
  12. #include <sys/socket.h>
  13. #include <sys/stat.h>
  14. #include <sys/mman.h>
  15. #include <sys/wait.h>
  16. #include <sys/sendfile.h>
  17. #include <netinet/in.h>
  18. #include <arpa/inet.h>
  19. #include <netinet/tcp.h>
  20. #include <net/if.h>
  21. #include <fcntl.h>
  22. #include <time.h>
  23. #include <sys/ioctl.h>
  24. #include <errno.h>
  25. #include <assert.h>
  26. #include <signal.h>
  27. #include <sys/epoll.h>
  28. #include <pthread.h>
  29. #include <errno.h>
  30. #define MAX_EPOLL_FD 4096
  31. #define MAX_BUF_SIZE (1<<20)
  32. #define WORKER_COUNT 2
  33. int ep_fd[WORKER_COUNT],listen_fd;
  34. int g_delay;
  35. int g_shutdown_flag;
  36. int g_quiet;
  37. FILE *g_logger;
  38. int g_pipe[WORKER_COUNT][2];
  39. enum version_t {
  40. HTTP_1_0 = 10,
  41. HTTP_1_1 = 11
  42. };
  43. struct io_data_t {
  44. int fd;
  45. struct sockaddr_in addr;
  46. char *in_buf;
  47. char *out_buf;
  48. int in_buf_cur;
  49. int out_buf_cur;
  50. int out_buf_total;
  51. int keep_alive;
  52. enum version_t version;
  53. };
  54. struct slice_t {
  55. char *begin;
  56. size_t size;
  57. };
  58. struct thread_data_t{
  59. struct slice_t data_from_file;
  60. int myep_fd;
  61. int mypipe_fd;
  62. };
  63. static void *handle_io_loop(void *param);
  64. static void httpstub_log(const char *fmt, ...);
  65. static void setnonblocking(int fd)
  66. {
  67. int opts;
  68. opts = fcntl(fd, F_GETFL);
  69. if (opts < 0) {
  70. fprintf(stderr, "fcntl failed\n");
  71. return;
  72. }
  73. opts = opts | O_NONBLOCK;
  74. if (fcntl(fd, F_SETFL, opts) < 0) {
  75. fprintf(stderr, "fcntl failed\n");
  76. return;
  77. }
  78. return;
  79. }
  80. static void usage()
  81. {
  82. printf("usage: httpstub -p <port> -f <data file> -d <delay (ms)> [-q quiet] \n");
  83. }
  84. static struct slice_t load_data(char *fname)
  85. {
  86. struct stat buf;
  87. char *bin = NULL;
  88. FILE *fptr;
  89. int ret;
  90. struct slice_t result;
  91. ret = stat(fname, &buf);
  92. if (ret < 0) {
  93. printf("open %s failed\n", fname);
  94. perror("");
  95. exit(1);
  96. }
  97. printf(">> size of %s is %d\n", fname, (int)buf.st_size);
  98. if (buf.st_size <= 0) {
  99. printf("the file is empty or broken\n");
  100. exit(1);
  101. }
  102. if (buf.st_size <= 0 || buf.st_size > MAX_BUF_SIZE) {
  103. printf("file is too large\n");
  104. exit(1);
  105. }
  106. bin = (char *)malloc(sizeof(char) * buf.st_size + 1);
  107. bin[buf.st_size] = '\0';
  108. result.size = buf.st_size;
  109. result.begin = bin;
  110. fptr = fopen(fname, "rb");
  111. if(fread(bin, buf.st_size, 1, fptr)<=0){
  112. perror("failed to read file");
  113. exit(1);
  114. };
  115. fclose(fptr);
  116. return result;
  117. }
  118. static struct io_data_t * alloc_io_data(int client_fd, struct sockaddr_in *client_addr)
  119. {
  120. struct io_data_t *io_data_ptr = (struct io_data_t *)malloc(sizeof(struct io_data_t));
  121. io_data_ptr->fd = client_fd;
  122. io_data_ptr->in_buf = (char *)malloc(4096);
  123. io_data_ptr->out_buf = (char *)malloc(MAX_BUF_SIZE);
  124. io_data_ptr->in_buf_cur = 0;
  125. io_data_ptr->out_buf_cur = 0;
  126. io_data_ptr->keep_alive = 1;
  127. if (client_addr)
  128. io_data_ptr->addr = *client_addr;
  129. return io_data_ptr;
  130. }
  131. static void destroy_io_data(struct io_data_t *io_data_ptr)
  132. {
  133. if(NULL == io_data_ptr)return;
  134. if(io_data_ptr->in_buf)free(io_data_ptr->in_buf);
  135. if(io_data_ptr->out_buf)free(io_data_ptr->out_buf);
  136. io_data_ptr->in_buf = NULL;
  137. io_data_ptr->out_buf = NULL;
  138. free(io_data_ptr);
  139. }
  140. void exit_hook(int number)
  141. {
  142. close(listen_fd);
  143. g_shutdown_flag=1;
  144. printf(">> [%d]will shutdown...[%d]\n", getpid(),number);
  145. }
  146. int main(int argc, char **argv)
  147. {
  148. const char *ip_binding = "0.0.0.0";
  149. int port_listening = 8402;
  150. char *data_file=NULL;
  151. int opt;
  152. int on = 1;
  153. int client_fd=0;
  154. int worker_count=WORKER_COUNT,i;
  155. register int worker_pointer = 0;
  156. struct sockaddr_in server_addr;
  157. struct slice_t data_from_file;
  158. pthread_t tid[WORKER_COUNT];
  159. pthread_attr_t tattr[WORKER_COUNT];
  160. struct thread_data_t tdata[WORKER_COUNT];
  161. char ip_buf[256] = { 0 };
  162. struct sockaddr_in client_addr;
  163. socklen_t client_n;
  164. g_delay = 0;
  165. g_shutdown_flag = 0;
  166. if (argc == 1) {
  167. usage();
  168. return 1;
  169. }
  170. g_quiet = 0;
  171. while ((opt = getopt(argc, argv, "l:p:f:d:hq")) != -1) {
  172. switch (opt) {
  173. case 'l':
  174. ip_binding = strdup(optarg);
  175. break;
  176. case 'p':
  177. port_listening = atoi(optarg);
  178. if (port_listening == 0) {
  179. printf(">> invalid port : %s\n", optarg);
  180. exit(1);
  181. }
  182. break;
  183. case 'f':
  184. data_file = strdup(optarg);
  185. break;
  186. case 'd':
  187. g_delay = atoi(optarg);
  188. break;
  189. case 'q':
  190. g_quiet = 1;
  191. break;
  192. case 'h':
  193. usage();
  194. return 1;
  195. }
  196. }
  197. printf(">> IP listening:%s\n", ip_binding);
  198. printf(">> port: %d\n", port_listening);
  199. printf(">> data_file: %s\n", data_file);
  200. printf(">> reponse delay(MS): %d\n", g_delay);
  201. printf(">> quite:%d\n",g_quiet);
  202. if (NULL == data_file || strlen(data_file) == 0) {
  203. printf("\033[31m-data file is needed!~ \033[0m\n");
  204. usage();
  205. return 1;
  206. }
  207. g_logger = fopen("stub.log", "a");
  208. if (g_logger ==NULL) {
  209. perror("create log file stub.log failed.");
  210. exit(1);
  211. }
  212. data_from_file = load_data(data_file);
  213. signal(SIGPIPE, SIG_IGN);
  214. signal(SIGINT, exit_hook);
  215. signal(SIGKILL, exit_hook);
  216. signal(SIGQUIT, exit_hook);
  217. signal(SIGTERM, exit_hook);
  218. signal(SIGHUP, exit_hook);
  219. for(i=0;i<WORKER_COUNT;i++){
  220. if(pipe(g_pipe[i])<0){
  221. perror("failed to create pipe");
  222. exit(1);
  223. }
  224. }
  225. listen_fd = socket(AF_INET, SOCK_STREAM, 0);
  226. if (-1 == listen_fd) {
  227. perror("listen faild!");
  228. exit(-1);
  229. }
  230. setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  231. setsockopt(listen_fd, IPPROTO_TCP, TCP_NODELAY, (int[]) {1}, sizeof(int));
  232. setsockopt(listen_fd, IPPROTO_TCP, TCP_QUICKACK, (int[]) {1}, sizeof(int));
  233. memset(&server_addr, 0, sizeof(server_addr));
  234. server_addr.sin_family = AF_INET;
  235. server_addr.sin_port = htons((short)port_listening);
  236. server_addr.sin_addr.s_addr = inet_addr(ip_binding);
  237. if (-1 == bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr))) {
  238. perror("bind error");
  239. exit(-1);
  240. }
  241. if (-1 == listen(listen_fd, 32)) {
  242. perror("listen error");
  243. exit(-1);
  244. }
  245. for(i=0;i<worker_count;i++){
  246. ep_fd[i] = epoll_create(MAX_EPOLL_FD);
  247. if(ep_fd[i]<0){
  248. perror("epoll_create failed.");
  249. exit(-1);
  250. }
  251. }
  252. for(i=0;i<worker_count;i++){
  253. pthread_attr_init(tattr+i);
  254. pthread_attr_setdetachstate(tattr+i, PTHREAD_CREATE_JOINABLE);
  255. tdata[i].data_from_file = data_from_file;
  256. tdata[i].myep_fd = ep_fd[i];
  257. tdata[i].mypipe_fd = g_pipe[i][0];
  258. if (pthread_create(tid+i, tattr+i, handle_io_loop, tdata+i ) != 0) {
  259. fprintf(stderr, "pthread_create failed\n");
  260. return -1;
  261. }
  262. }
  263. while(1){
  264. if ((client_fd = accept(listen_fd, (struct sockaddr *)&client_addr, &client_n)) > 0) {
  265. if(write(g_pipe[worker_pointer][1],(char*)&client_fd,4)<0){
  266. perror("failed to write pipe");
  267. exit(1);
  268. }
  269. inet_ntop(AF_INET, &client_addr.sin_addr, ip_buf, sizeof(ip_buf));
  270. httpstub_log("[CONN]Connection from %s", ip_buf);
  271. worker_pointer++;
  272. if(worker_pointer == worker_count) worker_pointer=0;
  273. }
  274. else if(errno == EBADF && g_shutdown_flag){
  275. break;
  276. }
  277. else{
  278. if(0 == g_shutdown_flag){
  279. perror("please check ulimit -n");
  280. sleep(1);
  281. }
  282. }
  283. }
  284. free(data_from_file.begin);
  285. for(i=0; i< worker_count; i++){
  286. close(ep_fd[i]);
  287. }
  288. if(client_fd<0 && 0==g_shutdown_flag){
  289. perror("Accep failed, try ulimit -n");
  290. httpstub_log("[ERROR]too many fds open, try ulimit -n");
  291. g_shutdown_flag = 1;
  292. }
  293. fclose(g_logger);
  294. printf(">> [%d]waiting worker thread....\n",getpid());
  295. for(i=0; i< worker_count; i++)
  296. pthread_join(tid[i], NULL);
  297. printf(">> [%d]Bye~\n",getpid());
  298. return 0;
  299. }
  300. static void destroy_fd(int myep_fd, int client_fd, struct io_data_t *data_ptr, int case_no)
  301. {
  302. struct epoll_event ev;
  303. ev.data.ptr = data_ptr;
  304. epoll_ctl(myep_fd, EPOLL_CTL_DEL, client_fd, &ev);
  305. shutdown(client_fd, SHUT_RDWR);
  306. close(client_fd);
  307. destroy_io_data(data_ptr);
  308. httpstub_log("[DEBUG] close case %d",case_no);
  309. }
  310. static void httpstub_log(const char *fmt, ...)
  311. {
  312. if(0 == g_quiet){
  313. char msg[4096];
  314. char buf[64];
  315. time_t now = time(NULL);
  316. va_list ap;
  317. va_start(ap, fmt);
  318. vsnprintf(msg, sizeof(msg), fmt, ap);
  319. va_end(ap);
  320. strftime(buf, sizeof(buf), "%d %b %H:%M:%S", localtime(&now));
  321. fprintf(g_logger, "[%d] %s %s\n", (int)getpid(), buf, msg);
  322. fflush(g_logger);
  323. }
  324. }
  325. static void handle_output(int myep_fd, struct io_data_t *client_io_ptr)
  326. {
  327. int cfd, ret, case_no;
  328. struct epoll_event ev;
  329. cfd = client_io_ptr->fd;
  330. ret = send(cfd, client_io_ptr->out_buf + client_io_ptr->out_buf_cur, client_io_ptr->out_buf_total - client_io_ptr->out_buf_cur, MSG_NOSIGNAL);
  331. if (ret >= 0)
  332. client_io_ptr->out_buf_cur += ret;
  333. httpstub_log("[DEBUG]out_buf_cur %d", client_io_ptr->out_buf_cur);
  334. httpstub_log("[DEBUG]out_buf_total %d", client_io_ptr->out_buf_total);
  335. //printf("ret:%d\n",ret);
  336. //printf("errno:%d\n", errno);
  337. if (0 == ret || (ret < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
  338. //printf("loose 2\n");
  339. case_no = 2;
  340. //perror("send");
  341. //printf("cfd: %d\n", cfd);
  342. destroy_fd(myep_fd, cfd, client_io_ptr, case_no);
  343. return;
  344. }
  345. if (client_io_ptr->out_buf_cur == client_io_ptr->out_buf_total) { //have sent all
  346. httpstub_log("[NOTICE] all messages have been sent.(%d bytes)", client_io_ptr->out_buf_total);
  347. //printf("alive: %d\n", client_io_ptr->keep_alive);
  348. if (client_io_ptr->version == HTTP_1_0 && 0 == client_io_ptr->keep_alive) {
  349. case_no = 4;
  350. destroy_fd(myep_fd, cfd, client_io_ptr, case_no);
  351. return;
  352. }
  353. ev.data.ptr = client_io_ptr;
  354. ev.events = EPOLLIN;
  355. epoll_ctl(myep_fd, EPOLL_CTL_MOD, cfd, &ev);
  356. }
  357. }
  358. static void handle_input(int myep_fd, struct io_data_t *client_io_ptr, struct slice_t data_from_file, const char *rsps_msg_fmt, int delay)
  359. {
  360. int npos = 0;
  361. int total = 0;
  362. int ret = 0;
  363. int case_no = 0;
  364. char headmsg[256];
  365. char *sep = NULL;
  366. const char *CRLF = "\r\n\r\n";
  367. const char *LF = "\n\n";
  368. const char *sep_flag=NULL;
  369. struct epoll_event ev;
  370. int cfd = client_io_ptr->fd;
  371. int pkg_len = 0;
  372. assert(client_io_ptr->in_buf_cur >= 0);
  373. ret = recv(cfd, client_io_ptr->in_buf + client_io_ptr->in_buf_cur, 512, MSG_DONTWAIT);
  374. //printf("%u\n",(unsigned int)pthread_self());
  375. if (0 == ret || (ret < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
  376. case_no = 1;
  377. //perror("++++++++");
  378. destroy_fd(myep_fd, cfd, client_io_ptr, case_no);
  379. return;
  380. }
  381. client_io_ptr->in_buf_cur += ret;
  382. client_io_ptr->in_buf[client_io_ptr->in_buf_cur] = '\0';
  383. sep = strstr(client_io_ptr->in_buf, CRLF);
  384. if (NULL == sep) {
  385. sep = strstr(client_io_ptr->in_buf, LF);
  386. if (NULL == sep)
  387. return;
  388. else
  389. sep_flag = LF;
  390. } else {
  391. sep_flag = CRLF;
  392. }
  393. if (strstr(client_io_ptr->in_buf, "GET ") == client_io_ptr->in_buf) {
  394. if (strstr(client_io_ptr->in_buf, "HTTP/1.0") != NULL) {
  395. client_io_ptr->version = HTTP_1_0;
  396. if (NULL == strstr(client_io_ptr->in_buf, "Connection: Keep-Alive")) {
  397. client_io_ptr->keep_alive = 0;
  398. }
  399. } else {
  400. client_io_ptr->version = HTTP_1_1;
  401. }
  402. }
  403. npos = strcspn(client_io_ptr->in_buf, "\r\n");
  404. if (npos > 250)
  405. npos = 250;
  406. memcpy(headmsg, client_io_ptr->in_buf, npos);
  407. headmsg[npos] = '\0';
  408. httpstub_log("[RECV] %s ", headmsg);
  409. pkg_len = sep - client_io_ptr->in_buf + strlen(sep_flag);
  410. assert(pkg_len >= 0);
  411. assert(client_io_ptr->in_buf_cur - pkg_len >= 0);
  412. memmove(client_io_ptr->in_buf, sep + strlen(sep_flag), client_io_ptr->in_buf_cur - pkg_len);
  413. client_io_ptr->in_buf_cur -= pkg_len;
  414. client_io_ptr->out_buf_cur = 0;
  415. total = snprintf(client_io_ptr->out_buf, MAX_BUF_SIZE, rsps_msg_fmt, data_from_file.size);
  416. memcpy(client_io_ptr->out_buf + total, data_from_file.begin, data_from_file.size);
  417. total += data_from_file.size;
  418. httpstub_log("[DEBUG]total:%d", total);
  419. client_io_ptr->out_buf_total = total;
  420. ev.data.ptr = client_io_ptr;
  421. ev.events = EPOLLOUT;
  422. epoll_ctl(myep_fd, EPOLL_CTL_MOD, cfd, &ev);
  423. if (delay > 0) {
  424. //printf("usleep: %d\n",(int)(g_delay*2000/nfds) );
  425. usleep(delay);
  426. }
  427. }
  428. static void * handle_io_loop(void *param)
  429. {
  430. register int i;
  431. int cfd, nfds, case_no, new_sock_fd;
  432. struct epoll_event events[MAX_EPOLL_FD],ev;
  433. const char *rsps_msg_fmt = "HTTP/1.1 200 OK\r\nContent-Length: %d\r\nConnection: Keep-Alive\r\nContent-Type: text/plain\r\n\r\n";
  434. struct io_data_t *client_io_ptr;
  435. struct thread_data_t my_tdata = *(struct thread_data_t*)param;
  436. ev.data.fd = my_tdata.mypipe_fd;
  437. ev.events = EPOLLIN;
  438. epoll_ctl(my_tdata.myep_fd,EPOLL_CTL_ADD,my_tdata.mypipe_fd,&ev);
  439. while (1) {
  440. nfds = epoll_wait(my_tdata.myep_fd, events, MAX_EPOLL_FD, 1000);
  441. //printf("nfds:%d, epoll fd:%d\n",nfds,my_tdata.myep_fd);
  442. if(nfds<=0 && 0!=g_shutdown_flag){
  443. break;
  444. }
  445. for (i = 0; i < nfds && nfds>0; i++) {
  446. if( (events[i].data.fd == my_tdata.mypipe_fd) && (events[i].events & EPOLLIN)){
  447. if(read(my_tdata.mypipe_fd,&new_sock_fd,4)==-1){
  448. perror("faild to read pipe");
  449. exit(1);
  450. }
  451. setnonblocking(new_sock_fd);
  452. ev.data.ptr = alloc_io_data(new_sock_fd, (struct sockaddr_in *)NULL);
  453. ev.events = EPOLLIN;
  454. epoll_ctl(my_tdata.myep_fd, EPOLL_CTL_ADD, new_sock_fd, &ev);
  455. continue;
  456. }
  457. client_io_ptr = (struct io_data_t *)events[i].data.ptr;
  458. if(client_io_ptr->fd<=0) continue;
  459. if (events[i].events & EPOLLIN) {
  460. handle_input(my_tdata.myep_fd, client_io_ptr, my_tdata.data_from_file, rsps_msg_fmt, (int)(g_delay * 1000 / nfds));
  461. } else if (events[i].events & EPOLLOUT) {
  462. handle_output(my_tdata.myep_fd, client_io_ptr);
  463. } else if (events[i].events & EPOLLERR) {
  464. cfd = client_io_ptr->fd;
  465. case_no = 3;
  466. destroy_fd(my_tdata.myep_fd, cfd, client_io_ptr, case_no);
  467. }
  468. }
  469. }
  470. return NULL;
  471. }