httpstub.c 18 KB

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