BSocksClient.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. BConnection_Free(&o->con);
  169. fail0:
  170. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  171. return;
  172. }
  173. void connection_handler (BSocksClient* o, int event)
  174. {
  175. DebugObject_Access(&o->d_obj);
  176. ASSERT(o->state != STATE_CONNECTING)
  177. if (o->state == STATE_UP && event == BCONNECTION_EVENT_RECVCLOSED) {
  178. report_error(o, BSOCKSCLIENT_EVENT_ERROR_CLOSED);
  179. return;
  180. }
  181. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  182. return;
  183. }
  184. void recv_handler_done (BSocksClient *o, int data_len)
  185. {
  186. ASSERT(data_len >= 0)
  187. ASSERT(data_len <= o->control.recv_total - o->control.recv_len)
  188. DebugObject_Access(&o->d_obj);
  189. o->control.recv_len += data_len;
  190. if (o->control.recv_len < o->control.recv_total) {
  191. do_receive(o);
  192. return;
  193. }
  194. switch (o->state) {
  195. case STATE_SENT_HELLO: {
  196. BLog(BLOG_DEBUG, "received hello");
  197. struct socks_server_hello *imsg = (void *)o->buffer;
  198. if (ntoh8(imsg->ver) != SOCKS_VERSION) {
  199. BLog(BLOG_NOTICE, "wrong version");
  200. goto fail;
  201. }
  202. size_t auth_index;
  203. for (auth_index = 0; auth_index < o->num_auth_info; auth_index++) {
  204. if (o->auth_info[auth_index].auth_type == ntoh8(imsg->method)) {
  205. break;
  206. }
  207. }
  208. if (auth_index == o->num_auth_info) {
  209. BLog(BLOG_NOTICE, "server didn't accept any authentication method");
  210. goto fail;
  211. }
  212. const struct BSocksClient_auth_info *ai = &o->auth_info[auth_index];
  213. switch (ai->auth_type) {
  214. case SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED: {
  215. BLog(BLOG_DEBUG, "no authentication");
  216. auth_finished(o);
  217. } break;
  218. case SOCKS_METHOD_USERNAME_PASSWORD: {
  219. BLog(BLOG_DEBUG, "password authentication");
  220. if (ai->password.username_len == 0 || ai->password.username_len > 255 ||
  221. ai->password.password_len == 0 || ai->password.password_len > 255
  222. ) {
  223. BLog(BLOG_NOTICE, "invalid username/password length");
  224. goto fail;
  225. }
  226. // allocate password packet
  227. bsize_t size = bsize_fromsize(1 + 1 + ai->password.username_len + 1 + ai->password.password_len);
  228. if (!reserve_buffer(o, size)) {
  229. goto fail;
  230. }
  231. // write password packet
  232. char *ptr = o->buffer;
  233. *ptr++ = 1;
  234. *ptr++ = ai->password.username_len;
  235. memcpy(ptr, ai->password.username, ai->password.username_len);
  236. ptr += ai->password.username_len;
  237. *ptr++ = ai->password.password_len;
  238. memcpy(ptr, ai->password.password, ai->password.password_len);
  239. ptr += ai->password.password_len;
  240. // start sending
  241. PacketPassInterface_Sender_Send(o->control.send_if, (uint8_t *)o->buffer, size.value);
  242. // set state
  243. o->state = STATE_SENDING_PASSWORD;
  244. } break;
  245. default: ASSERT(0);
  246. }
  247. } break;
  248. case STATE_SENT_REQUEST: {
  249. BLog(BLOG_DEBUG, "received reply header");
  250. struct BSocksClient__reply *imsg = (void *)o->buffer;
  251. if (ntoh8(imsg->header.ver) != SOCKS_VERSION) {
  252. BLog(BLOG_NOTICE, "wrong version");
  253. goto fail;
  254. }
  255. if (ntoh8(imsg->header.rep) != SOCKS_REP_SUCCEEDED) {
  256. BLog(BLOG_NOTICE, "reply not successful");
  257. goto fail;
  258. }
  259. int addr_len;
  260. switch (ntoh8(imsg->header.atyp)) {
  261. case SOCKS_ATYP_IPV4:
  262. addr_len = sizeof(struct socks_addr_ipv4);
  263. break;
  264. case SOCKS_ATYP_IPV6:
  265. addr_len = sizeof(struct socks_addr_ipv6);
  266. break;
  267. default:
  268. BLog(BLOG_NOTICE, "reply has unknown address type");
  269. goto fail;
  270. }
  271. // receive the rest of the reply
  272. start_receive(o, (uint8_t *)&imsg->addr, addr_len);
  273. // set state
  274. o->state = STATE_RECEIVED_REPLY_HEADER;
  275. } break;
  276. case STATE_SENT_PASSWORD: {
  277. BLog(BLOG_DEBUG, "received password reply");
  278. if (o->buffer[0] != 1) {
  279. BLog(BLOG_NOTICE, "password reply has unknown version");
  280. goto fail;
  281. }
  282. if (o->buffer[1] != 0) {
  283. BLog(BLOG_NOTICE, "password reply is negative");
  284. goto fail;
  285. }
  286. auth_finished(o);
  287. } break;
  288. case STATE_RECEIVED_REPLY_HEADER: {
  289. BLog(BLOG_DEBUG, "received reply rest");
  290. // free buffer
  291. BFree(o->buffer);
  292. o->buffer = NULL;
  293. // free control I/O
  294. free_control_io(o);
  295. // init up I/O
  296. init_up_io(o);
  297. // set state
  298. o->state = STATE_UP;
  299. // call handler
  300. o->handler(o->user, BSOCKSCLIENT_EVENT_UP);
  301. return;
  302. } break;
  303. default:
  304. ASSERT(0);
  305. }
  306. return;
  307. fail:
  308. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  309. }
  310. void send_handler_done (BSocksClient *o)
  311. {
  312. DebugObject_Access(&o->d_obj);
  313. ASSERT(o->buffer)
  314. switch (o->state) {
  315. case STATE_SENDING_HELLO: {
  316. BLog(BLOG_DEBUG, "sent hello");
  317. // allocate buffer for receiving hello
  318. bsize_t size = bsize_fromsize(sizeof(struct socks_server_hello));
  319. if (!reserve_buffer(o, size)) {
  320. goto fail;
  321. }
  322. // receive hello
  323. start_receive(o, (uint8_t *)o->buffer, size.value);
  324. // set state
  325. o->state = STATE_SENT_HELLO;
  326. } break;
  327. case STATE_SENDING_REQUEST: {
  328. BLog(BLOG_DEBUG, "sent request");
  329. // allocate buffer for receiving reply
  330. bsize_t size = bsize_fromsize(sizeof(struct BSocksClient__reply));
  331. if (!reserve_buffer(o, size)) {
  332. goto fail;
  333. }
  334. // receive reply header
  335. start_receive(o, (uint8_t *)o->buffer, sizeof(struct socks_reply_header));
  336. // set state
  337. o->state = STATE_SENT_REQUEST;
  338. } break;
  339. case STATE_SENDING_PASSWORD: {
  340. BLog(BLOG_DEBUG, "send password");
  341. // allocate buffer for receiving reply
  342. bsize_t size = bsize_fromsize(2);
  343. if (!reserve_buffer(o, size)) {
  344. goto fail;
  345. }
  346. // receive reply header
  347. start_receive(o, (uint8_t *)o->buffer, size.value);
  348. // set state
  349. o->state = STATE_SENT_PASSWORD;
  350. } break;
  351. default:
  352. ASSERT(0);
  353. }
  354. return;
  355. fail:
  356. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  357. }
  358. void auth_finished (BSocksClient *o)
  359. {
  360. // allocate request buffer
  361. bsize_t size = bsize_fromsize(sizeof(struct socks_request_header));
  362. switch (o->dest_addr.type) {
  363. case BADDR_TYPE_IPV4: size = bsize_add(size, bsize_fromsize(sizeof(struct socks_addr_ipv4))); break;
  364. case BADDR_TYPE_IPV6: size = bsize_add(size, bsize_fromsize(sizeof(struct socks_addr_ipv6))); break;
  365. }
  366. if (!reserve_buffer(o, size)) {
  367. report_error(o, BSOCKSCLIENT_EVENT_ERROR);
  368. return;
  369. }
  370. // send request
  371. struct BSocksClient__request *omsg = (void *)o->buffer;
  372. omsg->header.ver = hton8(SOCKS_VERSION);
  373. omsg->header.cmd = hton8(SOCKS_CMD_CONNECT);
  374. omsg->header.rsv = hton8(0);
  375. switch (o->dest_addr.type) {
  376. case BADDR_TYPE_IPV4:
  377. omsg->header.atyp = hton8(SOCKS_ATYP_IPV4);
  378. omsg->addr.ipv4.addr = o->dest_addr.ipv4.ip;
  379. omsg->addr.ipv4.port = o->dest_addr.ipv4.port;
  380. break;
  381. case BADDR_TYPE_IPV6:
  382. omsg->header.atyp = hton8(SOCKS_ATYP_IPV6);
  383. memcpy(omsg->addr.ipv6.addr, o->dest_addr.ipv6.ip, sizeof(o->dest_addr.ipv6.ip));
  384. omsg->addr.ipv6.port = o->dest_addr.ipv6.port;
  385. break;
  386. default:
  387. ASSERT(0);
  388. }
  389. PacketPassInterface_Sender_Send(o->control.send_if, (uint8_t *)o->buffer, size.value);
  390. // set state
  391. o->state = STATE_SENDING_REQUEST;
  392. }
  393. struct BSocksClient_auth_info BSocksClient_auth_none (void)
  394. {
  395. struct BSocksClient_auth_info info;
  396. info.auth_type = SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED;
  397. return info;
  398. }
  399. struct BSocksClient_auth_info BSocksClient_auth_password (const char *username, size_t username_len, const char *password, size_t password_len)
  400. {
  401. struct BSocksClient_auth_info info;
  402. info.auth_type = SOCKS_METHOD_USERNAME_PASSWORD;
  403. info.password.username = username;
  404. info.password.username_len = username_len;
  405. info.password.password = password;
  406. info.password.password_len = password_len;
  407. return info;
  408. }
  409. int BSocksClient_Init (BSocksClient *o,
  410. BAddr server_addr, const struct BSocksClient_auth_info *auth_info, size_t num_auth_info,
  411. BAddr dest_addr, BSocksClient_handler handler, void *user, BReactor *reactor)
  412. {
  413. ASSERT(!BAddr_IsInvalid(&server_addr))
  414. ASSERT(dest_addr.type == BADDR_TYPE_IPV4 || dest_addr.type == BADDR_TYPE_IPV6)
  415. #ifndef NDEBUG
  416. for (size_t i = 0; i < num_auth_info; i++) {
  417. ASSERT(auth_info[i].auth_type == SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED ||
  418. auth_info[i].auth_type == SOCKS_METHOD_USERNAME_PASSWORD)
  419. }
  420. #endif
  421. // init arguments
  422. o->auth_info = auth_info;
  423. o->num_auth_info = num_auth_info;
  424. o->dest_addr = dest_addr;
  425. o->handler = handler;
  426. o->user = user;
  427. o->reactor = reactor;
  428. // set no buffer
  429. o->buffer = NULL;
  430. // init connector
  431. if (!BConnector_Init(&o->connector, server_addr, o->reactor, o, (BConnector_handler)connector_handler)) {
  432. BLog(BLOG_ERROR, "BConnector_Init failed");
  433. goto fail0;
  434. }
  435. // set state
  436. o->state = STATE_CONNECTING;
  437. DebugError_Init(&o->d_err, BReactor_PendingGroup(o->reactor));
  438. DebugObject_Init(&o->d_obj);
  439. return 1;
  440. fail0:
  441. return 0;
  442. }
  443. void BSocksClient_Free (BSocksClient *o)
  444. {
  445. DebugObject_Free(&o->d_obj);
  446. DebugError_Free(&o->d_err);
  447. if (o->state != STATE_CONNECTING) {
  448. if (o->state == STATE_UP) {
  449. // free up I/O
  450. free_up_io(o);
  451. } else {
  452. // free control I/O
  453. free_control_io(o);
  454. }
  455. // free connection
  456. BConnection_Free(&o->con);
  457. }
  458. // free connector
  459. BConnector_Free(&o->connector);
  460. // free buffer
  461. if (o->buffer) {
  462. BFree(o->buffer);
  463. }
  464. }
  465. StreamPassInterface * BSocksClient_GetSendInterface (BSocksClient *o)
  466. {
  467. ASSERT(o->state == STATE_UP)
  468. DebugObject_Access(&o->d_obj);
  469. return BConnection_SendAsync_GetIf(&o->con);
  470. }
  471. StreamRecvInterface * BSocksClient_GetRecvInterface (BSocksClient *o)
  472. {
  473. ASSERT(o->state == STATE_UP)
  474. DebugObject_Access(&o->d_obj);
  475. return BConnection_RecvAsync_GetIf(&o->con);
  476. }