BSocksClient.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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 <string.h>
  30. #include <misc/byteorder.h>
  31. #include <misc/balloc.h>
  32. #include <base/BLog.h>
  33. #include <socksclient/BSocksClient.h>
  34. #include <generated/blog_channel_BSocksClient.h>
  35. #define STATE_CONNECTING 1
  36. #define STATE_SENDING_HELLO 2
  37. #define STATE_SENT_HELLO 3
  38. #define STATE_SENDING_PASSWORD 10
  39. #define STATE_SENT_PASSWORD 11
  40. #define STATE_SENDING_REQUEST 4
  41. #define STATE_SENT_REQUEST 5
  42. #define STATE_RECEIVED_REPLY_HEADER 6
  43. #define STATE_UP 7
  44. static void report_error (BSocksClient *o, int error);
  45. static void init_control_io (BSocksClient *o);
  46. static void free_control_io (BSocksClient *o);
  47. static void init_up_io (BSocksClient *o);
  48. static void free_up_io (BSocksClient *o);
  49. static int reserve_buffer (BSocksClient *o, bsize_t size);
  50. static void start_receive (BSocksClient *o, uint8_t *dest, int total);
  51. static void do_receive (BSocksClient *o);
  52. static void connector_handler (BSocksClient* o, int is_error);
  53. static void connection_handler (BSocksClient* o, int event);
  54. static void recv_handler_done (BSocksClient *o, int data_len);
  55. static void send_handler_done (BSocksClient *o);
  56. static void auth_finished (BSocksClient *p);
  57. void report_error (BSocksClient *o, int error)
  58. {
  59. DEBUGERROR(&o->d_err, o->handler(o->user, error))
  60. }
  61. void init_control_io (BSocksClient *o)
  62. {
  63. // init receiving
  64. BConnection_RecvAsync_Init(&o->con);
  65. o->control.recv_if = BConnection_RecvAsync_GetIf(&o->con);
  66. StreamRecvInterface_Receiver_Init(o->control.recv_if, (StreamRecvInterface_handler_done)recv_handler_done, o);
  67. // init sending
  68. BConnection_SendAsync_Init(&o->con);
  69. PacketStreamSender_Init(&o->control.send_sender, BConnection_SendAsync_GetIf(&o->con), INT_MAX, BReactor_PendingGroup(o->reactor));
  70. o->control.send_if = PacketStreamSender_GetInput(&o->control.send_sender);
  71. PacketPassInterface_Sender_Init(o->control.send_if, (PacketPassInterface_handler_done)send_handler_done, o);
  72. }
  73. void free_control_io (BSocksClient *o)
  74. {
  75. // free sending
  76. PacketStreamSender_Free(&o->control.send_sender);
  77. BConnection_SendAsync_Free(&o->con);
  78. // free receiving
  79. BConnection_RecvAsync_Free(&o->con);
  80. }
  81. void init_up_io (BSocksClient *o)
  82. {
  83. // init receiving
  84. BConnection_RecvAsync_Init(&o->con);
  85. // init sending
  86. BConnection_SendAsync_Init(&o->con);
  87. }
  88. void free_up_io (BSocksClient *o)
  89. {
  90. // free sending
  91. BConnection_SendAsync_Free(&o->con);
  92. // free receiving
  93. BConnection_RecvAsync_Free(&o->con);
  94. }
  95. int reserve_buffer (BSocksClient *o, bsize_t size)
  96. {
  97. if (size.is_overflow) {
  98. BLog(BLOG_ERROR, "size overflow");
  99. return 0;
  100. }
  101. char *buffer = (char *)BRealloc(o->buffer, size.value);
  102. if (!buffer) {
  103. BLog(BLOG_ERROR, "BRealloc failed");
  104. return 0;
  105. }
  106. o->buffer = buffer;
  107. return 1;
  108. }
  109. void start_receive (BSocksClient *o, uint8_t *dest, int total)
  110. {
  111. ASSERT(total > 0)
  112. o->control.recv_dest = dest;
  113. o->control.recv_len = 0;
  114. o->control.recv_total = total;
  115. do_receive(o);
  116. }
  117. void do_receive (BSocksClient *o)
  118. {
  119. ASSERT(o->control.recv_len < o->control.recv_total)
  120. StreamRecvInterface_Receiver_Recv(o->control.recv_if, o->control.recv_dest + o->control.recv_len, o->control.recv_total - o->control.recv_len);
  121. }
  122. void connector_handler (BSocksClient* o, int is_error)
  123. {
  124. DebugObject_Access(&o->d_obj);
  125. ASSERT(o->state == STATE_CONNECTING)
  126. // check connection result
  127. if (is_error) {
  128. BLog(BLOG_ERROR, "connection failed");
  129. goto fail0;
  130. }
  131. // init connection
  132. if (!BConnection_Init(&o->con, BConnection_source_connector(&o->connector), o->reactor, o, (BConnection_handler)connection_handler)) {
  133. BLog(BLOG_ERROR, "BConnection_Init failed");
  134. goto fail0;
  135. }
  136. BLog(BLOG_DEBUG, "connected");
  137. // init control I/O
  138. init_control_io(o);
  139. // check number of methods
  140. if (o->num_auth_info == 0 || o->num_auth_info > 255) {
  141. BLog(BLOG_ERROR, "invalid number of authentication methods");
  142. goto fail1;
  143. }
  144. // allocate buffer for sending hello
  145. bsize_t size = bsize_add(
  146. bsize_fromsize(sizeof(struct socks_client_hello_header)),
  147. bsize_mul(
  148. bsize_fromsize(o->num_auth_info),
  149. bsize_fromsize(sizeof(struct socks_client_hello_method))
  150. )
  151. );
  152. if (!reserve_buffer(o, size)) {
  153. goto fail1;
  154. }
  155. // write hello header
  156. struct socks_client_hello_header header;
  157. header.ver = hton8(SOCKS_VERSION);
  158. header.nmethods = hton8(o->num_auth_info);
  159. memcpy(o->buffer, &header, sizeof(header));
  160. // write hello methods
  161. for (size_t i = 0; i < o->num_auth_info; i++) {
  162. struct socks_client_hello_method method;
  163. method.method = hton8(o->auth_info[i].auth_type);
  164. memcpy(o->buffer + sizeof(header) + i * sizeof(method), &method, sizeof(method));
  165. }
  166. // send
  167. PacketPassInterface_Sender_Send(o->control.send_if, (uint8_t *)o->buffer, size.value);
  168. // set state
  169. o->state = STATE_SENDING_HELLO;
  170. return;
  171. fail1:
  172. free_control_io(o);
  173. BConnection_Free(&o->con);
  174. fail0:
  175. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  176. return;
  177. }
  178. void connection_handler (BSocksClient* o, int event)
  179. {
  180. DebugObject_Access(&o->d_obj);
  181. ASSERT(o->state != STATE_CONNECTING)
  182. if (o->state == STATE_UP && event == BCONNECTION_EVENT_RECVCLOSED) {
  183. report_error(o, BSOCKSCLIENT_EVENT_ERROR_CLOSED);
  184. return;
  185. }
  186. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  187. return;
  188. }
  189. void recv_handler_done (BSocksClient *o, int data_len)
  190. {
  191. ASSERT(data_len >= 0)
  192. ASSERT(data_len <= o->control.recv_total - o->control.recv_len)
  193. DebugObject_Access(&o->d_obj);
  194. o->control.recv_len += data_len;
  195. if (o->control.recv_len < o->control.recv_total) {
  196. do_receive(o);
  197. return;
  198. }
  199. switch (o->state) {
  200. case STATE_SENT_HELLO: {
  201. BLog(BLOG_DEBUG, "received hello");
  202. struct socks_server_hello imsg;
  203. memcpy(&imsg, o->buffer, sizeof(imsg));
  204. if (ntoh8(imsg.ver) != SOCKS_VERSION) {
  205. BLog(BLOG_NOTICE, "wrong version");
  206. goto fail;
  207. }
  208. size_t auth_index;
  209. for (auth_index = 0; auth_index < o->num_auth_info; auth_index++) {
  210. if (o->auth_info[auth_index].auth_type == ntoh8(imsg.method)) {
  211. break;
  212. }
  213. }
  214. if (auth_index == o->num_auth_info) {
  215. BLog(BLOG_NOTICE, "server didn't accept any authentication method");
  216. goto fail;
  217. }
  218. const struct BSocksClient_auth_info *ai = &o->auth_info[auth_index];
  219. switch (ai->auth_type) {
  220. case SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED: {
  221. BLog(BLOG_DEBUG, "no authentication");
  222. auth_finished(o);
  223. } break;
  224. case SOCKS_METHOD_USERNAME_PASSWORD: {
  225. BLog(BLOG_DEBUG, "password authentication");
  226. if (ai->password.username_len == 0 || ai->password.username_len > 255 ||
  227. ai->password.password_len == 0 || ai->password.password_len > 255
  228. ) {
  229. BLog(BLOG_NOTICE, "invalid username/password length");
  230. goto fail;
  231. }
  232. // allocate password packet
  233. bsize_t size = bsize_fromsize(1 + 1 + ai->password.username_len + 1 + ai->password.password_len);
  234. if (!reserve_buffer(o, size)) {
  235. goto fail;
  236. }
  237. // write password packet
  238. char *ptr = o->buffer;
  239. *ptr++ = 1;
  240. *ptr++ = ai->password.username_len;
  241. memcpy(ptr, ai->password.username, ai->password.username_len);
  242. ptr += ai->password.username_len;
  243. *ptr++ = ai->password.password_len;
  244. memcpy(ptr, ai->password.password, ai->password.password_len);
  245. ptr += ai->password.password_len;
  246. // start sending
  247. PacketPassInterface_Sender_Send(o->control.send_if, (uint8_t *)o->buffer, size.value);
  248. // set state
  249. o->state = STATE_SENDING_PASSWORD;
  250. } break;
  251. default: ASSERT(0);
  252. }
  253. } break;
  254. case STATE_SENT_REQUEST: {
  255. BLog(BLOG_DEBUG, "received reply header");
  256. struct socks_reply_header imsg;
  257. memcpy(&imsg, o->buffer, sizeof(imsg));
  258. if (ntoh8(imsg.ver) != SOCKS_VERSION) {
  259. BLog(BLOG_NOTICE, "wrong version");
  260. goto fail;
  261. }
  262. if (ntoh8(imsg.rep) != SOCKS_REP_SUCCEEDED) {
  263. BLog(BLOG_NOTICE, "reply not successful");
  264. goto fail;
  265. }
  266. int addr_len;
  267. switch (ntoh8(imsg.atyp)) {
  268. case SOCKS_ATYP_IPV4:
  269. addr_len = sizeof(struct socks_addr_ipv4);
  270. break;
  271. case SOCKS_ATYP_IPV6:
  272. addr_len = sizeof(struct socks_addr_ipv6);
  273. break;
  274. default:
  275. BLog(BLOG_NOTICE, "reply has unknown address type");
  276. goto fail;
  277. }
  278. // receive the rest of the reply
  279. start_receive(o, (uint8_t *)o->buffer + sizeof(imsg), addr_len);
  280. // set state
  281. o->state = STATE_RECEIVED_REPLY_HEADER;
  282. } break;
  283. case STATE_SENT_PASSWORD: {
  284. BLog(BLOG_DEBUG, "received password reply");
  285. if (o->buffer[0] != 1) {
  286. BLog(BLOG_NOTICE, "password reply has unknown version");
  287. goto fail;
  288. }
  289. if (o->buffer[1] != 0) {
  290. BLog(BLOG_NOTICE, "password reply is negative");
  291. goto fail;
  292. }
  293. auth_finished(o);
  294. } break;
  295. case STATE_RECEIVED_REPLY_HEADER: {
  296. BLog(BLOG_DEBUG, "received reply rest");
  297. // free buffer
  298. BFree(o->buffer);
  299. o->buffer = NULL;
  300. // free control I/O
  301. free_control_io(o);
  302. // init up I/O
  303. init_up_io(o);
  304. // set state
  305. o->state = STATE_UP;
  306. // call handler
  307. o->handler(o->user, BSOCKSCLIENT_EVENT_UP);
  308. return;
  309. } break;
  310. default:
  311. ASSERT(0);
  312. }
  313. return;
  314. fail:
  315. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  316. }
  317. void send_handler_done (BSocksClient *o)
  318. {
  319. DebugObject_Access(&o->d_obj);
  320. ASSERT(o->buffer)
  321. switch (o->state) {
  322. case STATE_SENDING_HELLO: {
  323. BLog(BLOG_DEBUG, "sent hello");
  324. // allocate buffer for receiving hello
  325. bsize_t size = bsize_fromsize(sizeof(struct socks_server_hello));
  326. if (!reserve_buffer(o, size)) {
  327. goto fail;
  328. }
  329. // receive hello
  330. start_receive(o, (uint8_t *)o->buffer, size.value);
  331. // set state
  332. o->state = STATE_SENT_HELLO;
  333. } break;
  334. case STATE_SENDING_REQUEST: {
  335. BLog(BLOG_DEBUG, "sent request");
  336. // allocate buffer for receiving reply
  337. bsize_t size = bsize_add(
  338. bsize_fromsize(sizeof(struct socks_reply_header)),
  339. bsize_max(bsize_fromsize(sizeof(struct socks_addr_ipv4)), bsize_fromsize(sizeof(struct socks_addr_ipv6)))
  340. );
  341. if (!reserve_buffer(o, size)) {
  342. goto fail;
  343. }
  344. // receive reply header
  345. start_receive(o, (uint8_t *)o->buffer, sizeof(struct socks_reply_header));
  346. // set state
  347. o->state = STATE_SENT_REQUEST;
  348. } break;
  349. case STATE_SENDING_PASSWORD: {
  350. BLog(BLOG_DEBUG, "send password");
  351. // allocate buffer for receiving reply
  352. bsize_t size = bsize_fromsize(2);
  353. if (!reserve_buffer(o, size)) {
  354. goto fail;
  355. }
  356. // receive reply header
  357. start_receive(o, (uint8_t *)o->buffer, size.value);
  358. // set state
  359. o->state = STATE_SENT_PASSWORD;
  360. } break;
  361. default:
  362. ASSERT(0);
  363. }
  364. return;
  365. fail:
  366. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  367. }
  368. void auth_finished (BSocksClient *o)
  369. {
  370. // allocate request buffer
  371. bsize_t size = bsize_fromsize(sizeof(struct socks_request_header));
  372. switch (o->dest_addr.type) {
  373. case BADDR_TYPE_IPV4: size = bsize_add(size, bsize_fromsize(sizeof(struct socks_addr_ipv4))); break;
  374. case BADDR_TYPE_IPV6: size = bsize_add(size, bsize_fromsize(sizeof(struct socks_addr_ipv6))); break;
  375. }
  376. if (!reserve_buffer(o, size)) {
  377. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  378. return;
  379. }
  380. // write request
  381. struct socks_request_header header;
  382. header.ver = hton8(SOCKS_VERSION);
  383. header.cmd = hton8(SOCKS_CMD_CONNECT);
  384. header.rsv = hton8(0);
  385. switch (o->dest_addr.type) {
  386. case BADDR_TYPE_IPV4: {
  387. header.atyp = hton8(SOCKS_ATYP_IPV4);
  388. struct socks_addr_ipv4 addr;
  389. addr.addr = o->dest_addr.ipv4.ip;
  390. addr.port = o->dest_addr.ipv4.port;
  391. memcpy(o->buffer + sizeof(header), &addr, sizeof(addr));
  392. } break;
  393. case BADDR_TYPE_IPV6: {
  394. header.atyp = hton8(SOCKS_ATYP_IPV6);
  395. struct socks_addr_ipv6 addr;
  396. memcpy(addr.addr, o->dest_addr.ipv6.ip, sizeof(o->dest_addr.ipv6.ip));
  397. addr.port = o->dest_addr.ipv6.port;
  398. memcpy(o->buffer + sizeof(header), &addr, sizeof(addr));
  399. } break;
  400. default:
  401. ASSERT(0);
  402. }
  403. memcpy(o->buffer, &header, sizeof(header));
  404. // send request
  405. PacketPassInterface_Sender_Send(o->control.send_if, (uint8_t *)o->buffer, size.value);
  406. // set state
  407. o->state = STATE_SENDING_REQUEST;
  408. }
  409. struct BSocksClient_auth_info BSocksClient_auth_none (void)
  410. {
  411. struct BSocksClient_auth_info info;
  412. info.auth_type = SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED;
  413. return info;
  414. }
  415. struct BSocksClient_auth_info BSocksClient_auth_password (const char *username, size_t username_len, const char *password, size_t password_len)
  416. {
  417. struct BSocksClient_auth_info info;
  418. info.auth_type = SOCKS_METHOD_USERNAME_PASSWORD;
  419. info.password.username = username;
  420. info.password.username_len = username_len;
  421. info.password.password = password;
  422. info.password.password_len = password_len;
  423. return info;
  424. }
  425. int BSocksClient_Init (BSocksClient *o,
  426. BAddr server_addr, const struct BSocksClient_auth_info *auth_info, size_t num_auth_info,
  427. BAddr dest_addr, BSocksClient_handler handler, void *user, BReactor *reactor)
  428. {
  429. ASSERT(!BAddr_IsInvalid(&server_addr))
  430. ASSERT(dest_addr.type == BADDR_TYPE_IPV4 || dest_addr.type == BADDR_TYPE_IPV6)
  431. #ifndef NDEBUG
  432. for (size_t i = 0; i < num_auth_info; i++) {
  433. ASSERT(auth_info[i].auth_type == SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED ||
  434. auth_info[i].auth_type == SOCKS_METHOD_USERNAME_PASSWORD)
  435. }
  436. #endif
  437. // init arguments
  438. o->auth_info = auth_info;
  439. o->num_auth_info = num_auth_info;
  440. o->dest_addr = dest_addr;
  441. o->handler = handler;
  442. o->user = user;
  443. o->reactor = reactor;
  444. // set no buffer
  445. o->buffer = NULL;
  446. // init connector
  447. if (!BConnector_Init(&o->connector, server_addr, o->reactor, o, (BConnector_handler)connector_handler)) {
  448. BLog(BLOG_ERROR, "BConnector_Init failed");
  449. goto fail0;
  450. }
  451. // set state
  452. o->state = STATE_CONNECTING;
  453. DebugError_Init(&o->d_err, BReactor_PendingGroup(o->reactor));
  454. DebugObject_Init(&o->d_obj);
  455. return 1;
  456. fail0:
  457. return 0;
  458. }
  459. void BSocksClient_Free (BSocksClient *o)
  460. {
  461. DebugObject_Free(&o->d_obj);
  462. DebugError_Free(&o->d_err);
  463. if (o->state != STATE_CONNECTING) {
  464. if (o->state == STATE_UP) {
  465. // free up I/O
  466. free_up_io(o);
  467. } else {
  468. // free control I/O
  469. free_control_io(o);
  470. }
  471. // free connection
  472. BConnection_Free(&o->con);
  473. }
  474. // free connector
  475. BConnector_Free(&o->connector);
  476. // free buffer
  477. if (o->buffer) {
  478. BFree(o->buffer);
  479. }
  480. }
  481. StreamPassInterface * BSocksClient_GetSendInterface (BSocksClient *o)
  482. {
  483. ASSERT(o->state == STATE_UP)
  484. DebugObject_Access(&o->d_obj);
  485. return BConnection_SendAsync_GetIf(&o->con);
  486. }
  487. StreamRecvInterface * BSocksClient_GetRecvInterface (BSocksClient *o)
  488. {
  489. ASSERT(o->state == STATE_UP)
  490. DebugObject_Access(&o->d_obj);
  491. return BConnection_RecvAsync_GetIf(&o->con);
  492. }