1
0

tcp_proxy_server.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #include "hloop.h"
  20. #include "hsocket.h"
  21. static char proxy_host[64] = "0.0.0.0";
  22. static int proxy_port = 1080;
  23. static int proxy_ssl = 0;
  24. static char backend_host[64] = "127.0.0.1";
  25. static int backend_port = 80;
  26. static int backend_ssl = 0;
  27. // hloop_create_tcp_server -> on_accept -> hio_setup_tcp_upstream
  28. static void on_accept(hio_t* io) {
  29. /*
  30. printf("on_accept connfd=%d\n", hio_fd(io));
  31. char localaddrstr[SOCKADDR_STRLEN] = {0};
  32. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  33. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  34. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  35. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  36. */
  37. if (backend_port % 1000 == 443) backend_ssl = 1;
  38. hio_setup_tcp_upstream(io, backend_host, backend_port, backend_ssl);
  39. }
  40. int main(int argc, char** argv) {
  41. if (argc < 3) {
  42. printf("Usage: %s proxy_port backend_host:backend_port\n", argv[0]);
  43. return -10;
  44. }
  45. proxy_port = atoi(argv[1]);
  46. char* pos = strchr(argv[2], ':');
  47. if (pos) {
  48. int len = pos - argv[2];
  49. if (len > 0) {
  50. memcpy(backend_host, argv[2], len);
  51. backend_host[len] = '\0';
  52. }
  53. backend_port = atoi(pos + 1);
  54. } else {
  55. strncpy(backend_host, argv[2], sizeof(backend_host));
  56. }
  57. if (backend_port == 0) backend_port = 80;
  58. printf("%s:%d proxy %s:%d\n", proxy_host, proxy_port, backend_host, backend_port);
  59. hloop_t* loop = hloop_new(0);
  60. hio_t* listenio = hloop_create_tcp_server(loop, proxy_host, proxy_port, on_accept);
  61. if (listenio == NULL) {
  62. return -20;
  63. }
  64. printf("listenfd=%d\n", hio_fd(listenio));
  65. if (proxy_ssl) {
  66. hio_enable_ssl(listenio);
  67. }
  68. hloop_run(loop);
  69. hloop_free(&loop);
  70. return 0;
  71. }