add sanity checking for \r and \n
[fillybot.git] / mod.c
blobb2a25ae55ca2e8eb71a2aff7c9dbe2eca4286ad4
1 #include "mod.h"
3 #include <libxml/xmlstring.h>
4 #include <libxml/HTMLparser.h>
6 #include <stdint.h>
7 #include <inttypes.h>
8 #include <sys/wait.h>
9 #include <curl/curl.h>
11 #include <magic.h>
13 #include "entities.h"
14 #include "quotes.h"
16 static const char *nick_self;
17 static unsigned ponify;
18 #define elements(x) (sizeof(x)/sizeof(*x))
20 static struct tdb_context *feed_db, *chan_db, *mail_db, *seen_db;
22 static struct command_hash command_channel = { "#", NULL };
24 #define sstrncmp(a, b) (strncmp(a, b, sizeof(b)-1))
25 #define sstrncasecmp(a, b) (strncasecmp(a, b, sizeof(b)-1))
27 #define SPAM_CUTOFF 5
29 static int pipe_command(struct bio *b, const char *target, const char *nick, int redirect_stdout, int redirect_stderr, char *argv[])
31 int fd[2];
32 int lines = 0;
33 if (pipe2(fd, O_CLOEXEC) < 0) {
34 privmsg(b, target, "Could not create pipe: %m");
35 return -1;
37 pid_t pid = fork();
38 if (pid < 0) {
39 privmsg(b, target, "Could not fork: %m");
40 close(fd[0]);
41 close(fd[1]);
42 return -1;
43 } else if (!pid) {
44 int fdnull = open("/dev/null", O_WRONLY|O_CLOEXEC);
45 close(fd[0]);
46 if (dup3(redirect_stdout ? fd[1] : fdnull, 1, 0) < 0)
47 exit(errno);
48 if (dup3(redirect_stderr ? fd[1] : fdnull, 2, 0) < 0)
49 exit(errno);
50 exit(execv(argv[0], argv));
51 } else {
52 int loc = -1;
53 char buffer[0x100];
54 int bufptr = 0, ret;
55 close(fd[1]);
56 fcntl(fd[0], F_SETFL, O_NONBLOCK);
57 while ((ret = waitpid(pid, &loc, WNOHANG)) >= 0) {
58 while (read(fd[0], buffer+bufptr, 1) == 1) {
59 if (buffer[bufptr] != '\n' && bufptr < sizeof(buffer)-1) {
60 bufptr++;
61 continue;
62 } else if (bufptr) {
63 buffer[bufptr] = 0;
64 bufptr = 0;
65 lines++;
66 if (lines < SPAM_CUTOFF)
67 privmsg(b, nick, "%s", buffer);
68 else
69 fprintf(stderr, "%s\n", buffer);
73 if (ret) {
74 if (bufptr) {
75 buffer[bufptr] = 0;
76 if (lines < SPAM_CUTOFF)
77 privmsg(b, nick, "%s", buffer);
78 else
79 fprintf(stderr, "%s\n", buffer);
81 if (lines >= SPAM_CUTOFF)
82 privmsg(b, nick, "%i lines suppressed", lines - SPAM_CUTOFF + 1);
83 break;
86 if (ret < 0)
87 privmsg(b, target, "error on waitpid: %m");
88 else
89 ret = loc;
90 close(fd[0]);
91 return ret;
95 #include "local.c"
97 static struct command_hash commands[2048];
99 static void command_abort(struct bio *b, const char *nick, const char *host, const char *target, char *args)
101 abort();
102 return;
105 static void command_crash(struct bio *b, const char *nick, const char *host, const char *target, char *args)
107 *(char*)0 = 0;
110 static void command_coinflip(struct bio *b, const char *nick, const char *host, const char *target, char *args)
112 static const char *insults[] = {
113 "whirrrs and clicks excitedly at %s",
114 "eyes %s as nothing happens"
116 action(b, target, insults[getrand() % elements(insults)], nick);
119 static void command_shesaid(struct bio *b, const char *nick, const char *host, const char *target, char *args)
121 privmsg(b, target, "%s: \"%s\"", args ? args : nick, women_quotes[getrand() % elements(women_quotes)]);
124 static void squash(char *title)
126 char *start = title;
127 goto start;
128 while (*title) {
129 while (*title != '\n' && *title != '\r' && *title != '\t' && *title != ' ' && *title) {
130 *(start++) = *(title++);
132 if (*title)
133 *(start++) = ' ';
134 start:
135 while (*title == '\n' || *title == '\r' || *title == '\t' || *title == ' ')
136 title++;
138 *start = 0;
141 struct curl_download_context
143 char *data;
144 size_t len;
147 static size_t write_data(void *ptr, size_t size, size_t nmemb, void *member) {
148 struct curl_download_context *ctx = member;
149 size *= nmemb;
150 ctx->data = realloc(ctx->data, ctx->len + size);
151 memcpy(ctx->data + ctx->len, ptr, size);
152 ctx->len += size;
153 return size;
156 static const char *get_text(xmlNode *cur)
158 for (; cur; cur = cur->next) {
159 if (cur->type == XML_TEXT_NODE)
160 return cur->content;
162 return NULL;
165 static const char *get_link(xmlAttr *cur, const char *which)
167 for (; cur; cur = cur->next) {
168 if (!strcasecmp(cur->name, which))
169 return get_text(cur->children);
171 return NULL;
174 static int get_feed_entry(struct bio *b, const char *nick, const char *target, const char *category, xmlNode *entry, const char **title, const char **link)
176 const char *cur_title = NULL, *cur_link = NULL;
177 xmlNode *cur;
178 int cur_match = !category;
179 for (cur = entry->children; cur; cur = cur->next) {
180 const char *name = cur->name, *cur_cat;
181 if (cur->type != XML_ELEMENT_NODE)
182 continue;
183 else if (!strcasecmp(name, "link")) {
184 const char *ishtml = get_link(cur->properties, "type");
185 const char *rel = get_link(cur->properties, "rel");
186 if ((!ishtml || !strcasecmp(ishtml, "text/html")) &&
187 rel && !strcasecmp(rel, "alternate"))
188 cur_link = get_link(cur->properties, "href");
189 } else if (!strcasecmp(name, "title"))
190 cur_title = get_text(cur->children);
191 else if (!cur_match && !strcasecmp(name, "category") &&
192 (cur_cat = get_link(cur->properties, "term")) &&
193 strcasestr(cur_cat, category))
194 cur_match = 1;
197 if (cur_title)
198 *title = cur_title;
199 else
200 *title = "<no title>";
201 *link = cur_link;
202 return !cur_link ? -1 : cur_match;
205 static const char *walk_feed(struct bio *b, const char *nick, const char *target, const char *url, const char *category, xmlNode *root, const char *last_link)
207 const char *main_title = NULL, *main_subtitle = NULL, *main_link = NULL, *title, *link, *prev_link = NULL, *prev_title = NULL;
208 int match, updates = 0;
209 xmlNode *cur, *entry = NULL;
210 for (cur = root->children; cur; cur = cur->next) {
211 const char *name = cur->name;
212 if (cur->type != XML_ELEMENT_NODE)
213 continue;
214 else if (!strcasecmp(name, "category"))
215 continue;
216 else if (!strcasecmp(name, "entry"))
217 entry = entry ? entry : cur;
218 else if (!strcasecmp(name, "title"))
219 main_title = get_text(cur->children);
220 else if (!strcasecmp(name, "subtitle"))
221 main_subtitle = get_text(cur->children);
222 else if (!strcasecmp(name, "link")) {
223 const char *ishtml = get_link(cur->properties, "type");
224 const char *rel = get_link(cur->properties, "rel");
225 if ((!ishtml || !strcasecmp(ishtml, "text/html")) && rel && !strcasecmp(rel, "alternate"))
226 main_link = get_link(cur->properties, "href");
229 if (!main_link || !main_title) {
230 privmsg(b, target, "%s: Failed to parse main: %s %s", nick, main_link, main_title);
231 return NULL;
233 if (!entry)
234 return NULL;
236 if (!last_link)
237 privmsg(b, target, "adding blog %s \"%s\": %s", main_link, main_title, main_subtitle);
239 match = get_feed_entry(b, nick, target, category, entry, &title, &link);
240 if (match < 0)
241 return NULL;
243 for (; !match && entry; entry = entry->next) {
244 if (!strcasecmp(entry->name, "entry"))
245 match = get_feed_entry(b, nick, target, category, entry, &title, &link);
248 if (match < 0)
249 return NULL;
250 if (!last_link) {
251 if (match > 0)
252 privmsg(b, target, "Most recent entry: %s %s", link, title);
253 else
254 privmsg(b, target, "Currently having no entries for this feed that matches the filter");
255 return link;
257 if (!strcmp(last_link, link) || !match || !entry)
258 return link;
260 for (entry = entry->next; entry; entry = entry->next) {
261 const char *cur_link, *cur_title;
262 if (strcasecmp(entry->name, "entry"))
263 continue;
264 match = get_feed_entry(b, nick, target, category, entry, &cur_title, &cur_link);
265 if (match < 0 || !strcmp(last_link, cur_link))
266 break;
267 if (match) {
268 prev_link = cur_link;
269 prev_title = cur_title;
270 updates++;
273 if (updates == 1)
274 privmsg(b, target, "( %s ): %s", prev_link, prev_title);
275 else if (updates > 1)
276 privmsg(b, target, "( %s ): %u updates, linking most recent", main_link, 1+updates);
277 privmsg(b, target, "( %s ): %s", link, title);
278 return link;
281 static const char *walk_rss(struct bio *b, const char *nick, const char *target, const char *url, xmlNode *root, const char *last_link)
283 const char *main_title = NULL, *main_link = NULL, *title = NULL, *link = NULL, *ver;
284 xmlNode *cur, *entry = NULL;
285 ver = get_link(root->properties, "version");
286 if (!ver || strcmp(ver, "2.0")) {
287 if (!ver)
288 privmsg(b, target, "%s: Could not parse rss feed", nick);
289 else
290 privmsg(b, target, "%s: Invalid rss version \"%s\"", nick, ver);
291 return NULL;
293 for (cur = root->children; cur && cur->type != XML_ELEMENT_NODE; cur = cur->next);
294 if (!cur)
295 return NULL;
296 for (cur = cur->children; cur; cur = cur->next) {
297 const char *name = cur->name;
298 if (cur->type != XML_ELEMENT_NODE)
299 continue;
300 if (!strcasecmp(name, "title"))
301 main_title = get_text(cur->children);
302 else if (!strcasecmp(name, "link"))
303 main_link = main_link ? main_link : get_text(cur->children);
304 else if (!strcasecmp(name, "item"))
305 entry = entry ? entry : cur;
307 if (!main_link || !main_title) {
308 privmsg(b, target, "%s: Failed to parse main: %s %s", nick, main_link, main_title);
309 return NULL;
311 if (!entry)
312 return NULL;
314 link = title = NULL;
315 for (cur = entry->children; cur; cur = cur->next) {
316 const char *name = cur->name;
317 if (cur->type != XML_ELEMENT_NODE)
318 continue;
319 if (!strcasecmp(name, "title"))
320 title = get_text(cur->children);
321 else if (!strcasecmp(name, "link"))
322 link = get_text(cur->children);
324 if (!title)
325 title = "<no title>";
326 if (!link) {
327 privmsg(b, target, "%s: Failed to parse entry: %s %s", nick, link, title);
328 return NULL;
330 if (!last_link) {
331 privmsg(b, target, "adding blog %s \"%s\"", main_link, main_title);
332 privmsg(b, target, "Most recent entry: %s %s", link, title);
333 } else if (strcmp(last_link, link)) {
334 int updates = 0;
335 const char *prev_title = NULL, *prev_link = NULL, *cur_title = NULL, *cur_link = NULL;
336 for (entry = entry->next; entry; entry = entry->next) {
337 if (strcasecmp(entry->name, "item"))
338 continue;
339 prev_title = cur_title;
340 prev_link = cur_link;
341 cur_title = cur_link = NULL;
342 for (cur = entry->children; cur; cur = cur->next) {
343 const char *name = cur->name;
344 if (cur->type != XML_ELEMENT_NODE)
345 continue;
346 if (!strcasecmp(name, "title"))
347 cur_title = get_text(cur->children);
348 else if (!strcasecmp(name, "link"))
349 cur_link = get_text(cur->children);
351 if (!cur_title)
352 cur_title = "<no title>";
353 if (!cur_link || !strcmp(last_link, cur_link))
354 break;
355 updates++;
357 if (updates == 1)
358 privmsg(b, target, "( %s ): %s", prev_link, prev_title);
359 else if (updates > 1)
360 privmsg(b, target, "( %s ): %u updates, linking most recent", main_link, 1+updates);
361 privmsg(b, target, "( %s ): %s", link, title);
363 return link;
366 // HTML is a mess, so I'm just walking the tree depth first until I find the next element..
367 static xmlNode *next_link(xmlNode *cur_node)
369 if (cur_node->children)
370 return cur_node->children;
371 while (cur_node) {
372 if (cur_node->next)
373 return cur_node->next;
374 cur_node = cur_node->parent;
376 return NULL;
379 static const char *get_atom_link(xmlNode *cur)
381 for (; cur; cur = next_link(cur)) {
382 if (cur->type != XML_ELEMENT_NODE)
383 continue;
384 if (!strcasecmp(cur->name, "link")) {
385 const char *isxml = get_link(cur->properties, "type");
386 if (isxml && !strcasecmp(isxml, "application/atom+xml"))
387 return get_link(cur->properties, "href");
390 return NULL;
393 static const char *get_rss_link(xmlNode *cur)
395 for (; cur; cur = next_link(cur)) {
396 if (cur->type != XML_ELEMENT_NODE)
397 continue;
398 if (!strcasecmp(cur->name, "link")) {
399 const char *isxml = get_link(cur->properties, "type");
400 if (isxml && !strcasecmp(isxml, "application/rss+xml"))
401 return get_link(cur->properties, "href");
404 return NULL;
407 static void do_html(struct bio *b, const char *nick, const char *target, const char *url, const char *data, unsigned len)
409 htmlDocPtr ctx = htmlReadMemory(data, len, 0, url, HTML_PARSE_RECOVER|HTML_PARSE_NOERROR|HTML_PARSE_NOWARNING);
410 xmlNode *root = xmlDocGetRootElement(ctx);
411 const char *link = get_atom_link(root);
412 if (link)
413 privmsg(b, target, "%s: not a valid feed link, try atom: %s", nick, link);
414 else if ((link = get_rss_link(root)))
415 privmsg(b, target, "%s: not a valid feed link, try rss: %s", nick, link);
416 else
417 privmsg(b, target, "%s: not a valid feed link, no suggestion found", nick);
418 xmlFreeDoc(ctx);
421 static size_t get_time_from_header(void *data, size_t size, size_t size2, void *ptr)
423 char *d, *e;
424 size *= size2;
425 if (sstrncmp(data, "Last-Modified: "))
426 return size;
427 data += sizeof("Last-Modified: ")-1;
428 *(char**)ptr = d = strdup(data);
429 if ((e = strchr(d, '\r')))
430 *e = 0;
431 return size;
434 static int check_single_feed(struct bio *b, const char *target, TDB_DATA key, const char *last_modified, const char *url, const char *link, const char *nick)
436 struct curl_download_context curl_ctx = {};
437 struct curl_slist *headers = NULL;
438 char error[CURL_ERROR_SIZE], *category = strchr(url, '#');
439 int retval = -1;
440 headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
441 headers = curl_slist_append(headers, "Accept: */*");
442 if (category)
443 *(category++) = 0;
445 CURL *h = curl_easy_init();
446 curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
447 curl_easy_setopt(h, CURLOPT_URL, url);
448 curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
449 curl_easy_setopt(h, CURLOPT_WRITEDATA, &curl_ctx);
450 curl_easy_setopt(h, CURLOPT_ERRORBUFFER, error);
451 curl_easy_setopt(h, CURLOPT_FOLLOWLOCATION, 1);
452 curl_easy_setopt(h, CURLOPT_MAXREDIRS, 3);
453 curl_easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 0);
454 curl_easy_setopt(h, CURLOPT_TIMEOUT, 8);
455 curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, 8);
456 curl_easy_setopt(h, CURLOPT_FILETIME, 1);
457 curl_easy_setopt(h, CURLOPT_HEADERFUNCTION, get_time_from_header);
458 curl_easy_setopt(h, CURLOPT_WRITEHEADER, &last_modified);
459 //curl_easy_setopt(h, CURLOPT_VERBOSE, 1);
461 if (last_modified) {
462 char *tmp;
463 asprintf(&tmp, "If-Modified-Since: %s", last_modified);
464 headers = curl_slist_append(headers, tmp);
465 free(tmp);
468 int success = curl_easy_perform(h);
469 curl_slist_free_all(headers);
470 if (success == CURLE_OK) {
471 char *mime = NULL;
472 long code;
473 curl_easy_getinfo(h, CURLINFO_CONTENT_TYPE, &mime);
474 curl_easy_getinfo(h, CURLINFO_RESPONSE_CODE, &code);
475 if (code == 304)
477 else if (!mime || !sstrncmp(mime, "application/xml") || !sstrncmp(mime, "text/xml")) {
478 const char *ret_link = NULL;
479 xmlDocPtr ctx = xmlReadMemory(curl_ctx.data, curl_ctx.len, 0, url, XML_PARSE_NOWARNING | XML_PARSE_NOERROR);
480 xmlNode *root = xmlDocGetRootElement(ctx);
482 if (!root || !root->name)
483 fprintf(stderr, "Failed to parse feed %s %p", url, root);
484 else if (!strcasecmp(root->name, "feed"))
485 ret_link = walk_feed(b, nick, target, url, category, root, link);
486 else if (!strcasecmp(root->name, "rss"))
487 ret_link = walk_rss(b, nick, target, url, root, link);
488 else {
489 privmsg(b, target, "Unknown feed type \"%s\"", root->name);
490 goto free_ctx;
492 if (category)
493 category[-1] = '#';
495 if (!ret_link)
496 privmsg(b, target, "Could not feed parse correctly");
497 else if (ret_link && (!link || strcmp(ret_link, link))) {
498 TDB_DATA val;
499 asprintf((char**)&val.dptr, "%s\001%s", last_modified ? last_modified : "", ret_link);
500 val.dsize = strlen(val.dptr)+1;
501 if (tdb_store(feed_db, key, val, 0) < 0)
502 privmsg(b, target, "updating returns %s", tdb_errorstr(feed_db));
503 free(val.dptr);
504 retval = 1;
506 else
507 retval = 0;
509 free_ctx:
510 xmlFreeDoc(ctx);
511 } else if (link)
513 else if (!sstrncmp(mime, "text/html") || !sstrncmp(mime, "application/xhtml+xml"))
514 do_html(b, nick, target, url, curl_ctx.data, curl_ctx.len);
515 else
516 privmsg(b, target, "unhandled content type %s", mime);
517 } else if (!link)
518 privmsg(b, target, "Error %s (%u)\n", error, success);
520 free(curl_ctx.data);
521 curl_easy_cleanup(h);
522 return retval;
525 static void command_follow(struct bio *b, const char *nick, const char *host, const char *target, char *args)
527 char *space, *last_link = NULL;
528 TDB_DATA key, val;
529 int ret;
530 if (!feed_db)
531 return;
532 if (target[0] != '#') {
533 privmsg(b, target, "%s: Can only follow on channels", nick);
534 return;
536 if (!args || !*args) {
537 privmsg(b, target, "%s: Usage: !follow <url>", nick);
538 return;
541 if (((space = strchr(args, ' ')) && space < strchr(args, '#')) ||
542 (sstrncmp(args, "http://") && sstrncmp(args, "https://"))) {
543 privmsg(b, target, "%s: Invalid url", nick);
544 return;
547 key.dsize = asprintf((char**)&key.dptr, "%s,%s", target, args)+1;
548 val = tdb_fetch(feed_db, key);
549 if (val.dptr)
550 last_link = strchr(val.dptr, '\001');
551 ret = check_single_feed(b, target, key, NULL, args, last_link ? last_link+1 : NULL, nick);
552 free(val.dptr);
553 if (!ret)
554 privmsg(b, target, "%s: Not updated", nick);
555 free(key.dptr);
558 static void channel_feed_check(struct bio *b, const char *target, int64_t now)
560 int len = strlen(target);
561 int64_t save[] = { now, 0, 0 };
563 TDB_DATA chan, res;
564 if (!feed_db || !chan_db)
565 return;
566 chan.dptr = (char*)target;
567 chan.dsize = len+1;
568 res = tdb_fetch(chan_db, chan);
569 if (res.dptr && res.dsize >= 8) {
570 uint64_t then = *(uint64_t*)res.dptr;
571 if (now - then <= 2000)
572 return;
573 if (res.dsize >= 16)
574 save[1] = ((uint64_t*)res.dptr)[1];
575 if (res.dsize >= 24)
576 save[2] = ((uint64_t*)res.dptr)[2];
578 free(res.dptr);
579 res.dptr = (unsigned char*)save;
580 res.dsize = sizeof(save);
581 if (tdb_store(chan_db, chan, res, 0) < 0) {
582 static int complain_db;
583 if (!complain_db++)
584 privmsg(b, target, "updating database: %s", tdb_errorstr(feed_db));
585 return;
588 for (TDB_DATA d = tdb_firstkey(feed_db); d.dptr;) {
589 TDB_DATA f = tdb_fetch(feed_db, d);
590 TDB_DATA next = tdb_nextkey(feed_db, d);
592 if (!strncmp(d.dptr, target, len) && d.dptr[len] == ',') {
593 const char *url = (char*)d.dptr + len + 1;
594 char *sep;
595 if ((sep = strchr(f.dptr, '\001'))) {
596 *(sep++) = 0;
597 check_single_feed(b, target, d, f.dptr, url, sep, target);
600 free(d.dptr);
601 free(f.dptr);
602 d = next;
606 static void command_unfollow(struct bio *b, const char *nick, const char *host, const char *target, char *args)
608 TDB_DATA key;
609 char *url;
611 if (!feed_db)
612 return;
614 if (!(url = token(&args, ' ')) || (sstrncmp(url, "http://") && sstrncmp(url, "https://"))) {
615 privmsg(b, target, "%s: Invalid url", nick);
616 return;
618 if (target[0] != '#') {
619 privmsg(b, target, "%s: Can only unfollow on channels", nick);
620 return;
622 key.dsize = asprintf((char**)&key.dptr, "%s,%s", target, url)+1;
623 if (tdb_delete(feed_db, key) < 0) {
624 if (tdb_error(feed_db) == TDB_ERR_NOEXIST)
625 privmsg(b, target, "%s: Not following %s on this channel", nick, url);
626 else
627 privmsg(b, target, "%s: Could not delete: %s", nick, tdb_errorstr(feed_db));
628 } else
629 privmsg(b, target, "%s: No longer following %s", nick, url);
630 free(key.dptr);
633 static void command_g(struct bio *b, const char *nick, const char *host, const char *target, char *args)
635 int ret = 0;
636 int64_t g = 0, g_total = 0;
637 TDB_DATA chan, res;
639 if (!chan_db || target[0] != '#')
640 return;
642 chan.dptr = (char*)target;
643 chan.dsize = strlen(chan.dptr)+1;
644 res = tdb_fetch(chan_db, chan);
645 if (res.dptr && res.dsize >= 16) {
646 g = ((int64_t*)res.dptr)[1];
647 ((int64_t*)res.dptr)[1] = 0;
648 if (res.dsize >= 24)
649 g_total = ((int64_t*)res.dptr)[2];
650 ret = tdb_store(chan_db, chan, res, 0);
652 free(res.dptr);
653 if (ret < 0)
654 fprintf(stderr, "updating database: %s", tdb_errorstr(feed_db));
655 else
656 privmsg(b, target, "%s: %"PRIi64" g's since last check, %"PRIi64" total\n", nick, g, g_total);
659 static void command_feeds(struct bio *b, const char *nick, const char *host, const char *target, char *args)
661 int len = strlen(target), found = 0;
662 if (!feed_db)
663 return;
664 if (target[0] != '#') {
665 privmsg(b, target, "%s: Only useful in channels..", nick);
666 return;
668 for (TDB_DATA d = tdb_firstkey(feed_db); d.dptr;) {
669 TDB_DATA f = tdb_fetch(feed_db, d);
670 TDB_DATA next = tdb_nextkey(feed_db, d);
672 if (!strncmp(d.dptr, target, len) && d.dptr[len] == ',') {
673 privmsg(b, target, "%s: following %s", nick, d.dptr + len + 1);
674 found++;
676 free(d.dptr);
677 free(f.dptr);
678 d = next;
680 if (!found)
681 privmsg(b, target, "%s: not following any feed on %s", nick, target);
684 static void command_feed_get(struct bio *b, const char *nick, const char *host, const char *target, char *args)
686 if (!feed_db)
687 return;
688 for (TDB_DATA d = tdb_firstkey(feed_db); d.dptr;) {
689 TDB_DATA next = tdb_nextkey(feed_db, d);
690 if (!args || strcasestr(d.dptr, args)) {
691 TDB_DATA f = tdb_fetch(feed_db, d);
692 privmsg(b, target, "%s: %s = %s", nick, d.dptr, f.dptr);
693 free(f.dptr);
695 if (strlen(d.dptr)+1 < d.dsize) {
696 privmsg(b, target, "%s: removed buggy entry", nick);
697 tdb_delete(feed_db, d);
699 free(d.dptr);
700 d = next;
704 static void command_feed_set(struct bio *b, const char *nick, const char *host, const char *target, char *args)
706 if (!feed_db)
707 return;
708 TDB_DATA key, val;
709 key.dptr = token(&args, ' ');
710 char *value = token(&args, ' ');
711 if (!key.dptr || !value)
712 return;
713 key.dsize = strlen(key.dptr) + 1;
714 val.dsize = strlen(value) + 2;
715 val.dptr = malloc(val.dsize);
716 strcpy(val.dptr+1, value);
717 val.dptr[0] = '\001';
718 if (tdb_store(feed_db, key, val, 0) < 0)
719 privmsg(b, target, "%s: setting failed: %s", nick, tdb_errorstr(feed_db));
720 else
721 privmsg(b, target, "%s: burp", nick);
722 free(val.dptr);
725 static void command_feed_rem(struct bio *b, const char *nick, const char *host, const char *target, char *args)
727 if (!feed_db || !args)
728 return;
729 TDB_DATA key = { .dptr = (unsigned char*)args, .dsize = strlen(args)+1 };
730 if (tdb_delete(feed_db, key) < 0)
731 privmsg(b, target, "%s: removing failed: %s", nick, tdb_errorstr(feed_db));
732 else
733 privmsg(b, target, "%s: burp", nick);
736 static void command_feed_xxx(struct bio *b, const char *nick, const char *host, const char *target, char *args)
738 if (!feed_db)
739 return;
741 tdb_wipe_all(feed_db);
742 privmsg(b, target, "%s: all evidence erased", nick);
745 static void command_seen_xxx(struct bio *b, const char *nick, const char *host, const char *target, char *args)
747 if (!seen_db)
748 return;
750 tdb_wipe_all(seen_db);
751 privmsg(b, target, "%s: all evidence erased", nick);
754 static void command_feed_counter(struct bio *b, const char *nick, const char *host, const char *target, char *args)
756 if (!chan_db)
757 return;
758 tdb_wipe_all(chan_db);
759 privmsg(b, target, "%s: All update counters reset", nick);
762 static char *get_text_appended(xmlNode *cur)
764 for (; cur; cur = cur->next) {
765 if (cur->type != XML_TEXT_NODE)
766 continue;
767 return strdup(cur->content);
769 return NULL;
772 static char *get_title(struct bio *b, xmlNode *cur_node)
774 for (; cur_node; cur_node = next_link(cur_node)) {
775 if (cur_node->type == XML_ELEMENT_NODE && !strcasecmp(cur_node->name, "title")) {
776 if (!cur_node->children)
777 return NULL;
778 return get_text_appended(cur_node->children);
781 return NULL;
784 static void internal_link(struct bio *b, const char *nick, const char *host, const char *target, char *args, unsigned verbose)
786 CURL *h;
787 struct curl_slist *headers = NULL;
788 char error[CURL_ERROR_SIZE];
789 int success, sent = verbose;
790 struct curl_download_context curl_ctx = {};
792 if (!args)
793 return;
794 int64_t stop, start = get_time(b, target);
796 h = curl_easy_init();
797 headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
798 headers = curl_slist_append(headers, "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
799 headers = curl_slist_append(headers, "Accept-Language: en-us,en;q=0.7");
800 headers = curl_slist_append(headers, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
801 headers = curl_slist_append(headers, "DNT: 1");
802 headers = curl_slist_append(headers, "Connection: keep-alive");
803 curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
804 curl_easy_setopt(h, CURLOPT_URL, args);
805 curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
806 curl_easy_setopt(h, CURLOPT_WRITEDATA, &curl_ctx);
807 curl_easy_setopt(h, CURLOPT_ERRORBUFFER, error);
808 curl_easy_setopt(h, CURLOPT_FOLLOWLOCATION, 1);
809 curl_easy_setopt(h, CURLOPT_MAXREDIRS, 3);
810 curl_easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 0);
811 curl_easy_setopt(h, CURLOPT_TIMEOUT, 8);
812 curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, 8);
813 //curl_easy_setopt(h, CURLOPT_VERBOSE, 1);
814 success = curl_easy_perform(h);
815 curl_easy_cleanup(h);
816 curl_slist_free_all(headers);
817 if (success == CURLE_OK) {
818 magic_t m = magic_open(MAGIC_MIME_TYPE);
819 magic_load(m, NULL);
820 const char *mime = magic_buffer(m, curl_ctx.data, curl_ctx.len);
821 if (strstr(mime, "text/html") || strstr(mime, "application/xml") || strstr(mime, "application/xhtml+xml")) {
822 htmlDocPtr ctx = htmlReadMemory(curl_ctx.data, curl_ctx.len, 0, args, HTML_PARSE_RECOVER|HTML_PARSE_NOERROR|HTML_PARSE_NOWARNING);
823 xmlNode *root_element = xmlDocGetRootElement(ctx);
824 char *title = get_title(b, root_element);
825 if (title) {
826 char *nuke;
827 squash(title);
828 decode_html_entities_utf8(title, NULL);
829 if ((nuke = strstr(title, " on SoundCloud - Create")))
830 *nuke = 0;
831 if (*title) {
832 privmsg(b, target, "%s linked %s", nick, title);
833 sent = 1;
835 free(title);
837 if (verbose && !title)
838 privmsg(b, target, "%s linked %s page with invalid title", nick, mime);
839 xmlFreeDoc(ctx);
840 } else if (verbose) {
841 magic_setflags(m, MAGIC_COMPRESS);
842 const char *desc = magic_buffer(m, curl_ctx.data, curl_ctx.len);
843 privmsg(b, target, "%s linked type %s", nick, desc);
845 magic_close(m);
847 if (verbose && success != CURLE_OK)
848 privmsg(b, target, "Error %s (%u)\n", error, success);
849 else if (!sent && (stop = get_time(b, target)) - start >= 15) {
850 privmsg(b, target, "Link (%s) by %s timed out, disabling links for 10 seconds", args, nick);
851 commands[strhash("get") % elements(commands)].disabled_until = stop + 10;
853 free(curl_ctx.data);
856 static void command_get(struct bio *b, const char *nick, const char *host, const char *target, char *args)
858 if (!args || (sstrncmp(args, "http://") && sstrncmp(args, "https://")))
859 return;
860 internal_link(b, nick, host, target, token(&args, ' '), 1);
863 static void command_hugs(struct bio *b, const char *nick, const char *host, const char *target, char *args)
865 action(b, target, "gives a lunar hug to %s", args ? args : nick);
868 static void command_hug(struct bio *b, const char *nick, const char *host, const char *target, char *args)
870 if ((host && !strcmp(host, "life.on.the.moon.is.great.I.know.all.about.it")) ||
871 (args && !sstrncasecmp(args, "lu")))
872 command_hugs(b, nick, host, target, args);
873 else
874 action(b, target, "gives a robotic hug to %s", args ? args : nick);
877 static void command_snuggles(struct bio *b, const char *nick, const char *host, const char *target, char *args)
879 action(b, target, "gives a lunar snuggle to %s", args ? args : nick);
882 static void command_snuggle(struct bio *b, const char *nick, const char *host, const char *target, char *args)
884 if ((host && !strcmp(host, "life.on.the.moon.is.great.I.know.all.about.it")) ||
885 (args && !sstrncasecmp(args, "lu")))
886 command_snuggles(b, nick, host, target, args);
887 else
888 action(b, target, "gives a robotic snuggle to %s", args ? args : nick);
891 static void command_cookie(struct bio *b, const char *nick, const char *host, const char *target, char *args)
893 action(b, target, "hands a metallic looking cookie to %s", args ? args : nick);
896 static void command_derpy(struct bio *b, const char *nick, const char *host, const char *target, char *args)
898 static const char *insults[] = {
899 "accidentally shocks herself",
900 "tumbles down the stairs like a slinky",
901 "whirrrs and clicks in a screeching way",
902 "had problems executing this command",
903 "breaks down entirely",
904 "uses her magic to levitate herself off the ground, then hits it face first"
906 action(b, target, "%s", insults[getrand() % elements(insults)]);
909 static void command_inspect(struct bio *b, const char *nick, const char *host, const char *target, char *args)
911 struct command_hash *c;
912 unsigned leave, crash;
913 char *cmd;
914 if (!args || !(cmd = token(&args, ' ')))
915 return;
917 if (strcmp(cmd, "#")) {
918 c = &commands[strhash(cmd) % elements(commands)];
919 if (!c->string || strcasecmp(c->string, cmd)) {
920 privmsg(b, target, "Command %s not valid", cmd);
921 return;
923 } else
924 c = &command_channel;
926 leave = c->left + (c->cmd == command_inspect);
927 crash = c->enter - leave;
928 if (c->enter != leave)
929 privmsg(b, target, "%s: %u successes and %u crash%s, last crashing command: %s", c->string, leave, crash, crash == 1 ? "" : "es", c->failed_command);
930 else
931 privmsg(b, target, "%s: %u time%s executed succesfully", c->string, leave, leave == 1 ? "" : "s");
934 static void command_rebuild(struct bio *b, const char *nick, const char *host, const char *target, char *args)
936 int ret;
937 char *make[] = { "/usr/bin/make", "-j4", NULL };
938 char *git_reset[] = { "/usr/bin/git", "reset", "--hard", "master", NULL };
939 ret = pipe_command(b, target, nick, 0, 1, git_reset);
940 if (ret) {
941 action(b, target, "could not rebuild");
942 return;
944 ret = pipe_command(b, target, nick, 0, 1, make);
945 if (!ret)
946 kill(getpid(), SIGUSR1);
947 else if (ret > 0)
948 action(b, target, "displays an ominous %i", ret);
951 static void command_swear(struct bio *b, const char *nick, const char *host, const char *target, char *args)
953 static const char *insults[] = {
954 "featherbrain",
955 "ponyfeathers",
956 "What in the hey?",
957 "What are you, a dictionary?",
958 "TAR-DY!",
959 "[BUY SOME APPLES]",
960 "{ Your lack of bloodlust on the battlefield is proof positive that you are a soulless automaton! }",
961 "Your royal snootiness"
963 privmsg(b, target, "%s: %s", args ? args : nick, insults[getrand() % elements(insults)]);
966 static const char *perty(int64_t *t)
968 if (*t >= 14 * 24 * 3600) {
969 *t /= 7 * 24 * 3600;
970 return "weeks";
971 } else if (*t >= 48 * 3600) {
972 *t /= 24 * 3600;
973 return "days";
974 } else if (*t >= 7200) {
975 *t /= 3600;
976 return "hours";
977 } else if (*t >= 120) {
978 *t /= 60;
979 return "minutes";
981 return *t == 1 ? "second" : "seconds";
984 static void command_timeout(struct bio *b, const char *nick, const char *host, const char *target, char *args)
986 struct command_hash *c;
987 int64_t t = get_time(b, target);
988 int64_t howlong;
989 if (t < 0)
990 return;
991 char *arg = token(&args, ' ');
992 if (!arg || !args || !(howlong = atoi(args))) {
993 action(b, target, "pretends to time out");;
994 return;
996 c = &commands[strhash(arg) % elements(commands)];
997 if (c->string && !strcasecmp(c->string, arg)) {
998 c->disabled_until = t + howlong;
999 const char *str = perty(&howlong);
1000 action(b, target, "disables %s for %"PRIi64" %s", arg, howlong, str);
1001 } else
1002 action(b, target, "clicks sadly at %s for not being able to find that command", nick);
1005 static void command_mfw(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1007 char error[CURL_ERROR_SIZE], *new_url;
1008 CURL *h = curl_easy_init();
1009 struct curl_slist *headers = NULL;
1010 struct curl_download_context curl_ctx = {};
1011 headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
1012 headers = curl_slist_append(headers, "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
1013 headers = curl_slist_append(headers, "Accept-Language: en-us,en;q=0.7");
1014 headers = curl_slist_append(headers, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
1015 headers = curl_slist_append(headers, "DNT: 1");
1016 headers = curl_slist_append(headers, "Connection: keep-alive");
1017 curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
1018 curl_easy_setopt(h, CURLOPT_URL, "http://mylittlefacewhen.com/random/");
1019 curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
1020 curl_easy_setopt(h, CURLOPT_WRITEDATA, &curl_ctx);
1021 curl_easy_setopt(h, CURLOPT_ERRORBUFFER, error);
1022 curl_easy_setopt(h, CURLOPT_TIMEOUT, 8);
1023 curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, 8);
1024 //curl_easy_setopt(h, CURLOPT_VERBOSE, 1);
1025 CURLcode ret = curl_easy_perform(h);
1026 if (ret == CURLE_OK && curl_easy_getinfo(h, CURLINFO_REDIRECT_URL, &new_url) == CURLE_OK)
1027 privmsg(b, target, "%s: %s", nick, new_url);
1028 curl_slist_free_all(headers);
1029 curl_easy_cleanup(h);
1030 if (ret != CURLE_OK)
1031 privmsg(b, target, "%s: You have no face", nick);
1034 static TDB_DATA get_mail_key(const char *nick)
1036 TDB_DATA d;
1037 int i;
1038 d.dsize = strlen(nick)+1;
1039 d.dptr = malloc(d.dsize);
1040 for (i = 0; i < d.dsize - 1; ++i)
1041 d.dptr[i] = tolower(nick[i]);
1042 d.dptr[i] = 0;
1043 return d;
1046 static void command_mail(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1048 char *victim, *x;
1049 size_t len;
1050 int override = 0;
1052 if (!mail_db || !seen_db)
1053 return;
1054 TDB_DATA key, val;
1055 victim = token(&args, ' ');
1056 if (victim && !strcasecmp(victim, "-seen")) {
1057 victim = token(&args, ' ');
1058 override = 1;
1060 if (!victim || !args || victim[0] == '#' || strchr(victim, '@') || strchr(victim, '.')) {
1061 privmsg(b, target, "%s: Usage: !mail <nick> <message>", nick);
1062 return;
1064 if (!strcasecmp(victim, nick_self)) {
1065 action(b, target, "whirrs and clicks excitedly at the mail she received from %s", nick);
1066 return;
1068 if (!strcasecmp(victim, nick)) {
1069 action(b, target, "echos the words from %s back to them: %s", nick, args);
1070 return;
1072 int64_t now = get_time(b, target);
1073 if (now < 0)
1074 return;
1076 key = get_mail_key(victim);
1078 val = tdb_fetch(seen_db, key);
1079 if (val.dptr && (x = strchr(val.dptr, ','))) {
1080 *(x++) = 0;
1081 if (!admin(host) && (now - atoll(val.dptr)) < 300 && (!sstrncasecmp(x, "in ") || !sstrncasecmp(x, "joining "))) {
1082 action(b, target, "would rather not store mail for someone active so recently");
1083 goto out;
1085 } else if (!override) {
1086 privmsg(b, target, "%s: I've never seen \"%s\" use !mail -seen %s <message> to override this check.", nick, victim, victim);
1087 return;
1090 val = tdb_fetch(mail_db, key);
1091 if (!val.dptr)
1092 val.dsize = 0;
1093 else {
1094 unsigned char *cur;
1095 int letters = 0;
1096 for (cur = val.dptr; cur < val.dptr + val.dsize; cur += strlen(cur)+1)
1097 letters++;
1098 if (letters >= 4) {
1099 action(b, target, "looks sadly at %s as she cannot hold any more mail to %s", nick, victim);
1100 goto out;
1103 len = snprintf(NULL, 0, "%"PRIi64 ",%s: %s", now, nick, args) + 1;
1104 val.dptr = realloc(val.dptr, val.dsize + len);
1105 snprintf(val.dptr + val.dsize, len, "%"PRIi64 ",%s: %s", now, nick, args);
1106 val.dsize += len;
1107 if (tdb_store(mail_db, key, val, 0) < 0)
1108 privmsg(b, target, "%s: updating mail returns %s", nick, tdb_errorstr(mail_db));
1109 else
1110 action(b, target, "whirrs and clicks at %s as she stores the mail for %s", nick, victim);
1111 out:
1112 free(val.dptr);
1113 free(key.dptr);
1116 static void single_message(struct bio *b, const char *target, char *cur, int64_t now)
1118 char *endtime, *sep = strchr(cur, ':');
1119 int64_t delta = -1;
1120 if (sep && (endtime = strchr(cur, ',')) && endtime < sep) {
1121 int64_t t = atoll(cur);
1122 if (t > 0)
1123 delta = now - t;
1124 cur = endtime + 1;
1126 if (delta >= 0) {
1127 const char *str = perty(&delta);
1128 privmsg(b, target, "%"PRIi64" %s ago from %s", delta, str, cur);
1129 } else
1130 privmsg(b, target, "From %s", cur);
1133 static void command_deliver(struct bio *b, const char *nick, const char *target)
1135 TDB_DATA key, val;
1136 unsigned char *cur;
1137 static unsigned mail_enter, mail_leave;
1138 if (mail_enter++ != mail_leave)
1139 return;
1141 if (!mail_db)
1142 return;
1143 key = get_mail_key(nick);
1144 val = tdb_fetch(mail_db, key);
1145 if (!val.dptr)
1146 goto end;
1147 int64_t now = get_time(b, NULL);
1148 if (strcasecmp(key.dptr, nick_self)) {
1149 privmsg(b, target, "%s: You've got mail!", nick);
1150 for (cur = val.dptr; cur < val.dptr + val.dsize; cur += strlen(cur)+1)
1151 single_message(b, target, cur, now);
1153 free(val.dptr);
1154 tdb_delete(mail_db, key);
1155 end:
1156 free(key.dptr);
1157 mail_leave++;
1160 static void update_seen(struct bio *b, char *doingwhat, const char *nick)
1162 TDB_DATA key;
1163 key = get_mail_key(nick);
1164 TDB_DATA val = { .dptr = doingwhat, .dsize = strlen(doingwhat)+1 };
1165 if (seen_db)
1166 tdb_store(seen_db, key, val, 0);
1167 free(key.dptr);
1170 static void command_seen(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1172 char *arg = token(&args, ' '), *x;
1173 int64_t now = get_time(b, target);
1174 TDB_DATA key, val;
1175 if (now < 0)
1176 return;
1177 if (!seen_db || !arg) {
1178 privmsg(b, target, "%s: { Error... }", nick);
1179 return;
1181 if (!strcasecmp(arg, nick_self)) {
1182 action(b, target, "whirrs and clicks at %s", nick);
1183 return;
1185 key = get_mail_key(arg);
1186 val = tdb_fetch(seen_db, key);
1187 if (val.dptr && (x = strchr(val.dptr, ','))) {
1188 int64_t delta;
1189 const char *str;
1190 *(x++) = 0;
1191 delta = now - atoll(val.dptr);
1192 str = perty(&delta);
1193 if (delta < 0)
1194 privmsg(b, target, "%s was last seen in the future %s", arg, x);
1195 else
1196 privmsg(b, target, "%s was last seen %"PRIi64" %s ago %s", arg, delta, str, x);
1197 } else
1198 action(b, target, "cannot find any evidence that %s exists", arg);
1201 static void command_mailbag(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1203 char buffer[256];
1204 unsigned rem = sizeof(buffer)-1, first = 2;
1205 if (!mail_db)
1206 return;
1207 buffer[rem] = 0;
1209 for (TDB_DATA f = tdb_firstkey(mail_db); f.dptr;) {
1210 if (f.dsize + 4 > rem) {
1211 privmsg(b, target, "%s: Holding mail for: %s", nick, &buffer[rem]);
1212 first = 2;
1213 rem = sizeof(buffer)-1;
1214 assert(f.dsize + 4 < rem);
1216 if (f.dptr) {
1217 if (first == 2) {
1218 first = 1;
1219 } else if (first) {
1220 rem -= 5;
1221 memcpy(&buffer[rem], " and ", 5);
1222 first = 0;
1223 } else {
1224 rem -= 2;
1225 memcpy(&buffer[rem], ", ", 2);
1227 rem -= f.dsize - 1;
1228 memcpy(&buffer[rem], f.dptr, f.dsize - 1);
1230 TDB_DATA next = tdb_nextkey(mail_db, f);
1231 free(f.dptr);
1232 f = next;
1234 if (first < 2)
1235 privmsg(b, target, "%s: Holding mail for: %s", nick, &buffer[rem]);
1238 static void command_mailread(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1240 TDB_DATA key, val;
1241 char *victim;
1242 if (!mail_db || !(victim = token(&args, ' ')))
1243 return;
1244 key = get_mail_key(victim);
1245 val = tdb_fetch(mail_db, key);
1246 if (!val.dptr)
1247 action(b, target, "ponyshrugs as no mail for %s was found", victim);
1248 else {
1249 unsigned char *cur;
1250 int64_t now = get_time(b, NULL);
1251 action(b, target, "peeks through %s's mail", victim);
1252 for (cur = val.dptr; cur < val.dptr + val.dsize; cur += strlen(cur)+1)
1253 single_message(b, target, cur, now);
1255 free(val.dptr);
1256 free(key.dptr);
1259 static void command_no_deliver(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1261 TDB_DATA key, val;
1262 char *cur;
1263 if (!mail_db || !(cur = token(&args, ' ')))
1264 return;
1265 key = get_mail_key(cur);
1266 val = tdb_fetch(mail_db, key);
1267 if (!val.dptr)
1268 action(b, target, "ponyshrugs as no mail for %s was found", cur);
1269 else {
1270 action(b, target, "deletes all evidence of %s's mail", cur);
1271 tdb_delete(mail_db, key);
1273 free(val.dptr);
1274 free(key.dptr);
1277 static void perform_roll(struct bio *b, const char *nick, const char *target, long sides, long dice, long bonus)
1279 long rem = dice, total = bonus;
1280 while (rem--)
1281 total += 1 + (getrand() % sides);
1282 action(b, target, "rolls %li %li-sided %s for a total of %li (%+li)", dice, sides, dice == 1 ? "die" : "dice", total, bonus);
1285 static void command_roll(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1287 char *cur;
1288 long dice = 1, sides = 20;
1289 if ((cur = token(&args, ' '))) {
1290 char *first = cur;
1291 dice = strtol(first, &cur, 10);
1292 if (first == cur)
1293 dice = 1;
1294 if (*cur && *cur != 'd' && *cur != 'D')
1295 goto syntax;
1297 if (*cur) {
1298 char *last = cur+1;
1299 sides = strtol(last, &cur, 10);
1300 if (last == cur)
1301 goto syntax;
1304 if (dice <= 0 || dice > 10 || sides < 2 || sides > 20)
1305 goto syntax;
1306 perform_roll(b, nick, target, sides, dice, 0);
1307 return;
1309 syntax:
1310 action(b, target, "bleeps at %s in a confused manner", nick);
1313 static void add_g(struct bio *b, const char *target, int g)
1315 int ret = 0;
1316 int64_t total_g = 0;
1317 TDB_DATA chan, res;
1319 if (!chan_db || target[0] != '#')
1320 return;
1322 chan.dptr = (char*)target;
1323 chan.dsize = strlen(chan.dptr)+1;
1324 res = tdb_fetch(chan_db, chan);
1325 if (res.dptr && res.dsize >= 16) {
1326 ((int64_t*)res.dptr)[1] += g;
1327 if (res.dsize >= 24)
1328 total_g = ((int64_t*)res.dptr)[2] += g;
1329 ret = tdb_store(chan_db, chan, res, 0);
1331 free(res.dptr);
1332 if (ret < 0)
1333 fprintf(stderr, "updating database: %s", tdb_errorstr(feed_db));
1334 else if (g < total_g) {
1335 int64_t last_g = total_g - g;
1336 last_g -= last_g % 1000;
1337 if (last_g + 1000 <= total_g)
1338 privmsg(b, target, "g has been said %"PRIi64" times!", total_g);
1342 static int parse_g(const char *cur, int *g)
1344 int this_g = 0;
1345 for (const unsigned char *ptr = cur; *ptr; ptr++) {
1346 if (*ptr >= 0x80)
1347 return 0;
1348 if (*ptr == 'g' || *ptr == 'G')
1349 this_g++;
1350 else if ((*ptr >= 'a' && *ptr <= 'z') || (*ptr >= 'A' && *ptr <= 'Z'))
1351 return 0;
1352 else if (*ptr != '1' && *ptr >= '0' && *ptr <= '9')
1353 return 0;
1355 *g += this_g;
1356 return this_g;
1359 static void channel_msg(struct bio *b, const char *nick, const char *host,
1360 const char *chan, char *msg, int64_t t)
1362 char *cur = NULL, *next;
1363 int is_action = 0;
1364 int g = 0;
1366 int that = 0, what = 0, she = 0;
1368 if (!msg || !strcmp(nick, "`Daring_Do`") || !strcmp(nick, "`Celestia`") || !strcmp(nick, "derpy") || !strcmp(nick, "`Derpy`") || !strcmp(nick, "`Luna`") || !sstrncmp(nick, "GitHub") || !sstrncmp(nick, "CIA-") || !strcmp(nick, "Terminus-Bot") || !strcmp(nick, "r0m"))
1369 return;
1371 if (!sstrncasecmp(msg, "\001ACTION ")) {
1372 msg += sizeof("\001ACTION ")-1;
1373 is_action = 1;
1374 asprintf(&cur, "%"PRIi64 ",in %s: * %s %s", t, chan, nick, msg);
1375 } else
1376 asprintf(&cur, "%"PRIi64 ",in %s: <%s> %s", t, chan, nick, msg);
1377 if (t > 0)
1378 update_seen(b, cur, nick);
1379 free(cur);
1380 (void)is_action;
1382 next = msg;
1383 while ((cur = token(&next, ' '))) {
1384 if (!strcasecmp(cur, ">mfw") || !strcasecmp(cur, "mfw")) {
1385 if (!strcasecmp(chan, "#brony") || !ponify)
1386 continue;
1387 if (t < 0 || t > commands[strhash("mfw") % elements(commands)].disabled_until)
1388 command_mfw(b, nick, host, chan, NULL);
1389 return;
1390 } else if (!sstrncasecmp(cur, "http://") || !sstrncasecmp(cur, "https://")) {
1391 static char last_url[512];
1392 char *part;
1393 if (!strcmp(cur, last_url))
1394 return;
1395 strncpy(last_url, cur, sizeof(last_url)-1);
1397 if (t >= 0 && t < commands[strhash("get") % elements(commands)].disabled_until)
1398 return;
1400 else if (strcasestr(cur, "youtube.com/user") && (part = strstr(cur, "#p/"))) {
1401 char *foo;
1402 part = strrchr(part, '/') + 1;
1403 asprintf(&foo, "http://youtube.com/watch?v=%s", part);
1404 if (foo)
1405 internal_link(b, nick, host, chan, foo, 0);
1406 free(foo);
1407 return;
1408 } else if (strcasestr(cur, "twitter.com/") || strcasestr(cur, "mlfw.info") || strcasestr(cur, "mylittlefacewhen.com") || !strcasecmp(chan, "#geek"))
1409 return;
1410 internal_link(b, nick, host, chan, cur, 0);
1411 return;
1413 else if (!sstrncasecmp(cur, "that") || !sstrncasecmp(cur, "dat"))
1414 that = 1;
1415 else if (that && (!sstrncasecmp(cur, "what") || !sstrncasecmp(cur, "wat")))
1416 what = 1;
1417 else if (what && !sstrncasecmp(cur, "she"))
1418 she = 1;
1419 else if (she && !sstrncasecmp(cur, "said")) {
1420 if (t <= 0 || t >= commands[strhash("shesaid") % elements(commands)].disabled_until)
1421 privmsg(b, chan, "%s: \"%s\"", nick, women_quotes[getrand() % elements(women_quotes)]);
1422 return;
1423 } else if (parse_g(cur, &g))
1424 continue;
1426 if (g)
1427 add_g(b, chan, g);
1430 static struct command_hash unhashed[] = {
1431 { "1", command_coinflip },
1432 { "get", command_get },
1433 { "hug", command_hug },
1434 { "hugs", command_hugs },
1435 { "snug", command_snuggle },
1436 { "snugs", command_snuggles },
1437 { "snuggle", command_snuggle },
1438 { "snuggles", command_snuggles },
1439 { "cookie", command_cookie },
1440 { "mfw", command_mfw },
1441 { "swear", command_swear },
1442 { "mail", command_mail },
1443 { "seen", command_seen },
1444 { "derpy", command_derpy },
1445 { "g", command_g },
1446 { "shesaid", command_shesaid },
1447 { "roll", command_roll },
1449 { "rebuild", command_rebuild, 1 },
1450 { "abort", command_abort, 1 },
1451 { "crash", command_crash, 1 },
1452 { "inspect", command_inspect, 1 },
1453 { "timeout", command_timeout, 1 },
1455 { "follow", command_follow },
1456 { "unfollow", command_unfollow },
1457 { "feeds", command_feeds },
1459 // DEBUG
1460 { "feed_get", command_feed_get, 1 },
1461 { "feed_set", command_feed_set, 1 },
1462 { "feed_rem", command_feed_rem, 1 },
1463 { "feed_xxx", command_feed_xxx, 1 },
1464 { "feed_counter", command_feed_counter, 1 },
1465 { "seen_xxx", command_seen_xxx, 1 },
1466 { "mailbag", command_mailbag },
1467 { "mailread", command_mailread, 1 },
1468 { "\"deliver\"", command_no_deliver, 1 },
1471 static void init_hash(struct bio *b, const char *target)
1473 int i;
1474 for (i = 0; i < elements(unhashed); ++i) {
1475 unsigned h = strhash(unhashed[i].string) % elements(commands);
1476 if (commands[h].string)
1477 privmsg(b, target, "%s is a duplicate command with %s", commands[h].string, unhashed[i].string);
1478 else
1479 commands[h] = unhashed[i];
1481 #ifdef local_commands
1482 for (i = 0; i < elements(local_commands); ++i) {
1483 unsigned h = strhash(local_commands[i].string) % elements(commands);
1484 if (commands[h].string)
1485 privmsg(b, target, "%s is a duplicate command with %s", commands[h].string, local_commands[i].string);
1486 else
1487 commands[h] = local_commands[i];
1489 #endif
1492 void init_hook(struct bio *b, const char *target, const char *nick, unsigned is_ponified)
1494 char *cwd, *path = NULL;
1495 nick_self = nick;
1496 static const char *messages[] = {
1497 "feels circuits being activated that weren't before",
1498 "suddenly gets a better feel of her surroundings",
1499 "looks the same, yet there's definitely something different",
1500 "emits a beep as her lights begin to pulse slowly",
1501 "whirrrs and bleeps like never before",
1502 "bleeps a few times happily",
1503 "excitedly peeks at her surroundings"
1505 init_hash(b, target);
1506 ponify = is_ponified;
1508 cwd = getcwd(NULL, 0);
1509 asprintf(&path, "%s/db/feed.tdb", cwd);
1510 feed_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1511 free(path);
1512 if (!feed_db)
1513 privmsg(b, target, "Opening feed db failed: %m");
1515 asprintf(&path, "%s/db/chan.tdb", cwd);
1516 chan_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1517 free(path);
1518 if (!chan_db)
1519 privmsg(b, target, "Opening chan db failed: %m");
1521 asprintf(&path, "%s/db/mail.tdb", cwd);
1522 mail_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1523 free(path);
1524 if (!mail_db)
1525 privmsg(b, target, "Opening mail db failed: %m");
1527 asprintf(&path, "%s/db/seen.tdb", cwd);
1528 seen_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1529 free(path);
1530 if (!seen_db)
1531 privmsg(b, target, "Opening seen db failed: %m");
1533 free(cwd);
1534 action(b, target, "%s", messages[getrand() % elements(messages)]);
1537 static void __attribute__((destructor)) shutdown_hook(void)
1539 if (seen_db)
1540 tdb_close(seen_db);
1541 if (mail_db)
1542 tdb_close(mail_db);
1543 if (feed_db)
1544 tdb_close(feed_db);
1545 if (chan_db)
1546 tdb_close(chan_db);
1549 static char *nom_special(char *line)
1551 while (*line) {
1552 if (*line == 0x03) {
1553 line++;
1554 if (*line >= '0' && *line <= '9')
1555 line++;
1556 else continue;
1557 if (*line >= '0' && *line <= '9')
1558 line++;
1559 if (line[0] == ',' && line[1] >= '0' && line[1] <= '9')
1560 line += 2;
1561 else continue;
1562 if (*line >= '0' && *line <= '9')
1563 line++;
1564 } else if (*line != 0x02 && /* BOLD */
1565 *line != 0x1f && /* UNDERLINE */
1566 *line != 0x16 && /* ITALIC */
1567 *line != 0x06 && /* NFI, is this even used? */
1568 *line != 0x07 && /* NFI, is this even used? */
1569 *line != 0x0f) /* NORMAL */
1570 return line;
1571 else
1572 line++;
1574 return line;
1577 static char *cleanup_special(char *line)
1579 char *cur, *start = nom_special(line);
1580 if (!*start)
1581 return NULL;
1582 for (line = cur = start; *line; line = nom_special(line))
1583 *(cur++) = *(line++);
1585 for (cur--; cur >= start; --cur)
1586 if (*cur != ' ' && *cur != '\001')
1587 break;
1589 if (cur < start)
1590 return NULL;
1591 cur[1] = 0;
1592 return start;
1595 static void rss_check(struct bio *b, const char *channel, int64_t t)
1597 static unsigned rss_enter, rss_leave;
1598 if (t >= 0 && rss_enter == rss_leave) {
1599 rss_enter++;
1600 channel_feed_check(b, channel, t);
1601 rss_leave++;
1605 static const char *privileged_command[] = {
1606 "{ Rarity, I love you so much! }",
1607 "{ Rarity, have I ever told you that I love you? }",
1608 "{ Yes, I love my sister, Rarity. }",
1609 "{ Raaaaaaaaaaaaaarity. }",
1610 "{ You do not fool me, Rari...bot! }"
1613 static int cmd_check(struct bio *b, struct command_hash *c, int is_admin, int64_t t, const char *prefix, const char *target)
1615 if (c->left != c->enter)
1616 privmsg(b, target, "Command %s is disabled because of a crash", c->string);
1617 else if (t > 0 && t < c->disabled_until && !is_admin) {
1618 int64_t delta = c->disabled_until - t;
1619 const char *str = perty(&delta);
1620 b->writeline(b, "NOTICE %s :Command %s is on timeout for the next %"PRIi64 " %s", prefix, c->string, delta, str);
1621 } else if (c->admin && !is_admin)
1622 privmsg(b, target, "%s: %s", prefix, privileged_command[getrand() % elements(privileged_command)]);
1623 else
1624 return 1;
1625 return 0;
1628 void privmsg_hook(struct bio *b, const char *prefix, const char *ident, const char *host,
1629 const char *const *args, unsigned nargs)
1631 char *cmd_args, *cmd;
1632 const char *target = args[0][0] == '#' ? args[0] : prefix;
1633 unsigned chan, nick_len;
1634 struct command_hash *c;
1635 int64_t t = get_time(b, target);
1636 int is_admin = admin(host);
1638 chan = args[0][0] == '#';
1639 if (chan) {
1640 rss_check(b, args[0], t);
1641 command_deliver(b, prefix, args[0]);
1643 cmd_args = cleanup_special((char*)args[1]);
1644 if (!cmd_args)
1645 return;
1647 if (ident && (!strcasecmp(ident, "Revolver") || !strcasecmp(ident, "Rev")))
1648 return;
1650 if (chan && cmd_args[0] == '!') {
1651 cmd_args++;
1652 } else if (chan && (nick_len = strlen(nick_self)) &&
1653 !strncasecmp(cmd_args, nick_self, nick_len) &&
1654 (cmd_args[nick_len] == ':' || cmd_args[nick_len] == ',') && cmd_args[nick_len+1] == ' ') {
1655 cmd_args += nick_len + 2;
1656 if (!cmd_args[0])
1657 return;
1658 chan = 2;
1659 } else if (chan) {
1660 if (command_channel.enter == command_channel.left) {
1661 command_channel.enter++;
1662 snprintf(command_channel.failed_command,
1663 sizeof(command_channel) - offsetof(struct command_hash, failed_command) - 1,
1664 "%s:%s (%s@%s) \"#\" %s", target, prefix, ident, host, cmd_args);
1665 channel_msg(b, prefix, host, args[0], cmd_args, t);
1666 command_channel.left++;
1668 return;
1670 cmd = token(&cmd_args, ' ');
1671 if (!chan && cmd_args && cmd_args[0] == '#') {
1672 if (!is_admin) {
1673 privmsg(b, target, "%s: %s", prefix, privileged_command[getrand() % elements(privileged_command)]);
1674 return;
1676 target = token(&cmd_args, ' ');
1679 c = &commands[strhash(cmd) % elements(commands)];
1680 if (c->string && !strcasecmp(c->string, cmd)) {
1681 if (cmd_check(b, c, is_admin, t, prefix, target)) {
1682 c->enter++;
1683 snprintf(c->failed_command, sizeof(*c) - offsetof(struct command_hash, failed_command) - 1,
1684 "%s:%s (%s@%s) \"%s\" %s", target, prefix, ident, host, cmd, cmd_args);
1685 c->cmd(b, prefix, host, target, cmd_args);
1686 c->left++;
1688 return;
1689 } else if (cmd[0] == 'd' && cmd[1] >= '0' && cmd[1] <= '9') {
1690 char *end;
1691 long base;
1692 base = strtol(cmd+1, &end, 10);
1693 if (base > 1 && base <= 20 && !*end) {
1694 long dice = 1, bonus = 0;
1695 char *strdice;
1696 c = &commands[strhash("roll") % elements(commands)];
1697 if (!cmd_check(b, c, is_admin, t, prefix, target))
1698 return;
1699 c->enter++;
1700 snprintf(c->failed_command, sizeof(*c) - offsetof(struct command_hash, failed_command) - 1,
1701 "%s:%s (%s@%s) \"%s\" %s", target, prefix, ident, host, cmd, cmd_args);
1703 strdice = token(&cmd_args, ' ');
1704 if (strdice) {
1705 dice = strtol(strdice, &end, 10);
1706 if (*end || !dice || dice > 10)
1707 goto syntax;
1708 strdice = token(&cmd_args, ' ');
1709 if (strdice) {
1710 bonus = strtol(strdice, &end, 10);
1711 if (*end)
1712 goto syntax;
1715 perform_roll(b, prefix, target, base, dice, bonus);
1716 c->left++;
1717 return;
1719 syntax:
1720 c->left++;
1721 action(b, target, "bleeps at %s in a confused manner", prefix);
1722 return;
1725 if (chan == 2 && t > 0) {
1726 static int64_t last_t;
1727 if (t - last_t > 3)
1728 privmsg(b, target, "%s: { I love you! }", prefix);
1729 last_t = t;
1733 void command_hook(struct bio *b, const char *prefix, const char *ident, const char *host,
1734 const char *command, const char *const *args, unsigned nargs)
1736 char *buf = NULL;
1737 int64_t t = -1;
1738 if (!strcasecmp(command, "NOTICE")) {
1739 if (nargs < 2 || args[0][0] == '#')
1740 return;
1741 if (admin(host))
1742 b->writeline(b, "%s", args[1]);
1743 else
1744 fprintf(stderr, "%s: %s\n", prefix, args[1]);
1745 } else if (!strcasecmp(command, "JOIN")) {
1746 t = get_time(b, args[0]);
1747 rss_check(b, args[0], t);
1748 command_deliver(b, prefix, args[0]);
1749 asprintf(&buf, "%"PRIi64",joining %s", t, args[0]);
1750 } else if (!strcasecmp(command, "PART")) {
1751 t = get_time(b, args[0]);
1752 rss_check(b, args[0], t);
1753 asprintf(&buf, "%"PRIi64",leaving %s", t, args[0]);
1754 } else if (!strcasecmp(command, "QUIT")) {
1755 t = get_time(b, NULL);
1756 asprintf(&buf, "%"PRIi64",quitting with the message \"%s\"", t, args[0]);
1757 } else if (!strcasecmp(command, "NICK")) {
1758 t = get_time(b, NULL);
1759 if (t >= 0) {
1760 asprintf(&buf, "%"PRIi64",changing nick from %s", t, prefix);
1761 if (buf)
1762 update_seen(b, buf, args[0]);
1763 free(buf);
1764 buf = NULL;
1766 asprintf(&buf, "%"PRIi64",changing nick to %s", t, args[0]);
1767 } else if (0) {
1768 int i;
1769 fprintf(stderr, ":%s!%s%s %s", prefix, ident, host, command);
1770 for (i = 0; i < nargs; ++i)
1771 fprintf(stderr, " %s", args[i]);
1772 fprintf(stderr, "\n");
1774 if (t >= 0 && buf)
1775 update_seen(b, buf, prefix);
1776 free(buf);
1777 return;