tcp_proxy_server.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * tcp proxy server
  3. *
  4. * @build: make clean && make examples WITH_OPENSSL=yes
  5. * @http_server: bin/httpd -s restart -d
  6. * @proxy_server: bin/tcp_proxy_server 1080 127.0.0.1:8080
  7. * bin/tcp_proxy_server 1080 127.0.0.1:8443
  8. * bin/tcp_proxy_server 1080 www.baidu.com
  9. * bin/tcp_proxy_server 1080 www.baidu.com:443
  10. * @client: bin/curl -v 127.0.0.1:1080
  11. * bin/nc 127.0.0.1 1080
  12. * > GET / HTTP/1.1
  13. * > Connection: close
  14. * > [Enter]
  15. * > GET / HTTP/1.1
  16. * > Connection: keep-alive
  17. * > [Enter]
  18. *
  19. * @benchmark: sudo apt install iperf
  20. * iperf -s -p 5001
  21. * bin/tcp_proxy_server 1212 127.0.0.1:5001
  22. * iperf -c 127.0.0.1 -p 5001 -l 8K
  23. * iperf -c 127.0.0.1 -p 1212 -l 8K
  24. */
  25. #include "hloop.h"
  26. #include "hsocket.h"
  27. static char proxy_host[64] = "0.0.0.0";
  28. static int proxy_port = 1080;
  29. static int proxy_ssl = 0;
  30. static char backend_host[64] = "127.0.0.1";
  31. static int backend_port = 80;
  32. static int backend_ssl = 0;
  33. // hloop_create_tcp_server -> on_accept -> hio_setup_tcp_upstream
  34. static void on_accept(hio_t* io) {
  35. /*
  36. printf("on_accept connfd=%d\n", hio_fd(io));
  37. char localaddrstr[SOCKADDR_STRLEN] = {0};
  38. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  39. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  40. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  41. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  42. */
  43. if (backend_port % 1000 == 443) backend_ssl = 1;
  44. hio_setup_tcp_upstream(io, backend_host, backend_port, backend_ssl);
  45. }
  46. int main(int argc, char** argv) {
  47. if (argc < 3) {
  48. printf("Usage: %s proxy_port backend_host:backend_port\n", argv[0]);
  49. return -10;
  50. }
  51. proxy_port = atoi(argv[1]);
  52. if (proxy_port % 1000 == 443) proxy_ssl = 1;
  53. char* pos = strchr(argv[2], ':');
  54. if (pos) {
  55. int len = pos - argv[2];
  56. if (len > 0) {
  57. memcpy(backend_host, argv[2], len);
  58. backend_host[len] = '\0';
  59. }
  60. backend_port = atoi(pos + 1);
  61. } else {
  62. strncpy(backend_host, argv[2], sizeof(backend_host));
  63. }
  64. if (backend_port == 0) backend_port = 80;
  65. printf("%s:%d proxy %s:%d\n", proxy_host, proxy_port, backend_host, backend_port);
  66. hloop_t* loop = hloop_new(0);
  67. hio_t* listenio = hloop_create_tcp_server(loop, proxy_host, proxy_port, on_accept);
  68. if (listenio == NULL) {
  69. return -20;
  70. }
  71. printf("listenfd=%d\n", hio_fd(listenio));
  72. if (proxy_ssl) {
  73. hio_enable_ssl(listenio);
  74. }
  75. hloop_run(loop);
  76. hloop_free(&loop);
  77. return 0;
  78. }