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.

1112 lines
30KB

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