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.

common.c 28KB

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