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.

zyklonb.c 56KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044
  1. /*
  2. * zyklonb.c: the experimental IRC bot
  3. *
  4. * Copyright (c) 2014 - 2016, 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. #include "config.h"
  19. #define PROGRAM_NAME "ZyklonB"
  20. #define PLUGIN_DIR ZYKLONB_PLUGIN_DIR
  21. #include "common.c"
  22. // --- Configuration (application-specific) ------------------------------------
  23. static struct simple_config_item g_config_table[] =
  24. {
  25. { "nickname", "ZyklonB", "IRC nickname" },
  26. { "username", "bot", "IRC user name" },
  27. { "realname", "ZyklonB IRC bot", "IRC real name/e-mail" },
  28. { "irc_host", NULL, "Address of the IRC server" },
  29. { "irc_port", "6667", "Port of the IRC server" },
  30. { "tls", "off", "Whether to use TLS" },
  31. { "tls_cert", NULL, "Client TLS certificate (PEM)" },
  32. { "tls_verify", "on", "Whether to verify certificates" },
  33. { "tls_ca_file", NULL, "OpenSSL CA bundle file" },
  34. { "tls_ca_path", NULL, "OpenSSL CA bundle path" },
  35. { "autojoin", NULL, "Channels to join on start" },
  36. { "reconnect", "on", "Whether to reconnect on error" },
  37. { "reconnect_delay", "5", "Time between reconnecting" },
  38. { "socks_host", NULL, "Address of a SOCKS 4a/5 proxy" },
  39. { "socks_port", "1080", "SOCKS port number" },
  40. { "socks_username", NULL, "SOCKS auth. username" },
  41. { "socks_password", NULL, "SOCKS auth. password" },
  42. { "prefix", ":", "The prefix for bot commands" },
  43. { "admin", NULL, "Host mask for administrators" },
  44. { "plugins", NULL, "The plugins to load on startup" },
  45. { "plugin_dir", PLUGIN_DIR, "Where to search for plugins" },
  46. { "recover", "on", "Whether to re-launch on crash" },
  47. { NULL, NULL, NULL }
  48. };
  49. // --- Application data --------------------------------------------------------
  50. struct plugin
  51. {
  52. LIST_HEADER (struct plugin)
  53. struct bot_context *ctx; ///< Parent context
  54. char *name; ///< Plugin identifier
  55. pid_t pid; ///< PID of the plugin process
  56. bool is_zombie; ///< Whether the child is a zombie
  57. bool initialized; ///< Ready to exchange IRC messages
  58. struct str queued_output; ///< Output queued up until initialized
  59. // Since we're doing non-blocking I/O, we need to queue up data so that
  60. // we don't stall on plugins unnecessarily.
  61. int read_fd; ///< The read end of the comm. pipe
  62. int write_fd; ///< The write end of the comm. pipe
  63. struct poller_fd read_event; ///< Read FD event
  64. struct poller_fd write_event; ///< Write FD event
  65. struct str read_buffer; ///< Unprocessed input
  66. struct str write_buffer; ///< Output yet to be sent out
  67. };
  68. static struct plugin *
  69. plugin_new (void)
  70. {
  71. struct plugin *self = xcalloc (1, sizeof *self);
  72. self->pid = -1;
  73. self->queued_output = str_make ();
  74. self->read_fd = -1;
  75. self->read_buffer = str_make ();
  76. self->write_fd = -1;
  77. self->write_buffer = str_make ();
  78. return self;
  79. }
  80. static void
  81. plugin_destroy (struct plugin *self)
  82. {
  83. soft_assert (self->pid == -1);
  84. free (self->name);
  85. str_free (&self->read_buffer);
  86. if (!soft_assert (self->read_fd == -1))
  87. xclose (self->read_fd);
  88. str_free (&self->write_buffer);
  89. if (!soft_assert (self->write_fd == -1))
  90. xclose (self->write_fd);
  91. if (!self->initialized)
  92. str_free (&self->queued_output);
  93. free (self);
  94. }
  95. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  96. struct bot_context
  97. {
  98. struct str_map config; ///< User configuration
  99. regex_t *admin_re; ///< Regex to match our administrator
  100. bool reconnect; ///< Whether to reconnect on conn. fail.
  101. unsigned long reconnect_delay; ///< Reconnect delay in seconds
  102. int irc_fd; ///< Socket FD of the server
  103. struct str read_buffer; ///< Input yet to be processed
  104. struct poller_fd irc_event; ///< IRC FD event
  105. bool irc_registered; ///< Whether we may send messages now
  106. struct poller_fd signal_event; ///< Signal FD event
  107. struct poller_timer ping_tmr; ///< We should send a ping
  108. struct poller_timer timeout_tmr; ///< Connection seems to be dead
  109. struct poller_timer reconnect_tmr; ///< We should reconnect now
  110. SSL_CTX *ssl_ctx; ///< SSL context
  111. SSL *ssl; ///< SSL connection
  112. struct plugin *plugins; ///< Linked list of plugins
  113. struct str_map plugins_by_name; ///< Indexes @em plugins by their name
  114. struct poller poller; ///< Manages polled descriptors
  115. bool quitting; ///< User requested quitting
  116. bool polling; ///< The event loop is running
  117. };
  118. static void on_irc_ping_timeout (void *user_data);
  119. static void on_irc_timeout (void *user_data);
  120. static void on_irc_reconnect_timeout (void *user_data);
  121. static void
  122. bot_context_init (struct bot_context *self)
  123. {
  124. self->config = str_map_make (free);
  125. simple_config_load_defaults (&self->config, g_config_table);
  126. self->admin_re = NULL;
  127. self->irc_fd = -1;
  128. self->read_buffer = str_make ();
  129. self->irc_registered = false;
  130. self->ssl = NULL;
  131. self->ssl_ctx = NULL;
  132. self->plugins = NULL;
  133. self->plugins_by_name = str_map_make (NULL);
  134. poller_init (&self->poller);
  135. self->quitting = false;
  136. self->polling = false;
  137. self->timeout_tmr = poller_timer_make (&self->poller);
  138. self->timeout_tmr.dispatcher = on_irc_timeout;
  139. self->timeout_tmr.user_data = self;
  140. self->ping_tmr = poller_timer_make (&self->poller);
  141. self->ping_tmr.dispatcher = on_irc_ping_timeout;
  142. self->ping_tmr.user_data = self;
  143. self->reconnect_tmr = poller_timer_make (&self->poller);
  144. self->reconnect_tmr.dispatcher = on_irc_reconnect_timeout;
  145. self->reconnect_tmr.user_data = self;
  146. }
  147. static void
  148. bot_context_free (struct bot_context *self)
  149. {
  150. str_map_free (&self->config);
  151. if (self->admin_re)
  152. regex_free (self->admin_re);
  153. str_free (&self->read_buffer);
  154. // TODO: terminate the plugins properly before this is called
  155. LIST_FOR_EACH (struct plugin, link, self->plugins)
  156. plugin_destroy (link);
  157. if (self->irc_fd != -1)
  158. {
  159. poller_fd_reset (&self->irc_event);
  160. xclose (self->irc_fd);
  161. }
  162. if (self->ssl)
  163. SSL_free (self->ssl);
  164. if (self->ssl_ctx)
  165. SSL_CTX_free (self->ssl_ctx);
  166. str_map_free (&self->plugins_by_name);
  167. poller_free (&self->poller);
  168. }
  169. static void
  170. irc_shutdown (struct bot_context *ctx)
  171. {
  172. // TODO: set a timer after which we cut the connection?
  173. // Generally non-critical
  174. if (ctx->ssl)
  175. soft_assert (SSL_shutdown (ctx->ssl) != -1);
  176. else
  177. soft_assert (shutdown (ctx->irc_fd, SHUT_WR) == 0);
  178. }
  179. static void
  180. try_finish_quit (struct bot_context *ctx)
  181. {
  182. if (ctx->quitting && ctx->irc_fd == -1 && !ctx->plugins)
  183. ctx->polling = false;
  184. }
  185. static bool plugin_zombify (struct plugin *);
  186. static void
  187. initiate_quit (struct bot_context *ctx)
  188. {
  189. // Initiate bringing down of the two things that block our shutdown:
  190. // a/ the IRC socket, b/ our child processes:
  191. for (struct plugin *plugin = ctx->plugins;
  192. plugin; plugin = plugin->next)
  193. plugin_zombify (plugin);
  194. if (ctx->irc_fd != -1)
  195. irc_shutdown (ctx);
  196. ctx->quitting = true;
  197. try_finish_quit (ctx);
  198. }
  199. static bool irc_send (struct bot_context *ctx,
  200. const char *format, ...) ATTRIBUTE_PRINTF (2, 3);
  201. static bool
  202. irc_send (struct bot_context *ctx, const char *format, ...)
  203. {
  204. va_list ap;
  205. if (g_debug_mode)
  206. {
  207. fputs ("[IRC] <== \"", stderr);
  208. va_start (ap, format);
  209. vfprintf (stderr, format, ap);
  210. va_end (ap);
  211. fputs ("\"\n", stderr);
  212. }
  213. if (!soft_assert (ctx->irc_fd != -1))
  214. return false;
  215. va_start (ap, format);
  216. struct str str = str_make ();
  217. str_append_vprintf (&str, format, ap);
  218. str_append (&str, "\r\n");
  219. va_end (ap);
  220. bool result = true;
  221. if (ctx->ssl)
  222. {
  223. // TODO: call SSL_get_error() to detect if a clean shutdown has occured
  224. ERR_clear_error ();
  225. if (SSL_write (ctx->ssl, str.str, str.len) != (int) str.len)
  226. {
  227. print_debug ("%s: %s: %s", __func__, "SSL_write",
  228. ERR_error_string (ERR_get_error (), NULL));
  229. result = false;
  230. }
  231. }
  232. else if (write (ctx->irc_fd, str.str, str.len) != (ssize_t) str.len)
  233. {
  234. print_debug ("%s: %s: %s", __func__, "write", strerror (errno));
  235. result = false;
  236. }
  237. str_free (&str);
  238. return result;
  239. }
  240. static bool
  241. irc_get_boolean_from_config
  242. (struct bot_context *ctx, const char *name, bool *value, struct error **e)
  243. {
  244. const char *str = str_map_find (&ctx->config, name);
  245. hard_assert (str != NULL);
  246. if (set_boolean_if_valid (value, str))
  247. return true;
  248. return error_set (e, "invalid configuration value for `%s'", name);
  249. }
  250. static bool
  251. irc_initialize_ca_set (SSL_CTX *ssl_ctx, const char *file, const char *path,
  252. struct error **e)
  253. {
  254. ERR_clear_error ();
  255. if (file || path)
  256. {
  257. if (SSL_CTX_load_verify_locations (ssl_ctx, file, path))
  258. return true;
  259. return error_set (e, "%s: %s",
  260. "failed to set locations for the CA certificate bundle",
  261. ERR_reason_error_string (ERR_get_error ()));
  262. }
  263. if (!SSL_CTX_set_default_verify_paths (ssl_ctx))
  264. return error_set (e, "%s: %s",
  265. "couldn't load the default CA certificate bundle",
  266. ERR_reason_error_string (ERR_get_error ()));
  267. return true;
  268. }
  269. static bool
  270. irc_initialize_ca (struct bot_context *ctx, struct error **e)
  271. {
  272. const char *ca_file = str_map_find (&ctx->config, "tls_ca_file");
  273. const char *ca_path = str_map_find (&ctx->config, "tls_ca_path");
  274. char *full_file = ca_file
  275. ? resolve_filename (ca_file, resolve_relative_config_filename) : NULL;
  276. char *full_path = ca_path
  277. ? resolve_filename (ca_path, resolve_relative_config_filename) : NULL;
  278. bool ok = false;
  279. if (ca_file && !full_file)
  280. error_set (e, "couldn't find the CA bundle file");
  281. else if (ca_path && !full_path)
  282. error_set (e, "couldn't find the CA bundle path");
  283. else
  284. ok = irc_initialize_ca_set (ctx->ssl_ctx, full_file, full_path, e);
  285. free (full_file);
  286. free (full_path);
  287. return ok;
  288. }
  289. static bool
  290. irc_initialize_ssl_ctx (struct bot_context *ctx, struct error **e)
  291. {
  292. // Disable deprecated protocols (see RFC 7568)
  293. SSL_CTX_set_options (ctx->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
  294. bool verify;
  295. if (!irc_get_boolean_from_config (ctx, "tls_verify", &verify, e))
  296. return false;
  297. SSL_CTX_set_verify (ctx->ssl_ctx,
  298. verify ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
  299. struct error *error = NULL;
  300. if (!irc_initialize_ca (ctx, &error))
  301. {
  302. if (verify)
  303. {
  304. error_propagate (e, error);
  305. return false;
  306. }
  307. // Only inform the user if we're not actually verifying
  308. print_warning ("%s", error->message);
  309. error_free (error);
  310. }
  311. return true;
  312. }
  313. static bool
  314. irc_initialize_tls (struct bot_context *ctx, struct error **e)
  315. {
  316. const char *error_info = NULL;
  317. ctx->ssl_ctx = SSL_CTX_new (SSLv23_client_method ());
  318. if (!ctx->ssl_ctx)
  319. goto error_ssl_1;
  320. if (!irc_initialize_ssl_ctx (ctx, e))
  321. goto error_ssl_2;
  322. ctx->ssl = SSL_new (ctx->ssl_ctx);
  323. if (!ctx->ssl)
  324. goto error_ssl_2;
  325. const char *tls_cert = str_map_find (&ctx->config, "tls_cert");
  326. if (tls_cert)
  327. {
  328. char *path = resolve_filename
  329. (tls_cert, resolve_relative_config_filename);
  330. if (!path)
  331. print_error ("%s: %s", "cannot open file", tls_cert);
  332. // XXX: perhaps we should read the file ourselves for better messages
  333. else if (!SSL_use_certificate_file (ctx->ssl, path, SSL_FILETYPE_PEM)
  334. || !SSL_use_PrivateKey_file (ctx->ssl, path, SSL_FILETYPE_PEM))
  335. print_error ("%s: %s", "setting the TLS client certificate failed",
  336. ERR_error_string (ERR_get_error (), NULL));
  337. free (path);
  338. }
  339. SSL_set_connect_state (ctx->ssl);
  340. if (!SSL_set_fd (ctx->ssl, ctx->irc_fd))
  341. goto error_ssl_3;
  342. // Avoid SSL_write() returning SSL_ERROR_WANT_READ
  343. SSL_set_mode (ctx->ssl, SSL_MODE_AUTO_RETRY);
  344. switch (xssl_get_error (ctx->ssl, SSL_connect (ctx->ssl), &error_info))
  345. {
  346. case SSL_ERROR_NONE:
  347. return true;
  348. case SSL_ERROR_ZERO_RETURN:
  349. error_info = "server closed the connection";
  350. default:
  351. break;
  352. }
  353. error_ssl_3:
  354. SSL_free (ctx->ssl);
  355. ctx->ssl = NULL;
  356. error_ssl_2:
  357. SSL_CTX_free (ctx->ssl_ctx);
  358. ctx->ssl_ctx = NULL;
  359. error_ssl_1:
  360. // XXX: these error strings are really nasty; also there could be
  361. // multiple errors on the OpenSSL stack.
  362. if (!error_info)
  363. error_info = ERR_error_string (ERR_get_error (), NULL);
  364. return error_set (e, "%s: %s", "could not initialize TLS", error_info);
  365. }
  366. static bool
  367. irc_establish_connection (struct bot_context *ctx,
  368. const char *host, const char *port, struct error **e)
  369. {
  370. struct addrinfo gai_hints, *gai_result, *gai_iter;
  371. memset (&gai_hints, 0, sizeof gai_hints);
  372. gai_hints.ai_socktype = SOCK_STREAM;
  373. int err = getaddrinfo (host, port, &gai_hints, &gai_result);
  374. if (err)
  375. return error_set (e, "%s: %s: %s", "connection failed",
  376. "getaddrinfo", gai_strerror (err));
  377. int sockfd;
  378. for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next)
  379. {
  380. sockfd = socket (gai_iter->ai_family,
  381. gai_iter->ai_socktype, gai_iter->ai_protocol);
  382. if (sockfd == -1)
  383. continue;
  384. set_cloexec (sockfd);
  385. int yes = 1;
  386. soft_assert (setsockopt (sockfd, SOL_SOCKET, SO_KEEPALIVE,
  387. &yes, sizeof yes) != -1);
  388. const char *real_host = host;
  389. // Let's try to resolve the address back into a real hostname;
  390. // we don't really need this, so we can let it quietly fail
  391. char buf[NI_MAXHOST];
  392. err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen,
  393. buf, sizeof buf, NULL, 0, 0);
  394. if (err)
  395. print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
  396. else
  397. real_host = buf;
  398. // XXX: we shouldn't mix these statuses with `struct error'; choose 1!
  399. char *address = format_host_port_pair (real_host, port);
  400. print_status ("connecting to %s...", address);
  401. free (address);
  402. if (!connect (sockfd, gai_iter->ai_addr, gai_iter->ai_addrlen))
  403. break;
  404. xclose (sockfd);
  405. }
  406. freeaddrinfo (gai_result);
  407. if (!gai_iter)
  408. return error_set (e, "connection failed");
  409. ctx->irc_fd = sockfd;
  410. return true;
  411. }
  412. // --- Signals -----------------------------------------------------------------
  413. static int g_signal_pipe[2]; ///< A pipe used to signal... signals
  414. static struct strv
  415. g_original_argv, ///< Original program arguments
  416. g_recovery_env; ///< Environment for re-exec recovery
  417. /// Program termination has been requested by a signal
  418. static volatile sig_atomic_t g_termination_requested;
  419. /// Points to startup reason location within `g_recovery_environment'
  420. static char **g_startup_reason_location;
  421. /// The environment variable used to pass the startup reason when re-executing
  422. static const char g_startup_reason_str[] = "STARTUP_REASON";
  423. static void
  424. sigchld_handler (int signum)
  425. {
  426. (void) signum;
  427. int original_errno = errno;
  428. // Just so that the read end of the pipe wakes up the poller.
  429. // NOTE: Linux has signalfd() and eventfd(), and the BSD's have kqueue.
  430. // All of them are better than this approach, although platform-specific.
  431. if (write (g_signal_pipe[1], "c", 1) == -1)
  432. soft_assert (errno == EAGAIN);
  433. errno = original_errno;
  434. }
  435. static void
  436. sigterm_handler (int signum)
  437. {
  438. (void) signum;
  439. g_termination_requested = true;
  440. int original_errno = errno;
  441. if (write (g_signal_pipe[1], "t", 1) == -1)
  442. soft_assert (errno == EAGAIN);
  443. errno = original_errno;
  444. }
  445. static void
  446. setup_signal_handlers (void)
  447. {
  448. if (pipe (g_signal_pipe) == -1)
  449. exit_fatal ("%s: %s", "pipe", strerror (errno));
  450. set_cloexec (g_signal_pipe[0]);
  451. set_cloexec (g_signal_pipe[1]);
  452. // So that the pipe cannot overflow; it would make write() block within
  453. // the signal handler, which is something we really don't want to happen.
  454. // The same holds true for read().
  455. set_blocking (g_signal_pipe[0], false);
  456. set_blocking (g_signal_pipe[1], false);
  457. struct sigaction sa;
  458. sa.sa_flags = SA_RESTART;
  459. sa.sa_handler = sigchld_handler;
  460. sigemptyset (&sa.sa_mask);
  461. if (sigaction (SIGCHLD, &sa, NULL) == -1)
  462. exit_fatal ("sigaction: %s", strerror (errno));
  463. signal (SIGPIPE, SIG_IGN);
  464. sa.sa_handler = sigterm_handler;
  465. if (sigaction (SIGINT, &sa, NULL) == -1
  466. || sigaction (SIGTERM, &sa, NULL) == -1)
  467. exit_fatal ("sigaction: %s", strerror (errno));
  468. }
  469. static void
  470. translate_signal_info (int no, const char **name, int code, const char **reason)
  471. {
  472. if (code == SI_USER) *reason = "signal sent by kill()";
  473. if (code == SI_QUEUE) *reason = "signal sent by sigqueue()";
  474. switch (no)
  475. {
  476. case SIGILL:
  477. *name = "SIGILL";
  478. if (code == ILL_ILLOPC) *reason = "illegal opcode";
  479. if (code == ILL_ILLOPN) *reason = "illegal operand";
  480. if (code == ILL_ILLADR) *reason = "illegal addressing mode";
  481. if (code == ILL_ILLTRP) *reason = "illegal trap";
  482. if (code == ILL_PRVOPC) *reason = "privileged opcode";
  483. if (code == ILL_PRVREG) *reason = "privileged register";
  484. if (code == ILL_COPROC) *reason = "coprocessor error";
  485. if (code == ILL_BADSTK) *reason = "internal stack error";
  486. break;
  487. case SIGFPE:
  488. *name = "SIGFPE";
  489. if (code == FPE_INTDIV) *reason = "integer divide by zero";
  490. if (code == FPE_INTOVF) *reason = "integer overflow";
  491. if (code == FPE_FLTDIV) *reason = "floating-point divide by zero";
  492. if (code == FPE_FLTOVF) *reason = "floating-point overflow";
  493. if (code == FPE_FLTUND) *reason = "floating-point underflow";
  494. if (code == FPE_FLTRES) *reason = "floating-point inexact result";
  495. if (code == FPE_FLTINV) *reason = "invalid floating-point operation";
  496. if (code == FPE_FLTSUB) *reason = "subscript out of range";
  497. break;
  498. case SIGSEGV:
  499. *name = "SIGSEGV";
  500. if (code == SEGV_MAPERR)
  501. *reason = "address not mapped to object";
  502. if (code == SEGV_ACCERR)
  503. *reason = "invalid permissions for mapped object";
  504. break;
  505. case SIGBUS:
  506. *name = "SIGBUS";
  507. if (code == BUS_ADRALN) *reason = "invalid address alignment";
  508. if (code == BUS_ADRERR) *reason = "nonexistent physical address";
  509. if (code == BUS_OBJERR) *reason = "object-specific hardware error";
  510. break;
  511. default:
  512. *name = NULL;
  513. }
  514. }
  515. static void
  516. recovery_handler (int signum, siginfo_t *info, void *context)
  517. {
  518. (void) context;
  519. // TODO: maybe try to force a core dump like this: if (fork() == 0) return;
  520. // TODO: maybe we could even send "\r\nQUIT :reason\r\n" to the server. >_>
  521. // As long as we're not connected via TLS, that is.
  522. const char *signal_name = NULL, *reason = NULL;
  523. translate_signal_info (signum, &signal_name, info->si_code, &reason);
  524. char buf[128], numbuf[8];
  525. if (!signal_name)
  526. {
  527. snprintf (numbuf, sizeof numbuf, "%d", signum);
  528. signal_name = numbuf;
  529. }
  530. if (reason)
  531. snprintf (buf, sizeof buf, "%s=%s: %s: %s", g_startup_reason_str,
  532. "signal received", signal_name, reason);
  533. else
  534. snprintf (buf, sizeof buf, "%s=%s: %s", g_startup_reason_str,
  535. "signal received", signal_name);
  536. *g_startup_reason_location = buf;
  537. // Avoid annoying resource intensive infinite loops by sleeping for a bit
  538. (void) sleep (1);
  539. // TODO: maybe pregenerate the path, see the following for some other ways
  540. // that would be illegal to do from within a signal handler:
  541. // http://stackoverflow.com/a/1024937
  542. // http://stackoverflow.com/q/799679
  543. // Especially if we change the current working directory in the program.
  544. //
  545. // Note that I can just overwrite g_orig_argv[0].
  546. // NOTE: our children will read EOF on the read ends of their pipes as a
  547. // a result of O_CLOEXEC. That should be enough to make them terminate.
  548. char **argv = g_original_argv.vector, **argp = g_recovery_env.vector;
  549. execve ("/proc/self/exe", argv, argp); // Linux
  550. execve ("/proc/curproc/file", argv, argp); // BSD
  551. execve ("/proc/curproc/exe", argv, argp); // BSD
  552. execve ("/proc/self/path/a.out", argv, argp); // Solaris
  553. execve (argv[0], argv, argp); // unreliable fallback
  554. // Let's just crash
  555. perror ("execve");
  556. signal (signum, SIG_DFL);
  557. raise (signum);
  558. }
  559. static void
  560. prepare_recovery_environment (void)
  561. {
  562. g_recovery_env = strv_make ();
  563. strv_append_vector (&g_recovery_env, environ);
  564. // Prepare a location within the environment where we will put the startup
  565. // (or maybe rather restart) reason in case of an irrecoverable error.
  566. char **iter;
  567. for (iter = g_recovery_env.vector; *iter; iter++)
  568. {
  569. const size_t len = sizeof g_startup_reason_str - 1;
  570. if (!strncmp (*iter, g_startup_reason_str, len) && (*iter)[len] == '=')
  571. break;
  572. }
  573. if (*iter)
  574. g_startup_reason_location = iter;
  575. else
  576. {
  577. g_startup_reason_location = g_recovery_env.vector + g_recovery_env.len;
  578. strv_append (&g_recovery_env, "");
  579. }
  580. }
  581. static bool
  582. setup_recovery_handler (struct bot_context *ctx, struct error **e)
  583. {
  584. bool recover;
  585. if (!irc_get_boolean_from_config (ctx, "recover", &recover, e))
  586. return false;
  587. if (!recover)
  588. return true;
  589. // Make sure these signals aren't blocked, otherwise we would be unable
  590. // to handle them, making the critical conditions fatal.
  591. sigset_t mask;
  592. sigemptyset (&mask);
  593. sigaddset (&mask, SIGSEGV);
  594. sigaddset (&mask, SIGBUS);
  595. sigaddset (&mask, SIGFPE);
  596. sigaddset (&mask, SIGILL);
  597. sigprocmask (SIG_UNBLOCK, &mask, NULL);
  598. struct sigaction sa;
  599. sa.sa_flags = SA_SIGINFO;
  600. sa.sa_sigaction = recovery_handler;
  601. sigemptyset (&sa.sa_mask);
  602. prepare_recovery_environment ();
  603. // TODO: also handle SIGABRT... or avoid doing abort() in the first place?
  604. if (sigaction (SIGSEGV, &sa, NULL) == -1
  605. || sigaction (SIGBUS, &sa, NULL) == -1
  606. || sigaction (SIGFPE, &sa, NULL) == -1
  607. || sigaction (SIGILL, &sa, NULL) == -1)
  608. print_error ("sigaction: %s", strerror (errno));
  609. return true;
  610. }
  611. // --- Plugins -----------------------------------------------------------------
  612. /// The name of the special IRC command for interprocess communication
  613. static const char *plugin_ipc_command = "ZYKLONB";
  614. static struct plugin *
  615. plugin_find_by_pid (struct bot_context *ctx, pid_t pid)
  616. {
  617. struct plugin *iter;
  618. for (iter = ctx->plugins; iter; iter = iter->next)
  619. if (iter->pid == pid)
  620. return iter;
  621. return NULL;
  622. }
  623. static bool
  624. plugin_zombify (struct plugin *plugin)
  625. {
  626. if (plugin->is_zombie)
  627. return false;
  628. // FIXME: make sure that we don't remove entries from the poller while we
  629. // still may have stuff to read; maybe just check that the read pipe is
  630. // empty before closing it... and then on EOF check if `pid == -1' and
  631. // only then dispose of it (it'd be best to simulate that both of these
  632. // cases may happen).
  633. poller_fd_reset (&plugin->write_event);
  634. // TODO: try to flush the write buffer (non-blocking)?
  635. // The plugin should terminate itself after it receives EOF.
  636. xclose (plugin->write_fd);
  637. plugin->write_fd = -1;
  638. // Make it a pseudo-anonymous zombie. In this state we process any
  639. // remaining commands it attempts to send to us before it finally dies.
  640. str_map_set (&plugin->ctx->plugins_by_name, plugin->name, NULL);
  641. plugin->is_zombie = true;
  642. // TODO: wait a few seconds and then send SIGKILL to the plugin
  643. return true;
  644. }
  645. static void
  646. on_plugin_writable (const struct pollfd *fd, struct plugin *plugin)
  647. {
  648. struct str *buf = &plugin->write_buffer;
  649. size_t written_total = 0;
  650. if (fd->revents & ~(POLLOUT | POLLHUP | POLLERR))
  651. print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);
  652. while (written_total != buf->len)
  653. {
  654. ssize_t n_written = write (fd->fd, buf->str + written_total,
  655. buf->len - written_total);
  656. if (n_written < 0)
  657. {
  658. if (errno == EAGAIN)
  659. break;
  660. if (errno == EINTR)
  661. continue;
  662. soft_assert (errno == EPIPE);
  663. // Zombies shouldn't get dispatched for writability
  664. hard_assert (!plugin->is_zombie);
  665. print_debug ("%s: %s", "write", strerror (errno));
  666. print_error ("failure on writing to plugin `%s',"
  667. " therefore I'm unloading it", plugin->name);
  668. plugin_zombify (plugin);
  669. break;
  670. }
  671. // This may be equivalent to EAGAIN on some implementations
  672. if (n_written == 0)
  673. break;
  674. written_total += n_written;
  675. }
  676. if (written_total != 0)
  677. str_remove_slice (buf, 0, written_total);
  678. if (buf->len == 0)
  679. // Everything has been written, there's no need to end up in here again
  680. poller_fd_reset (&plugin->write_event);
  681. }
  682. static void
  683. plugin_queue_write (struct plugin *plugin)
  684. {
  685. if (plugin->is_zombie)
  686. return;
  687. // Don't let the write buffer grow indefinitely. If there's a ton of data
  688. // waiting to be processed by the plugin, it usually means there's something
  689. // wrong with it (such as someone stopping the process).
  690. if (plugin->write_buffer.len >= (1 << 20))
  691. {
  692. print_warning ("plugin `%s' does not seem to process messages fast"
  693. " enough, I'm unloading it", plugin->name);
  694. plugin_zombify (plugin);
  695. return;
  696. }
  697. poller_fd_set (&plugin->write_event, POLLOUT);
  698. }
  699. static void
  700. plugin_send (struct plugin *plugin, const char *format, ...)
  701. ATTRIBUTE_PRINTF (2, 3);
  702. static void
  703. plugin_send (struct plugin *plugin, const char *format, ...)
  704. {
  705. va_list ap;
  706. if (g_debug_mode)
  707. {
  708. fprintf (stderr, "[%s] <-- \"", plugin->name);
  709. va_start (ap, format);
  710. vfprintf (stderr, format, ap);
  711. va_end (ap);
  712. fputs ("\"\n", stderr);
  713. }
  714. va_start (ap, format);
  715. str_append_vprintf (&plugin->write_buffer, format, ap);
  716. va_end (ap);
  717. str_append (&plugin->write_buffer, "\r\n");
  718. plugin_queue_write (plugin);
  719. }
  720. static void
  721. plugin_process_ipc (struct plugin *plugin, const struct irc_message *msg)
  722. {
  723. // Replies are sent in the order in which they came in, so there's
  724. // no need to attach a special identifier to them. It might be
  725. // desirable in some cases, though.
  726. if (msg->params.len < 1)
  727. return;
  728. const char *command = msg->params.vector[0];
  729. if (!plugin->initialized && !strcasecmp (command, "register"))
  730. {
  731. // Register for relaying of IRC traffic
  732. plugin->initialized = true;
  733. // Flush any queued up traffic here. The point of queuing it in
  734. // the first place is so that we don't have to wait for plugin
  735. // initialization during startup.
  736. //
  737. // Note that if we start filtering data coming to the plugins e.g.
  738. // based on what it tells us upon registration, we might need to
  739. // filter `queued_output' as well.
  740. str_append_str (&plugin->write_buffer, &plugin->queued_output);
  741. str_free (&plugin->queued_output);
  742. // NOTE: this may trigger the buffer length check
  743. plugin_queue_write (plugin);
  744. }
  745. else if (!strcasecmp (command, "get_config"))
  746. {
  747. if (msg->params.len < 2)
  748. return;
  749. const char *value =
  750. str_map_find (&plugin->ctx->config, msg->params.vector[1]);
  751. // TODO: escape the value (although there's no need to ATM)
  752. plugin_send (plugin, "%s :%s",
  753. plugin_ipc_command, value ? value : "");
  754. }
  755. else if (!strcasecmp (command, "print"))
  756. {
  757. if (msg->params.len < 2)
  758. return;
  759. printf ("%s\n", msg->params.vector[1]);
  760. }
  761. }
  762. static void
  763. plugin_process_message (const struct irc_message *msg,
  764. const char *raw, void *user_data)
  765. {
  766. struct plugin *plugin = user_data;
  767. struct bot_context *ctx = plugin->ctx;
  768. if (g_debug_mode)
  769. fprintf (stderr, "[%s] --> \"%s\"\n", plugin->name, raw);
  770. if (!strcasecmp (msg->command, plugin_ipc_command))
  771. plugin_process_ipc (plugin, msg);
  772. else if (plugin->initialized && ctx->irc_registered)
  773. {
  774. // Pass everything else through to the IRC server
  775. // XXX: when the server isn't ready yet, these messages get silently
  776. // discarded, which shouldn't pose a problem most of the time.
  777. // Perhaps we could send a "connected" notification on `register'
  778. // if `irc_ready' is true, or after it becomes true later, so that
  779. // plugins know when to start sending unprovoked IRC messages.
  780. // XXX: another case is when the connection gets interrupted and the
  781. // plugin tries to send something back while we're reconnecting.
  782. // For that we might set up a global buffer that gets flushed out
  783. // after `irc_ready' becomes true. Note that there is always some
  784. // chance of messages getting lost without us even noticing it.
  785. irc_send (ctx, "%s", raw);
  786. }
  787. }
  788. static void
  789. on_plugin_readable (const struct pollfd *fd, struct plugin *plugin)
  790. {
  791. if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
  792. print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);
  793. // TODO: see if I can reuse irc_fill_read_buffer()
  794. struct str *buf = &plugin->read_buffer;
  795. while (true)
  796. {
  797. str_reserve (buf, 512 + 1);
  798. ssize_t n_read = read (fd->fd, buf->str + buf->len,
  799. buf->alloc - buf->len - 1);
  800. if (n_read < 0)
  801. {
  802. if (errno == EAGAIN)
  803. break;
  804. if (soft_assert (errno == EINTR))
  805. continue;
  806. if (!plugin->is_zombie)
  807. {
  808. print_error ("failure on reading from plugin `%s',"
  809. " therefore I'm unloading it", plugin->name);
  810. plugin_zombify (plugin);
  811. }
  812. return;
  813. }
  814. // EOF; hopefully it will die soon (maybe it already has)
  815. if (n_read == 0)
  816. break;
  817. buf->str[buf->len += n_read] = '\0';
  818. if (buf->len >= (1 << 20))
  819. {
  820. // XXX: this isn't really the best flood prevention mechanism,
  821. // but it wasn't even supposed to be one.
  822. if (plugin->is_zombie)
  823. {
  824. print_error ("a zombie of plugin `%s' is trying to flood us,"
  825. " therefore I'm killing it", plugin->name);
  826. kill (plugin->pid, SIGKILL);
  827. }
  828. else
  829. {
  830. print_error ("plugin `%s' seems to spew out data frantically,"
  831. " therefore I'm unloading it", plugin->name);
  832. plugin_zombify (plugin);
  833. }
  834. return;
  835. }
  836. }
  837. irc_process_buffer (buf, plugin_process_message, plugin);
  838. }
  839. static bool
  840. is_valid_plugin_name (const char *name)
  841. {
  842. if (!*name)
  843. return false;
  844. for (const char *p = name; *p; p++)
  845. if (!isgraph (*p) || *p == '/')
  846. return false;
  847. return true;
  848. }
  849. static struct plugin *
  850. plugin_launch (struct bot_context *ctx, const char *name, struct error **e)
  851. {
  852. const char *plugin_dir = str_map_find (&ctx->config, "plugin_dir");
  853. if (!plugin_dir)
  854. {
  855. error_set (e, "plugin directory not set");
  856. return NULL;
  857. }
  858. int stdin_pipe[2];
  859. if (pipe (stdin_pipe) == -1)
  860. {
  861. error_set (e, "%s: %s", "pipe", strerror (errno));
  862. return NULL;
  863. }
  864. int stdout_pipe[2];
  865. if (pipe (stdout_pipe) == -1)
  866. {
  867. error_set (e, "%s: %s", "pipe", strerror (errno));
  868. goto fail_1;
  869. }
  870. struct str work_dir = str_make ();
  871. get_xdg_home_dir (&work_dir, "XDG_DATA_HOME", ".local/share");
  872. str_append_printf (&work_dir, "/%s", PROGRAM_NAME);
  873. if (!mkdir_with_parents (work_dir.str, e))
  874. goto fail_2;
  875. set_cloexec (stdin_pipe[1]);
  876. set_cloexec (stdout_pipe[0]);
  877. pid_t pid = fork ();
  878. if (pid == -1)
  879. {
  880. error_set (e, "%s: %s", "fork", strerror (errno));
  881. goto fail_2;
  882. }
  883. if (pid == 0)
  884. {
  885. // Redirect the child's stdin and stdout to the pipes
  886. if (dup2 (stdin_pipe[0], STDIN_FILENO) == -1
  887. || dup2 (stdout_pipe[1], STDOUT_FILENO) == -1)
  888. {
  889. print_error ("%s: %s: %s", "failed to load the plugin",
  890. "dup2", strerror (errno));
  891. _exit (EXIT_FAILURE);
  892. }
  893. if (chdir (work_dir.str))
  894. {
  895. print_error ("%s: %s: %s", "failed to load the plugin",
  896. "chdir", strerror (errno));
  897. _exit (EXIT_FAILURE);
  898. }
  899. xclose (stdin_pipe[0]);
  900. xclose (stdout_pipe[1]);
  901. // Restore some of the signal handling
  902. signal (SIGPIPE, SIG_DFL);
  903. char *argv[] = { xstrdup_printf ("%s/%s", plugin_dir, name), NULL };
  904. execve (argv[0], argv, environ);
  905. // We will collect the failure later via SIGCHLD
  906. print_error ("%s: %s: %s", "failed to load the plugin",
  907. "exec", strerror (errno));
  908. _exit (EXIT_FAILURE);
  909. }
  910. str_free (&work_dir);
  911. xclose (stdin_pipe[0]);
  912. xclose (stdout_pipe[1]);
  913. struct plugin *plugin = plugin_new ();
  914. plugin->ctx = ctx;
  915. plugin->pid = pid;
  916. plugin->name = xstrdup (name);
  917. plugin->read_fd = stdout_pipe[0];
  918. plugin->write_fd = stdin_pipe[1];
  919. return plugin;
  920. fail_2:
  921. str_free (&work_dir);
  922. xclose (stdout_pipe[0]);
  923. xclose (stdout_pipe[1]);
  924. fail_1:
  925. xclose (stdin_pipe[0]);
  926. xclose (stdin_pipe[1]);
  927. return NULL;
  928. }
  929. static bool
  930. plugin_load (struct bot_context *ctx, const char *name, struct error **e)
  931. {
  932. if (!is_valid_plugin_name (name))
  933. return error_set (e, "invalid plugin name");
  934. if (str_map_find (&ctx->plugins_by_name, name))
  935. return error_set (e, "the plugin has already been loaded");
  936. struct plugin *plugin;
  937. if (!(plugin = plugin_launch (ctx, name, e)))
  938. return false;
  939. set_blocking (plugin->read_fd, false);
  940. set_blocking (plugin->write_fd, false);
  941. plugin->read_event = poller_fd_make (&ctx->poller, plugin->read_fd);
  942. plugin->read_event.dispatcher = (poller_fd_fn) on_plugin_readable;
  943. plugin->read_event.user_data = plugin;
  944. plugin->write_event = poller_fd_make (&ctx->poller, plugin->write_fd);
  945. plugin->write_event.dispatcher = (poller_fd_fn) on_plugin_writable;
  946. plugin->write_event.user_data = plugin;
  947. LIST_PREPEND (ctx->plugins, plugin);
  948. str_map_set (&ctx->plugins_by_name, name, plugin);
  949. poller_fd_set (&plugin->read_event, POLLIN);
  950. return true;
  951. }
  952. static bool
  953. plugin_unload (struct bot_context *ctx, const char *name, struct error **e)
  954. {
  955. struct plugin *plugin = str_map_find (&ctx->plugins_by_name, name);
  956. if (!plugin)
  957. return error_set (e, "no such plugin is loaded");
  958. plugin_zombify (plugin);
  959. // TODO: add a `kill zombies' command to forcefully get rid of processes
  960. // that do not understand the request.
  961. return true;
  962. }
  963. static void
  964. plugin_load_all_from_config (struct bot_context *ctx)
  965. {
  966. const char *plugin_list = str_map_find (&ctx->config, "plugins");
  967. if (!plugin_list)
  968. return;
  969. struct strv plugins = strv_make ();
  970. cstr_split (plugin_list, ",", true, &plugins);
  971. for (size_t i = 0; i < plugins.len; i++)
  972. {
  973. char *name = cstr_strip_in_place (plugins.vector[i], " ");
  974. struct error *e = NULL;
  975. if (!plugin_load (ctx, name, &e))
  976. {
  977. print_error ("plugin `%s' failed to load: %s", name, e->message);
  978. error_free (e);
  979. }
  980. }
  981. strv_free (&plugins);
  982. }
  983. // --- Main program ------------------------------------------------------------
  984. static bool
  985. parse_bot_command (const char *s, const char *command, const char **following)
  986. {
  987. size_t command_len = strlen (command);
  988. if (strncasecmp (s, command, command_len))
  989. return false;
  990. s += command_len;
  991. // Expect a word boundary, so that we don't respond to invalid things
  992. if (isalnum (*s))
  993. return false;
  994. // Ignore any initial spaces; the rest is the command's argument
  995. while (isblank (*s))
  996. s++;
  997. *following = s;
  998. return true;
  999. }
  1000. static void
  1001. split_bot_command_argument_list (const char *arguments, struct strv *out)
  1002. {
  1003. cstr_split (arguments, ",", true, out);
  1004. for (size_t i = 0; i < out->len; )
  1005. {
  1006. if (!*cstr_strip_in_place (out->vector[i], " \t"))
  1007. strv_remove (out, i);
  1008. else
  1009. i++;
  1010. }
  1011. }
  1012. static bool
  1013. is_private_message (const struct irc_message *msg)
  1014. {
  1015. hard_assert (msg->params.len);
  1016. return !strchr ("#&+!", *msg->params.vector[0]);
  1017. }
  1018. static bool
  1019. is_sent_by_admin (struct bot_context *ctx, const struct irc_message *msg)
  1020. {
  1021. // No administrator set -> everyone is an administrator
  1022. if (!ctx->admin_re)
  1023. return true;
  1024. return regexec (ctx->admin_re, msg->prefix, 0, NULL, 0) != REG_NOMATCH;
  1025. }
  1026. static void respond_to_user (struct bot_context *ctx, const struct
  1027. irc_message *msg, const char *format, ...) ATTRIBUTE_PRINTF (3, 4);
  1028. static void
  1029. respond_to_user (struct bot_context *ctx, const struct irc_message *msg,
  1030. const char *format, ...)
  1031. {
  1032. if (!soft_assert (msg->prefix && msg->params.len))
  1033. return;
  1034. char nick[strcspn (msg->prefix, "!") + 1];
  1035. strncpy (nick, msg->prefix, sizeof nick - 1);
  1036. nick[sizeof nick - 1] = '\0';
  1037. va_list ap;
  1038. struct str text = str_make ();
  1039. va_start (ap, format);
  1040. str_append_vprintf (&text, format, ap);
  1041. va_end (ap);
  1042. if (is_private_message (msg))
  1043. irc_send (ctx, "PRIVMSG %s :%s", nick, text.str);
  1044. else
  1045. irc_send (ctx, "PRIVMSG %s :%s: %s",
  1046. msg->params.vector[0], nick, text.str);
  1047. str_free (&text);
  1048. }
  1049. static void
  1050. process_plugin_load (struct bot_context *ctx,
  1051. const struct irc_message *msg, const char *name)
  1052. {
  1053. struct error *e = NULL;
  1054. if (plugin_load (ctx, name, &e))
  1055. respond_to_user (ctx, msg, "plugin `%s' queued for loading", name);
  1056. else
  1057. {
  1058. respond_to_user (ctx, msg, "plugin `%s' could not be loaded: %s",
  1059. name, e->message);
  1060. error_free (e);
  1061. }
  1062. }
  1063. static void
  1064. process_plugin_unload (struct bot_context *ctx,
  1065. const struct irc_message *msg, const char *name)
  1066. {
  1067. struct error *e = NULL;
  1068. if (plugin_unload (ctx, name, &e))
  1069. respond_to_user (ctx, msg, "plugin `%s' unloaded", name);
  1070. else
  1071. {
  1072. respond_to_user (ctx, msg, "plugin `%s' could not be unloaded: %s",
  1073. name, e->message);
  1074. error_free (e);
  1075. }
  1076. }
  1077. static void
  1078. process_plugin_reload (struct bot_context *ctx,
  1079. const struct irc_message *msg, const char *name)
  1080. {
  1081. // XXX: we might want to wait until the plugin terminates before we try
  1082. // to reload it (so that it can save its configuration or whatever)
  1083. // So far the only error that can occur is that the plugin hasn't been
  1084. // loaded, which in this case doesn't really matter.
  1085. plugin_unload (ctx, name, NULL);
  1086. process_plugin_load (ctx, msg, name);
  1087. }
  1088. static char *
  1089. make_status_report (struct bot_context *ctx)
  1090. {
  1091. struct str report = str_make ();
  1092. const char *reason = getenv (g_startup_reason_str);
  1093. if (!reason)
  1094. reason = "launched normally";
  1095. str_append_printf (&report, "\x02startup reason:\x0f %s", reason);
  1096. size_t zombies = 0;
  1097. const char *prepend = "; \x02plugins:\x0f ";
  1098. for (struct plugin *plugin = ctx->plugins; plugin; plugin = plugin->next)
  1099. {
  1100. if (plugin->is_zombie)
  1101. zombies++;
  1102. else
  1103. {
  1104. str_append_printf (&report, "%s%s", prepend, plugin->name);
  1105. prepend = ", ";
  1106. }
  1107. }
  1108. if (!ctx->plugins)
  1109. str_append_printf (&report, "%s\x02none\x0f", prepend);
  1110. str_append_printf (&report, "; \x02zombies:\x0f %zu", zombies);
  1111. return str_steal (&report);
  1112. }
  1113. static void
  1114. process_privmsg (struct bot_context *ctx, const struct irc_message *msg)
  1115. {
  1116. if (!is_sent_by_admin (ctx, msg))
  1117. return;
  1118. if (msg->params.len < 2)
  1119. return;
  1120. const char *prefix = str_map_find (&ctx->config, "prefix");
  1121. hard_assert (prefix != NULL); // We have a default value for this
  1122. // For us to recognize the command, it has to start with the prefix,
  1123. // with the exception of PM's sent directly to us.
  1124. const char *text = msg->params.vector[1];
  1125. if (!strncmp (text, prefix, strlen (prefix)))
  1126. text += strlen (prefix);
  1127. else if (!is_private_message (msg))
  1128. return;
  1129. const char *following;
  1130. struct strv list = strv_make ();
  1131. if (parse_bot_command (text, "quote", &following))
  1132. // This seems to replace tons of random stupid commands
  1133. irc_send (ctx, "%s", following);
  1134. else if (parse_bot_command (text, "quit", &following))
  1135. {
  1136. // We actually need this command (instead of just `quote') because we
  1137. // could try to reconnect to the server automatically otherwise.
  1138. if (*following)
  1139. irc_send (ctx, "QUIT :%s", following);
  1140. else
  1141. irc_send (ctx, "QUIT");
  1142. initiate_quit (ctx);
  1143. }
  1144. else if (parse_bot_command (text, "status", &following))
  1145. {
  1146. char *report = make_status_report (ctx);
  1147. respond_to_user (ctx, msg, "%s", report);
  1148. free (report);
  1149. }
  1150. else if (parse_bot_command (text, "load", &following))
  1151. {
  1152. split_bot_command_argument_list (following, &list);
  1153. for (size_t i = 0; i < list.len; i++)
  1154. process_plugin_load (ctx, msg, list.vector[i]);
  1155. }
  1156. else if (parse_bot_command (text, "reload", &following))
  1157. {
  1158. split_bot_command_argument_list (following, &list);
  1159. for (size_t i = 0; i < list.len; i++)
  1160. process_plugin_reload (ctx, msg, list.vector[i]);
  1161. }
  1162. else if (parse_bot_command (text, "unload", &following))
  1163. {
  1164. split_bot_command_argument_list (following, &list);
  1165. for (size_t i = 0; i < list.len; i++)
  1166. process_plugin_unload (ctx, msg, list.vector[i]);
  1167. }
  1168. strv_free (&list);
  1169. }
  1170. static void
  1171. irc_forward_message_to_plugins (struct bot_context *ctx, const char *raw)
  1172. {
  1173. // For consistency with plugin_process_message()
  1174. if (!ctx->irc_registered)
  1175. return;
  1176. for (struct plugin *plugin = ctx->plugins;
  1177. plugin; plugin = plugin->next)
  1178. {
  1179. if (plugin->is_zombie)
  1180. continue;
  1181. if (plugin->initialized)
  1182. plugin_send (plugin, "%s", raw);
  1183. else
  1184. // TODO: make sure that this buffer doesn't get too large either
  1185. str_append_printf (&plugin->queued_output, "%s\r\n", raw);
  1186. }
  1187. }
  1188. static void
  1189. irc_process_message (const struct irc_message *msg,
  1190. const char *raw, void *user_data)
  1191. {
  1192. struct bot_context *ctx = user_data;
  1193. if (g_debug_mode)
  1194. fprintf (stderr, "[%s] ==> \"%s\"\n", "IRC", raw);
  1195. // This should be as minimal as possible, I don't want to have the whole bot
  1196. // written in C, especially when I have this overengineered plugin system.
  1197. // Therefore the very basic functionality only.
  1198. //
  1199. // I should probably even rip out the autojoin...
  1200. irc_forward_message_to_plugins (ctx, raw);
  1201. if (!strcasecmp (msg->command, "PING"))
  1202. {
  1203. if (msg->params.len)
  1204. irc_send (ctx, "PONG :%s", msg->params.vector[0]);
  1205. else
  1206. irc_send (ctx, "PONG");
  1207. }
  1208. else if (!ctx->irc_registered && !strcasecmp (msg->command, "001"))
  1209. {
  1210. print_status ("successfully connected");
  1211. ctx->irc_registered = true;
  1212. const char *autojoin = str_map_find (&ctx->config, "autojoin");
  1213. if (autojoin)
  1214. irc_send (ctx, "JOIN :%s", autojoin);
  1215. }
  1216. else if (!strcasecmp (msg->command, "PRIVMSG"))
  1217. process_privmsg (ctx, msg);
  1218. }
  1219. enum irc_read_result
  1220. {
  1221. IRC_READ_OK, ///< Some data were read successfully
  1222. IRC_READ_EOF, ///< The server has closed connection
  1223. IRC_READ_AGAIN, ///< No more data at the moment
  1224. IRC_READ_ERROR ///< General connection failure
  1225. };
  1226. static enum irc_read_result
  1227. irc_fill_read_buffer_tls (struct bot_context *ctx, struct str *buf)
  1228. {
  1229. int n_read;
  1230. start:
  1231. ERR_clear_error ();
  1232. n_read = SSL_read (ctx->ssl, buf->str + buf->len,
  1233. buf->alloc - buf->len - 1 /* null byte */);
  1234. const char *error_info = NULL;
  1235. switch (xssl_get_error (ctx->ssl, n_read, &error_info))
  1236. {
  1237. case SSL_ERROR_NONE:
  1238. buf->str[buf->len += n_read] = '\0';
  1239. return IRC_READ_OK;
  1240. case SSL_ERROR_ZERO_RETURN:
  1241. return IRC_READ_EOF;
  1242. case SSL_ERROR_WANT_READ:
  1243. return IRC_READ_AGAIN;
  1244. case SSL_ERROR_WANT_WRITE:
  1245. {
  1246. // Let it finish the handshake as we don't poll for writability;
  1247. // any errors are to be collected by SSL_read() in the next iteration
  1248. struct pollfd pfd = { .fd = ctx->irc_fd, .events = POLLOUT };
  1249. soft_assert (poll (&pfd, 1, 0) > 0);
  1250. goto start;
  1251. }
  1252. case XSSL_ERROR_TRY_AGAIN:
  1253. goto start;
  1254. default:
  1255. print_debug ("%s: %s: %s", __func__, "SSL_read", error_info);
  1256. return IRC_READ_ERROR;
  1257. }
  1258. }
  1259. static enum irc_read_result
  1260. irc_fill_read_buffer (struct bot_context *ctx, struct str *buf)
  1261. {
  1262. ssize_t n_read;
  1263. start:
  1264. n_read = recv (ctx->irc_fd, buf->str + buf->len,
  1265. buf->alloc - buf->len - 1 /* null byte */, 0);
  1266. if (n_read > 0)
  1267. {
  1268. buf->str[buf->len += n_read] = '\0';
  1269. return IRC_READ_OK;
  1270. }
  1271. if (n_read == 0)
  1272. return IRC_READ_EOF;
  1273. if (errno == EAGAIN)
  1274. return IRC_READ_AGAIN;
  1275. if (errno == EINTR)
  1276. goto start;
  1277. print_debug ("%s: %s: %s", __func__, "recv", strerror (errno));
  1278. return IRC_READ_ERROR;
  1279. }
  1280. static bool irc_connect (struct bot_context *, struct error **);
  1281. static void irc_queue_reconnect (struct bot_context *);
  1282. static void
  1283. irc_cancel_timers (struct bot_context *ctx)
  1284. {
  1285. poller_timer_reset (&ctx->timeout_tmr);
  1286. poller_timer_reset (&ctx->ping_tmr);
  1287. poller_timer_reset (&ctx->reconnect_tmr);
  1288. }
  1289. static void
  1290. on_irc_reconnect_timeout (void *user_data)
  1291. {
  1292. struct bot_context *ctx = user_data;
  1293. struct error *e = NULL;
  1294. if (irc_connect (ctx, &e))
  1295. {
  1296. // TODO: inform plugins about the new connection
  1297. return;
  1298. }
  1299. print_error ("%s", e->message);
  1300. error_free (e);
  1301. irc_queue_reconnect (ctx);
  1302. }
  1303. static void
  1304. irc_queue_reconnect (struct bot_context *ctx)
  1305. {
  1306. hard_assert (ctx->irc_fd == -1);
  1307. print_status ("trying to reconnect in %ld seconds...",
  1308. ctx->reconnect_delay);
  1309. poller_timer_set (&ctx->reconnect_tmr, ctx->reconnect_delay * 1000);
  1310. }
  1311. static void
  1312. on_irc_disconnected (struct bot_context *ctx)
  1313. {
  1314. // Get rid of the dead socket and related things
  1315. if (ctx->ssl)
  1316. {
  1317. SSL_free (ctx->ssl);
  1318. ctx->ssl = NULL;
  1319. SSL_CTX_free (ctx->ssl_ctx);
  1320. ctx->ssl_ctx = NULL;
  1321. }
  1322. poller_fd_reset (&ctx->irc_event);
  1323. xclose (ctx->irc_fd);
  1324. ctx->irc_fd = -1;
  1325. ctx->irc_registered = false;
  1326. // TODO: inform plugins about the disconnect event
  1327. // All of our timers have lost their meaning now
  1328. irc_cancel_timers (ctx);
  1329. if (ctx->quitting)
  1330. try_finish_quit (ctx);
  1331. else if (!ctx->reconnect)
  1332. initiate_quit (ctx);
  1333. else
  1334. irc_queue_reconnect (ctx);
  1335. }
  1336. static void
  1337. on_irc_ping_timeout (void *user_data)
  1338. {
  1339. struct bot_context *ctx = user_data;
  1340. print_error ("connection timeout");
  1341. on_irc_disconnected (ctx);
  1342. }
  1343. static void
  1344. on_irc_timeout (void *user_data)
  1345. {
  1346. // Provoke a response from the server
  1347. struct bot_context *ctx = user_data;
  1348. irc_send (ctx, "PING :%s",
  1349. (char *) str_map_find (&ctx->config, "nickname"));
  1350. }
  1351. static void
  1352. irc_reset_connection_timeouts (struct bot_context *ctx)
  1353. {
  1354. irc_cancel_timers (ctx);
  1355. poller_timer_set (&ctx->timeout_tmr, 3 * 60 * 1000);
  1356. poller_timer_set (&ctx->ping_tmr, (3 * 60 + 30) * 1000);
  1357. }
  1358. static void
  1359. on_irc_readable (const struct pollfd *fd, struct bot_context *ctx)
  1360. {
  1361. if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
  1362. print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);
  1363. (void) set_blocking (ctx->irc_fd, false);
  1364. struct str *buf = &ctx->read_buffer;
  1365. enum irc_read_result (*fill_buffer)(struct bot_context *, struct str *)
  1366. = ctx->ssl
  1367. ? irc_fill_read_buffer_tls
  1368. : irc_fill_read_buffer;
  1369. bool disconnected = false;
  1370. while (true)
  1371. {
  1372. str_reserve (buf, 512);
  1373. switch (fill_buffer (ctx, buf))
  1374. {
  1375. case IRC_READ_AGAIN:
  1376. goto end;
  1377. case IRC_READ_ERROR:
  1378. print_error ("reading from the IRC server failed");
  1379. disconnected = true;
  1380. goto end;
  1381. case IRC_READ_EOF:
  1382. print_status ("the IRC server closed the connection");
  1383. disconnected = true;
  1384. goto end;
  1385. case IRC_READ_OK:
  1386. break;
  1387. }
  1388. if (buf->len >= (1 << 20))
  1389. {
  1390. print_error ("the IRC server seems to spew out data frantically");
  1391. irc_shutdown (ctx);
  1392. goto end;
  1393. }
  1394. }
  1395. end:
  1396. (void) set_blocking (ctx->irc_fd, true);
  1397. irc_process_buffer (buf, irc_process_message, ctx);
  1398. if (disconnected)
  1399. on_irc_disconnected (ctx);
  1400. else
  1401. irc_reset_connection_timeouts (ctx);
  1402. }
  1403. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1404. // The bot is currently mostly synchronous (which also makes it shorter),
  1405. // however our current SOCKS code is not, hence we must wrap it.
  1406. struct irc_socks_data
  1407. {
  1408. struct bot_context *ctx; ///< Bot context
  1409. struct poller inner_poller; ///< Special inner poller
  1410. bool polling; ///< Inner poller is no longer needed
  1411. struct socks_connector connector; ///< SOCKS connector
  1412. bool succeeded; ///< Were we successful in connecting?
  1413. };
  1414. static void
  1415. irc_on_socks_connected (void *user_data, int socket, const char *hostname)
  1416. {
  1417. (void) hostname;
  1418. struct irc_socks_data *data = user_data;
  1419. data->ctx->irc_fd = socket;
  1420. data->succeeded = true;
  1421. data->polling = false;
  1422. }
  1423. static void
  1424. irc_on_socks_failure (void *user_data)
  1425. {
  1426. struct irc_socks_data *data = user_data;
  1427. data->succeeded = false;
  1428. data->polling = false;
  1429. }
  1430. static void
  1431. irc_on_socks_connecting (void *user_data,
  1432. const char *address, const char *via, const char *version)
  1433. {
  1434. (void) user_data;
  1435. print_status ("connecting to %s via %s (%s)...", address, via, version);
  1436. }
  1437. static void
  1438. irc_on_socks_error (void *user_data, const char *error)
  1439. {
  1440. (void) user_data;
  1441. print_error ("%s: %s", "SOCKS connection failed", error);
  1442. }
  1443. static bool
  1444. irc_establish_connection_socks (struct bot_context *ctx,
  1445. const char *socks_host, const char *socks_port,
  1446. const char *host, const char *service, struct error **e)
  1447. {
  1448. struct irc_socks_data data;
  1449. struct poller *poller = &data.inner_poller;
  1450. struct socks_connector *connector = &data.connector;
  1451. data.ctx = ctx;
  1452. poller_init (poller);
  1453. data.polling = true;
  1454. socks_connector_init (connector, poller);
  1455. data.succeeded = false;
  1456. connector->on_connected = irc_on_socks_connected;
  1457. connector->on_connecting = irc_on_socks_connecting;
  1458. connector->on_error = irc_on_socks_error;
  1459. connector->on_failure = irc_on_socks_failure;
  1460. connector->user_data = &data;
  1461. if (socks_connector_add_target (connector, host, service, e))
  1462. {
  1463. socks_connector_run (connector, socks_host, socks_port,
  1464. str_map_find (&ctx->config, "socks_username"),
  1465. str_map_find (&ctx->config, "socks_password"));
  1466. while (data.polling)
  1467. poller_run (poller);
  1468. if (!data.succeeded)
  1469. error_set (e, "connection failed");
  1470. }
  1471. socks_connector_free (connector);
  1472. poller_free (poller);
  1473. return data.succeeded;
  1474. }
  1475. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1476. static bool
  1477. irc_connect (struct bot_context *ctx, struct error **e)
  1478. {
  1479. const char *irc_host = str_map_find (&ctx->config, "irc_host");
  1480. const char *irc_port = str_map_find (&ctx->config, "irc_port");
  1481. const char *socks_host = str_map_find (&ctx->config, "socks_host");
  1482. const char *socks_port = str_map_find (&ctx->config, "socks_port");
  1483. const char *nickname = str_map_find (&ctx->config, "nickname");
  1484. const char *username = str_map_find (&ctx->config, "username");
  1485. const char *realname = str_map_find (&ctx->config, "realname");
  1486. // We have a default value for these
  1487. hard_assert (irc_port && socks_port);
  1488. hard_assert (nickname && username && realname);
  1489. // TODO: again, get rid of `struct error' in here. The question is: how
  1490. // do we tell our caller that he should not try to reconnect?
  1491. if (!irc_host)
  1492. return error_set (e, "no hostname specified in configuration");
  1493. bool use_tls;
  1494. if (!irc_get_boolean_from_config (ctx, "tls", &use_tls, e))
  1495. return false;
  1496. bool connected = socks_host
  1497. ? irc_establish_connection_socks (ctx,
  1498. socks_host, socks_port, irc_host, irc_port, e)
  1499. : irc_establish_connection (ctx, irc_host, irc_port, e);
  1500. if (!connected)
  1501. return false;
  1502. if (use_tls && !irc_initialize_tls (ctx, e))
  1503. {
  1504. xclose (ctx->irc_fd);
  1505. ctx->irc_fd = -1;
  1506. return false;
  1507. }
  1508. print_status ("connection established");
  1509. ctx->irc_event = poller_fd_make (&ctx->poller, ctx->irc_fd);
  1510. ctx->irc_event.dispatcher = (poller_fd_fn) on_irc_readable;
  1511. ctx->irc_event.user_data = ctx;
  1512. // TODO: in exec try: 1/ set blocking, 2/ setsockopt() SO_LINGER,
  1513. // (struct linger) { .l_onoff = true; .l_linger = 1 /* 1s should do */; }
  1514. // 3/ /* O_CLOEXEC */ But only if the QUIT message proves unreliable.
  1515. poller_fd_set (&ctx->irc_event, POLLIN);
  1516. irc_reset_connection_timeouts (ctx);
  1517. irc_send (ctx, "NICK %s", nickname);
  1518. irc_send (ctx, "USER %s 8 * :%s", username, realname);
  1519. return true;
  1520. }
  1521. static bool
  1522. parse_config (struct bot_context *ctx, struct error **e)
  1523. {
  1524. if (!irc_get_boolean_from_config (ctx, "reconnect", &ctx->reconnect, e))
  1525. return false;
  1526. const char *delay_str = str_map_find (&ctx->config, "reconnect_delay");
  1527. hard_assert (delay_str != NULL); // We have a default value for this
  1528. if (!xstrtoul (&ctx->reconnect_delay, delay_str, 10))
  1529. {
  1530. return error_set (e,
  1531. "invalid configuration value for `%s'", "reconnect_delay");
  1532. }
  1533. hard_assert (!ctx->admin_re);
  1534. const char *admin = str_map_find (&ctx->config, "admin");
  1535. if (!admin)
  1536. return true;
  1537. struct error *error = NULL;
  1538. ctx->admin_re = regex_compile (admin, REG_EXTENDED | REG_NOSUB, &error);
  1539. if (!error)
  1540. return true;
  1541. error_set (e, "invalid configuration value for `%s': %s",
  1542. "admin", error->message);
  1543. error_free (error);
  1544. return false;
  1545. }
  1546. static void
  1547. on_plugin_death (struct plugin *plugin, int status)
  1548. {
  1549. struct bot_context *ctx = plugin->ctx;
  1550. // TODO: callbacks on children death, so that we may tell the user
  1551. // "plugin `name' died like a dirty jewish pig"; use `status'
  1552. if (!plugin->is_zombie && WIFSIGNALED (status))
  1553. {
  1554. const char *notes = "";
  1555. #ifdef WCOREDUMP
  1556. if (WCOREDUMP (status))
  1557. notes = " (core dumped)";
  1558. #endif
  1559. print_warning ("Plugin `%s' died from signal %d%s",
  1560. plugin->name, WTERMSIG (status), notes);
  1561. }
  1562. // Let's go through the zombie state to simplify things a bit
  1563. // TODO: might not be a completely bad idea to restart the plugin
  1564. plugin_zombify (plugin);
  1565. plugin->pid = -1;
  1566. // In theory we could close `read_fd', set `read_event->closed' to true
  1567. // and expect epoll to no longer return events for the descriptor, as
  1568. // all the pipe ends should be closed by then (the child is dead, so its
  1569. // pipe FDs have been closed [assuming it hasn't forked without closing
  1570. // the descriptors, which would be evil], and we would have closed all
  1571. // of our FDs for this pipe as well). In practice that doesn't work.
  1572. poller_fd_reset (&plugin->read_event);
  1573. xclose (plugin->read_fd);
  1574. plugin->read_fd = -1;
  1575. LIST_UNLINK (ctx->plugins, plugin);
  1576. plugin_destroy (plugin);
  1577. // Living child processes block us from quitting
  1578. try_finish_quit (ctx);
  1579. }
  1580. static bool
  1581. try_reap_plugin (struct bot_context *ctx)
  1582. {
  1583. int status;
  1584. pid_t zombie = waitpid (-1, &status, WNOHANG);
  1585. if (zombie == -1)
  1586. {
  1587. // No children to wait on
  1588. if (errno == ECHILD)
  1589. return false;
  1590. hard_assert (errno == EINTR);
  1591. return true;
  1592. }
  1593. if (zombie == 0)
  1594. return false;
  1595. struct plugin *plugin = plugin_find_by_pid (ctx, zombie);
  1596. // XXX: re-exec if something has died that we don't recognize?
  1597. if (soft_assert (plugin != NULL))
  1598. on_plugin_death (plugin, status);
  1599. return true;
  1600. }
  1601. static void
  1602. kill_all_zombies (struct bot_context *ctx)
  1603. {
  1604. for (struct plugin *plugin = ctx->plugins; plugin; plugin = plugin->next)
  1605. {
  1606. if (!plugin->is_zombie)
  1607. continue;
  1608. print_status ("forcefully killing a zombie of `%s' (PID %d)",
  1609. plugin->name, (int) plugin->pid);
  1610. kill (plugin->pid, SIGKILL);
  1611. }
  1612. }
  1613. static void
  1614. on_signal_pipe_readable (const struct pollfd *fd, struct bot_context *ctx)
  1615. {
  1616. char dummy;
  1617. (void) read (fd->fd, &dummy, 1);
  1618. if (g_termination_requested)
  1619. {
  1620. g_termination_requested = false;
  1621. if (!ctx->quitting)
  1622. {
  1623. // There may be a timer set to reconnect to the server
  1624. irc_cancel_timers (ctx);
  1625. if (ctx->irc_fd != -1)
  1626. irc_send (ctx, "QUIT :Terminated by signal");
  1627. initiate_quit (ctx);
  1628. }
  1629. else
  1630. // Disregard proper termination, just kill all the children
  1631. kill_all_zombies (ctx);
  1632. }
  1633. // Reap all dead children (since the signal pipe may overflow etc. we run
  1634. // waitpid() in a loop to return all the zombies it knows about).
  1635. while (try_reap_plugin (ctx))
  1636. ;
  1637. }
  1638. int
  1639. main (int argc, char *argv[])
  1640. {
  1641. g_original_argv = strv_make ();
  1642. strv_append_vector (&g_original_argv, argv);
  1643. static const struct opt opts[] =
  1644. {
  1645. { 'd', "debug", NULL, 0, "run in debug mode" },
  1646. { 'h', "help", NULL, 0, "display this help and exit" },
  1647. { 'V', "version", NULL, 0, "output version information and exit" },
  1648. { 'w', "write-default-cfg", "FILENAME",
  1649. OPT_OPTIONAL_ARG | OPT_LONG_ONLY,
  1650. "write a default configuration file and exit" },
  1651. { 0, NULL, NULL, 0, NULL }
  1652. };
  1653. struct opt_handler oh =
  1654. opt_handler_make (argc, argv, opts, NULL, "Experimental IRC bot.");
  1655. int c;
  1656. while ((c = opt_handler_get (&oh)) != -1)
  1657. switch (c)
  1658. {
  1659. case 'd':
  1660. g_debug_mode = true;
  1661. break;
  1662. case 'h':
  1663. opt_handler_usage (&oh, stdout);
  1664. exit (EXIT_SUCCESS);
  1665. case 'V':
  1666. printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
  1667. exit (EXIT_SUCCESS);
  1668. case 'w':
  1669. call_simple_config_write_default (optarg, g_config_table);
  1670. exit (EXIT_SUCCESS);
  1671. default:
  1672. print_error ("wrong options");
  1673. opt_handler_usage (&oh, stderr);
  1674. exit (EXIT_FAILURE);
  1675. }
  1676. opt_handler_free (&oh);
  1677. print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting");
  1678. setup_signal_handlers ();
  1679. init_openssl ();
  1680. struct bot_context ctx;
  1681. bot_context_init (&ctx);
  1682. struct error *e = NULL;
  1683. if (!simple_config_update_from_file (&ctx.config, &e)
  1684. || !setup_recovery_handler (&ctx, &e))
  1685. {
  1686. print_error ("%s", e->message);
  1687. error_free (e);
  1688. exit (EXIT_FAILURE);
  1689. }
  1690. ctx.signal_event = poller_fd_make (&ctx.poller, g_signal_pipe[0]);
  1691. ctx.signal_event.dispatcher = (poller_fd_fn) on_signal_pipe_readable;
  1692. ctx.signal_event.user_data = &ctx;
  1693. poller_fd_set (&ctx.signal_event, POLLIN);
  1694. #if OpenBSD >= 201605
  1695. // cpath is for creating the plugin home directory
  1696. if (pledge ("stdio rpath cpath inet proc exec", NULL))
  1697. exit_fatal ("%s: %s", "pledge", strerror (errno));
  1698. #endif
  1699. plugin_load_all_from_config (&ctx);
  1700. if (!parse_config (&ctx, &e)
  1701. || !irc_connect (&ctx, &e))
  1702. {
  1703. print_error ("%s", e->message);
  1704. error_free (e);
  1705. exit (EXIT_FAILURE);
  1706. }
  1707. // TODO: clean re-exec support; to save the state I can either use argv,
  1708. // argp, or I can create a temporary file, unlink it and use the FD
  1709. // (mkstemp() on a `struct str' constructed from XDG_RUNTIME_DIR, TMPDIR
  1710. // or /tmp as a last resort + PROGRAM_NAME + ".XXXXXX" -> unlink();
  1711. // remember to use O_CREAT | O_EXCL). The state needs to be versioned.
  1712. // Unfortunately I cannot de/serialize SSL state.
  1713. ctx.polling = true;
  1714. while (ctx.polling)
  1715. poller_run (&ctx.poller);
  1716. bot_context_free (&ctx);
  1717. strv_free (&g_original_argv);
  1718. return EXIT_SUCCESS;
  1719. }