Experimental IRC client, daemon and bot
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.

1050 lines
28KB

  1. /*
  2. * common.c: common functionality
  3. *
  4. * Copyright (c) 2014 - 2015, Přemysl Janouch <p.janouch@gmail.com>
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  13. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  15. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  16. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. *
  18. */
  19. #define LIBERTY_WANT_SSL
  20. #define LIBERTY_WANT_ASYNC
  21. #define LIBERTY_WANT_POLLER
  22. #define LIBERTY_WANT_PROTO_IRC
  23. #ifdef WANT_SYSLOG_LOGGING
  24. #define print_fatal_data ((void *) LOG_ERR)
  25. #define print_error_data ((void *) LOG_ERR)
  26. #define print_warning_data ((void *) LOG_WARNING)
  27. #define print_status_data ((void *) LOG_INFO)
  28. #define print_debug_data ((void *) LOG_DEBUG)
  29. #endif // WANT_SYSLOG_LOGGING
  30. #include "liberty/liberty.c"
  31. #include <arpa/inet.h>
  32. #include <netinet/tcp.h>
  33. static void
  34. init_openssl (void)
  35. {
  36. #if OPENSSL_VERSION_NUMBER < 0x10100000L || LIBRESSL_VERSION_NUMBER
  37. SSL_library_init ();
  38. // XXX: this list is probably not complete
  39. atexit (EVP_cleanup);
  40. SSL_load_error_strings ();
  41. atexit (ERR_free_strings);
  42. #else
  43. // Cleanup is done automatically via atexit()
  44. OPENSSL_init_ssl (0, NULL);
  45. #endif
  46. }
  47. // --- To be moved to liberty --------------------------------------------------
  48. static ssize_t
  49. strv_find (const struct strv *v, const char *s)
  50. {
  51. for (size_t i = 0; i < v->len; i++)
  52. if (!strcmp (v->vector[i], s))
  53. return i;
  54. return -1;
  55. }
  56. static time_t
  57. unixtime_msec (long *msec)
  58. {
  59. #ifdef _POSIX_TIMERS
  60. struct timespec tp;
  61. hard_assert (clock_gettime (CLOCK_REALTIME, &tp) != -1);
  62. *msec = tp.tv_nsec / 1000000;
  63. #else // ! _POSIX_TIMERS
  64. struct timeval tp;
  65. hard_assert (gettimeofday (&tp, NULL) != -1);
  66. *msec = tp.tv_usec / 1000;
  67. #endif // ! _POSIX_TIMERS
  68. return tp.tv_sec;
  69. }
  70. /// This differs from the non-unique version in that we expect the filename
  71. /// to be something like a pattern for mkstemp(), so the resulting path can
  72. /// reside in a system-wide directory with no risk of a conflict.
  73. static char *
  74. resolve_relative_runtime_unique_filename (const char *filename)
  75. {
  76. const char *runtime_dir = getenv ("XDG_RUNTIME_DIR");
  77. const char *tmpdir = getenv ("TMPDIR");
  78. struct str path = str_make ();
  79. if (runtime_dir && *runtime_dir == '/')
  80. str_append (&path, runtime_dir);
  81. else if (tmpdir && *tmpdir == '/')
  82. str_append (&path, tmpdir);
  83. else
  84. str_append (&path, "/tmp");
  85. str_append_printf (&path, "/%s/%s", PROGRAM_NAME, filename);
  86. // Try to create the file's ancestors;
  87. // typically the user will want to immediately create a file in there
  88. const char *last_slash = strrchr (path.str, '/');
  89. if (last_slash && last_slash != path.str)
  90. {
  91. char *copy = xstrndup (path.str, last_slash - path.str);
  92. (void) mkdir_with_parents (copy, NULL);
  93. free (copy);
  94. }
  95. return str_steal (&path);
  96. }
  97. static bool
  98. xwrite (int fd, const char *data, size_t len, struct error **e)
  99. {
  100. size_t written = 0;
  101. while (written < len)
  102. {
  103. ssize_t res = write (fd, data + written, len - written);
  104. if (res >= 0)
  105. written += res;
  106. else if (errno != EINTR)
  107. return error_set (e, "%s", strerror (errno));
  108. }
  109. return true;
  110. }
  111. // --- Logging -----------------------------------------------------------------
  112. static void
  113. log_message_syslog (void *user_data, const char *quote, const char *fmt,
  114. va_list ap)
  115. {
  116. int prio = (int) (intptr_t) user_data;
  117. va_list va;
  118. va_copy (va, ap);
  119. int size = vsnprintf (NULL, 0, fmt, va);
  120. va_end (va);
  121. if (size < 0)
  122. return;
  123. char buf[size + 1];
  124. if (vsnprintf (buf, sizeof buf, fmt, ap) >= 0)
  125. syslog (prio, "%s%s", quote, buf);
  126. }
  127. // --- SOCKS 5/4a --------------------------------------------------------------
  128. // Asynchronous SOCKS connector. Adds more stuff on top of the regular one.
  129. // Note that the `username' is used differently in SOCKS 4a and 5. In the
  130. // former version, it is the username that you can get ident'ed against.
  131. // In the latter version, it forms a pair with the password field and doesn't
  132. // need to be an actual user on your machine.
  133. struct socks_addr
  134. {
  135. enum socks_addr_type
  136. {
  137. SOCKS_IPV4 = 1, ///< IPv4 address
  138. SOCKS_DOMAIN = 3, ///< Domain name to be resolved
  139. SOCKS_IPV6 = 4 ///< IPv6 address
  140. }
  141. type; ///< The type of this address
  142. union
  143. {
  144. uint8_t ipv4[4]; ///< IPv4 address, network octet order
  145. char *domain; ///< Domain name
  146. uint8_t ipv6[16]; ///< IPv6 address, network octet order
  147. }
  148. data; ///< The address itself
  149. };
  150. static void
  151. socks_addr_free (struct socks_addr *self)
  152. {
  153. if (self->type == SOCKS_DOMAIN)
  154. free (self->data.domain);
  155. }
  156. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  157. struct socks_target
  158. {
  159. LIST_HEADER (struct socks_target)
  160. char *address_str; ///< Target address as a string
  161. struct socks_addr address; ///< Target address
  162. uint16_t port; ///< Target service port
  163. };
  164. enum socks_protocol
  165. {
  166. SOCKS_5, ///< SOCKS5
  167. SOCKS_4A, ///< SOCKS4A
  168. SOCKS_MAX ///< End of protocol
  169. };
  170. static inline const char *
  171. socks_protocol_to_string (enum socks_protocol self)
  172. {
  173. switch (self)
  174. {
  175. case SOCKS_5: return "SOCKS5";
  176. case SOCKS_4A: return "SOCKS4A";
  177. default: return NULL;
  178. }
  179. }
  180. struct socks_connector
  181. {
  182. struct connector *connector; ///< Proxy server iterator (effectively)
  183. enum socks_protocol protocol_iter; ///< Protocol iterator
  184. struct socks_target *targets_iter; ///< Targets iterator
  185. // Negotiation:
  186. struct poller_timer timeout; ///< Timeout timer
  187. int socket_fd; ///< Current socket file descriptor
  188. struct poller_fd socket_event; ///< Socket can be read from/written to
  189. struct str read_buffer; ///< Read buffer
  190. struct str write_buffer; ///< Write buffer
  191. bool done; ///< Tunnel succesfully established
  192. uint8_t bound_address_len; ///< Length of domain name
  193. size_t data_needed; ///< How much data "on_data" needs
  194. /// Process incoming data if there's enough of it available
  195. bool (*on_data) (struct socks_connector *, struct msg_unpacker *);
  196. // Configuration:
  197. char *hostname; ///< SOCKS server hostname
  198. char *service; ///< SOCKS server service name or port
  199. char *username; ///< Username for authentication
  200. char *password; ///< Password for authentication
  201. struct socks_target *targets; ///< Targets
  202. struct socks_target *targets_tail; ///< Tail of targets
  203. void *user_data; ///< User data for callbacks
  204. // Additional results:
  205. struct socks_addr bound_address; ///< Bound address at the server
  206. uint16_t bound_port; ///< Bound port at the server
  207. // You may destroy the connector object in these two main callbacks:
  208. /// Connection has been successfully established
  209. void (*on_connected) (void *user_data, int socket, const char *hostname);
  210. /// Failed to establish a connection to either target
  211. void (*on_failure) (void *user_data);
  212. // Optional:
  213. /// Connecting to a new address
  214. void (*on_connecting) (void *user_data,
  215. const char *address, const char *via, const char *version);
  216. /// Connecting to the last address has failed
  217. void (*on_error) (void *user_data, const char *error);
  218. };
  219. // I've tried to make the actual protocol handlers as simple as possible
  220. #define SOCKS_FAIL(...) \
  221. BLOCK_START \
  222. char *error = xstrdup_printf (__VA_ARGS__); \
  223. if (self->on_error) \
  224. self->on_error (self->user_data, error); \
  225. free (error); \
  226. return false; \
  227. BLOCK_END
  228. #define SOCKS_DATA_CB(name) static bool name \
  229. (struct socks_connector *self, struct msg_unpacker *unpacker)
  230. #define SOCKS_GO(name, data_needed_) \
  231. self->on_data = name; \
  232. self->data_needed = data_needed_; \
  233. return true
  234. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  235. SOCKS_DATA_CB (socks_4a_finish)
  236. {
  237. uint8_t null, status;
  238. hard_assert (msg_unpacker_u8 (unpacker, &null));
  239. hard_assert (msg_unpacker_u8 (unpacker, &status));
  240. if (null != 0)
  241. SOCKS_FAIL ("protocol error");
  242. switch (status)
  243. {
  244. case 90:
  245. self->done = true;
  246. return false;
  247. case 91:
  248. SOCKS_FAIL ("request rejected or failed");
  249. case 92:
  250. SOCKS_FAIL ("%s: %s", "request rejected",
  251. "SOCKS server cannot connect to identd on the client");
  252. case 93:
  253. SOCKS_FAIL ("%s: %s", "request rejected",
  254. "identd reports different user-id");
  255. default:
  256. SOCKS_FAIL ("protocol error");
  257. }
  258. }
  259. static bool
  260. socks_4a_start (struct socks_connector *self)
  261. {
  262. struct socks_target *target = self->targets_iter;
  263. const void *dest_ipv4 = "\x00\x00\x00\x01";
  264. const char *dest_domain = NULL;
  265. char buf[INET6_ADDRSTRLEN];
  266. switch (target->address.type)
  267. {
  268. case SOCKS_IPV4:
  269. dest_ipv4 = target->address.data.ipv4;
  270. break;
  271. case SOCKS_IPV6:
  272. // About the best thing we can do, not sure if it works anywhere at all
  273. if (!inet_ntop (AF_INET6, &target->address.data.ipv6, buf, sizeof buf))
  274. SOCKS_FAIL ("%s: %s", "inet_ntop", strerror (errno));
  275. dest_domain = buf;
  276. break;
  277. case SOCKS_DOMAIN:
  278. dest_domain = target->address.data.domain;
  279. }
  280. struct str *wb = &self->write_buffer;
  281. str_pack_u8 (wb, 4); // version
  282. str_pack_u8 (wb, 1); // connect
  283. str_pack_u16 (wb, target->port); // port
  284. str_append_data (wb, dest_ipv4, 4); // destination address
  285. if (self->username)
  286. str_append (wb, self->username);
  287. str_append_c (wb, '\0');
  288. if (dest_domain)
  289. {
  290. str_append (wb, dest_domain);
  291. str_append_c (wb, '\0');
  292. }
  293. SOCKS_GO (socks_4a_finish, 8);
  294. }
  295. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  296. SOCKS_DATA_CB (socks_5_request_port)
  297. {
  298. hard_assert (msg_unpacker_u16 (unpacker, &self->bound_port));
  299. self->done = true;
  300. return false;
  301. }
  302. SOCKS_DATA_CB (socks_5_request_ipv4)
  303. {
  304. memcpy (self->bound_address.data.ipv4, unpacker->data, unpacker->len);
  305. SOCKS_GO (socks_5_request_port, 2);
  306. }
  307. SOCKS_DATA_CB (socks_5_request_ipv6)
  308. {
  309. memcpy (self->bound_address.data.ipv6, unpacker->data, unpacker->len);
  310. SOCKS_GO (socks_5_request_port, 2);
  311. }
  312. SOCKS_DATA_CB (socks_5_request_domain_data)
  313. {
  314. self->bound_address.data.domain = xstrndup (unpacker->data, unpacker->len);
  315. SOCKS_GO (socks_5_request_port, 2);
  316. }
  317. SOCKS_DATA_CB (socks_5_request_domain)
  318. {
  319. hard_assert (msg_unpacker_u8 (unpacker, &self->bound_address_len));
  320. SOCKS_GO (socks_5_request_domain_data, self->bound_address_len);
  321. }
  322. SOCKS_DATA_CB (socks_5_request_finish)
  323. {
  324. uint8_t version, status, reserved, type;
  325. hard_assert (msg_unpacker_u8 (unpacker, &version));
  326. hard_assert (msg_unpacker_u8 (unpacker, &status));
  327. hard_assert (msg_unpacker_u8 (unpacker, &reserved));
  328. hard_assert (msg_unpacker_u8 (unpacker, &type));
  329. if (version != 0x05)
  330. SOCKS_FAIL ("protocol error");
  331. switch (status)
  332. {
  333. case 0x00:
  334. break;
  335. case 0x01: SOCKS_FAIL ("general SOCKS server failure");
  336. case 0x02: SOCKS_FAIL ("connection not allowed by ruleset");
  337. case 0x03: SOCKS_FAIL ("network unreachable");
  338. case 0x04: SOCKS_FAIL ("host unreachable");
  339. case 0x05: SOCKS_FAIL ("connection refused");
  340. case 0x06: SOCKS_FAIL ("TTL expired");
  341. case 0x07: SOCKS_FAIL ("command not supported");
  342. case 0x08: SOCKS_FAIL ("address type not supported");
  343. default: SOCKS_FAIL ("protocol error");
  344. }
  345. switch ((self->bound_address.type = type))
  346. {
  347. case SOCKS_IPV4:
  348. SOCKS_GO (socks_5_request_ipv4, sizeof self->bound_address.data.ipv4);
  349. case SOCKS_IPV6:
  350. SOCKS_GO (socks_5_request_ipv6, sizeof self->bound_address.data.ipv6);
  351. case SOCKS_DOMAIN:
  352. SOCKS_GO (socks_5_request_domain, 1);
  353. default:
  354. SOCKS_FAIL ("protocol error");
  355. }
  356. }
  357. static bool
  358. socks_5_request_start (struct socks_connector *self)
  359. {
  360. struct socks_target *target = self->targets_iter;
  361. struct str *wb = &self->write_buffer;
  362. str_pack_u8 (wb, 0x05); // version
  363. str_pack_u8 (wb, 0x01); // connect
  364. str_pack_u8 (wb, 0x00); // reserved
  365. str_pack_u8 (wb, target->address.type);
  366. switch (target->address.type)
  367. {
  368. case SOCKS_IPV4:
  369. str_append_data (wb,
  370. target->address.data.ipv4, sizeof target->address.data.ipv4);
  371. break;
  372. case SOCKS_DOMAIN:
  373. {
  374. size_t dlen = strlen (target->address.data.domain);
  375. if (dlen > 255)
  376. dlen = 255;
  377. str_pack_u8 (wb, dlen);
  378. str_append_data (wb, target->address.data.domain, dlen);
  379. break;
  380. }
  381. case SOCKS_IPV6:
  382. str_append_data (wb,
  383. target->address.data.ipv6, sizeof target->address.data.ipv6);
  384. break;
  385. }
  386. str_pack_u16 (wb, target->port);
  387. SOCKS_GO (socks_5_request_finish, 4);
  388. }
  389. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  390. SOCKS_DATA_CB (socks_5_userpass_finish)
  391. {
  392. uint8_t version, status;
  393. hard_assert (msg_unpacker_u8 (unpacker, &version));
  394. hard_assert (msg_unpacker_u8 (unpacker, &status));
  395. if (version != 0x01)
  396. SOCKS_FAIL ("protocol error");
  397. if (status != 0x00)
  398. SOCKS_FAIL ("authentication failure");
  399. return socks_5_request_start (self);
  400. }
  401. static bool
  402. socks_5_userpass_start (struct socks_connector *self)
  403. {
  404. size_t ulen = strlen (self->username);
  405. if (ulen > 255)
  406. ulen = 255;
  407. size_t plen = strlen (self->password);
  408. if (plen > 255)
  409. plen = 255;
  410. struct str *wb = &self->write_buffer;
  411. str_pack_u8 (wb, 0x01); // version
  412. str_pack_u8 (wb, ulen); // username length
  413. str_append_data (wb, self->username, ulen);
  414. str_pack_u8 (wb, plen); // password length
  415. str_append_data (wb, self->password, plen);
  416. SOCKS_GO (socks_5_userpass_finish, 2);
  417. }
  418. SOCKS_DATA_CB (socks_5_auth_finish)
  419. {
  420. uint8_t version, method;
  421. hard_assert (msg_unpacker_u8 (unpacker, &version));
  422. hard_assert (msg_unpacker_u8 (unpacker, &method));
  423. if (version != 0x05)
  424. SOCKS_FAIL ("protocol error");
  425. bool can_auth = self->username && self->password;
  426. switch (method)
  427. {
  428. case 0x02:
  429. if (!can_auth)
  430. SOCKS_FAIL ("protocol error");
  431. return socks_5_userpass_start (self);
  432. case 0x00:
  433. return socks_5_request_start (self);
  434. case 0xFF:
  435. SOCKS_FAIL ("no acceptable authentication methods");
  436. default:
  437. SOCKS_FAIL ("protocol error");
  438. }
  439. }
  440. static bool
  441. socks_5_auth_start (struct socks_connector *self)
  442. {
  443. bool can_auth = self->username && self->password;
  444. struct str *wb = &self->write_buffer;
  445. str_pack_u8 (wb, 0x05); // version
  446. str_pack_u8 (wb, 1 + can_auth); // number of authentication methods
  447. str_pack_u8 (wb, 0x00); // no authentication required
  448. if (can_auth)
  449. str_pack_u8 (wb, 0x02); // username/password
  450. SOCKS_GO (socks_5_auth_finish, 2);
  451. }
  452. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  453. static void socks_connector_start (struct socks_connector *self);
  454. static void
  455. socks_connector_destroy_connector (struct socks_connector *self)
  456. {
  457. if (self->connector)
  458. {
  459. connector_free (self->connector);
  460. free (self->connector);
  461. self->connector = NULL;
  462. }
  463. }
  464. static void
  465. socks_connector_cancel_events (struct socks_connector *self)
  466. {
  467. // Before calling the final callbacks, we should cancel events that
  468. // could potentially fire; caller should destroy us immediately, though
  469. poller_fd_reset (&self->socket_event);
  470. poller_timer_reset (&self->timeout);
  471. }
  472. static void
  473. socks_connector_fail (struct socks_connector *self)
  474. {
  475. socks_connector_cancel_events (self);
  476. self->on_failure (self->user_data);
  477. }
  478. static bool
  479. socks_connector_step_iterators (struct socks_connector *self)
  480. {
  481. // At the lowest level we iterate over all addresses for the SOCKS server
  482. // and just try to connect; this is done automatically by the connector
  483. // Then we iterate over available protocols
  484. if (++self->protocol_iter != SOCKS_MAX)
  485. return true;
  486. // At the highest level we iterate over possible targets
  487. self->protocol_iter = 0;
  488. if (self->targets_iter && (self->targets_iter = self->targets_iter->next))
  489. return true;
  490. return false;
  491. }
  492. static void
  493. socks_connector_step (struct socks_connector *self)
  494. {
  495. if (self->socket_fd != -1)
  496. {
  497. poller_fd_reset (&self->socket_event);
  498. xclose (self->socket_fd);
  499. self->socket_fd = -1;
  500. }
  501. socks_connector_destroy_connector (self);
  502. if (socks_connector_step_iterators (self))
  503. socks_connector_start (self);
  504. else
  505. socks_connector_fail (self);
  506. }
  507. static void
  508. socks_connector_on_timeout (struct socks_connector *self)
  509. {
  510. if (self->on_error)
  511. self->on_error (self->user_data, "timeout");
  512. socks_connector_destroy_connector (self);
  513. socks_connector_fail (self);
  514. }
  515. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  516. static void
  517. socks_connector_on_connected
  518. (void *user_data, int socket_fd, const char *hostname)
  519. {
  520. set_blocking (socket_fd, false);
  521. (void) hostname;
  522. struct socks_connector *self = user_data;
  523. self->socket_fd = socket_fd;
  524. self->socket_event.fd = socket_fd;
  525. poller_fd_set (&self->socket_event, POLLIN | POLLOUT);
  526. str_reset (&self->read_buffer);
  527. str_reset (&self->write_buffer);
  528. if (!(self->protocol_iter == SOCKS_5 && socks_5_auth_start (self))
  529. && !(self->protocol_iter == SOCKS_4A && socks_4a_start (self)))
  530. socks_connector_fail (self);
  531. }
  532. static void
  533. socks_connector_on_failure (void *user_data)
  534. {
  535. struct socks_connector *self = user_data;
  536. // TODO: skip SOCKS server on connection failure
  537. socks_connector_step (self);
  538. }
  539. static void
  540. socks_connector_on_connecting (void *user_data, const char *via)
  541. {
  542. struct socks_connector *self = user_data;
  543. if (!self->on_connecting)
  544. return;
  545. struct socks_target *target = self->targets_iter;
  546. char *port = xstrdup_printf ("%u", target->port);
  547. char *address = format_host_port_pair (target->address_str, port);
  548. free (port);
  549. self->on_connecting (self->user_data, address, via,
  550. socks_protocol_to_string (self->protocol_iter));
  551. free (address);
  552. }
  553. static void
  554. socks_connector_on_error (void *user_data, const char *error)
  555. {
  556. struct socks_connector *self = user_data;
  557. // TODO: skip protocol on protocol failure
  558. if (self->on_error)
  559. self->on_error (self->user_data, error);
  560. }
  561. static void
  562. socks_connector_start (struct socks_connector *self)
  563. {
  564. hard_assert (!self->connector);
  565. struct connector *connector =
  566. self->connector = xcalloc (1, sizeof *connector);
  567. connector_init (connector, self->socket_event.poller);
  568. connector->user_data = self;
  569. connector->on_connected = socks_connector_on_connected;
  570. connector->on_connecting = socks_connector_on_connecting;
  571. connector->on_error = socks_connector_on_error;
  572. connector->on_failure = socks_connector_on_failure;
  573. connector_add_target (connector, self->hostname, self->service);
  574. poller_timer_set (&self->timeout, 60 * 1000);
  575. self->done = false;
  576. self->bound_port = 0;
  577. socks_addr_free (&self->bound_address);
  578. memset (&self->bound_address, 0, sizeof self->bound_address);
  579. }
  580. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  581. static bool
  582. socks_try_fill_read_buffer (struct socks_connector *self, size_t n)
  583. {
  584. ssize_t remains = (ssize_t) n - (ssize_t) self->read_buffer.len;
  585. if (remains <= 0)
  586. return true;
  587. ssize_t received;
  588. str_reserve (&self->read_buffer, remains);
  589. do
  590. received = recv (self->socket_fd,
  591. self->read_buffer.str + self->read_buffer.len, remains, 0);
  592. while ((received == -1) && errno == EINTR);
  593. if (received == 0)
  594. SOCKS_FAIL ("%s: %s", "protocol error", "unexpected EOF");
  595. if (received == -1 && errno != EAGAIN)
  596. SOCKS_FAIL ("%s: %s", "recv", strerror (errno));
  597. if (received > 0)
  598. self->read_buffer.len += received;
  599. return true;
  600. }
  601. static bool
  602. socks_call_on_data (struct socks_connector *self)
  603. {
  604. size_t to_consume = self->data_needed;
  605. if (!socks_try_fill_read_buffer (self, to_consume))
  606. return false;
  607. if (self->read_buffer.len < to_consume)
  608. return true;
  609. struct msg_unpacker unpacker =
  610. msg_unpacker_make (self->read_buffer.str, self->read_buffer.len);
  611. bool result = self->on_data (self, &unpacker);
  612. str_remove_slice (&self->read_buffer, 0, to_consume);
  613. return result;
  614. }
  615. static bool
  616. socks_try_flush_write_buffer (struct socks_connector *self)
  617. {
  618. struct str *wb = &self->write_buffer;
  619. ssize_t n_written;
  620. while (wb->len)
  621. {
  622. n_written = send (self->socket_fd, wb->str, wb->len, 0);
  623. if (n_written >= 0)
  624. {
  625. str_remove_slice (wb, 0, n_written);
  626. continue;
  627. }
  628. if (errno == EAGAIN)
  629. break;
  630. if (errno == EINTR)
  631. continue;
  632. SOCKS_FAIL ("%s: %s", "send", strerror (errno));
  633. }
  634. return true;
  635. }
  636. static void
  637. socks_connector_on_ready
  638. (const struct pollfd *pfd, struct socks_connector *self)
  639. {
  640. (void) pfd;
  641. if (socks_call_on_data (self) && socks_try_flush_write_buffer (self))
  642. {
  643. poller_fd_set (&self->socket_event,
  644. self->write_buffer.len ? (POLLIN | POLLOUT) : POLLIN);
  645. }
  646. else if (self->done)
  647. {
  648. socks_connector_cancel_events (self);
  649. int fd = self->socket_fd;
  650. self->socket_fd = -1;
  651. struct socks_target *target = self->targets_iter;
  652. set_blocking (fd, true);
  653. self->on_connected (self->user_data, fd, target->address_str);
  654. }
  655. else
  656. // We've failed this target, let's try to move on
  657. socks_connector_step (self);
  658. }
  659. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  660. static void
  661. socks_connector_init (struct socks_connector *self, struct poller *poller)
  662. {
  663. memset (self, 0, sizeof *self);
  664. self->socket_event = poller_fd_make (poller, (self->socket_fd = -1));
  665. self->socket_event.dispatcher = (poller_fd_fn) socks_connector_on_ready;
  666. self->socket_event.user_data = self;
  667. self->timeout = poller_timer_make (poller);
  668. self->timeout.dispatcher = (poller_timer_fn) socks_connector_on_timeout;
  669. self->timeout.user_data = self;
  670. self->read_buffer = str_make ();
  671. self->write_buffer = str_make ();
  672. }
  673. static void
  674. socks_connector_free (struct socks_connector *self)
  675. {
  676. socks_connector_destroy_connector (self);
  677. socks_connector_cancel_events (self);
  678. if (self->socket_fd != -1)
  679. xclose (self->socket_fd);
  680. str_free (&self->read_buffer);
  681. str_free (&self->write_buffer);
  682. free (self->hostname);
  683. free (self->service);
  684. free (self->username);
  685. free (self->password);
  686. LIST_FOR_EACH (struct socks_target, iter, self->targets)
  687. {
  688. socks_addr_free (&iter->address);
  689. free (iter->address_str);
  690. free (iter);
  691. }
  692. socks_addr_free (&self->bound_address);
  693. }
  694. static bool
  695. socks_connector_add_target (struct socks_connector *self,
  696. const char *host, const char *service, struct error **e)
  697. {
  698. unsigned long port;
  699. const struct servent *serv;
  700. if ((serv = getservbyname (service, "tcp")))
  701. port = (uint16_t) ntohs (serv->s_port);
  702. else if (!xstrtoul (&port, service, 10) || !port || port > UINT16_MAX)
  703. {
  704. error_set (e, "invalid port number");
  705. return false;
  706. }
  707. struct socks_target *target = xcalloc (1, sizeof *target);
  708. if (inet_pton (AF_INET, host, &target->address.data.ipv4) == 1)
  709. target->address.type = SOCKS_IPV4;
  710. else if (inet_pton (AF_INET6, host, &target->address.data.ipv6) == 1)
  711. target->address.type = SOCKS_IPV6;
  712. else
  713. {
  714. target->address.type = SOCKS_DOMAIN;
  715. target->address.data.domain = xstrdup (host);
  716. }
  717. target->port = port;
  718. target->address_str = xstrdup (host);
  719. LIST_APPEND_WITH_TAIL (self->targets, self->targets_tail, target);
  720. return true;
  721. }
  722. static void
  723. socks_connector_run (struct socks_connector *self,
  724. const char *host, const char *service,
  725. const char *username, const char *password)
  726. {
  727. hard_assert (self->targets);
  728. hard_assert (host && service);
  729. self->hostname = xstrdup (host);
  730. self->service = xstrdup (service);
  731. if (username) self->username = xstrdup (username);
  732. if (password) self->password = xstrdup (password);
  733. self->targets_iter = self->targets;
  734. self->protocol_iter = 0;
  735. // XXX: this can fail immediately from an error creating the connector
  736. socks_connector_start (self);
  737. }
  738. // --- CTCP decoding -----------------------------------------------------------
  739. #define CTCP_M_QUOTE '\020'
  740. #define CTCP_X_DELIM '\001'
  741. #define CTCP_X_QUOTE '\\'
  742. struct ctcp_chunk
  743. {
  744. LIST_HEADER (struct ctcp_chunk)
  745. bool is_extended; ///< Is this a tagged extended message?
  746. bool is_partial; ///< Unterminated extended message
  747. struct str tag; ///< The tag, if any
  748. struct str text; ///< Message contents
  749. };
  750. static struct ctcp_chunk *
  751. ctcp_chunk_new (void)
  752. {
  753. struct ctcp_chunk *self = xcalloc (1, sizeof *self);
  754. self->tag = str_make ();
  755. self->text = str_make ();
  756. return self;
  757. }
  758. static void
  759. ctcp_chunk_destroy (struct ctcp_chunk *self)
  760. {
  761. str_free (&self->tag);
  762. str_free (&self->text);
  763. free (self);
  764. }
  765. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  766. static void
  767. ctcp_low_level_decode (const char *message, struct str *output)
  768. {
  769. bool escape = false;
  770. for (const char *p = message; *p; p++)
  771. {
  772. if (escape)
  773. {
  774. switch (*p)
  775. {
  776. case '0': str_append_c (output, '\0'); break;
  777. case 'r': str_append_c (output, '\r'); break;
  778. case 'n': str_append_c (output, '\n'); break;
  779. default: str_append_c (output, *p);
  780. }
  781. escape = false;
  782. }
  783. else if (*p == CTCP_M_QUOTE)
  784. escape = true;
  785. else
  786. str_append_c (output, *p);
  787. }
  788. }
  789. static void
  790. ctcp_intra_decode (const char *chunk, size_t len, struct str *output)
  791. {
  792. bool escape = false;
  793. for (size_t i = 0; i < len; i++)
  794. {
  795. char c = chunk[i];
  796. if (escape)
  797. {
  798. if (c == 'a')
  799. str_append_c (output, CTCP_X_DELIM);
  800. else
  801. str_append_c (output, c);
  802. escape = false;
  803. }
  804. else if (c == CTCP_X_QUOTE)
  805. escape = true;
  806. else
  807. str_append_c (output, c);
  808. }
  809. }
  810. // According to the original CTCP specification we should use
  811. // ctcp_intra_decode() on all parts, however no one seems to use that
  812. // and it breaks normal text with backslashes
  813. #ifndef SUPPORT_CTCP_X_QUOTES
  814. #define ctcp_intra_decode(s, len, output) str_append_data (output, s, len)
  815. #endif
  816. static void
  817. ctcp_parse_tagged (const char *chunk, size_t len, struct ctcp_chunk *output)
  818. {
  819. // We may search for the space before doing the higher level decoding,
  820. // as it doesn't concern space characters at all
  821. size_t tag_end = len;
  822. for (size_t i = 0; i < len; i++)
  823. if (chunk[i] == ' ')
  824. {
  825. tag_end = i;
  826. break;
  827. }
  828. output->is_extended = true;
  829. ctcp_intra_decode (chunk, tag_end, &output->tag);
  830. if (tag_end++ != len)
  831. ctcp_intra_decode (chunk + tag_end, len - tag_end, &output->text);
  832. }
  833. static struct ctcp_chunk *
  834. ctcp_parse (const char *message)
  835. {
  836. struct str m = str_make ();
  837. ctcp_low_level_decode (message, &m);
  838. struct ctcp_chunk *result = NULL, *result_tail = NULL;
  839. size_t start = 0;
  840. bool in_ctcp = false;
  841. for (size_t i = 0; i < m.len; i++)
  842. {
  843. char c = m.str[i];
  844. if (c != CTCP_X_DELIM)
  845. continue;
  846. // Remember the current state
  847. size_t my_start = start;
  848. bool my_is_ctcp = in_ctcp;
  849. start = i + 1;
  850. in_ctcp = !in_ctcp;
  851. // Skip empty chunks
  852. if (my_start == i)
  853. continue;
  854. struct ctcp_chunk *chunk = ctcp_chunk_new ();
  855. if (my_is_ctcp)
  856. ctcp_parse_tagged (m.str + my_start, i - my_start, chunk);
  857. else
  858. ctcp_intra_decode (m.str + my_start, i - my_start, &chunk->text);
  859. LIST_APPEND_WITH_TAIL (result, result_tail, chunk);
  860. }
  861. // Finish the last part. Unended tagged chunks are marked as such.
  862. if (start != m.len)
  863. {
  864. struct ctcp_chunk *chunk = ctcp_chunk_new ();
  865. if (in_ctcp)
  866. {
  867. ctcp_parse_tagged (m.str + start, m.len - start, chunk);
  868. chunk->is_partial = true;
  869. }
  870. else
  871. ctcp_intra_decode (m.str + start, m.len - start, &chunk->text);
  872. LIST_APPEND_WITH_TAIL (result, result_tail, chunk);
  873. }
  874. str_free (&m);
  875. return result;
  876. }
  877. static void
  878. ctcp_destroy (struct ctcp_chunk *list)
  879. {
  880. LIST_FOR_EACH (struct ctcp_chunk, iter, list)
  881. ctcp_chunk_destroy (iter);
  882. }