You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1772 lines
53 KiB

12 years ago
12 years ago
9 years ago
11 years ago
10 years ago
11 years ago
8 years ago
7 years ago
10 years ago
10 years ago
8 years ago
11 years ago
10 years ago
10 years ago
12 years ago
12 years ago
8 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
11 years ago
10 years ago
12 years ago
8 years ago
8 years ago
8 years ago
11 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
11 years ago
10 years ago
8 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
8 years ago
8 years ago
8 years ago
11 years ago
10 years ago
8 years ago
10 years ago
10 years ago
11 years ago
10 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
8 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
8 years ago
12 years ago
8 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
11 years ago
10 years ago
10 years ago
8 years ago
11 years ago
10 years ago
10 years ago
8 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
8 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
11 years ago
10 years ago
10 years ago
12 years ago
11 years ago
8 years ago
11 years ago
10 years ago
12 years ago
11 years ago
8 years ago
11 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
11 years ago
8 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
12 years ago
11 years ago
8 years ago
11 years ago
10 years ago
12 years ago
11 years ago
8 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
8 years ago
10 years ago
8 years ago
10 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
10 years ago
10 years ago
8 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
9 years ago
9 years ago
10 years ago
8 years ago
7 years ago
7 years ago
8 years ago
11 years ago
11 years ago
11 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
12 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
7 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
  1. /*
  2. * local.c - Setup a socks5 proxy through remote shadowsocks server
  3. *
  4. * Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
  5. *
  6. * This file is part of the shadowsocks-libev.
  7. *
  8. * shadowsocks-libev is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * shadowsocks-libev is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with shadowsocks-libev; see the file COPYING. If not, see
  20. * <http://www.gnu.org/licenses/>.
  21. */
  22. #ifdef HAVE_CONFIG_H
  23. #include "config.h"
  24. #endif
  25. #include <sys/stat.h>
  26. #include <sys/types.h>
  27. #include <fcntl.h>
  28. #include <locale.h>
  29. #include <signal.h>
  30. #include <string.h>
  31. #include <strings.h>
  32. #include <unistd.h>
  33. #include <getopt.h>
  34. #ifndef __MINGW32__
  35. #include <errno.h>
  36. #include <arpa/inet.h>
  37. #include <netdb.h>
  38. #include <netinet/in.h>
  39. #include <pthread.h>
  40. #endif
  41. #ifdef LIB_ONLY
  42. #include <pthread.h>
  43. #include "shadowsocks.h"
  44. #endif
  45. #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__)
  46. #include <net/if.h>
  47. #include <sys/ioctl.h>
  48. #define SET_INTERFACE
  49. #endif
  50. #include <libcork/core.h>
  51. #include <udns.h>
  52. #ifdef __MINGW32__
  53. #include "win32.h"
  54. #endif
  55. #include "netutils.h"
  56. #include "utils.h"
  57. #include "socks5.h"
  58. #include "acl.h"
  59. #include "http.h"
  60. #include "tls.h"
  61. #include "plugin.h"
  62. #include "local.h"
  63. #ifndef LIB_ONLY
  64. #ifdef __APPLE__
  65. #include <AvailabilityMacros.h>
  66. #if defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10
  67. #include <launch.h>
  68. #define HAVE_LAUNCHD
  69. #endif
  70. #endif
  71. #endif
  72. #ifndef EAGAIN
  73. #define EAGAIN EWOULDBLOCK
  74. #endif
  75. #ifndef EWOULDBLOCK
  76. #define EWOULDBLOCK EAGAIN
  77. #endif
  78. #ifndef BUF_SIZE
  79. #define BUF_SIZE 2048
  80. #endif
  81. int verbose = 0;
  82. int keep_resolving = 1;
  83. #ifdef ANDROID
  84. int vpn = 0;
  85. uint64_t tx = 0;
  86. uint64_t rx = 0;
  87. ev_tstamp last = 0;
  88. char *prefix;
  89. #endif
  90. static int acl = 0;
  91. static int auth = 0;
  92. static int mode = TCP_ONLY;
  93. static int ipv6first = 0;
  94. static int fast_open = 0;
  95. static struct ev_signal sigint_watcher;
  96. static struct ev_signal sigterm_watcher;
  97. #ifndef __MINGW32__
  98. static struct ev_signal sigchld_watcher;
  99. static struct ev_signal sigusr1_watcher;
  100. #endif
  101. #ifdef HAVE_SETRLIMIT
  102. #ifndef LIB_ONLY
  103. static int nofile = 0;
  104. #endif
  105. #endif
  106. static void server_recv_cb(EV_P_ ev_io *w, int revents);
  107. static void server_send_cb(EV_P_ ev_io *w, int revents);
  108. static void remote_recv_cb(EV_P_ ev_io *w, int revents);
  109. static void remote_send_cb(EV_P_ ev_io *w, int revents);
  110. static void accept_cb(EV_P_ ev_io *w, int revents);
  111. static void signal_cb(EV_P_ ev_signal *w, int revents);
  112. static int create_and_bind(const char *addr, const char *port);
  113. #ifdef HAVE_LAUNCHD
  114. static int launch_or_create(const char *addr, const char *port);
  115. #endif
  116. static remote_t *create_remote(listen_ctx_t *listener, struct sockaddr *addr);
  117. static void free_remote(remote_t *remote);
  118. static void close_and_free_remote(EV_P_ remote_t *remote);
  119. static void free_server(server_t *server);
  120. static void close_and_free_server(EV_P_ server_t *server);
  121. static remote_t *new_remote(int fd, int timeout);
  122. static server_t *new_server(int fd, int method);
  123. static struct cork_dllist connections;
  124. #ifndef __MINGW32__
  125. int
  126. setnonblocking(int fd)
  127. {
  128. int flags;
  129. if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
  130. flags = 0;
  131. }
  132. return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  133. }
  134. #endif
  135. int
  136. create_and_bind(const char *addr, const char *port)
  137. {
  138. struct addrinfo hints;
  139. struct addrinfo *result, *rp;
  140. int s, listen_sock;
  141. memset(&hints, 0, sizeof(struct addrinfo));
  142. hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
  143. hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
  144. s = getaddrinfo(addr, port, &hints, &result);
  145. if (s != 0) {
  146. LOGI("getaddrinfo: %s", gai_strerror(s));
  147. return -1;
  148. }
  149. for (rp = result; rp != NULL; rp = rp->ai_next) {
  150. listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  151. if (listen_sock == -1) {
  152. continue;
  153. }
  154. int opt = 1;
  155. setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  156. #ifdef SO_NOSIGPIPE
  157. setsockopt(listen_sock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
  158. #endif
  159. int err = set_reuseport(listen_sock);
  160. if (err == 0) {
  161. LOGI("tcp port reuse enabled");
  162. }
  163. s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen);
  164. if (s == 0) {
  165. /* We managed to bind successfully! */
  166. break;
  167. } else {
  168. ERROR("bind");
  169. }
  170. close(listen_sock);
  171. }
  172. if (rp == NULL) {
  173. LOGE("Could not bind");
  174. return -1;
  175. }
  176. freeaddrinfo(result);
  177. return listen_sock;
  178. }
  179. #ifdef HAVE_LAUNCHD
  180. int
  181. launch_or_create(const char *addr, const char *port)
  182. {
  183. int *fds;
  184. size_t cnt;
  185. int error = launch_activate_socket("Listeners", &fds, &cnt);
  186. if (error == 0) {
  187. if (cnt == 1) {
  188. return fds[0];
  189. } else {
  190. FATAL("please don't specify multi entry");
  191. }
  192. } else if (error == ESRCH || error == ENOENT) {
  193. /* ESRCH: The calling process is not managed by launchd(8).
  194. * ENOENT: The socket name specified does not exist
  195. * in the caller's launchd.plist(5).
  196. */
  197. if (port == NULL) {
  198. usage();
  199. exit(EXIT_FAILURE);
  200. }
  201. return create_and_bind(addr, port);
  202. } else {
  203. FATAL("launch_activate_socket() error");
  204. }
  205. return -1;
  206. }
  207. #endif
  208. static void
  209. free_connections(struct ev_loop *loop)
  210. {
  211. struct cork_dllist_item *curr, *next;
  212. cork_dllist_foreach_void(&connections, curr, next) {
  213. server_t *server = cork_container_of(curr, server_t, entries);
  214. remote_t *remote = server->remote;
  215. close_and_free_server(loop, server);
  216. close_and_free_remote(loop, remote);
  217. }
  218. }
  219. static void
  220. server_recv_cb(EV_P_ ev_io *w, int revents)
  221. {
  222. server_ctx_t *server_recv_ctx = (server_ctx_t *)w;
  223. server_t *server = server_recv_ctx->server;
  224. remote_t *remote = server->remote;
  225. buffer_t *buf;
  226. ssize_t r;
  227. if (remote == NULL) {
  228. buf = server->buf;
  229. } else {
  230. buf = remote->buf;
  231. }
  232. r = recv(server->fd, buf->data + buf->len, BUF_SIZE - buf->len, 0);
  233. if (r == 0) {
  234. // connection closed
  235. close_and_free_remote(EV_A_ remote);
  236. close_and_free_server(EV_A_ server);
  237. return;
  238. } else if (r == -1) {
  239. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  240. // no data
  241. // continue to wait for recv
  242. return;
  243. } else {
  244. if (verbose)
  245. ERROR("server_recv_cb_recv");
  246. close_and_free_remote(EV_A_ remote);
  247. close_and_free_server(EV_A_ server);
  248. return;
  249. }
  250. }
  251. buf->len += r;
  252. while (1) {
  253. // local socks5 server
  254. if (server->stage == STAGE_STREAM) {
  255. if (remote == NULL) {
  256. LOGE("invalid remote");
  257. close_and_free_server(EV_A_ server);
  258. return;
  259. }
  260. if (!remote->direct && remote->send_ctx->connected && auth) {
  261. ss_gen_hash(remote->buf, &remote->counter, server->e_ctx, BUF_SIZE);
  262. }
  263. // insert shadowsocks header
  264. if (!remote->direct) {
  265. #ifdef ANDROID
  266. tx += remote->buf->len;
  267. #endif
  268. int err = ss_encrypt(remote->buf, server->e_ctx, BUF_SIZE);
  269. if (err) {
  270. LOGE("invalid password or cipher");
  271. close_and_free_remote(EV_A_ remote);
  272. close_and_free_server(EV_A_ server);
  273. return;
  274. }
  275. }
  276. if (!remote->send_ctx->connected) {
  277. #ifdef ANDROID
  278. if (vpn) {
  279. int not_protect = 0;
  280. if (remote->addr.ss_family == AF_INET) {
  281. struct sockaddr_in *s = (struct sockaddr_in *)&remote->addr;
  282. if (s->sin_addr.s_addr == inet_addr("127.0.0.1"))
  283. not_protect = 1;
  284. }
  285. if (!not_protect) {
  286. if (protect_socket(remote->fd) == -1) {
  287. ERROR("protect_socket");
  288. close_and_free_remote(EV_A_ remote);
  289. close_and_free_server(EV_A_ server);
  290. return;
  291. }
  292. }
  293. }
  294. #endif
  295. remote->buf->idx = 0;
  296. if (!fast_open || remote->direct) {
  297. // connecting, wait until connected
  298. int r = connect(remote->fd, (struct sockaddr *)&(remote->addr), remote->addr_len);
  299. if (r == -1 && errno != CONNECT_IN_PROGRESS) {
  300. ERROR("connect");
  301. close_and_free_remote(EV_A_ remote);
  302. close_and_free_server(EV_A_ server);
  303. return;
  304. }
  305. // wait on remote connected event
  306. ev_io_stop(EV_A_ & server_recv_ctx->io);
  307. ev_io_start(EV_A_ & remote->send_ctx->io);
  308. ev_timer_start(EV_A_ & remote->send_ctx->watcher);
  309. } else {
  310. #ifdef TCP_FASTOPEN
  311. #ifdef __APPLE__
  312. ((struct sockaddr_in *)&(remote->addr))->sin_len = sizeof(struct sockaddr_in);
  313. sa_endpoints_t endpoints;
  314. memset((char *)&endpoints, 0, sizeof(endpoints));
  315. endpoints.sae_dstaddr = (struct sockaddr *)&(remote->addr);
  316. endpoints.sae_dstaddrlen = remote->addr_len;
  317. int s = connectx(remote->fd, &endpoints, SAE_ASSOCID_ANY,
  318. CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
  319. NULL, 0, NULL, NULL);
  320. if (s == 0) {
  321. s = send(remote->fd, remote->buf->data, remote->buf->len, 0);
  322. }
  323. #else
  324. int s = sendto(remote->fd, remote->buf->data, remote->buf->len, MSG_FASTOPEN,
  325. (struct sockaddr *)&(remote->addr), remote->addr_len);
  326. #endif
  327. if (s == -1) {
  328. if (errno == CONNECT_IN_PROGRESS) {
  329. // in progress, wait until connected
  330. remote->buf->idx = 0;
  331. ev_io_stop(EV_A_ & server_recv_ctx->io);
  332. ev_io_start(EV_A_ & remote->send_ctx->io);
  333. return;
  334. } else {
  335. ERROR("sendto");
  336. if (errno == ENOTCONN) {
  337. LOGE("fast open is not supported on this platform");
  338. // just turn it off
  339. fast_open = 0;
  340. }
  341. close_and_free_remote(EV_A_ remote);
  342. close_and_free_server(EV_A_ server);
  343. return;
  344. }
  345. } else if (s < (int)(remote->buf->len)) {
  346. remote->buf->len -= s;
  347. remote->buf->idx = s;
  348. ev_io_stop(EV_A_ & server_recv_ctx->io);
  349. ev_io_start(EV_A_ & remote->send_ctx->io);
  350. ev_timer_start(EV_A_ & remote->send_ctx->watcher);
  351. return;
  352. } else {
  353. // Just connected
  354. remote->buf->idx = 0;
  355. remote->buf->len = 0;
  356. #ifdef __APPLE__
  357. ev_io_stop(EV_A_ & server_recv_ctx->io);
  358. ev_io_start(EV_A_ & remote->send_ctx->io);
  359. ev_timer_start(EV_A_ & remote->send_ctx->watcher);
  360. #else
  361. remote->send_ctx->connected = 1;
  362. ev_timer_stop(EV_A_ & remote->send_ctx->watcher);
  363. ev_timer_start(EV_A_ & remote->recv_ctx->watcher);
  364. ev_io_start(EV_A_ & remote->recv_ctx->io);
  365. return;
  366. #endif
  367. }
  368. #else
  369. // if TCP_FASTOPEN is not defined, fast_open will always be 0
  370. LOGE("can't come here");
  371. exit(1);
  372. #endif
  373. }
  374. } else {
  375. int s = send(remote->fd, remote->buf->data, remote->buf->len, 0);
  376. if (s == -1) {
  377. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  378. // no data, wait for send
  379. remote->buf->idx = 0;
  380. ev_io_stop(EV_A_ & server_recv_ctx->io);
  381. ev_io_start(EV_A_ & remote->send_ctx->io);
  382. return;
  383. } else {
  384. ERROR("server_recv_cb_send");
  385. close_and_free_remote(EV_A_ remote);
  386. close_and_free_server(EV_A_ server);
  387. return;
  388. }
  389. } else if (s < (int)(remote->buf->len)) {
  390. remote->buf->len -= s;
  391. remote->buf->idx = s;
  392. ev_io_stop(EV_A_ & server_recv_ctx->io);
  393. ev_io_start(EV_A_ & remote->send_ctx->io);
  394. return;
  395. } else {
  396. remote->buf->idx = 0;
  397. remote->buf->len = 0;
  398. }
  399. }
  400. // all processed
  401. return;
  402. } else if (server->stage == STAGE_INIT) {
  403. struct method_select_response response;
  404. response.ver = SVERSION;
  405. response.method = 0;
  406. char *send_buf = (char *)&response;
  407. send(server->fd, send_buf, sizeof(response), 0);
  408. server->stage = STAGE_HANDSHAKE;
  409. int off = (buf->data[1] & 0xff) + 2;
  410. if (buf->data[0] == 0x05 && off < (int)(buf->len)) {
  411. memmove(buf->data, buf->data + off, buf->len - off);
  412. buf->len -= off;
  413. continue;
  414. }
  415. buf->len = 0;
  416. return;
  417. } else if (server->stage == STAGE_HANDSHAKE || server->stage == STAGE_PARSE) {
  418. struct socks5_request *request = (struct socks5_request *)buf->data;
  419. struct sockaddr_in sock_addr;
  420. memset(&sock_addr, 0, sizeof(sock_addr));
  421. int udp_assc = 0;
  422. if (request->cmd == 3) {
  423. udp_assc = 1;
  424. socklen_t addr_len = sizeof(sock_addr);
  425. getsockname(server->fd, (struct sockaddr *)&sock_addr,
  426. &addr_len);
  427. if (verbose) {
  428. LOGI("udp assc request accepted");
  429. }
  430. } else if (request->cmd != 1) {
  431. LOGE("unsupported cmd: %d", request->cmd);
  432. struct socks5_response response;
  433. response.ver = SVERSION;
  434. response.rep = CMD_NOT_SUPPORTED;
  435. response.rsv = 0;
  436. response.atyp = 1;
  437. char *send_buf = (char *)&response;
  438. send(server->fd, send_buf, 4, 0);
  439. close_and_free_remote(EV_A_ remote);
  440. close_and_free_server(EV_A_ server);
  441. return;
  442. }
  443. // Fake reply
  444. if (server->stage == STAGE_HANDSHAKE) {
  445. struct socks5_response response;
  446. response.ver = SVERSION;
  447. response.rep = 0;
  448. response.rsv = 0;
  449. response.atyp = 1;
  450. buffer_t resp_to_send;
  451. buffer_t *resp_buf = &resp_to_send;
  452. balloc(resp_buf, BUF_SIZE);
  453. memcpy(resp_buf->data, &response, sizeof(struct socks5_response));
  454. memcpy(resp_buf->data + sizeof(struct socks5_response),
  455. &sock_addr.sin_addr, sizeof(sock_addr.sin_addr));
  456. memcpy(resp_buf->data + sizeof(struct socks5_response) +
  457. sizeof(sock_addr.sin_addr),
  458. &sock_addr.sin_port, sizeof(sock_addr.sin_port));
  459. int reply_size = sizeof(struct socks5_response) +
  460. sizeof(sock_addr.sin_addr) + sizeof(sock_addr.sin_port);
  461. int s = send(server->fd, resp_buf->data, reply_size, 0);
  462. bfree(resp_buf);
  463. if (s < reply_size) {
  464. LOGE("failed to send fake reply");
  465. close_and_free_remote(EV_A_ remote);
  466. close_and_free_server(EV_A_ server);
  467. return;
  468. }
  469. if (udp_assc) {
  470. close_and_free_remote(EV_A_ remote);
  471. close_and_free_server(EV_A_ server);
  472. return;
  473. }
  474. }
  475. char host[257], ip[INET6_ADDRSTRLEN], port[16];
  476. buffer_t ss_addr_to_send;
  477. buffer_t *abuf = &ss_addr_to_send;
  478. balloc(abuf, BUF_SIZE);
  479. abuf->data[abuf->len++] = request->atyp;
  480. int atyp = request->atyp;
  481. // get remote addr and port
  482. if (atyp == 1) {
  483. // IP V4
  484. size_t in_addr_len = sizeof(struct in_addr);
  485. memcpy(abuf->data + abuf->len, buf->data + 4, in_addr_len + 2);
  486. abuf->len += in_addr_len + 2;
  487. if (acl || verbose) {
  488. uint16_t p = ntohs(*(uint16_t *)(buf->data + 4 + in_addr_len));
  489. dns_ntop(AF_INET, (const void *)(buf->data + 4),
  490. ip, INET_ADDRSTRLEN);
  491. sprintf(port, "%d", p);
  492. }
  493. } else if (atyp == 3) {
  494. // Domain name
  495. uint8_t name_len = *(uint8_t *)(buf->data + 4);
  496. abuf->data[abuf->len++] = name_len;
  497. memcpy(abuf->data + abuf->len, buf->data + 4 + 1, name_len + 2);
  498. abuf->len += name_len + 2;
  499. if (acl || verbose) {
  500. uint16_t p =
  501. ntohs(*(uint16_t *)(buf->data + 4 + 1 + name_len));
  502. memcpy(host, buf->data + 4 + 1, name_len);
  503. host[name_len] = '\0';
  504. sprintf(port, "%d", p);
  505. }
  506. } else if (atyp == 4) {
  507. // IP V6
  508. size_t in6_addr_len = sizeof(struct in6_addr);
  509. memcpy(abuf->data + abuf->len, buf->data + 4, in6_addr_len + 2);
  510. abuf->len += in6_addr_len + 2;
  511. if (acl || verbose) {
  512. uint16_t p = ntohs(*(uint16_t *)(buf->data + 4 + in6_addr_len));
  513. dns_ntop(AF_INET6, (const void *)(buf->data + 4),
  514. ip, INET6_ADDRSTRLEN);
  515. sprintf(port, "%d", p);
  516. }
  517. } else {
  518. bfree(abuf);
  519. LOGE("unsupported addrtype: %d", request->atyp);
  520. close_and_free_remote(EV_A_ remote);
  521. close_and_free_server(EV_A_ server);
  522. return;
  523. }
  524. size_t abuf_len = abuf->len;
  525. int sni_detected = 0;
  526. if (atyp == 1 || atyp == 4) {
  527. char *hostname;
  528. uint16_t p = ntohs(*(uint16_t *)(abuf->data + abuf->len - 2));
  529. int ret = 0;
  530. if (p == http_protocol->default_port)
  531. ret = http_protocol->parse_packet(buf->data + 3 + abuf->len,
  532. buf->len - 3 - abuf->len, &hostname);
  533. else if (p == tls_protocol->default_port)
  534. ret = tls_protocol->parse_packet(buf->data + 3 + abuf->len,
  535. buf->len - 3 - abuf->len, &hostname);
  536. if (ret == -1 && buf->len < BUF_SIZE) {
  537. server->stage = STAGE_PARSE;
  538. bfree(abuf);
  539. return;
  540. } else if (ret > 0) {
  541. sni_detected = 1;
  542. // Reconstruct address buffer
  543. abuf->len = 0;
  544. abuf->data[abuf->len++] = 3;
  545. abuf->data[abuf->len++] = ret;
  546. memcpy(abuf->data + abuf->len, hostname, ret);
  547. abuf->len += ret;
  548. p = htons(p);
  549. memcpy(abuf->data + abuf->len, &p, 2);
  550. abuf->len += 2;
  551. if (acl || verbose) {
  552. memcpy(host, hostname, ret);
  553. host[ret] = '\0';
  554. }
  555. ss_free(hostname);
  556. }
  557. }
  558. server->stage = STAGE_STREAM;
  559. buf->len -= (3 + abuf_len);
  560. if (buf->len > 0) {
  561. memmove(buf->data, buf->data + 3 + abuf_len, buf->len);
  562. }
  563. if (verbose) {
  564. if (sni_detected || atyp == 3)
  565. LOGI("connect to %s:%s", host, port);
  566. else if (atyp == 1)
  567. LOGI("connect to %s:%s", ip, port);
  568. else if (atyp == 4)
  569. LOGI("connect to [%s]:%s", ip, port);
  570. }
  571. if (acl) {
  572. int host_match = acl_match_host(host);
  573. int bypass = 0;
  574. if (host_match > 0)
  575. bypass = 1; // bypass hostnames in black list
  576. else if (host_match < 0)
  577. bypass = 0; // proxy hostnames in white list
  578. else {
  579. int ip_match = acl_match_host(ip);
  580. switch (get_acl_mode()) {
  581. case BLACK_LIST:
  582. if (ip_match > 0)
  583. bypass = 1; // bypass IPs in black list
  584. break;
  585. case WHITE_LIST:
  586. bypass = 1;
  587. if (ip_match < 0)
  588. bypass = 0; // proxy IPs in white list
  589. break;
  590. }
  591. }
  592. if (bypass) {
  593. if (verbose) {
  594. if (sni_detected || atyp == 3)
  595. LOGI("bypass %s:%s", host, port);
  596. else if (atyp == 1)
  597. LOGI("bypass %s:%s", ip, port);
  598. else if (atyp == 4)
  599. LOGI("bypass [%s]:%s", ip, port);
  600. }
  601. struct sockaddr_storage storage;
  602. memset(&storage, 0, sizeof(struct sockaddr_storage));
  603. int err = get_sockaddr(ip, port, &storage, 0, ipv6first);
  604. if (err != -1) {
  605. remote = create_remote(server->listener, (struct sockaddr *)&storage);
  606. if (remote != NULL)
  607. remote->direct = 1;
  608. }
  609. }
  610. }
  611. // Not match ACL
  612. if (remote == NULL) {
  613. remote = create_remote(server->listener, NULL);
  614. }
  615. if (remote == NULL) {
  616. bfree(abuf);
  617. LOGE("invalid remote addr");
  618. close_and_free_server(EV_A_ server);
  619. return;
  620. }
  621. if (!remote->direct) {
  622. if (auth) {
  623. abuf->data[0] |= ONETIMEAUTH_FLAG;
  624. ss_onetimeauth(abuf, server->e_ctx->evp.iv, BUF_SIZE);
  625. }
  626. if (buf->len > 0 && auth) {
  627. ss_gen_hash(buf, &remote->counter, server->e_ctx, BUF_SIZE);
  628. }
  629. brealloc(remote->buf, buf->len + abuf->len, BUF_SIZE);
  630. memcpy(remote->buf->data, abuf->data, abuf->len);
  631. remote->buf->len = buf->len + abuf->len;
  632. if (buf->len > 0) {
  633. memcpy(remote->buf->data + abuf->len, buf->data, buf->len);
  634. }
  635. } else {
  636. if (buf->len > 0) {
  637. memcpy(remote->buf->data, buf->data, buf->len);
  638. remote->buf->len = buf->len;
  639. }
  640. }
  641. server->remote = remote;
  642. remote->server = server;
  643. bfree(abuf);
  644. }
  645. }
  646. }
  647. static void
  648. server_send_cb(EV_P_ ev_io *w, int revents)
  649. {
  650. server_ctx_t *server_send_ctx = (server_ctx_t *)w;
  651. server_t *server = server_send_ctx->server;
  652. remote_t *remote = server->remote;
  653. if (server->buf->len == 0) {
  654. // close and free
  655. close_and_free_remote(EV_A_ remote);
  656. close_and_free_server(EV_A_ server);
  657. return;
  658. } else {
  659. // has data to send
  660. ssize_t s = send(server->fd, server->buf->data + server->buf->idx,
  661. server->buf->len, 0);
  662. if (s == -1) {
  663. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  664. ERROR("server_send_cb_send");
  665. close_and_free_remote(EV_A_ remote);
  666. close_and_free_server(EV_A_ server);
  667. }
  668. return;
  669. } else if (s < (ssize_t)(server->buf->len)) {
  670. // partly sent, move memory, wait for the next time to send
  671. server->buf->len -= s;
  672. server->buf->idx += s;
  673. return;
  674. } else {
  675. // all sent out, wait for reading
  676. server->buf->len = 0;
  677. server->buf->idx = 0;
  678. ev_io_stop(EV_A_ & server_send_ctx->io);
  679. ev_io_start(EV_A_ & remote->recv_ctx->io);
  680. return;
  681. }
  682. }
  683. }
  684. #ifdef ANDROID
  685. static void
  686. stat_update_cb()
  687. {
  688. ev_tstamp now = ev_time();
  689. if (now - last > 1.0) {
  690. send_traffic_stat(tx, rx);
  691. last = now;
  692. }
  693. }
  694. #endif
  695. static void
  696. remote_timeout_cb(EV_P_ ev_timer *watcher, int revents)
  697. {
  698. remote_ctx_t *remote_ctx
  699. = cork_container_of(watcher, remote_ctx_t, watcher);
  700. remote_t *remote = remote_ctx->remote;
  701. server_t *server = remote->server;
  702. if (verbose) {
  703. LOGI("TCP connection timeout");
  704. }
  705. close_and_free_remote(EV_A_ remote);
  706. close_and_free_server(EV_A_ server);
  707. }
  708. static void
  709. remote_recv_cb(EV_P_ ev_io *w, int revents)
  710. {
  711. remote_ctx_t *remote_recv_ctx = (remote_ctx_t *)w;
  712. remote_t *remote = remote_recv_ctx->remote;
  713. server_t *server = remote->server;
  714. ev_timer_again(EV_A_ & remote->recv_ctx->watcher);
  715. #ifdef ANDROID
  716. stat_update_cb();
  717. #endif
  718. ssize_t r = recv(remote->fd, server->buf->data, BUF_SIZE, 0);
  719. if (r == 0) {
  720. // connection closed
  721. close_and_free_remote(EV_A_ remote);
  722. close_and_free_server(EV_A_ server);
  723. return;
  724. } else if (r == -1) {
  725. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  726. // no data
  727. // continue to wait for recv
  728. return;
  729. } else {
  730. ERROR("remote_recv_cb_recv");
  731. close_and_free_remote(EV_A_ remote);
  732. close_and_free_server(EV_A_ server);
  733. return;
  734. }
  735. }
  736. server->buf->len = r;
  737. if (!remote->direct) {
  738. #ifdef ANDROID
  739. rx += server->buf->len;
  740. #endif
  741. int err = ss_decrypt(server->buf, server->d_ctx, BUF_SIZE);
  742. if (err) {
  743. LOGE("invalid password or cipher");
  744. close_and_free_remote(EV_A_ remote);
  745. close_and_free_server(EV_A_ server);
  746. return;
  747. }
  748. }
  749. int s = send(server->fd, server->buf->data, server->buf->len, 0);
  750. if (s == -1) {
  751. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  752. // no data, wait for send
  753. server->buf->idx = 0;
  754. ev_io_stop(EV_A_ & remote_recv_ctx->io);
  755. ev_io_start(EV_A_ & server->send_ctx->io);
  756. } else {
  757. ERROR("remote_recv_cb_send");
  758. close_and_free_remote(EV_A_ remote);
  759. close_and_free_server(EV_A_ server);
  760. return;
  761. }
  762. } else if (s < (int)(server->buf->len)) {
  763. server->buf->len -= s;
  764. server->buf->idx = s;
  765. ev_io_stop(EV_A_ & remote_recv_ctx->io);
  766. ev_io_start(EV_A_ & server->send_ctx->io);
  767. }
  768. // Disable TCP_NODELAY after the first response are sent
  769. if (!remote->recv_ctx->connected) {
  770. int opt = 0;
  771. setsockopt(server->fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
  772. setsockopt(remote->fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
  773. remote->recv_ctx->connected = 1;
  774. }
  775. }
  776. static void
  777. remote_send_cb(EV_P_ ev_io *w, int revents)
  778. {
  779. remote_ctx_t *remote_send_ctx = (remote_ctx_t *)w;
  780. remote_t *remote = remote_send_ctx->remote;
  781. server_t *server = remote->server;
  782. if (!remote_send_ctx->connected) {
  783. struct sockaddr_storage addr;
  784. socklen_t len = sizeof addr;
  785. int r = getpeername(remote->fd, (struct sockaddr *)&addr, &len);
  786. if (r == 0) {
  787. remote_send_ctx->connected = 1;
  788. ev_timer_stop(EV_A_ & remote_send_ctx->watcher);
  789. ev_timer_start(EV_A_ & remote->recv_ctx->watcher);
  790. ev_io_start(EV_A_ & remote->recv_ctx->io);
  791. // no need to send any data
  792. if (remote->buf->len == 0) {
  793. ev_io_stop(EV_A_ & remote_send_ctx->io);
  794. ev_io_start(EV_A_ & server->recv_ctx->io);
  795. return;
  796. }
  797. } else {
  798. // not connected
  799. ERROR("getpeername");
  800. close_and_free_remote(EV_A_ remote);
  801. close_and_free_server(EV_A_ server);
  802. return;
  803. }
  804. }
  805. if (remote->buf->len == 0) {
  806. // close and free
  807. close_and_free_remote(EV_A_ remote);
  808. close_and_free_server(EV_A_ server);
  809. return;
  810. } else {
  811. // has data to send
  812. ssize_t s = send(remote->fd, remote->buf->data + remote->buf->idx,
  813. remote->buf->len, 0);
  814. if (s == -1) {
  815. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  816. ERROR("remote_send_cb_send");
  817. // close and free
  818. close_and_free_remote(EV_A_ remote);
  819. close_and_free_server(EV_A_ server);
  820. }
  821. return;
  822. } else if (s < (ssize_t)(remote->buf->len)) {
  823. // partly sent, move memory, wait for the next time to send
  824. remote->buf->len -= s;
  825. remote->buf->idx += s;
  826. return;
  827. } else {
  828. // all sent out, wait for reading
  829. remote->buf->len = 0;
  830. remote->buf->idx = 0;
  831. ev_io_stop(EV_A_ & remote_send_ctx->io);
  832. ev_io_start(EV_A_ & server->recv_ctx->io);
  833. }
  834. }
  835. }
  836. static remote_t *
  837. new_remote(int fd, int timeout)
  838. {
  839. remote_t *remote;
  840. remote = ss_malloc(sizeof(remote_t));
  841. memset(remote, 0, sizeof(remote_t));
  842. remote->buf = ss_malloc(sizeof(buffer_t));
  843. remote->recv_ctx = ss_malloc(sizeof(remote_ctx_t));
  844. remote->send_ctx = ss_malloc(sizeof(remote_ctx_t));
  845. balloc(remote->buf, BUF_SIZE);
  846. memset(remote->recv_ctx, 0, sizeof(remote_ctx_t));
  847. memset(remote->send_ctx, 0, sizeof(remote_ctx_t));
  848. remote->recv_ctx->connected = 0;
  849. remote->send_ctx->connected = 0;
  850. remote->fd = fd;
  851. remote->recv_ctx->remote = remote;
  852. remote->send_ctx->remote = remote;
  853. ev_io_init(&remote->recv_ctx->io, remote_recv_cb, fd, EV_READ);
  854. ev_io_init(&remote->send_ctx->io, remote_send_cb, fd, EV_WRITE);
  855. ev_timer_init(&remote->send_ctx->watcher, remote_timeout_cb,
  856. min(MAX_CONNECT_TIMEOUT, timeout), 0);
  857. ev_timer_init(&remote->recv_ctx->watcher, remote_timeout_cb,
  858. timeout, timeout);
  859. return remote;
  860. }
  861. static void
  862. free_remote(remote_t *remote)
  863. {
  864. if (remote->server != NULL) {
  865. remote->server->remote = NULL;
  866. }
  867. if (remote->buf != NULL) {
  868. bfree(remote->buf);
  869. ss_free(remote->buf);
  870. }
  871. ss_free(remote->recv_ctx);
  872. ss_free(remote->send_ctx);
  873. ss_free(remote);
  874. }
  875. static void
  876. close_and_free_remote(EV_P_ remote_t *remote)
  877. {
  878. if (remote != NULL) {
  879. ev_timer_stop(EV_A_ & remote->send_ctx->watcher);
  880. ev_timer_stop(EV_A_ & remote->recv_ctx->watcher);
  881. ev_io_stop(EV_A_ & remote->send_ctx->io);
  882. ev_io_stop(EV_A_ & remote->recv_ctx->io);
  883. close(remote->fd);
  884. free_remote(remote);
  885. }
  886. }
  887. static server_t *
  888. new_server(int fd, int method)
  889. {
  890. server_t *server;
  891. server = ss_malloc(sizeof(server_t));
  892. memset(server, 0, sizeof(server_t));
  893. server->recv_ctx = ss_malloc(sizeof(server_ctx_t));
  894. server->send_ctx = ss_malloc(sizeof(server_ctx_t));
  895. server->buf = ss_malloc(sizeof(buffer_t));
  896. balloc(server->buf, BUF_SIZE);
  897. memset(server->recv_ctx, 0, sizeof(server_ctx_t));
  898. memset(server->send_ctx, 0, sizeof(server_ctx_t));
  899. server->stage = STAGE_INIT;
  900. server->recv_ctx->connected = 0;
  901. server->send_ctx->connected = 0;
  902. server->fd = fd;
  903. server->recv_ctx->server = server;
  904. server->send_ctx->server = server;
  905. if (method) {
  906. server->e_ctx = ss_malloc(sizeof(struct enc_ctx));
  907. server->d_ctx = ss_malloc(sizeof(struct enc_ctx));
  908. enc_ctx_init(method, server->e_ctx, 1);
  909. enc_ctx_init(method, server->d_ctx, 0);
  910. } else {
  911. server->e_ctx = NULL;
  912. server->d_ctx = NULL;
  913. }
  914. ev_io_init(&server->recv_ctx->io, server_recv_cb, fd, EV_READ);
  915. ev_io_init(&server->send_ctx->io, server_send_cb, fd, EV_WRITE);
  916. cork_dllist_add(&connections, &server->entries);
  917. return server;
  918. }
  919. static void
  920. free_server(server_t *server)
  921. {
  922. cork_dllist_remove(&server->entries);
  923. if (server->remote != NULL) {
  924. server->remote->server = NULL;
  925. }
  926. if (server->e_ctx != NULL) {
  927. cipher_context_release(&server->e_ctx->evp);
  928. ss_free(server->e_ctx);
  929. }
  930. if (server->d_ctx != NULL) {
  931. cipher_context_release(&server->d_ctx->evp);
  932. ss_free(server->d_ctx);
  933. }
  934. if (server->buf != NULL) {
  935. bfree(server->buf);
  936. ss_free(server->buf);
  937. }
  938. ss_free(server->recv_ctx);
  939. ss_free(server->send_ctx);
  940. ss_free(server);
  941. }
  942. static void
  943. close_and_free_server(EV_P_ server_t *server)
  944. {
  945. if (server != NULL) {
  946. ev_io_stop(EV_A_ & server->send_ctx->io);
  947. ev_io_stop(EV_A_ & server->recv_ctx->io);
  948. close(server->fd);
  949. free_server(server);
  950. }
  951. }
  952. static remote_t *
  953. create_remote(listen_ctx_t *listener,
  954. struct sockaddr *addr)
  955. {
  956. struct sockaddr *remote_addr;
  957. int index = rand() % listener->remote_num;
  958. if (addr == NULL) {
  959. remote_addr = listener->remote_addr[index];
  960. } else {
  961. remote_addr = addr;
  962. }
  963. int remotefd = socket(remote_addr->sa_family, SOCK_STREAM, IPPROTO_TCP);
  964. if (remotefd == -1) {
  965. ERROR("socket");
  966. return NULL;
  967. }
  968. int opt = 1;
  969. setsockopt(remotefd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
  970. #ifdef SO_NOSIGPIPE
  971. setsockopt(remotefd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
  972. #endif
  973. if (listener->mptcp == 1) {
  974. int err = setsockopt(remotefd, SOL_TCP, MPTCP_ENABLED, &opt, sizeof(opt));
  975. if (err == -1) {
  976. ERROR("failed to enable multipath TCP");
  977. }
  978. }
  979. // Setup
  980. setnonblocking(remotefd);
  981. #ifdef SET_INTERFACE
  982. if (listener->iface) {
  983. if (setinterface(remotefd, listener->iface) == -1)
  984. ERROR("setinterface");
  985. }
  986. #endif
  987. remote_t *remote = new_remote(remotefd, listener->timeout);
  988. remote->addr_len = get_sockaddr_len(remote_addr);
  989. memcpy(&(remote->addr), remote_addr, remote->addr_len);
  990. return remote;
  991. }
  992. static void
  993. signal_cb(EV_P_ ev_signal *w, int revents)
  994. {
  995. if (revents & EV_SIGNAL) {
  996. switch (w->signum) {
  997. #ifndef __MINGW32__
  998. case SIGCHLD:
  999. if (!is_plugin_running())
  1000. LOGE("plugin service exit unexpectedly");
  1001. else
  1002. return;
  1003. case SIGUSR1:
  1004. #endif
  1005. case SIGINT:
  1006. case SIGTERM:
  1007. ev_signal_stop(EV_DEFAULT, &sigint_watcher);
  1008. ev_signal_stop(EV_DEFAULT, &sigterm_watcher);
  1009. #ifndef __MINGW32__
  1010. ev_signal_stop(EV_DEFAULT, &sigchld_watcher);
  1011. ev_signal_stop(EV_DEFAULT, &sigusr1_watcher);
  1012. #endif
  1013. keep_resolving = 0;
  1014. ev_unloop(EV_A_ EVUNLOOP_ALL);
  1015. }
  1016. }
  1017. }
  1018. void
  1019. accept_cb(EV_P_ ev_io *w, int revents)
  1020. {
  1021. listen_ctx_t *listener = (listen_ctx_t *)w;
  1022. int serverfd = accept(listener->fd, NULL, NULL);
  1023. if (serverfd == -1) {
  1024. ERROR("accept");
  1025. return;
  1026. }
  1027. setnonblocking(serverfd);
  1028. int opt = 1;
  1029. setsockopt(serverfd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
  1030. #ifdef SO_NOSIGPIPE
  1031. setsockopt(serverfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
  1032. #endif
  1033. server_t *server = new_server(serverfd, listener->method);
  1034. server->listener = listener;
  1035. ev_io_start(EV_A_ & server->recv_ctx->io);
  1036. }
  1037. #ifndef LIB_ONLY
  1038. int
  1039. main(int argc, char **argv)
  1040. {
  1041. int i, c;
  1042. int pid_flags = 0;
  1043. int mtu = 0;
  1044. int mptcp = 0;
  1045. char *user = NULL;
  1046. char *local_port = NULL;
  1047. char *local_addr = NULL;
  1048. char *password = NULL;
  1049. char *timeout = NULL;
  1050. char *method = NULL;
  1051. char *pid_path = NULL;
  1052. char *conf_path = NULL;
  1053. char *iface = NULL;
  1054. char *plugin = NULL;
  1055. char *plugin_opts = NULL;
  1056. char *plugin_host = NULL;
  1057. char *plugin_port = NULL;
  1058. char tmp_port[8];
  1059. srand(time(NULL));
  1060. int remote_num = 0;
  1061. ss_addr_t remote_addr[MAX_REMOTE_NUM];
  1062. char *remote_port = NULL;
  1063. int option_index = 0;
  1064. static struct option long_options[] = {
  1065. { "fast-open", no_argument, 0, 0 },
  1066. { "acl", required_argument, 0, 0 },
  1067. { "mtu", required_argument, 0, 0 },
  1068. { "mptcp", no_argument, 0, 0 },
  1069. { "plugin", required_argument, 0, 0 },
  1070. { "plugin-opts", required_argument, 0, 0 },
  1071. { "help", no_argument, 0, 0 },
  1072. { 0, 0, 0, 0 }
  1073. };
  1074. opterr = 0;
  1075. USE_TTY();
  1076. #ifdef ANDROID
  1077. while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:a:n:P:huUvVA6",
  1078. long_options, &option_index)) != -1) {
  1079. #else
  1080. while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:a:n:huUvA6",
  1081. long_options, &option_index)) != -1) {
  1082. #endif
  1083. switch (c) {
  1084. case 0:
  1085. if (option_index == 0) {
  1086. fast_open = 1;
  1087. } else if (option_index == 1) {
  1088. LOGI("initializing acl...");
  1089. acl = !init_acl(optarg);
  1090. } else if (option_index == 2) {
  1091. mtu = atoi(optarg);
  1092. LOGI("set MTU to %d", mtu);
  1093. } else if (option_index == 3) {
  1094. mptcp = 1;
  1095. LOGI("enable multipath TCP");
  1096. } else if (option_index == 4) {
  1097. plugin = optarg;
  1098. } else if (option_index == 5) {
  1099. plugin_opts = optarg;
  1100. } else if (option_index == 6) {
  1101. usage();
  1102. exit(EXIT_SUCCESS);
  1103. }
  1104. break;
  1105. case 's':
  1106. if (remote_num < MAX_REMOTE_NUM) {
  1107. remote_addr[remote_num].host = optarg;
  1108. remote_addr[remote_num++].port = NULL;
  1109. }
  1110. break;
  1111. case 'p':
  1112. remote_port = optarg;
  1113. break;
  1114. case 'l':
  1115. local_port = optarg;
  1116. break;
  1117. case 'k':
  1118. password = optarg;
  1119. break;
  1120. case 'f':
  1121. pid_flags = 1;
  1122. pid_path = optarg;
  1123. break;
  1124. case 't':
  1125. timeout = optarg;
  1126. break;
  1127. case 'm':
  1128. method = optarg;
  1129. break;
  1130. case 'c':
  1131. conf_path = optarg;
  1132. break;
  1133. case 'i':
  1134. iface = optarg;
  1135. break;
  1136. case 'b':
  1137. local_addr = optarg;
  1138. break;
  1139. case 'a':
  1140. user = optarg;
  1141. break;
  1142. #ifdef HAVE_SETRLIMIT
  1143. case 'n':
  1144. nofile = atoi(optarg);
  1145. break;
  1146. #endif
  1147. case 'u':
  1148. mode = TCP_AND_UDP;
  1149. break;
  1150. case 'U':
  1151. mode = UDP_ONLY;
  1152. break;
  1153. case 'v':
  1154. verbose = 1;
  1155. break;
  1156. case 'h':
  1157. usage();
  1158. exit(EXIT_SUCCESS);
  1159. case 'A':
  1160. auth = 1;
  1161. break;
  1162. case '6':
  1163. ipv6first = 1;
  1164. break;
  1165. #ifdef ANDROID
  1166. case 'V':
  1167. vpn = 1;
  1168. break;
  1169. case 'P':
  1170. prefix = optarg;
  1171. break;
  1172. #endif
  1173. case '?':
  1174. // The option character is not recognized.
  1175. LOGE("Unrecognized option: %s", optarg);
  1176. opterr = 1;
  1177. break;
  1178. }
  1179. }
  1180. if (opterr) {
  1181. usage();
  1182. exit(EXIT_FAILURE);
  1183. }
  1184. if (argc == 1) {
  1185. if (conf_path == NULL) {
  1186. conf_path = DEFAULT_CONF_PATH;
  1187. }
  1188. }
  1189. if (conf_path != NULL) {
  1190. jconf_t *conf = read_jconf(conf_path);
  1191. if (remote_num == 0) {
  1192. remote_num = conf->remote_num;
  1193. for (i = 0; i < remote_num; i++)
  1194. remote_addr[i] = conf->remote_addr[i];
  1195. }
  1196. if (remote_port == NULL) {
  1197. remote_port = conf->remote_port;
  1198. }
  1199. if (local_addr == NULL) {
  1200. local_addr = conf->local_addr;
  1201. }
  1202. if (local_port == NULL) {
  1203. local_port = conf->local_port;
  1204. }
  1205. if (password == NULL) {
  1206. password = conf->password;
  1207. }
  1208. if (method == NULL) {
  1209. method = conf->method;
  1210. }
  1211. if (timeout == NULL) {
  1212. timeout = conf->timeout;
  1213. }
  1214. if (user == NULL) {
  1215. user = conf->user;
  1216. }
  1217. if (plugin == NULL) {
  1218. plugin = conf->plugin;
  1219. }
  1220. if (plugin_opts == NULL) {
  1221. plugin_opts = conf->plugin_opts;
  1222. }
  1223. if (auth == 0) {
  1224. auth = conf->auth;
  1225. }
  1226. if (fast_open == 0) {
  1227. fast_open = conf->fast_open;
  1228. }
  1229. if (mode == TCP_ONLY) {
  1230. mode = conf->mode;
  1231. }
  1232. if (mtu == 0) {
  1233. mtu = conf->mtu;
  1234. }
  1235. if (mptcp == 0) {
  1236. mptcp = conf->mptcp;
  1237. }
  1238. #ifdef HAVE_SETRLIMIT
  1239. if (nofile == 0) {
  1240. nofile = conf->nofile;
  1241. }
  1242. #endif
  1243. }
  1244. if (remote_num == 0 || remote_port == NULL ||
  1245. #ifndef HAVE_LAUNCHD
  1246. local_port == NULL ||
  1247. #endif
  1248. password == NULL) {
  1249. usage();
  1250. exit(EXIT_FAILURE);
  1251. }
  1252. if (plugin != NULL) {
  1253. uint16_t port = get_local_port();
  1254. if (port == 0) {
  1255. FATAL("failed to find a free port");
  1256. }
  1257. snprintf(tmp_port, 8, "%d", port);
  1258. plugin_host = "127.0.0.1";
  1259. plugin_port = tmp_port;
  1260. LOGI("plugin \"%s\" enabled", plugin);
  1261. }
  1262. if (method == NULL) {
  1263. method = "rc4-md5";
  1264. }
  1265. if (timeout == NULL) {
  1266. timeout = "60";
  1267. }
  1268. #ifdef HAVE_SETRLIMIT
  1269. /*
  1270. * no need to check the return value here since we will show
  1271. * the user an error message if setrlimit(2) fails
  1272. */
  1273. if (nofile > 1024) {
  1274. if (verbose) {
  1275. LOGI("setting NOFILE to %d", nofile);
  1276. }
  1277. set_nofile(nofile);
  1278. }
  1279. #endif
  1280. if (local_addr == NULL) {
  1281. local_addr = "127.0.0.1";
  1282. }
  1283. if (pid_flags) {
  1284. USE_SYSLOG(argv[0]);
  1285. daemonize(pid_path);
  1286. }
  1287. if (fast_open == 1) {
  1288. #ifdef TCP_FASTOPEN
  1289. LOGI("using tcp fast open");
  1290. #else
  1291. LOGE("tcp fast open is not supported by this environment");
  1292. fast_open = 0;
  1293. #endif
  1294. }
  1295. if (ipv6first) {
  1296. LOGI("resolving hostname to IPv6 address first");
  1297. }
  1298. if (auth) {
  1299. LOGI("onetime authentication enabled");
  1300. }
  1301. if (plugin != NULL) {
  1302. int len = 0;
  1303. size_t buf_size = 256 * remote_num;
  1304. char *remote_str = ss_malloc(buf_size);
  1305. snprintf(remote_str, buf_size, "%s", remote_addr[0].host);
  1306. len = strlen(remote_str);
  1307. for (int i = 1; i < remote_num; i++) {
  1308. snprintf(remote_str + len, buf_size - len, "|%s", remote_addr[i].host);
  1309. len = strlen(remote_str);
  1310. }
  1311. int err = start_plugin(plugin, plugin_opts, remote_str,
  1312. remote_port, plugin_host, plugin_port);
  1313. if (err) {
  1314. FATAL("failed to start the plugin");
  1315. }
  1316. }
  1317. #ifdef __MINGW32__
  1318. winsock_init();
  1319. #else
  1320. // ignore SIGPIPE
  1321. signal(SIGPIPE, SIG_IGN);
  1322. signal(SIGABRT, SIG_IGN);
  1323. #endif
  1324. // Setup keys
  1325. LOGI("initializing ciphers... %s", method);
  1326. int m = enc_init(password, method);
  1327. // Setup proxy context
  1328. listen_ctx_t listen_ctx;
  1329. listen_ctx.remote_num = remote_num;
  1330. listen_ctx.remote_addr = ss_malloc(sizeof(struct sockaddr *) * remote_num);
  1331. memset(listen_ctx.remote_addr, 0, sizeof(struct sockaddr *) * remote_num);
  1332. for (i = 0; i < remote_num; i++) {
  1333. char *host = remote_addr[i].host;
  1334. char *port = remote_addr[i].port == NULL ? remote_port :
  1335. remote_addr[i].port;
  1336. if (plugin != NULL) {
  1337. host = plugin_host;
  1338. port = plugin_port;
  1339. }
  1340. struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
  1341. memset(storage, 0, sizeof(struct sockaddr_storage));
  1342. if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
  1343. FATAL("failed to resolve the provided hostname");
  1344. }
  1345. listen_ctx.remote_addr[i] = (struct sockaddr *)storage;
  1346. if (plugin != NULL) break;
  1347. }
  1348. listen_ctx.timeout = atoi(timeout);
  1349. listen_ctx.iface = iface;
  1350. listen_ctx.method = m;
  1351. listen_ctx.mptcp = mptcp;
  1352. // Setup signal handler
  1353. ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
  1354. ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
  1355. ev_signal_start(EV_DEFAULT, &sigint_watcher);
  1356. ev_signal_start(EV_DEFAULT, &sigterm_watcher);
  1357. #ifndef __MINGW32__
  1358. ev_signal_init(&sigchld_watcher, signal_cb, SIGCHLD);
  1359. ev_signal_start(EV_DEFAULT, &sigchld_watcher);
  1360. #endif
  1361. struct ev_loop *loop = EV_DEFAULT;
  1362. if (mode != UDP_ONLY) {
  1363. // Setup socket
  1364. int listenfd;
  1365. #ifdef HAVE_LAUNCHD
  1366. listenfd = launch_or_create(local_addr, local_port);
  1367. #else
  1368. listenfd = create_and_bind(local_addr, local_port);
  1369. #endif
  1370. if (listenfd == -1) {
  1371. FATAL("bind() error");
  1372. }
  1373. if (listen(listenfd, SOMAXCONN) == -1) {
  1374. FATAL("listen() error");
  1375. }
  1376. setnonblocking(listenfd);
  1377. listen_ctx.fd = listenfd;
  1378. ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
  1379. ev_io_start(loop, &listen_ctx.io);
  1380. }
  1381. // Setup UDP
  1382. if (mode != TCP_ONLY) {
  1383. LOGI("udprelay enabled");
  1384. char *host = remote_addr[0].host;
  1385. char *port = remote_addr[0].port == NULL ? remote_port : remote_addr[0].port;
  1386. struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
  1387. memset(storage, 0, sizeof(struct sockaddr_storage));
  1388. if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
  1389. FATAL("failed to resolve the provided hostname");
  1390. }
  1391. struct sockaddr *addr = (struct sockaddr *)storage;
  1392. init_udprelay(local_addr, local_port, addr,
  1393. get_sockaddr_len(addr), mtu, m, auth, listen_ctx.timeout, iface);
  1394. }
  1395. #ifdef HAVE_LAUNCHD
  1396. if (local_port == NULL)
  1397. LOGI("listening through launchd");
  1398. else
  1399. #endif
  1400. if (strcmp(local_addr, ":") > 0)
  1401. LOGI("listening at [%s]:%s", local_addr, local_port);
  1402. else
  1403. LOGI("listening at %s:%s", local_addr, local_port);
  1404. // setuid
  1405. if (user != NULL && !run_as(user)) {
  1406. FATAL("failed to switch user");
  1407. }
  1408. #ifndef __MINGW32__
  1409. if (geteuid() == 0) {
  1410. LOGI("running from root user");
  1411. }
  1412. #endif
  1413. // Init connections
  1414. cork_dllist_init(&connections);
  1415. // Enter the loop
  1416. ev_run(loop, 0);
  1417. if (verbose) {
  1418. LOGI("closed gracefully");
  1419. }
  1420. // Clean up
  1421. if (plugin != NULL) {
  1422. stop_plugin();
  1423. }
  1424. if (mode != UDP_ONLY) {
  1425. ev_io_stop(loop, &listen_ctx.io);
  1426. free_connections(loop);
  1427. for (i = 0; i < remote_num; i++)
  1428. ss_free(listen_ctx.remote_addr[i]);
  1429. ss_free(listen_ctx.remote_addr);
  1430. }
  1431. if (mode != TCP_ONLY) {
  1432. free_udprelay();
  1433. }
  1434. #ifdef __MINGW32__
  1435. winsock_cleanup();
  1436. #endif
  1437. return 0;
  1438. }
  1439. #else
  1440. int
  1441. start_ss_local_server(profile_t profile)
  1442. {
  1443. srand(time(NULL));
  1444. char *remote_host = profile.remote_host;
  1445. char *local_addr = profile.local_addr;
  1446. char *method = profile.method;
  1447. char *password = profile.password;
  1448. char *log = profile.log;
  1449. int remote_port = profile.remote_port;
  1450. int local_port = profile.local_port;
  1451. int timeout = profile.timeout;
  1452. int mtu = 0;
  1453. int mptcp = 0;
  1454. auth = profile.auth;
  1455. mode = profile.mode;
  1456. fast_open = profile.fast_open;
  1457. verbose = profile.verbose;
  1458. mtu = profile.mtu;
  1459. mptcp = profile.mptcp;
  1460. char local_port_str[16];
  1461. char remote_port_str[16];
  1462. sprintf(local_port_str, "%d", local_port);
  1463. sprintf(remote_port_str, "%d", remote_port);
  1464. USE_LOGFILE(log);
  1465. if (profile.acl != NULL) {
  1466. acl = !init_acl(profile.acl);
  1467. }
  1468. if (local_addr == NULL) {
  1469. local_addr = "127.0.0.1";
  1470. }
  1471. #ifdef __MINGW32__
  1472. winsock_init();
  1473. #else
  1474. // ignore SIGPIPE
  1475. signal(SIGPIPE, SIG_IGN);
  1476. signal(SIGABRT, SIG_IGN);
  1477. #endif
  1478. ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
  1479. ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
  1480. ev_signal_start(EV_DEFAULT, &sigint_watcher);
  1481. ev_signal_start(EV_DEFAULT, &sigterm_watcher);
  1482. #ifndef __MINGW32__
  1483. ev_signal_init(&sigusr1_watcher, signal_cb, SIGUSR1);
  1484. ev_signal_init(&sigchld_watcher, signal_cb, SIGCHLD);
  1485. ev_signal_start(EV_DEFAULT, &sigusr1_watcher);
  1486. ev_signal_start(EV_DEFAULT, &sigchld_watcher);
  1487. #endif
  1488. // Setup keys
  1489. LOGI("initializing ciphers... %s", method);
  1490. int m = enc_init(password, method);
  1491. struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
  1492. memset(storage, 0, sizeof(struct sockaddr_storage));
  1493. if (get_sockaddr(remote_host, remote_port_str, storage, 0, ipv6first) == -1) {
  1494. return -1;
  1495. }
  1496. // Setup proxy context
  1497. struct ev_loop *loop = EV_DEFAULT;
  1498. struct sockaddr **remote_addr_tmp = ss_malloc(sizeof(struct sockaddr *));
  1499. listen_ctx_t listen_ctx;
  1500. listen_ctx.remote_num = 1;
  1501. listen_ctx.remote_addr = remote_addr_tmp;
  1502. listen_ctx.remote_addr[0] = (struct sockaddr *)storage;
  1503. listen_ctx.timeout = timeout;
  1504. listen_ctx.method = m;
  1505. listen_ctx.iface = NULL;
  1506. listen_ctx.mptcp = mptcp;
  1507. if (mode != UDP_ONLY) {
  1508. // Setup socket
  1509. int listenfd;
  1510. listenfd = create_and_bind(local_addr, local_port_str);
  1511. if (listenfd == -1) {
  1512. ERROR("bind()");
  1513. return -1;
  1514. }
  1515. if (listen(listenfd, SOMAXCONN) == -1) {
  1516. ERROR("listen()");
  1517. return -1;
  1518. }
  1519. setnonblocking(listenfd);
  1520. listen_ctx.fd = listenfd;
  1521. ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
  1522. ev_io_start(loop, &listen_ctx.io);
  1523. }
  1524. // Setup UDP
  1525. if (mode != TCP_ONLY) {
  1526. LOGI("udprelay enabled");
  1527. struct sockaddr *addr = (struct sockaddr *)storage;
  1528. init_udprelay(local_addr, local_port_str, addr,
  1529. get_sockaddr_len(addr), mtu, m, auth, timeout, NULL);
  1530. }
  1531. if (strcmp(local_addr, ":") > 0)
  1532. LOGI("listening at [%s]:%s", local_addr, local_port_str);
  1533. else
  1534. LOGI("listening at %s:%s", local_addr, local_port_str);
  1535. // Init connections
  1536. cork_dllist_init(&connections);
  1537. // Enter the loop
  1538. ev_run(loop, 0);
  1539. if (verbose) {
  1540. LOGI("closed gracefully");
  1541. }
  1542. // Clean up
  1543. if (mode != TCP_ONLY) {
  1544. free_udprelay();
  1545. }
  1546. if (mode != UDP_ONLY) {
  1547. ev_io_stop(loop, &listen_ctx.io);
  1548. free_connections(loop);
  1549. close(listen_ctx.fd);
  1550. }
  1551. ss_free(listen_ctx.remote_addr[0]);
  1552. ss_free(remote_addr_tmp);
  1553. #ifdef __MINGW32__
  1554. winsock_cleanup();
  1555. #endif
  1556. // cannot reach here
  1557. return 0;
  1558. }
  1559. #endif