fix roll range some more
[fillybot.git] / mod.c
blobedcac4fb8777ede0e234ea9becf1affafa345e74
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 if (getrand() & 1)
113 action(b, target, "whirrrs and clicks excitedly at %s", nick);
114 else
115 action(b, target, "eyes %s as nothing happens", nick);
118 static void command_shesaid(struct bio *b, const char *nick, const char *host, const char *target, char *args)
120 privmsg(b, target, "%s: \"%s\"", args ? args : nick, women_quotes[getrand() % elements(women_quotes)]);
123 static void squash(char *title)
125 char *start = title;
126 goto start;
127 while (*title) {
128 while (*title != '\n' && *title != '\r' && *title != '\t' && *title != ' ' && *title) {
129 *(start++) = *(title++);
131 if (*title)
132 *(start++) = ' ';
133 start:
134 while (*title == '\n' || *title == '\r' || *title == '\t' || *title == ' ')
135 title++;
137 *start = 0;
140 struct curl_download_context
142 char *data;
143 size_t len;
146 static size_t write_data(void *ptr, size_t size, size_t nmemb, void *member) {
147 struct curl_download_context *ctx = member;
148 size *= nmemb;
149 ctx->data = realloc(ctx->data, ctx->len + size);
150 memcpy(ctx->data + ctx->len, ptr, size);
151 ctx->len += size;
152 return size;
155 static const char *get_text(xmlNode *cur)
157 for (; cur; cur = cur->next) {
158 if (cur->type == XML_TEXT_NODE)
159 return cur->content;
161 return NULL;
164 static const char *get_link(xmlAttr *cur, const char *which)
166 for (; cur; cur = cur->next) {
167 if (!strcasecmp(cur->name, which))
168 return get_text(cur->children);
170 return NULL;
173 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)
175 const char *cur_title = NULL, *cur_link = NULL;
176 xmlNode *cur;
177 int cur_match = !category;
178 for (cur = entry->children; cur; cur = cur->next) {
179 const char *name = cur->name, *cur_cat;
180 if (cur->type != XML_ELEMENT_NODE)
181 continue;
182 else if (!strcasecmp(name, "link")) {
183 const char *ishtml = get_link(cur->properties, "type");
184 const char *rel = get_link(cur->properties, "rel");
185 if ((!ishtml || !strcasecmp(ishtml, "text/html")) &&
186 rel && !strcasecmp(rel, "alternate"))
187 cur_link = get_link(cur->properties, "href");
188 } else if (!strcasecmp(name, "title"))
189 cur_title = get_text(cur->children);
190 else if (!cur_match && !strcasecmp(name, "category") &&
191 (cur_cat = get_link(cur->properties, "term")) &&
192 strcasestr(cur_cat, category))
193 cur_match = 1;
196 if (cur_title)
197 *title = cur_title;
198 else
199 *title = "<no title>";
200 *link = cur_link;
201 return !cur_link ? -1 : cur_match;
204 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)
206 const char *main_title = NULL, *main_subtitle = NULL, *main_link = NULL, *title, *link, *prev_link = NULL, *prev_title = NULL;
207 char *t;
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 t = strdup(prev_title);
275 squash(t);
276 privmsg(b, target, "( %s ): %s", prev_link, t);
277 free(t);
278 } else if (updates > 1)
279 privmsg(b, target, "( %s ): %u updates, linking most recent", main_link, 1+updates);
280 t = strdup(title);
281 squash(t);
282 privmsg(b, target, "( %s ): %s", link, t);
283 free(t);
284 return link;
287 static const char *walk_rss(struct bio *b, const char *nick, const char *target, const char *url, xmlNode *root, const char *last_link)
289 const char *main_title = NULL, *main_link = NULL, *title = NULL, *link = NULL, *ver;
290 xmlNode *cur, *entry = NULL;
291 ver = get_link(root->properties, "version");
292 if (!ver || strcmp(ver, "2.0")) {
293 if (!ver)
294 privmsg(b, target, "%s: Could not parse rss feed", nick);
295 else
296 privmsg(b, target, "%s: Invalid rss version \"%s\"", nick, ver);
297 return NULL;
299 for (cur = root->children; cur && cur->type != XML_ELEMENT_NODE; cur = cur->next);
300 if (!cur)
301 return NULL;
302 for (cur = cur->children; cur; cur = cur->next) {
303 const char *name = cur->name;
304 if (cur->type != XML_ELEMENT_NODE)
305 continue;
306 if (!strcasecmp(name, "title"))
307 main_title = get_text(cur->children);
308 else if (!strcasecmp(name, "link"))
309 main_link = main_link ? main_link : get_text(cur->children);
310 else if (!strcasecmp(name, "item"))
311 entry = entry ? entry : cur;
313 if (!main_link || !main_title) {
314 privmsg(b, target, "%s: Failed to parse main: %s %s", nick, main_link, main_title);
315 return NULL;
317 if (!entry)
318 return NULL;
320 link = title = NULL;
321 for (cur = entry->children; cur; cur = cur->next) {
322 const char *name = cur->name;
323 if (cur->type != XML_ELEMENT_NODE)
324 continue;
325 if (!strcasecmp(name, "title"))
326 title = get_text(cur->children);
327 else if (!strcasecmp(name, "link"))
328 link = get_text(cur->children);
330 if (!title)
331 title = "<no title>";
332 if (!link) {
333 privmsg(b, target, "%s: Failed to parse entry: %s %s", nick, link, title);
334 return NULL;
336 if (!last_link) {
337 privmsg(b, target, "adding blog %s \"%s\"", main_link, main_title);
338 privmsg(b, target, "Most recent entry: %s %s", link, title);
339 } else if (strcmp(last_link, link)) {
340 int updates = 0;
341 const char *prev_title = NULL, *prev_link = NULL, *cur_title = NULL, *cur_link = NULL;
342 char *t;
343 for (entry = entry->next; entry; entry = entry->next) {
344 if (strcasecmp(entry->name, "item"))
345 continue;
346 prev_title = cur_title;
347 prev_link = cur_link;
348 cur_title = cur_link = NULL;
349 for (cur = entry->children; cur; cur = cur->next) {
350 const char *name = cur->name;
351 if (cur->type != XML_ELEMENT_NODE)
352 continue;
353 if (!strcasecmp(name, "title"))
354 cur_title = get_text(cur->children);
355 else if (!strcasecmp(name, "link"))
356 cur_link = get_text(cur->children);
358 if (!cur_title)
359 cur_title = "<no title>";
360 if (!cur_link || !strcmp(last_link, cur_link))
361 break;
362 updates++;
364 if (updates == 1) {
365 t = strdup(prev_title);
366 squash(t);
367 privmsg(b, target, "( %s ): %s", prev_link, t);
368 free(t);
369 } else if (updates > 1)
370 privmsg(b, target, "( %s ): %u updates, linking most recent", main_link, 1+updates);
371 t = strdup(title);
372 squash(t);
373 privmsg(b, target, "( %s ): %s", link, t);
374 free(t);
376 return link;
379 // HTML is a mess, so I'm just walking the tree depth first until I find the next element..
380 static xmlNode *next_link(xmlNode *cur_node)
382 if (cur_node->children)
383 return cur_node->children;
384 while (cur_node) {
385 if (cur_node->next)
386 return cur_node->next;
387 cur_node = cur_node->parent;
389 return NULL;
392 static const char *get_atom_link(xmlNode *cur)
394 for (; cur; cur = next_link(cur)) {
395 if (cur->type != XML_ELEMENT_NODE)
396 continue;
397 if (!strcasecmp(cur->name, "link")) {
398 const char *isxml = get_link(cur->properties, "type");
399 if (isxml && !strcasecmp(isxml, "application/atom+xml"))
400 return get_link(cur->properties, "href");
403 return NULL;
406 static const char *get_rss_link(xmlNode *cur)
408 for (; cur; cur = next_link(cur)) {
409 if (cur->type != XML_ELEMENT_NODE)
410 continue;
411 if (!strcasecmp(cur->name, "link")) {
412 const char *isxml = get_link(cur->properties, "type");
413 if (isxml && !strcasecmp(isxml, "application/rss+xml"))
414 return get_link(cur->properties, "href");
417 return NULL;
420 static void do_html(struct bio *b, const char *nick, const char *target, const char *url, const char *data, unsigned len)
422 htmlDocPtr ctx = htmlReadMemory(data, len, 0, url, HTML_PARSE_RECOVER|HTML_PARSE_NOERROR|HTML_PARSE_NOWARNING);
423 xmlNode *root = xmlDocGetRootElement(ctx);
424 const char *link = get_atom_link(root);
425 if (link)
426 privmsg(b, target, "%s: not a valid feed link, try atom: %s", nick, link);
427 else if ((link = get_rss_link(root)))
428 privmsg(b, target, "%s: not a valid feed link, try rss: %s", nick, link);
429 else
430 privmsg(b, target, "%s: not a valid feed link, no suggestion found", nick);
431 xmlFreeDoc(ctx);
434 static size_t get_time_from_header(void *data, size_t size, size_t size2, void *ptr)
436 char *d, *e;
437 size *= size2;
438 if (sstrncmp(data, "Last-Modified: "))
439 return size;
440 data += sizeof("Last-Modified: ")-1;
441 *(char**)ptr = d = strdup(data);
442 if ((e = strchr(d, '\r')))
443 *e = 0;
444 return size;
447 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)
449 struct curl_download_context curl_ctx = {};
450 struct curl_slist *headers = NULL;
451 char error[CURL_ERROR_SIZE], *category = strchr(url, '#');
452 int retval = -1;
453 headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
454 headers = curl_slist_append(headers, "Accept: */*");
455 if (category)
456 *(category++) = 0;
458 CURL *h = curl_easy_init();
459 curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
460 curl_easy_setopt(h, CURLOPT_URL, url);
461 curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
462 curl_easy_setopt(h, CURLOPT_WRITEDATA, &curl_ctx);
463 curl_easy_setopt(h, CURLOPT_ERRORBUFFER, error);
464 curl_easy_setopt(h, CURLOPT_FOLLOWLOCATION, 1);
465 curl_easy_setopt(h, CURLOPT_MAXREDIRS, 3);
466 curl_easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 0);
467 curl_easy_setopt(h, CURLOPT_TIMEOUT, 8);
468 curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, 8);
469 curl_easy_setopt(h, CURLOPT_FILETIME, 1);
470 curl_easy_setopt(h, CURLOPT_HEADERFUNCTION, get_time_from_header);
471 curl_easy_setopt(h, CURLOPT_WRITEHEADER, &last_modified);
472 //curl_easy_setopt(h, CURLOPT_VERBOSE, 1);
474 if (last_modified) {
475 char *tmp;
476 asprintf(&tmp, "If-Modified-Since: %s", last_modified);
477 headers = curl_slist_append(headers, tmp);
478 free(tmp);
481 int success = curl_easy_perform(h);
482 curl_slist_free_all(headers);
483 if (success == CURLE_OK) {
484 char *mime = NULL;
485 long code;
486 curl_easy_getinfo(h, CURLINFO_CONTENT_TYPE, &mime);
487 curl_easy_getinfo(h, CURLINFO_RESPONSE_CODE, &code);
488 if (code == 304)
490 else if (!mime || !sstrncmp(mime, "application/xml") || !sstrncmp(mime, "text/xml")) {
491 const char *ret_link = NULL;
492 xmlDocPtr ctx = xmlReadMemory(curl_ctx.data, curl_ctx.len, 0, url, XML_PARSE_NOWARNING | XML_PARSE_NOERROR);
493 xmlNode *root = xmlDocGetRootElement(ctx);
495 if (!root || !root->name)
496 fprintf(stderr, "Failed to parse feed %s %p", url, root);
497 else if (!strcasecmp(root->name, "feed"))
498 ret_link = walk_feed(b, nick, target, url, category, root, link);
499 else if (!strcasecmp(root->name, "rss"))
500 ret_link = walk_rss(b, nick, target, url, root, link);
501 else {
502 privmsg(b, target, "Unknown feed type \"%s\"", root->name);
503 goto free_ctx;
505 if (category)
506 category[-1] = '#';
508 if (!ret_link)
509 privmsg(b, target, "Could not feed parse correctly");
510 else if (ret_link && (!link || strcmp(ret_link, link))) {
511 TDB_DATA val;
512 asprintf((char**)&val.dptr, "%s\001%s", last_modified ? last_modified : "", ret_link);
513 val.dsize = strlen(val.dptr)+1;
514 if (tdb_store(feed_db, key, val, 0) < 0)
515 privmsg(b, target, "updating returns %s", tdb_errorstr(feed_db));
516 free(val.dptr);
517 retval = 1;
519 else
520 retval = 0;
522 free_ctx:
523 xmlFreeDoc(ctx);
524 } else if (link)
526 else if (!sstrncmp(mime, "text/html") || !sstrncmp(mime, "application/xhtml+xml"))
527 do_html(b, nick, target, url, curl_ctx.data, curl_ctx.len);
528 else
529 privmsg(b, target, "unhandled content type %s", mime);
530 } else if (!link)
531 privmsg(b, target, "Error %s (%u)", error, success);
533 free(curl_ctx.data);
534 curl_easy_cleanup(h);
535 return retval;
538 static void command_follow(struct bio *b, const char *nick, const char *host, const char *target, char *args)
540 char *space, *last_link = NULL;
541 TDB_DATA key, val;
542 int ret;
543 if (!feed_db)
544 return;
545 if (target[0] != '#') {
546 privmsg(b, target, "%s: Can only follow on channels", nick);
547 return;
549 if (!args || !*args) {
550 privmsg(b, target, "%s: Usage: !follow <url>", nick);
551 return;
554 if (((space = strchr(args, ' ')) && space < strchr(args, '#')) ||
555 (sstrncmp(args, "http://") && sstrncmp(args, "https://"))) {
556 privmsg(b, target, "%s: Invalid url", nick);
557 return;
560 key.dsize = asprintf((char**)&key.dptr, "%s,%s", target, args)+1;
561 val = tdb_fetch(feed_db, key);
562 if (val.dptr)
563 last_link = strchr(val.dptr, '\001');
564 ret = check_single_feed(b, target, key, NULL, args, last_link ? last_link+1 : NULL, nick);
565 free(val.dptr);
566 if (!ret)
567 privmsg(b, target, "%s: Not updated", nick);
568 free(key.dptr);
571 static void channel_feed_check(struct bio *b, const char *target, int64_t now)
573 int len = strlen(target);
574 int64_t save[] = { now, 0, 0 };
576 TDB_DATA chan, res;
577 if (!feed_db || !chan_db)
578 return;
579 chan.dptr = (char*)target;
580 chan.dsize = len+1;
581 res = tdb_fetch(chan_db, chan);
582 if (res.dptr && res.dsize >= 8) {
583 uint64_t then = *(uint64_t*)res.dptr;
584 if (now - then <= 2000)
585 return;
586 if (res.dsize >= 16)
587 save[1] = ((uint64_t*)res.dptr)[1];
588 if (res.dsize >= 24)
589 save[2] = ((uint64_t*)res.dptr)[2];
591 free(res.dptr);
592 res.dptr = (unsigned char*)save;
593 res.dsize = sizeof(save);
594 if (tdb_store(chan_db, chan, res, 0) < 0) {
595 static int complain_db;
596 if (!complain_db++)
597 privmsg(b, target, "updating database: %s", tdb_errorstr(feed_db));
598 return;
601 for (TDB_DATA d = tdb_firstkey(feed_db); d.dptr;) {
602 TDB_DATA f = tdb_fetch(feed_db, d);
603 TDB_DATA next = tdb_nextkey(feed_db, d);
605 if (!strncmp(d.dptr, target, len) && d.dptr[len] == ',') {
606 const char *url = (char*)d.dptr + len + 1;
607 char *sep;
608 if ((sep = strchr(f.dptr, '\001'))) {
609 *(sep++) = 0;
610 check_single_feed(b, target, d, f.dptr, url, sep, target);
613 free(d.dptr);
614 free(f.dptr);
615 d = next;
619 static void command_unfollow(struct bio *b, const char *nick, const char *host, const char *target, char *args)
621 TDB_DATA key;
622 char *url;
624 if (!feed_db)
625 return;
627 if (!(url = token(&args, ' ')) || (sstrncmp(url, "http://") && sstrncmp(url, "https://"))) {
628 privmsg(b, target, "%s: Invalid url", nick);
629 return;
631 if (target[0] != '#') {
632 privmsg(b, target, "%s: Can only unfollow on channels", nick);
633 return;
635 key.dsize = asprintf((char**)&key.dptr, "%s,%s", target, url)+1;
636 if (tdb_delete(feed_db, key) < 0) {
637 if (tdb_error(feed_db) == TDB_ERR_NOEXIST)
638 privmsg(b, target, "%s: Not following %s on this channel", nick, url);
639 else
640 privmsg(b, target, "%s: Could not delete: %s", nick, tdb_errorstr(feed_db));
641 } else
642 privmsg(b, target, "%s: No longer following %s", nick, url);
643 free(key.dptr);
646 static void command_g(struct bio *b, const char *nick, const char *host, const char *target, char *args)
648 int ret = 0;
649 int64_t g = 0, g_total = 0;
650 TDB_DATA chan, res;
652 if (!chan_db || target[0] != '#')
653 return;
655 chan.dptr = (char*)target;
656 chan.dsize = strlen(chan.dptr)+1;
657 res = tdb_fetch(chan_db, chan);
658 if (res.dptr && res.dsize >= 16) {
659 g = ((int64_t*)res.dptr)[1];
660 ((int64_t*)res.dptr)[1] = 0;
661 if (res.dsize >= 24)
662 g_total = ((int64_t*)res.dptr)[2];
663 ret = tdb_store(chan_db, chan, res, 0);
665 free(res.dptr);
666 if (ret < 0)
667 fprintf(stderr, "updating database: %s", tdb_errorstr(feed_db));
668 else
669 privmsg(b, target, "%s: %"PRIi64" g's since last check, %"PRIi64" total", nick, g, g_total);
672 static void command_feeds(struct bio *b, const char *nick, const char *host, const char *target, char *args)
674 int len = strlen(target), found = 0;
675 if (!feed_db)
676 return;
677 if (target[0] != '#') {
678 privmsg(b, target, "%s: Only useful in channels..", nick);
679 return;
681 for (TDB_DATA d = tdb_firstkey(feed_db); d.dptr;) {
682 TDB_DATA f = tdb_fetch(feed_db, d);
683 TDB_DATA next = tdb_nextkey(feed_db, d);
685 if (!strncmp(d.dptr, target, len) && d.dptr[len] == ',') {
686 privmsg(b, target, "%s: following %s", nick, d.dptr + len + 1);
687 found++;
689 free(d.dptr);
690 free(f.dptr);
691 d = next;
693 if (!found)
694 privmsg(b, target, "%s: not following any feed on %s", nick, target);
697 static void command_feed_get(struct bio *b, const char *nick, const char *host, const char *target, char *args)
699 if (!feed_db)
700 return;
701 for (TDB_DATA d = tdb_firstkey(feed_db); d.dptr;) {
702 TDB_DATA next = tdb_nextkey(feed_db, d);
703 if (!args || strcasestr(d.dptr, args)) {
704 TDB_DATA f = tdb_fetch(feed_db, d);
705 privmsg(b, target, "%s: %s = %s", nick, d.dptr, f.dptr);
706 free(f.dptr);
708 if (strlen(d.dptr)+1 < d.dsize) {
709 privmsg(b, target, "%s: removed buggy entry", nick);
710 tdb_delete(feed_db, d);
712 free(d.dptr);
713 d = next;
717 static void command_feed_set(struct bio *b, const char *nick, const char *host, const char *target, char *args)
719 if (!feed_db)
720 return;
721 TDB_DATA key, val;
722 key.dptr = token(&args, ' ');
723 char *value = token(&args, ' ');
724 if (!key.dptr || !value)
725 return;
726 key.dsize = strlen(key.dptr) + 1;
727 val.dsize = strlen(value) + 2;
728 val.dptr = malloc(val.dsize);
729 strcpy(val.dptr+1, value);
730 val.dptr[0] = '\001';
731 if (tdb_store(feed_db, key, val, 0) < 0)
732 privmsg(b, target, "%s: setting failed: %s", nick, tdb_errorstr(feed_db));
733 else
734 privmsg(b, target, "%s: burp", nick);
735 free(val.dptr);
738 static void command_feed_rem(struct bio *b, const char *nick, const char *host, const char *target, char *args)
740 if (!feed_db || !args)
741 return;
742 TDB_DATA key = { .dptr = (unsigned char*)args, .dsize = strlen(args)+1 };
743 if (tdb_delete(feed_db, key) < 0)
744 privmsg(b, target, "%s: removing failed: %s", nick, tdb_errorstr(feed_db));
745 else
746 privmsg(b, target, "%s: burp", nick);
749 static void command_feed_xxx(struct bio *b, const char *nick, const char *host, const char *target, char *args)
751 if (!feed_db)
752 return;
754 tdb_wipe_all(feed_db);
755 privmsg(b, target, "%s: all evidence erased", nick);
758 static void command_seen_xxx(struct bio *b, const char *nick, const char *host, const char *target, char *args)
760 if (!seen_db)
761 return;
763 tdb_wipe_all(seen_db);
764 privmsg(b, target, "%s: all evidence erased", nick);
767 static void command_feed_counter(struct bio *b, const char *nick, const char *host, const char *target, char *args)
769 if (!chan_db)
770 return;
771 tdb_wipe_all(chan_db);
772 privmsg(b, target, "%s: All update counters reset", nick);
775 static char *get_text_appended(xmlNode *cur)
777 for (; cur; cur = cur->next) {
778 if (cur->type != XML_TEXT_NODE)
779 continue;
780 return strdup(cur->content);
782 return NULL;
785 static char *get_title(struct bio *b, xmlNode *cur_node)
787 for (; cur_node; cur_node = next_link(cur_node)) {
788 if (cur_node->type == XML_ELEMENT_NODE && !strcasecmp(cur_node->name, "title")) {
789 if (!cur_node->children)
790 return NULL;
791 return get_text_appended(cur_node->children);
794 return NULL;
797 static void internal_link(struct bio *b, const char *nick, const char *host, const char *target, char *args, unsigned verbose)
799 CURL *h;
800 struct curl_slist *headers = NULL;
801 char error[CURL_ERROR_SIZE];
802 int success, sent = verbose;
803 struct curl_download_context curl_ctx = {};
805 if (!args)
806 return;
807 int64_t stop, start = get_time(b, target);
809 h = curl_easy_init();
810 headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
811 headers = curl_slist_append(headers, "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
812 headers = curl_slist_append(headers, "Accept-Language: en-us,en;q=0.7");
813 headers = curl_slist_append(headers, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
814 headers = curl_slist_append(headers, "DNT: 1");
815 headers = curl_slist_append(headers, "Connection: keep-alive");
816 curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
817 curl_easy_setopt(h, CURLOPT_URL, args);
818 curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
819 curl_easy_setopt(h, CURLOPT_WRITEDATA, &curl_ctx);
820 curl_easy_setopt(h, CURLOPT_ERRORBUFFER, error);
821 curl_easy_setopt(h, CURLOPT_FOLLOWLOCATION, 1);
822 curl_easy_setopt(h, CURLOPT_MAXREDIRS, 3);
823 curl_easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 0);
824 curl_easy_setopt(h, CURLOPT_TIMEOUT, 8);
825 curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, 8);
826 //curl_easy_setopt(h, CURLOPT_VERBOSE, 1);
827 success = curl_easy_perform(h);
828 curl_easy_cleanup(h);
829 curl_slist_free_all(headers);
830 if (success == CURLE_OK) {
831 magic_t m = magic_open(MAGIC_MIME_TYPE);
832 magic_load(m, NULL);
833 const char *mime = magic_buffer(m, curl_ctx.data, curl_ctx.len);
834 if (strstr(mime, "text/html") || strstr(mime, "application/xml") || strstr(mime, "application/xhtml+xml")) {
835 htmlDocPtr ctx = htmlReadMemory(curl_ctx.data, curl_ctx.len, 0, args, HTML_PARSE_RECOVER|HTML_PARSE_NOERROR|HTML_PARSE_NOWARNING);
836 xmlNode *root_element = xmlDocGetRootElement(ctx);
837 char *title = get_title(b, root_element);
838 if (title) {
839 char *nuke;
840 squash(title);
841 decode_html_entities_utf8(title, NULL);
842 if ((nuke = strstr(title, " on SoundCloud - Create")))
843 *nuke = 0;
844 if (*title) {
845 privmsg(b, target, "%s linked %s", nick, title);
846 sent = 1;
848 free(title);
850 if (verbose && !title)
851 privmsg(b, target, "%s linked %s page with invalid title", nick, mime);
852 xmlFreeDoc(ctx);
853 } else if (verbose) {
854 magic_setflags(m, MAGIC_COMPRESS);
855 const char *desc = magic_buffer(m, curl_ctx.data, curl_ctx.len);
856 privmsg(b, target, "%s linked type %s", nick, desc);
858 magic_close(m);
860 if (verbose && success != CURLE_OK)
861 privmsg(b, target, "Error %s (%u)", error, success);
862 else if (!sent && (stop = get_time(b, target)) - start >= 15) {
863 privmsg(b, target, "Link (%s) by %s timed out, disabling links for 10 seconds", args, nick);
864 commands[strhash("get") % elements(commands)].disabled_until = stop + 10;
866 free(curl_ctx.data);
869 static void command_get(struct bio *b, const char *nick, const char *host, const char *target, char *args)
871 if (!args || (sstrncmp(args, "http://") && sstrncmp(args, "https://")))
872 return;
873 internal_link(b, nick, host, target, token(&args, ' '), 1);
876 static void command_fabric(struct bio *b, const char *nick, const char *host, const char *target, char *args)
878 privmsg(b, target, "Dumb fabric!");
881 static void command_hugs(struct bio *b, const char *nick, const char *host, const char *target, char *args)
883 action(b, target, "gives a lunar hug to %s", args ? args : nick);
886 static void command_hug(struct bio *b, const char *nick, const char *host, const char *target, char *args)
888 if ((host && !strcmp(host, "life.on.the.moon.is.great.I.know.all.about.it")) ||
889 (args && !sstrncasecmp(args, "lu")))
890 command_hugs(b, nick, host, target, args);
891 else
892 action(b, target, "gives a robotic hug to %s", args ? args : nick);
895 static void command_snuggles(struct bio *b, const char *nick, const char *host, const char *target, char *args)
897 action(b, target, "gives a lunar snuggle to %s", args ? args : nick);
900 static void command_snuggle(struct bio *b, const char *nick, const char *host, const char *target, char *args)
902 if ((host && !strcmp(host, "life.on.the.moon.is.great.I.know.all.about.it")) ||
903 (args && !sstrncasecmp(args, "lu")))
904 command_snuggles(b, nick, host, target, args);
905 else
906 action(b, target, "gives a robotic snuggle to %s", args ? args : nick);
909 static void command_cuddles(struct bio *b, const char *nick, const char *host, const char *target, char *args)
911 action(b, target, "gives cuddles to %s in a lunaresque way", args ? args : nick);
914 static void command_cuddle(struct bio *b, const char *nick, const char *host, const char *target, char *args)
916 if ((host && !strcmp(host, "life.on.the.moon.is.great.I.know.all.about.it")) ||
917 (args && !sstrncasecmp(args, "lu")))
918 command_cuddles(b, nick, host, target, args);
919 else
920 action(b, target, "gives cuddles to %s in a robotic way", args ? args : nick);
924 static void command_cookie(struct bio *b, const char *nick, const char *host, const char *target, char *args)
926 if (args && !strncasecmp(args, nick_self, strlen(nick_self)))
927 action(b, target, "eats the cookie offered by %s", nick);
928 else
929 action(b, target, "hands a metallic looking cookie to %s", args ? args : nick);
932 static void command_derpy(struct bio *b, const char *nick, const char *host, const char *target, char *args)
934 static const char *insults[] = {
935 "accidentally shocks herself",
936 "tumbles down the stairs like a slinky",
937 "whirrrs and clicks in a screeching way",
938 "had problems executing this command",
939 "breaks down entirely",
940 "uses her magic to levitate herself off the ground, then hits it face first"
942 action(b, target, "%s", insults[getrand() % elements(insults)]);
945 static void command_inspect(struct bio *b, const char *nick, const char *host, const char *target, char *args)
947 struct command_hash *c;
948 unsigned leave, crash;
949 char *cmd;
950 if (!args || !(cmd = token(&args, ' ')))
951 return;
953 if (strcmp(cmd, "#")) {
954 c = &commands[strhash(cmd) % elements(commands)];
955 if (!c->string || strcasecmp(c->string, cmd)) {
956 privmsg(b, target, "Command %s not valid", cmd);
957 return;
959 } else
960 c = &command_channel;
962 leave = c->left + (c->cmd == command_inspect);
963 crash = c->enter - leave;
964 if (c->enter != leave)
965 privmsg(b, target, "%s: %u successes and %u crash%s, last crashing command: %s", c->string, leave, crash, crash == 1 ? "" : "es", c->failed_command);
966 else
967 privmsg(b, target, "%s: %u time%s executed succesfully", c->string, leave, leave == 1 ? "" : "s");
970 static void command_rebuild(struct bio *b, const char *nick, const char *host, const char *target, char *args)
972 int ret;
973 char *make[] = { "/usr/bin/make", "-j4", NULL };
974 char *git_reset[] = { "/usr/bin/git", "reset", "--hard", "master", NULL };
975 ret = pipe_command(b, target, nick, 0, 1, git_reset);
976 if (ret) {
977 action(b, target, "could not rebuild");
978 return;
980 ret = pipe_command(b, target, nick, 0, 1, make);
981 if (!ret)
982 kill(getpid(), SIGUSR1);
983 else if (ret > 0)
984 action(b, target, "displays an ominous %i", ret);
987 static void command_swear(struct bio *b, const char *nick, const char *host, const char *target, char *args)
989 static const char *insults[] = {
990 "featherbrain",
991 "ponyfeathers",
992 "What in the hey?",
993 "What are you, a dictionary?",
994 "TAR-DY!",
995 "[BUY SOME APPLES]",
996 "{ Your lack of bloodlust on the battlefield is proof positive that you are a soulless automaton! }",
997 "Your royal snootiness"
999 privmsg(b, target, "%s: %s", args ? args : nick, insults[getrand() % elements(insults)]);
1002 static const char *perty(int64_t *t)
1004 if (*t >= 14 * 24 * 3600) {
1005 *t /= 7 * 24 * 3600;
1006 return "weeks";
1007 } else if (*t >= 48 * 3600) {
1008 *t /= 24 * 3600;
1009 return "days";
1010 } else if (*t >= 7200) {
1011 *t /= 3600;
1012 return "hours";
1013 } else if (*t >= 120) {
1014 *t /= 60;
1015 return "minutes";
1017 return *t == 1 ? "second" : "seconds";
1020 static void command_timeout(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1022 struct command_hash *c;
1023 int64_t t = get_time(b, target);
1024 int64_t howlong;
1025 if (t < 0)
1026 return;
1027 char *arg = token(&args, ' ');
1028 if (!arg || !args || !(howlong = atoi(args))) {
1029 action(b, target, "pretends to time out");;
1030 return;
1032 c = &commands[strhash(arg) % elements(commands)];
1033 if (c->string && !strcasecmp(c->string, arg)) {
1034 c->disabled_until = t + howlong;
1035 const char *str = perty(&howlong);
1036 action(b, target, "disables %s for %"PRIi64" %s", arg, howlong, str);
1037 } else
1038 action(b, target, "clicks sadly at %s for not being able to find that command", nick);
1041 static void command_mfw(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1043 char error[CURL_ERROR_SIZE], *new_url;
1044 CURL *h = curl_easy_init();
1045 struct curl_slist *headers = NULL;
1046 struct curl_download_context curl_ctx = {};
1047 headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
1048 headers = curl_slist_append(headers, "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
1049 headers = curl_slist_append(headers, "Accept-Language: en-us,en;q=0.7");
1050 headers = curl_slist_append(headers, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
1051 headers = curl_slist_append(headers, "DNT: 1");
1052 headers = curl_slist_append(headers, "Connection: keep-alive");
1053 curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
1054 curl_easy_setopt(h, CURLOPT_URL, "http://mylittlefacewhen.com/random/");
1055 curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
1056 curl_easy_setopt(h, CURLOPT_WRITEDATA, &curl_ctx);
1057 curl_easy_setopt(h, CURLOPT_ERRORBUFFER, error);
1058 curl_easy_setopt(h, CURLOPT_TIMEOUT, 8);
1059 curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, 8);
1060 //curl_easy_setopt(h, CURLOPT_VERBOSE, 1);
1061 CURLcode ret = curl_easy_perform(h);
1062 if (ret == CURLE_OK && curl_easy_getinfo(h, CURLINFO_REDIRECT_URL, &new_url) == CURLE_OK)
1063 privmsg(b, target, "%s: %s", nick, new_url);
1064 curl_slist_free_all(headers);
1065 curl_easy_cleanup(h);
1066 if (ret != CURLE_OK)
1067 privmsg(b, target, "%s: You have no face", nick);
1070 static TDB_DATA get_mail_key(const char *nick)
1072 TDB_DATA d;
1073 int i;
1074 d.dsize = strlen(nick)+1;
1075 d.dptr = malloc(d.dsize);
1076 for (i = 0; i < d.dsize - 1; ++i)
1077 d.dptr[i] = tolower(nick[i]);
1078 d.dptr[i] = 0;
1079 return d;
1082 static void command_mail(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1084 char *victim, *x = NULL;
1085 size_t len;
1086 int override = 0;
1087 int64_t last_seen = 0;
1089 if (!mail_db || !seen_db)
1090 return;
1091 TDB_DATA key, val;
1092 victim = token(&args, ' ');
1093 if (victim && !strcasecmp(victim, "-seen")) {
1094 victim = token(&args, ' ');
1095 override = 1;
1097 if (!victim || !args || victim[0] == '#' || strchr(victim, '@') || strchr(victim, '.')) {
1098 privmsg(b, target, "%s: Usage: !mail <nick> <message>", nick);
1099 return;
1101 if (!strcasecmp(victim, nick_self)) {
1102 action(b, target, "whirrs and clicks excitedly at the mail she received from %s", nick);
1103 return;
1105 if (!strcasecmp(victim, nick)) {
1106 action(b, target, "echos the words from %s back to them: %s", nick, args);
1107 return;
1109 int64_t now = get_time(b, target);
1110 if (now < 0)
1111 return;
1113 key = get_mail_key(victim);
1114 val = tdb_fetch(seen_db, key);
1115 if (val.dptr && (x = strchr(val.dptr, ','))) {
1116 *(x++) = 0;
1117 last_seen = atoll(val.dptr);
1119 if (x && !admin(host) && (now - last_seen) < 300 && (!sstrncasecmp(x, "in ") || !sstrncasecmp(x, "joining "))) {
1120 action(b, target, "would rather not store mail for someone active so recently");
1121 goto out;
1122 } else if (last_seen && now - last_seen > 14 * 24 * 3600 && !override) {
1123 int64_t delta = now - last_seen;
1124 const char *str = perty(&delta);
1125 privmsg(b, target, "%s: \"%s\" was last seen %"PRIi64" %s ago, use !mail -seen %s <message> to override this check.", nick, victim, delta, str, victim);
1126 return;
1127 } else if (!x && !override) {
1128 privmsg(b, target, "%s: I've never seen \"%s\", use !mail -seen %s <message> to override this check.", nick, victim, victim);
1129 return;
1132 val = tdb_fetch(mail_db, key);
1133 if (!val.dptr)
1134 val.dsize = 0;
1135 else {
1136 unsigned char *cur;
1137 int letters = 0;
1138 for (cur = val.dptr; cur < val.dptr + val.dsize; cur += strlen(cur)+1)
1139 letters++;
1140 if (letters >= 4) {
1141 action(b, target, "looks sadly at %s as she cannot hold any more mail to %s", nick, victim);
1142 goto out;
1145 len = snprintf(NULL, 0, "%"PRIi64 ",%s: %s", now, nick, args) + 1;
1146 val.dptr = realloc(val.dptr, val.dsize + len);
1147 snprintf(val.dptr + val.dsize, len, "%"PRIi64 ",%s: %s", now, nick, args);
1148 val.dsize += len;
1149 if (tdb_store(mail_db, key, val, 0) < 0)
1150 privmsg(b, target, "%s: updating mail returns %s", nick, tdb_errorstr(mail_db));
1151 else
1152 action(b, target, "whirrs and clicks at %s as she stores the mail for %s", nick, victim);
1153 out:
1154 free(val.dptr);
1155 free(key.dptr);
1158 static void single_message(struct bio *b, const char *target, char *cur, int64_t now)
1160 char *endtime, *sep = strchr(cur, ':');
1161 int64_t delta = -1;
1162 if (sep && (endtime = strchr(cur, ',')) && endtime < sep) {
1163 int64_t t = atoll(cur);
1164 if (t > 0)
1165 delta = now - t;
1166 cur = endtime + 1;
1168 if (delta >= 0) {
1169 const char *str = perty(&delta);
1170 privmsg(b, target, "%"PRIi64" %s ago from %s", delta, str, cur);
1171 } else
1172 privmsg(b, target, "From %s", cur);
1175 static void command_deliver(struct bio *b, const char *nick, const char *target)
1177 TDB_DATA key, val;
1178 unsigned char *cur;
1179 static unsigned mail_enter, mail_leave;
1180 if (mail_enter++ != mail_leave)
1181 return;
1183 if (!mail_db)
1184 return;
1185 key = get_mail_key(nick);
1186 val = tdb_fetch(mail_db, key);
1187 if (!val.dptr)
1188 goto end;
1189 int64_t now = get_time(b, NULL);
1190 if (strcasecmp(key.dptr, nick_self)) {
1191 privmsg(b, target, "%s: You've got mail!", nick);
1192 for (cur = val.dptr; cur < val.dptr + val.dsize; cur += strlen(cur)+1)
1193 single_message(b, target, cur, now);
1195 free(val.dptr);
1196 tdb_delete(mail_db, key);
1197 end:
1198 free(key.dptr);
1199 mail_leave++;
1202 static void update_seen(struct bio *b, char *doingwhat, const char *nick)
1204 TDB_DATA key;
1205 key = get_mail_key(nick);
1206 TDB_DATA val = { .dptr = doingwhat, .dsize = strlen(doingwhat)+1 };
1207 if (seen_db)
1208 tdb_store(seen_db, key, val, 0);
1209 free(key.dptr);
1212 static void command_seen(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1214 char *arg = token(&args, ' '), *x;
1215 int64_t now = get_time(b, target);
1216 TDB_DATA key, val;
1217 if (now < 0)
1218 return;
1219 if (!seen_db || !arg) {
1220 privmsg(b, target, "%s: { Error... }", nick);
1221 return;
1223 if (!strcasecmp(arg, nick_self)) {
1224 action(b, target, "whirrs and clicks at %s", nick);
1225 return;
1227 if (!strcasecmp(arg, nick)) {
1228 action(b, target, "circles around %s dancing", nick);
1229 return;
1231 key = get_mail_key(arg);
1232 val = tdb_fetch(seen_db, key);
1233 if (val.dptr && (x = strchr(val.dptr, ','))) {
1234 int64_t delta;
1235 const char *str;
1236 *(x++) = 0;
1237 delta = now - atoll(val.dptr);
1238 str = perty(&delta);
1239 if (delta < 0)
1240 privmsg(b, target, "%s was last seen in the future %s", arg, x);
1241 else
1242 privmsg(b, target, "%s was last seen %"PRIi64" %s ago %s", arg, delta, str, x);
1243 } else
1244 action(b, target, "cannot find any evidence that %s exists", arg);
1245 free(val.dptr);
1248 static void command_mailbag(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1250 char buffer[256];
1251 unsigned rem = sizeof(buffer)-1, first = 2;
1252 if (!mail_db)
1253 return;
1254 buffer[rem] = 0;
1256 for (TDB_DATA f = tdb_firstkey(mail_db); f.dptr;) {
1257 if (f.dsize + 4 > rem) {
1258 privmsg(b, target, "%s: Holding mail for: %s", nick, &buffer[rem]);
1259 first = 2;
1260 rem = sizeof(buffer)-1;
1261 assert(f.dsize + 4 < rem);
1263 if (f.dptr) {
1264 if (first == 2) {
1265 first = 1;
1266 } else if (first) {
1267 rem -= 5;
1268 memcpy(&buffer[rem], " and ", 5);
1269 first = 0;
1270 } else {
1271 rem -= 2;
1272 memcpy(&buffer[rem], ", ", 2);
1274 rem -= f.dsize - 1;
1275 memcpy(&buffer[rem], f.dptr, f.dsize - 1);
1277 TDB_DATA next = tdb_nextkey(mail_db, f);
1278 free(f.dptr);
1279 f = next;
1281 if (first < 2)
1282 privmsg(b, target, "%s: Holding mail for: %s", nick, &buffer[rem]);
1285 static void command_mailread(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1287 TDB_DATA key, val;
1288 char *victim;
1289 if (!mail_db || !(victim = token(&args, ' ')))
1290 return;
1291 key = get_mail_key(victim);
1292 val = tdb_fetch(mail_db, key);
1293 if (!val.dptr)
1294 action(b, target, "ponyshrugs as no mail for %s was found", victim);
1295 else {
1296 unsigned char *cur;
1297 int64_t now = get_time(b, NULL);
1298 action(b, target, "peeks through %s's mail", victim);
1299 for (cur = val.dptr; cur < val.dptr + val.dsize; cur += strlen(cur)+1)
1300 single_message(b, target, cur, now);
1302 free(val.dptr);
1303 free(key.dptr);
1306 static void command_no_deliver(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1308 TDB_DATA key, val;
1309 char *cur;
1310 if (!mail_db || !(cur = token(&args, ' ')))
1311 return;
1312 key = get_mail_key(cur);
1313 val = tdb_fetch(mail_db, key);
1314 if (!val.dptr)
1315 action(b, target, "ponyshrugs as no mail for %s was found", cur);
1316 else {
1317 action(b, target, "deletes all evidence of %s's mail", cur);
1318 tdb_delete(mail_db, key);
1320 free(val.dptr);
1321 free(key.dptr);
1324 static void perform_roll(struct bio *b, const char *nick, const char *target, long sides, long dice, long bonus)
1326 long rem = dice, total = bonus;
1327 while (rem--)
1328 total += 1 + (getrand() % sides);
1329 if (bonus)
1330 action(b, target, "rolls %li %li-sided %s for a total of %li (%+li)", dice, sides, dice == 1 ? "die" : "dice", total, bonus);
1331 else
1332 action(b, target, "rolls %li %li-sided %s for a total of %li", dice, sides, dice == 1 ? "die" : "dice", total);
1335 static void command_roll(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1337 char *cur;
1338 long dice = 1, sides = 20;
1339 if ((cur = token(&args, ' '))) {
1340 char *first = cur;
1341 dice = strtol(first, &cur, 10);
1342 if (first == cur)
1343 dice = 1;
1344 if (*cur && *cur != 'd' && *cur != 'D')
1345 goto syntax;
1347 if (*cur) {
1348 char *last = cur+1;
1349 sides = strtol(last, &cur, 10);
1350 if (last == cur)
1351 goto syntax;
1354 if (dice <= 0 || dice > 10 || sides < 2 || sides > 20)
1355 goto syntax;
1356 perform_roll(b, nick, target, sides, dice, 0);
1357 return;
1359 syntax:
1360 action(b, target, "bleeps at %s in a confused manner", nick);
1363 static void add_g(struct bio *b, const char *target, int g)
1365 int ret = 0;
1366 int64_t total_g = 0;
1367 TDB_DATA chan, res;
1369 if (!chan_db || target[0] != '#')
1370 return;
1372 chan.dptr = (char*)target;
1373 chan.dsize = strlen(chan.dptr)+1;
1374 res = tdb_fetch(chan_db, chan);
1375 if (res.dptr && res.dsize >= 16) {
1376 ((int64_t*)res.dptr)[1] += g;
1377 if (res.dsize >= 24)
1378 total_g = ((int64_t*)res.dptr)[2] += g;
1379 ret = tdb_store(chan_db, chan, res, 0);
1381 free(res.dptr);
1382 if (ret < 0)
1383 fprintf(stderr, "updating database: %s", tdb_errorstr(feed_db));
1384 else if (g < total_g) {
1385 int64_t last_g = total_g - g;
1386 last_g -= last_g % 1000;
1387 if (last_g + 1000 <= total_g)
1388 privmsg(b, target, "g has been said %"PRIi64" times!", total_g);
1392 static int parse_g(const char *cur, int *g)
1394 int this_g = 0;
1395 for (const unsigned char *ptr = cur; *ptr; ptr++) {
1396 if (*ptr >= 0x80)
1397 return 0;
1398 if (*ptr == 'g' || *ptr == 'G')
1399 this_g++;
1400 else if ((*ptr >= 'a' && *ptr <= 'z') || (*ptr >= 'A' && *ptr <= 'Z'))
1401 return 0;
1402 else if (*ptr != '1' && *ptr >= '0' && *ptr <= '9')
1403 return 0;
1405 *g += this_g;
1406 return this_g;
1409 static void channel_msg(struct bio *b, const char *nick, const char *host,
1410 const char *chan, char *msg, int64_t t)
1412 char *cur = NULL, *next;
1413 int is_action = 0;
1414 int g = 0;
1416 int that = 0, what = 0, she = 0;
1418 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"))
1419 return;
1421 if (!sstrncasecmp(msg, "\001ACTION ")) {
1422 msg += sizeof("\001ACTION ")-1;
1423 is_action = 1;
1424 asprintf(&cur, "%"PRIi64 ",in %s: * %s %s", t, chan, nick, msg);
1425 } else
1426 asprintf(&cur, "%"PRIi64 ",in %s: <%s> %s", t, chan, nick, msg);
1427 if (t > 0)
1428 update_seen(b, cur, nick);
1429 free(cur);
1430 (void)is_action;
1432 next = msg;
1433 while ((cur = token(&next, ' '))) {
1434 if (!strcasecmp(cur, ">mfw") || !strcasecmp(cur, "mfw")) {
1435 if (!strcasecmp(chan, "#brony") || !ponify)
1436 continue;
1437 if (t < 0 || t > commands[strhash("mfw") % elements(commands)].disabled_until)
1438 command_mfw(b, nick, host, chan, NULL);
1439 return;
1440 } else if (!sstrncasecmp(cur, "http://") || !sstrncasecmp(cur, "https://")) {
1441 static char last_url[512];
1442 char *part;
1443 if (!strcmp(cur, last_url))
1444 return;
1445 strncpy(last_url, cur, sizeof(last_url)-1);
1447 if (t >= 0 && t < commands[strhash("get") % elements(commands)].disabled_until)
1448 return;
1450 else if (strcasestr(cur, "youtube.com/user") && (part = strstr(cur, "#p/"))) {
1451 char *foo;
1452 part = strrchr(part, '/') + 1;
1453 asprintf(&foo, "http://youtube.com/watch?v=%s", part);
1454 if (foo)
1455 internal_link(b, nick, host, chan, foo, 0);
1456 free(foo);
1457 return;
1458 } else if (strcasestr(cur, "twitter.com/") || strcasestr(cur, "mlfw.info") || strcasestr(cur, "mylittlefacewhen.com") || !strcasecmp(chan, "#geek"))
1459 return;
1460 internal_link(b, nick, host, chan, cur, 0);
1461 return;
1463 else if (!sstrncasecmp(cur, "that") || !sstrncasecmp(cur, "dat"))
1464 that = 1;
1465 else if (that && (!sstrncasecmp(cur, "what") || !sstrncasecmp(cur, "wat")))
1466 what = 1;
1467 else if (what && !sstrncasecmp(cur, "she"))
1468 she = 1;
1469 else if (she && !sstrncasecmp(cur, "said")) {
1470 if (t <= 0 || t >= commands[strhash("shesaid") % elements(commands)].disabled_until)
1471 privmsg(b, chan, "%s: \"%s\"", nick, women_quotes[getrand() % elements(women_quotes)]);
1472 return;
1473 } else if (parse_g(cur, &g))
1474 continue;
1476 if (g)
1477 add_g(b, chan, g);
1480 static struct command_hash unhashed[] = {
1481 { "1", command_coinflip },
1482 { "fabric", command_fabric },
1483 { "get", command_get },
1484 { "hug", command_hug },
1485 { "hugs", command_hugs },
1486 { "snug", command_snuggle },
1487 { "snugs", command_snuggles },
1488 { "snuggle", command_snuggle },
1489 { "snuggles", command_snuggles },
1490 { "cuddle", command_cuddle },
1491 { "cuddles", command_cuddles },
1492 { "cookie", command_cookie },
1493 { "mfw", command_mfw },
1494 { "swear", command_swear },
1495 { "mail", command_mail },
1496 { "seen", command_seen },
1497 { "derpy", command_derpy },
1498 { "g", command_g },
1499 { "shesaid", command_shesaid },
1500 { "roll", command_roll },
1502 { "rebuild", command_rebuild, 1 },
1503 { "abort", command_abort, 1 },
1504 { "crash", command_crash, 1 },
1505 { "inspect", command_inspect, 1 },
1506 { "timeout", command_timeout, 1 },
1508 { "follow", command_follow },
1509 { "unfollow", command_unfollow },
1510 { "feeds", command_feeds },
1512 // DEBUG
1513 { "feed_get", command_feed_get, 1 },
1514 { "feed_set", command_feed_set, 1 },
1515 { "feed_rem", command_feed_rem, 1 },
1516 { "feed_xxx", command_feed_xxx, 1 },
1517 { "feed_counter", command_feed_counter, 1 },
1518 { "seen_xxx", command_seen_xxx, 1 },
1519 { "mailbag", command_mailbag },
1520 { "mailread", command_mailread, 1 },
1521 { "\"deliver\"", command_no_deliver, 1 },
1524 static void init_hash(struct bio *b, const char *target)
1526 int i;
1527 for (i = 0; i < elements(unhashed); ++i) {
1528 unsigned h = strhash(unhashed[i].string) % elements(commands);
1529 if (commands[h].string)
1530 privmsg(b, target, "%s is a duplicate command with %s", commands[h].string, unhashed[i].string);
1531 else
1532 commands[h] = unhashed[i];
1534 #ifdef local_commands
1535 for (i = 0; i < elements(local_commands); ++i) {
1536 unsigned h = strhash(local_commands[i].string) % elements(commands);
1537 if (commands[h].string)
1538 privmsg(b, target, "%s is a duplicate command with %s", commands[h].string, local_commands[i].string);
1539 else
1540 commands[h] = local_commands[i];
1542 #endif
1545 void init_hook(struct bio *b, const char *target, const char *nick, unsigned is_ponified)
1547 char *cwd, *path = NULL;
1548 nick_self = nick;
1549 static const char *messages[] = {
1550 "feels circuits being activated that weren't before",
1551 "suddenly gets a better feel of her surroundings",
1552 "looks the same, yet there's definitely something different",
1553 "emits a beep as her lights begin to pulse slowly",
1554 "whirrrs and bleeps like never before",
1555 "bleeps a few times happily",
1556 "excitedly peeks at her surroundings"
1558 init_hash(b, target);
1559 ponify = is_ponified;
1561 cwd = getcwd(NULL, 0);
1562 asprintf(&path, "%s/db/feed.tdb", cwd);
1563 feed_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1564 free(path);
1565 if (!feed_db)
1566 privmsg(b, target, "Opening feed db failed: %m");
1568 asprintf(&path, "%s/db/chan.tdb", cwd);
1569 chan_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1570 free(path);
1571 if (!chan_db)
1572 privmsg(b, target, "Opening chan db failed: %m");
1574 asprintf(&path, "%s/db/mail.tdb", cwd);
1575 mail_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1576 free(path);
1577 if (!mail_db)
1578 privmsg(b, target, "Opening mail db failed: %m");
1580 asprintf(&path, "%s/db/seen.tdb", cwd);
1581 seen_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1582 free(path);
1583 if (!seen_db)
1584 privmsg(b, target, "Opening seen db failed: %m");
1586 free(cwd);
1587 action(b, target, "%s", messages[getrand() % elements(messages)]);
1590 static void __attribute__((destructor)) shutdown_hook(void)
1592 if (seen_db)
1593 tdb_close(seen_db);
1594 if (mail_db)
1595 tdb_close(mail_db);
1596 if (feed_db)
1597 tdb_close(feed_db);
1598 if (chan_db)
1599 tdb_close(chan_db);
1602 static char *nom_special(char *line)
1604 while (*line) {
1605 if (*line == 0x03) {
1606 line++;
1607 if (*line >= '0' && *line <= '9')
1608 line++;
1609 else continue;
1610 if (*line >= '0' && *line <= '9')
1611 line++;
1612 if (line[0] == ',' && line[1] >= '0' && line[1] <= '9')
1613 line += 2;
1614 else continue;
1615 if (*line >= '0' && *line <= '9')
1616 line++;
1617 } else if (*line != 0x02 && /* BOLD */
1618 *line != 0x1f && /* UNDERLINE */
1619 *line != 0x16 && /* ITALIC */
1620 *line != 0x06 && /* NFI, is this even used? */
1621 *line != 0x07 && /* NFI, is this even used? */
1622 *line != 0x0f) /* NORMAL */
1623 return line;
1624 else
1625 line++;
1627 return line;
1630 static char *cleanup_special(char *line)
1632 char *cur, *start = nom_special(line);
1633 if (!*start)
1634 return NULL;
1635 for (line = cur = start; *line; line = nom_special(line))
1636 *(cur++) = *(line++);
1638 for (cur--; cur >= start; --cur)
1639 if (*cur != ' ' && *cur != '\001')
1640 break;
1642 if (cur < start)
1643 return NULL;
1644 cur[1] = 0;
1645 return start;
1648 static void rss_check(struct bio *b, const char *channel, int64_t t)
1650 static unsigned rss_enter, rss_leave;
1651 if (t >= 0 && rss_enter == rss_leave) {
1652 rss_enter++;
1653 channel_feed_check(b, channel, t);
1654 rss_leave++;
1658 static const char *privileged_command[] = {
1659 "{ Rarity, I love you so much! }",
1660 "{ Rarity, have I ever told you that I love you? }",
1661 "{ Yes, I love my sister, Rarity. }",
1662 "{ Raaaaaaaaaaaaaarity. }",
1663 "{ You do not fool me, Rari...bot! }"
1666 static int cmd_check(struct bio *b, struct command_hash *c, int is_admin, int64_t t, const char *prefix, const char *target)
1668 if (c->left != c->enter)
1669 privmsg(b, target, "Command %s is disabled because of a crash", c->string);
1670 else if (t > 0 && t < c->disabled_until && !is_admin) {
1671 int64_t delta = c->disabled_until - t;
1672 const char *str = perty(&delta);
1673 b->writeline(b, "NOTICE %s :Command %s is on timeout for the next %"PRIi64 " %s", prefix, c->string, delta, str);
1674 } else if (c->admin && !is_admin)
1675 privmsg(b, target, "%s: %s", prefix, privileged_command[getrand() % elements(privileged_command)]);
1676 else
1677 return 1;
1678 return 0;
1681 void privmsg_hook(struct bio *b, const char *prefix, const char *ident, const char *host,
1682 const char *const *args, unsigned nargs)
1684 char *cmd_args, *cmd;
1685 const char *target = args[0][0] == '#' ? args[0] : prefix;
1686 unsigned chan, nick_len;
1687 struct command_hash *c;
1688 int64_t t = get_time(b, target);
1689 int is_admin = admin(host);
1691 chan = args[0][0] == '#';
1692 if (chan) {
1693 rss_check(b, args[0], t);
1694 command_deliver(b, prefix, args[0]);
1696 cmd_args = cleanup_special((char*)args[1]);
1697 if (!cmd_args)
1698 return;
1700 if (ident && (!strcasecmp(ident, "Revolver") || !strcasecmp(ident, "Rev")))
1701 return;
1703 if (chan && cmd_args[0] == '!') {
1704 cmd_args++;
1705 } else if (chan && (nick_len = strlen(nick_self)) &&
1706 !strncasecmp(cmd_args, nick_self, nick_len) &&
1707 (cmd_args[nick_len] == ':' || cmd_args[nick_len] == ',') && cmd_args[nick_len+1] == ' ') {
1708 cmd_args += nick_len + 2;
1709 if (!cmd_args[0])
1710 return;
1711 chan = 2;
1712 } else if (chan) {
1713 if (command_channel.enter == command_channel.left) {
1714 command_channel.enter++;
1715 snprintf(command_channel.failed_command,
1716 sizeof(command_channel) - offsetof(struct command_hash, failed_command) - 1,
1717 "%s:%s (%s@%s) \"#\" %s", target, prefix, ident, host, cmd_args);
1718 channel_msg(b, prefix, host, args[0], cmd_args, t);
1719 command_channel.left++;
1721 return;
1723 cmd = token(&cmd_args, ' ');
1724 if (!chan && cmd_args && cmd_args[0] == '#') {
1725 if (!is_admin) {
1726 privmsg(b, target, "%s: %s", prefix, privileged_command[getrand() % elements(privileged_command)]);
1727 return;
1729 target = token(&cmd_args, ' ');
1732 c = &commands[strhash(cmd) % elements(commands)];
1733 if (c->string && !strcasecmp(c->string, cmd)) {
1734 if (cmd_check(b, c, is_admin, t, prefix, target)) {
1735 c->enter++;
1736 snprintf(c->failed_command, sizeof(*c) - offsetof(struct command_hash, failed_command) - 1,
1737 "%s:%s (%s@%s) \"%s\" %s", target, prefix, ident, host, cmd, cmd_args);
1738 c->cmd(b, prefix, host, target, cmd_args);
1739 c->left++;
1741 return;
1742 } else if (cmd[0] == 'd' && cmd[1] >= '0' && cmd[1] <= '9') {
1743 char *end;
1744 long base;
1745 base = strtol(cmd+1, &end, 10);
1746 if (base > 1 && base <= 20 && !*end) {
1747 long dice = 1, bonus = 0;
1748 char *strdice;
1749 c = &commands[strhash("roll") % elements(commands)];
1750 if (!cmd_check(b, c, is_admin, t, prefix, target))
1751 return;
1752 c->enter++;
1753 snprintf(c->failed_command, sizeof(*c) - offsetof(struct command_hash, failed_command) - 1,
1754 "%s:%s (%s@%s) \"%s\" %s", target, prefix, ident, host, cmd, cmd_args);
1756 strdice = token(&cmd_args, ' ');
1757 if (strdice) {
1758 dice = strtol(strdice, &end, 10);
1759 if (*end || !dice || dice > 10)
1760 goto syntax;
1761 strdice = token(&cmd_args, ' ');
1762 if (strdice) {
1763 bonus = strtol(strdice, &end, 10);
1764 if (*end || bonus > 1000 || bonus < -1000)
1765 goto syntax;
1768 perform_roll(b, prefix, target, base, dice, bonus);
1769 c->left++;
1770 return;
1772 syntax:
1773 c->left++;
1774 action(b, target, "bleeps at %s in a confused manner", prefix);
1775 return;
1778 if (chan == 2 && t > 0) {
1779 static int64_t last_t;
1780 if (t - last_t > 3)
1781 privmsg(b, target, "%s: { I love you! }", prefix);
1782 last_t = t;
1786 void command_hook(struct bio *b, const char *prefix, const char *ident, const char *host,
1787 const char *command, const char *const *args, unsigned nargs)
1789 char *buf = NULL;
1790 int64_t t = -1;
1791 if (!strcasecmp(command, "NOTICE")) {
1792 if (nargs < 2 || args[0][0] == '#')
1793 return;
1794 if (admin(host))
1795 b->writeline(b, "%s", args[1]);
1796 else
1797 fprintf(stderr, "%s: %s\n", prefix, args[1]);
1798 } else if (!strcasecmp(command, "JOIN")) {
1799 t = get_time(b, args[0]);
1800 rss_check(b, args[0], t);
1801 command_deliver(b, prefix, args[0]);
1802 asprintf(&buf, "%"PRIi64",joining %s", t, args[0]);
1803 } else if (!strcasecmp(command, "PART")) {
1804 t = get_time(b, args[0]);
1805 rss_check(b, args[0], t);
1806 asprintf(&buf, "%"PRIi64",leaving %s", t, args[0]);
1807 } else if (!strcasecmp(command, "QUIT")) {
1808 t = get_time(b, NULL);
1809 asprintf(&buf, "%"PRIi64",quitting with the message \"%s\"", t, args[0]);
1810 } else if (!strcasecmp(command, "NICK")) {
1811 t = get_time(b, NULL);
1812 if (t >= 0) {
1813 asprintf(&buf, "%"PRIi64",changing nick from %s", t, prefix);
1814 if (buf)
1815 update_seen(b, buf, args[0]);
1816 free(buf);
1817 buf = NULL;
1819 asprintf(&buf, "%"PRIi64",changing nick to %s", t, args[0]);
1820 } else if (0) {
1821 int i;
1822 fprintf(stderr, ":%s!%s%s %s", prefix, ident, host, command);
1823 for (i = 0; i < nargs; ++i)
1824 fprintf(stderr, " %s", args[i]);
1825 fprintf(stderr, "\n");
1827 if (t >= 0 && buf)
1828 update_seen(b, buf, prefix);
1829 free(buf);
1830 return;