BSocksClient.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. /**
  2. * @file BSocksClient.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <misc/byteorder.h>
  30. #include <misc/balloc.h>
  31. #include <base/BLog.h>
  32. #include <socksclient/BSocksClient.h>
  33. #include <generated/blog_channel_BSocksClient.h>
  34. #define STATE_CONNECTING 1
  35. #define STATE_SENDING_HELLO 2
  36. #define STATE_SENT_HELLO 3
  37. #define STATE_SENDING_PASSWORD 10
  38. #define STATE_SENT_PASSWORD 11
  39. #define STATE_SENDING_REQUEST 4
  40. #define STATE_SENT_REQUEST 5
  41. #define STATE_RECEIVED_REPLY_HEADER 6
  42. #define STATE_UP 7
  43. static void report_error (BSocksClient *o, int error);
  44. static void init_control_io (BSocksClient *o);
  45. static void free_control_io (BSocksClient *o);
  46. static void init_up_io (BSocksClient *o);
  47. static void free_up_io (BSocksClient *o);
  48. static int reserve_buffer (BSocksClient *o, bsize_t size);
  49. static void start_receive (BSocksClient *o, uint8_t *dest, int total);
  50. static void do_receive (BSocksClient *o);
  51. static void connector_handler (BSocksClient* o, int is_error);
  52. static void connection_handler (BSocksClient* o, int event);
  53. static void recv_handler_done (BSocksClient *o, int data_len);
  54. static void send_handler_done (BSocksClient *o);
  55. static void auth_finished (BSocksClient *p);
  56. void report_error (BSocksClient *o, int error)
  57. {
  58. DEBUGERROR(&o->d_err, o->handler(o->user, error))
  59. }
  60. void init_control_io (BSocksClient *o)
  61. {
  62. // init receiving
  63. BConnection_RecvAsync_Init(&o->con);
  64. o->control.recv_if = BConnection_RecvAsync_GetIf(&o->con);
  65. StreamRecvInterface_Receiver_Init(o->control.recv_if, (StreamRecvInterface_handler_done)recv_handler_done, o);
  66. // init sending
  67. BConnection_SendAsync_Init(&o->con);
  68. PacketStreamSender_Init(&o->control.send_sender, BConnection_SendAsync_GetIf(&o->con), INT_MAX, BReactor_PendingGroup(o->reactor));
  69. o->control.send_if = PacketStreamSender_GetInput(&o->control.send_sender);
  70. PacketPassInterface_Sender_Init(o->control.send_if, (PacketPassInterface_handler_done)send_handler_done, o);
  71. }
  72. void free_control_io (BSocksClient *o)
  73. {
  74. // free sending
  75. PacketStreamSender_Free(&o->control.send_sender);
  76. BConnection_SendAsync_Free(&o->con);
  77. // free receiving
  78. BConnection_RecvAsync_Free(&o->con);
  79. }
  80. void init_up_io (BSocksClient *o)
  81. {
  82. // init receiving
  83. BConnection_RecvAsync_Init(&o->con);
  84. // init sending
  85. BConnection_SendAsync_Init(&o->con);
  86. }
  87. void free_up_io (BSocksClient *o)
  88. {
  89. // free sending
  90. BConnection_SendAsync_Free(&o->con);
  91. // free receiving
  92. BConnection_RecvAsync_Free(&o->con);
  93. }
  94. int reserve_buffer (BSocksClient *o, bsize_t size)
  95. {
  96. if (size.is_overflow) {
  97. BLog(BLOG_ERROR, "size overflow");
  98. return 0;
  99. }
  100. char *buffer = BRealloc(o->buffer, size.value);
  101. if (!buffer) {
  102. BLog(BLOG_ERROR, "BRealloc failed");
  103. return 0;
  104. }
  105. o->buffer = buffer;
  106. return 1;
  107. }
  108. void start_receive (BSocksClient *o, uint8_t *dest, int total)
  109. {
  110. ASSERT(total > 0)
  111. o->control.recv_dest = dest;
  112. o->control.recv_len = 0;
  113. o->control.recv_total = total;
  114. do_receive(o);
  115. }
  116. void do_receive (BSocksClient *o)
  117. {
  118. ASSERT(o->control.recv_len < o->control.recv_total)
  119. StreamRecvInterface_Receiver_Recv(o->control.recv_if, o->control.recv_dest + o->control.recv_len, o->control.recv_total - o->control.recv_len);
  120. }
  121. void connector_handler (BSocksClient* o, int is_error)
  122. {
  123. DebugObject_Access(&o->d_obj);
  124. ASSERT(o->state == STATE_CONNECTING)
  125. // check connection result
  126. if (is_error) {
  127. BLog(BLOG_ERROR, "connection failed");
  128. goto fail0;
  129. }
  130. // init connection
  131. if (!BConnection_Init(&o->con, BConnection_source_connector(&o->connector), o->reactor, o, (BConnection_handler)connection_handler)) {
  132. BLog(BLOG_ERROR, "BConnection_Init failed");
  133. goto fail0;
  134. }
  135. BLog(BLOG_DEBUG, "connected");
  136. // init control I/O
  137. init_control_io(o);
  138. // check number of methods
  139. if (o->num_auth_info == 0 || o->num_auth_info > 255) {
  140. BLog(BLOG_ERROR, "invalid number of authentication methods");
  141. goto fail1;
  142. }
  143. // allocate buffer for sending hello
  144. bsize_t size = bsize_add(
  145. bsize_fromsize(sizeof(struct BSocksClient__client_hello)),
  146. bsize_mul(
  147. bsize_fromsize(o->num_auth_info),
  148. bsize_fromsize(sizeof(struct socks_client_hello_method))
  149. )
  150. );
  151. if (!reserve_buffer(o, size)) {
  152. goto fail1;
  153. }
  154. // build hello
  155. struct BSocksClient__client_hello *omsg = (void *)o->buffer;
  156. omsg->header.ver = hton8(SOCKS_VERSION);
  157. omsg->header.nmethods = hton8(o->num_auth_info);
  158. for (size_t i = 0; i < o->num_auth_info; i++) {
  159. omsg->methods[i].method = hton8(o->auth_info[i].auth_type);
  160. }
  161. // send
  162. PacketPassInterface_Sender_Send(o->control.send_if, (uint8_t *)o->buffer, size.value);
  163. // set state
  164. o->state = STATE_SENDING_HELLO;
  165. return;
  166. fail1:
  167. free_control_io(o);
  168. fail0:
  169. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  170. return;
  171. }
  172. void connection_handler (BSocksClient* o, int event)
  173. {
  174. DebugObject_Access(&o->d_obj);
  175. ASSERT(o->state != STATE_CONNECTING)
  176. if (o->state == STATE_UP && event == BCONNECTION_EVENT_RECVCLOSED) {
  177. report_error(o, BSOCKSCLIENT_EVENT_ERROR_CLOSED);
  178. return;
  179. }
  180. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  181. return;
  182. }
  183. void recv_handler_done (BSocksClient *o, int data_len)
  184. {
  185. ASSERT(data_len >= 0)
  186. ASSERT(data_len <= o->control.recv_total - o->control.recv_len)
  187. DebugObject_Access(&o->d_obj);
  188. o->control.recv_len += data_len;
  189. if (o->control.recv_len < o->control.recv_total) {
  190. do_receive(o);
  191. return;
  192. }
  193. switch (o->state) {
  194. case STATE_SENT_HELLO: {
  195. BLog(BLOG_DEBUG, "received hello");
  196. struct socks_server_hello *imsg = (void *)o->buffer;
  197. if (ntoh8(imsg->ver) != SOCKS_VERSION) {
  198. BLog(BLOG_NOTICE, "wrong version");
  199. goto fail;
  200. }
  201. size_t auth_index;
  202. for (auth_index = 0; auth_index < o->num_auth_info; auth_index++) {
  203. if (o->auth_info[auth_index].auth_type == ntoh8(imsg->method)) {
  204. break;
  205. }
  206. }
  207. if (auth_index == o->num_auth_info) {
  208. BLog(BLOG_NOTICE, "server didn't accept any authentication method");
  209. goto fail;
  210. }
  211. const struct BSocksClient_auth_info *ai = &o->auth_info[auth_index];
  212. switch (ai->auth_type) {
  213. case SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED: {
  214. BLog(BLOG_DEBUG, "no authentication");
  215. auth_finished(o);
  216. } break;
  217. case SOCKS_METHOD_USERNAME_PASSWORD: {
  218. BLog(BLOG_DEBUG, "password authentication");
  219. if (ai->password.username_len == 0 || ai->password.username_len > 255 ||
  220. ai->password.password_len == 0 || ai->password.password_len > 255
  221. ) {
  222. BLog(BLOG_NOTICE, "invalid username/password length");
  223. goto fail;
  224. }
  225. // allocate password packet
  226. bsize_t size = bsize_fromsize(1 + 1 + ai->password.username_len + 1 + ai->password.password_len);
  227. if (!reserve_buffer(o, size)) {
  228. goto fail;
  229. }
  230. // write password packet
  231. char *ptr = o->buffer;
  232. *ptr++ = 1;
  233. *ptr++ = ai->password.username_len;
  234. memcpy(ptr, ai->password.username, ai->password.username_len);
  235. ptr += ai->password.username_len;
  236. *ptr++ = ai->password.password_len;
  237. memcpy(ptr, ai->password.password, ai->password.password_len);
  238. ptr += ai->password.password_len;
  239. // start sending
  240. PacketPassInterface_Sender_Send(o->control.send_if, (uint8_t *)o->buffer, size.value);
  241. // set state
  242. o->state = STATE_SENDING_PASSWORD;
  243. } break;
  244. default: ASSERT(0);
  245. }
  246. } break;
  247. case STATE_SENT_REQUEST: {
  248. BLog(BLOG_DEBUG, "received reply header");
  249. struct BSocksClient__reply *imsg = (void *)o->buffer;
  250. if (ntoh8(imsg->header.ver) != SOCKS_VERSION) {
  251. BLog(BLOG_NOTICE, "wrong version");
  252. goto fail;
  253. }
  254. if (ntoh8(imsg->header.rep) != SOCKS_REP_SUCCEEDED) {
  255. BLog(BLOG_NOTICE, "reply not successful");
  256. goto fail;
  257. }
  258. int addr_len;
  259. switch (ntoh8(imsg->header.atyp)) {
  260. case SOCKS_ATYP_IPV4:
  261. addr_len = sizeof(struct socks_addr_ipv4);
  262. break;
  263. case SOCKS_ATYP_IPV6:
  264. addr_len = sizeof(struct socks_addr_ipv6);
  265. break;
  266. default:
  267. BLog(BLOG_NOTICE, "reply has unknown address type");
  268. goto fail;
  269. }
  270. // receive the rest of the reply
  271. start_receive(o, (uint8_t *)&imsg->addr, addr_len);
  272. // set state
  273. o->state = STATE_RECEIVED_REPLY_HEADER;
  274. } break;
  275. case STATE_SENT_PASSWORD: {
  276. BLog(BLOG_DEBUG, "received password reply");
  277. if (o->buffer[0] != 1) {
  278. BLog(BLOG_NOTICE, "password reply has unknown version");
  279. goto fail;
  280. }
  281. if (o->buffer[1] != 0) {
  282. BLog(BLOG_NOTICE, "password reply is negative");
  283. goto fail;
  284. }
  285. auth_finished(o);
  286. } break;
  287. case STATE_RECEIVED_REPLY_HEADER: {
  288. BLog(BLOG_DEBUG, "received reply rest");
  289. // free buffer
  290. BFree(o->buffer);
  291. o->buffer = NULL;
  292. // free control I/O
  293. free_control_io(o);
  294. // init up I/O
  295. init_up_io(o);
  296. // set state
  297. o->state = STATE_UP;
  298. // call handler
  299. o->handler(o->user, BSOCKSCLIENT_EVENT_UP);
  300. return;
  301. } break;
  302. default:
  303. ASSERT(0);
  304. }
  305. return;
  306. fail:
  307. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  308. }
  309. void send_handler_done (BSocksClient *o)
  310. {
  311. DebugObject_Access(&o->d_obj);
  312. ASSERT(o->buffer)
  313. switch (o->state) {
  314. case STATE_SENDING_HELLO: {
  315. BLog(BLOG_DEBUG, "sent hello");
  316. // allocate buffer for receiving hello
  317. bsize_t size = bsize_fromsize(sizeof(struct socks_server_hello));
  318. if (!reserve_buffer(o, size)) {
  319. goto fail;
  320. }
  321. // receive hello
  322. start_receive(o, (uint8_t *)o->buffer, size.value);
  323. // set state
  324. o->state = STATE_SENT_HELLO;
  325. } break;
  326. case STATE_SENDING_REQUEST: {
  327. BLog(BLOG_DEBUG, "sent request");
  328. // allocate buffer for receiving reply
  329. bsize_t size = bsize_fromsize(sizeof(struct BSocksClient__reply));
  330. if (!reserve_buffer(o, size)) {
  331. goto fail;
  332. }
  333. // receive reply header
  334. start_receive(o, (uint8_t *)o->buffer, sizeof(struct socks_reply_header));
  335. // set state
  336. o->state = STATE_SENT_REQUEST;
  337. } break;
  338. case STATE_SENDING_PASSWORD: {
  339. BLog(BLOG_DEBUG, "send password");
  340. // allocate buffer for receiving reply
  341. bsize_t size = bsize_fromsize(2);
  342. if (!reserve_buffer(o, size)) {
  343. goto fail;
  344. }
  345. // receive reply header
  346. start_receive(o, (uint8_t *)o->buffer, size.value);
  347. // set state
  348. o->state = STATE_SENT_PASSWORD;
  349. } break;
  350. default:
  351. ASSERT(0);
  352. }
  353. return;
  354. fail:
  355. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  356. }
  357. void auth_finished (BSocksClient *o)
  358. {
  359. // allocate request buffer
  360. bsize_t size = bsize_fromsize(sizeof(struct socks_request_header));
  361. switch (o->dest_addr.type) {
  362. case BADDR_TYPE_IPV4: size = bsize_add(size, bsize_fromsize(sizeof(struct socks_addr_ipv4))); break;
  363. case BADDR_TYPE_IPV6: size = bsize_add(size, bsize_fromsize(sizeof(struct socks_addr_ipv6))); break;
  364. }
  365. if (!reserve_buffer(o, size)) {
  366. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  367. return;
  368. }
  369. // send request
  370. struct BSocksClient__request *omsg = (void *)o->buffer;
  371. omsg->header.ver = hton8(SOCKS_VERSION);
  372. omsg->header.cmd = hton8(SOCKS_CMD_CONNECT);
  373. omsg->header.rsv = hton8(0);
  374. switch (o->dest_addr.type) {
  375. case BADDR_TYPE_IPV4:
  376. omsg->header.atyp = hton8(SOCKS_ATYP_IPV4);
  377. omsg->addr.ipv4.addr = o->dest_addr.ipv4.ip;
  378. omsg->addr.ipv4.port = o->dest_addr.ipv4.port;
  379. break;
  380. case BADDR_TYPE_IPV6:
  381. omsg->header.atyp = hton8(SOCKS_ATYP_IPV6);
  382. memcpy(omsg->addr.ipv6.addr, o->dest_addr.ipv6.ip, sizeof(o->dest_addr.ipv6.ip));
  383. omsg->addr.ipv6.port = o->dest_addr.ipv6.port;
  384. break;
  385. default:
  386. ASSERT(0);
  387. }
  388. PacketPassInterface_Sender_Send(o->control.send_if, (uint8_t *)o->buffer, size.value);
  389. // set state
  390. o->state = STATE_SENDING_REQUEST;
  391. }
  392. struct BSocksClient_auth_info BSocksClient_auth_none (void)
  393. {
  394. struct BSocksClient_auth_info info;
  395. info.auth_type = SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED;
  396. return info;
  397. }
  398. struct BSocksClient_auth_info BSocksClient_auth_password (const char *username, size_t username_len, const char *password, size_t password_len)
  399. {
  400. struct BSocksClient_auth_info info;
  401. info.auth_type = SOCKS_METHOD_USERNAME_PASSWORD;
  402. info.password.username = username;
  403. info.password.username_len = username_len;
  404. info.password.password = password;
  405. info.password.password_len = password_len;
  406. return info;
  407. }
  408. int BSocksClient_Init (BSocksClient *o,
  409. BAddr server_addr, const struct BSocksClient_auth_info *auth_info, size_t num_auth_info,
  410. BAddr dest_addr, BSocksClient_handler handler, void *user, BReactor *reactor)
  411. {
  412. ASSERT(!BAddr_IsInvalid(&server_addr))
  413. ASSERT(dest_addr.type == BADDR_TYPE_IPV4 || dest_addr.type == BADDR_TYPE_IPV6)
  414. #ifndef NDEBUG
  415. for (size_t i = 0; i < num_auth_info; i++) {
  416. ASSERT(auth_info[i].auth_type == SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED ||
  417. auth_info[i].auth_type == SOCKS_METHOD_USERNAME_PASSWORD)
  418. }
  419. #endif
  420. // init arguments
  421. o->auth_info = auth_info;
  422. o->num_auth_info = num_auth_info;
  423. o->dest_addr = dest_addr;
  424. o->handler = handler;
  425. o->user = user;
  426. o->reactor = reactor;
  427. // set no buffer
  428. o->buffer = NULL;
  429. // init connector
  430. if (!BConnector_Init(&o->connector, server_addr, o->reactor, o, (BConnector_handler)connector_handler)) {
  431. BLog(BLOG_ERROR, "BConnector_Init failed");
  432. goto fail0;
  433. }
  434. // set state
  435. o->state = STATE_CONNECTING;
  436. DebugError_Init(&o->d_err, BReactor_PendingGroup(o->reactor));
  437. DebugObject_Init(&o->d_obj);
  438. return 1;
  439. fail0:
  440. return 0;
  441. }
  442. void BSocksClient_Free (BSocksClient *o)
  443. {
  444. DebugObject_Free(&o->d_obj);
  445. DebugError_Free(&o->d_err);
  446. if (o->state != STATE_CONNECTING) {
  447. if (o->state == STATE_UP) {
  448. // free up I/O
  449. free_up_io(o);
  450. } else {
  451. // free control I/O
  452. free_control_io(o);
  453. }
  454. // free connection
  455. BConnection_Free(&o->con);
  456. }
  457. // free connector
  458. BConnector_Free(&o->connector);
  459. // free buffer
  460. if (o->buffer) {
  461. BFree(o->buffer);
  462. }
  463. }
  464. StreamPassInterface * BSocksClient_GetSendInterface (BSocksClient *o)
  465. {
  466. ASSERT(o->state == STATE_UP)
  467. DebugObject_Access(&o->d_obj);
  468. return BConnection_SendAsync_GetIf(&o->con);
  469. }
  470. StreamRecvInterface * BSocksClient_GetRecvInterface (BSocksClient *o)
  471. {
  472. ASSERT(o->state == STATE_UP)
  473. DebugObject_Access(&o->d_obj);
  474. return BConnection_RecvAsync_GetIf(&o->con);
  475. }