Ignore links by EqBot
[fillybot.git] / mod.c
blob1caeecdff0077f5d85dfc8cc2fb0736f9f59bdd7
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 t = strdup(title);
253 squash(t);
254 privmsg(b, target, "Most recent entry: %s %s", link, t);
255 free(t);
256 } else
257 privmsg(b, target, "Currently having no entries for this feed that matches the filter");
258 return link;
260 if (!strcmp(last_link, link) || !match || !entry)
261 return link;
263 for (entry = entry->next; entry; entry = entry->next) {
264 const char *cur_link, *cur_title;
265 if (strcasecmp(entry->name, "entry"))
266 continue;
267 match = get_feed_entry(b, nick, target, category, entry, &cur_title, &cur_link);
268 if (match < 0 || !strcmp(last_link, cur_link))
269 break;
270 if (match) {
271 prev_link = cur_link;
272 prev_title = cur_title;
273 updates++;
276 if (updates == 1) {
277 t = strdup(prev_title);
278 squash(t);
279 privmsg(b, target, "( %s ): %s", prev_link, t);
280 free(t);
281 } else if (updates > 1)
282 privmsg(b, target, "( %s ): %u updates, linking most recent", main_link, 1+updates);
283 t = strdup(title);
284 squash(t);
285 privmsg(b, target, "( %s ): %s", link, t);
286 free(t);
287 return link;
290 static const char *walk_rss(struct bio *b, const char *nick, const char *target, const char *url, xmlNode *root, const char *last_link)
292 const char *main_title = NULL, *main_link = NULL, *title = NULL, *link = NULL, *ver;
293 char *t;
294 xmlNode *cur, *entry = NULL;
295 ver = get_link(root->properties, "version");
296 if (!ver || strcmp(ver, "2.0")) {
297 if (!ver)
298 privmsg(b, target, "%s: Could not parse rss feed", nick);
299 else
300 privmsg(b, target, "%s: Invalid rss version \"%s\"", nick, ver);
301 return NULL;
303 for (cur = root->children; cur && cur->type != XML_ELEMENT_NODE; cur = cur->next);
304 if (!cur)
305 return NULL;
306 for (cur = cur->children; cur; cur = cur->next) {
307 const char *name = cur->name;
308 if (cur->type != XML_ELEMENT_NODE)
309 continue;
310 if (!strcasecmp(name, "title"))
311 main_title = get_text(cur->children);
312 else if (!strcasecmp(name, "link"))
313 main_link = main_link ? main_link : get_text(cur->children);
314 else if (!strcasecmp(name, "item"))
315 entry = entry ? entry : cur;
317 if (!main_link || !main_title) {
318 privmsg(b, target, "%s: Failed to parse main: %s %s", nick, main_link, main_title);
319 return NULL;
321 if (!entry)
322 return NULL;
324 link = title = NULL;
325 for (cur = entry->children; cur; cur = cur->next) {
326 const char *name = cur->name;
327 if (cur->type != XML_ELEMENT_NODE)
328 continue;
329 if (!strcasecmp(name, "title"))
330 title = get_text(cur->children);
331 else if (!strcasecmp(name, "link"))
332 link = get_text(cur->children);
334 if (!title)
335 title = "<no title>";
336 if (!link) {
337 privmsg(b, target, "%s: Failed to parse entry: %s %s", nick, link, title);
338 return NULL;
340 if (!last_link) {
341 t = strdup(title);
342 privmsg(b, target, "adding blog %s \"%s\"", main_link, main_title);
343 squash(t);
344 privmsg(b, target, "Most recent entry: %s %s", link, t);
345 free(t);
346 } else if (strcmp(last_link, link)) {
347 int updates = 0;
348 const char *prev_title = NULL, *prev_link = NULL, *cur_title = NULL, *cur_link = NULL;
349 for (entry = entry->next; entry; entry = entry->next) {
350 if (strcasecmp(entry->name, "item"))
351 continue;
352 prev_title = cur_title;
353 prev_link = cur_link;
354 cur_title = cur_link = NULL;
355 for (cur = entry->children; cur; cur = cur->next) {
356 const char *name = cur->name;
357 if (cur->type != XML_ELEMENT_NODE)
358 continue;
359 if (!strcasecmp(name, "title"))
360 cur_title = get_text(cur->children);
361 else if (!strcasecmp(name, "link"))
362 cur_link = get_text(cur->children);
364 if (!cur_title)
365 cur_title = "<no title>";
366 if (!cur_link || !strcmp(last_link, cur_link))
367 break;
368 updates++;
370 if (updates == 1) {
371 t = strdup(prev_title);
372 squash(t);
373 privmsg(b, target, "( %s ): %s", prev_link, t);
374 free(t);
375 } else if (updates > 1)
376 privmsg(b, target, "( %s ): %u updates, linking most recent", main_link, 1+updates);
377 t = strdup(title);
378 squash(t);
379 privmsg(b, target, "( %s ): %s", link, t);
380 free(t);
382 return link;
385 // HTML is a mess, so I'm just walking the tree depth first until I find the next element..
386 static xmlNode *next_link(xmlNode *cur_node)
388 if (cur_node->children)
389 return cur_node->children;
390 while (cur_node) {
391 if (cur_node->next)
392 return cur_node->next;
393 cur_node = cur_node->parent;
395 return NULL;
398 static const char *get_atom_link(xmlNode *cur)
400 for (; cur; cur = next_link(cur)) {
401 if (cur->type != XML_ELEMENT_NODE)
402 continue;
403 if (!strcasecmp(cur->name, "link")) {
404 const char *isxml = get_link(cur->properties, "type");
405 if (isxml && !strcasecmp(isxml, "application/atom+xml"))
406 return get_link(cur->properties, "href");
409 return NULL;
412 static const char *get_rss_link(xmlNode *cur)
414 for (; cur; cur = next_link(cur)) {
415 if (cur->type != XML_ELEMENT_NODE)
416 continue;
417 if (!strcasecmp(cur->name, "link")) {
418 const char *isxml = get_link(cur->properties, "type");
419 if (isxml && !strcasecmp(isxml, "application/rss+xml"))
420 return get_link(cur->properties, "href");
423 return NULL;
426 static void do_html(struct bio *b, const char *nick, const char *target, const char *url, const char *data, unsigned len)
428 htmlDocPtr ctx = htmlReadMemory(data, len, 0, url, HTML_PARSE_RECOVER|HTML_PARSE_NOERROR|HTML_PARSE_NOWARNING);
429 xmlNode *root = xmlDocGetRootElement(ctx);
430 const char *link = get_atom_link(root);
431 if (link)
432 privmsg(b, target, "%s: not a valid feed link, try atom: %s", nick, link);
433 else if ((link = get_rss_link(root)))
434 privmsg(b, target, "%s: not a valid feed link, try rss: %s", nick, link);
435 else
436 privmsg(b, target, "%s: not a valid feed link, no suggestion found", nick);
437 xmlFreeDoc(ctx);
440 static size_t get_time_from_header(void *data, size_t size, size_t size2, void *ptr)
442 char *d, *e;
443 size *= size2;
444 if (sstrncmp(data, "Last-Modified: "))
445 return size;
446 data += sizeof("Last-Modified: ")-1;
447 *(char**)ptr = d = strdup(data);
448 if ((e = strchr(d, '\r')))
449 *e = 0;
450 return size;
453 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)
455 struct curl_download_context curl_ctx = {};
456 struct curl_slist *headers = NULL;
457 char error[CURL_ERROR_SIZE], *category = strchr(url, '#');
458 int retval = -1;
459 headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
460 headers = curl_slist_append(headers, "Accept: */*");
461 if (category)
462 *(category++) = 0;
464 CURL *h = curl_easy_init();
465 curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
466 curl_easy_setopt(h, CURLOPT_URL, url);
467 curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
468 curl_easy_setopt(h, CURLOPT_WRITEDATA, &curl_ctx);
469 curl_easy_setopt(h, CURLOPT_ERRORBUFFER, error);
470 curl_easy_setopt(h, CURLOPT_FOLLOWLOCATION, 1);
471 curl_easy_setopt(h, CURLOPT_MAXREDIRS, 3);
472 curl_easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 0);
473 curl_easy_setopt(h, CURLOPT_TIMEOUT, 8);
474 curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, 8);
475 curl_easy_setopt(h, CURLOPT_FILETIME, 1);
476 curl_easy_setopt(h, CURLOPT_HEADERFUNCTION, get_time_from_header);
477 curl_easy_setopt(h, CURLOPT_WRITEHEADER, &last_modified);
478 //curl_easy_setopt(h, CURLOPT_VERBOSE, 1);
480 if (last_modified) {
481 char *tmp;
482 asprintf(&tmp, "If-Modified-Since: %s", last_modified);
483 headers = curl_slist_append(headers, tmp);
484 free(tmp);
487 int success = curl_easy_perform(h);
488 curl_slist_free_all(headers);
489 if (success == CURLE_OK) {
490 char *mime = NULL;
491 long code;
492 curl_easy_getinfo(h, CURLINFO_CONTENT_TYPE, &mime);
493 curl_easy_getinfo(h, CURLINFO_RESPONSE_CODE, &code);
494 if (code == 304)
496 else if (!mime || !sstrncmp(mime, "application/xml") || !sstrncmp(mime, "text/xml")) {
497 const char *ret_link = NULL;
498 xmlDocPtr ctx = xmlReadMemory(curl_ctx.data, curl_ctx.len, 0, url, XML_PARSE_NOWARNING | XML_PARSE_NOERROR);
499 xmlNode *root = xmlDocGetRootElement(ctx);
501 if (!root || !root->name)
502 fprintf(stderr, "Failed to parse feed %s %p", url, root);
503 else if (!strcasecmp(root->name, "feed"))
504 ret_link = walk_feed(b, nick, target, url, category, root, link);
505 else if (!strcasecmp(root->name, "rss"))
506 ret_link = walk_rss(b, nick, target, url, root, link);
507 else {
508 privmsg(b, target, "Unknown feed type \"%s\"", root->name);
509 goto free_ctx;
511 if (category)
512 category[-1] = '#';
514 if (!ret_link)
515 privmsg(b, target, "Could not feed parse correctly");
516 else if (ret_link && (!link || strcmp(ret_link, link))) {
517 TDB_DATA val;
518 asprintf((char**)&val.dptr, "%s\001%s", last_modified ? last_modified : "", ret_link);
519 val.dsize = strlen(val.dptr)+1;
520 if (tdb_store(feed_db, key, val, 0) < 0)
521 privmsg(b, target, "updating returns %s", tdb_errorstr(feed_db));
522 free(val.dptr);
523 retval = 1;
525 else
526 retval = 0;
528 free_ctx:
529 xmlFreeDoc(ctx);
530 } else if (link)
532 else if (!sstrncmp(mime, "text/html") || !sstrncmp(mime, "application/xhtml+xml"))
533 do_html(b, nick, target, url, curl_ctx.data, curl_ctx.len);
534 else
535 privmsg(b, target, "unhandled content type %s", mime);
536 } else if (!link)
537 privmsg(b, target, "Error %s (%u)", error, success);
539 free(curl_ctx.data);
540 curl_easy_cleanup(h);
541 return retval;
544 static void command_follow(struct bio *b, const char *nick, const char *host, const char *target, char *args)
546 char *space, *last_link = NULL;
547 TDB_DATA key, val;
548 int ret;
549 if (!feed_db)
550 return;
551 if (target[0] != '#') {
552 privmsg(b, target, "%s: Can only follow on channels", nick);
553 return;
555 if (!args || !*args) {
556 privmsg(b, target, "%s: Usage: !follow <url>", nick);
557 return;
560 if (((space = strchr(args, ' ')) && space < strchr(args, '#')) ||
561 (sstrncmp(args, "http://") && sstrncmp(args, "https://"))) {
562 privmsg(b, target, "%s: Invalid url", nick);
563 return;
566 key.dsize = asprintf((char**)&key.dptr, "%s,%s", target, args)+1;
567 val = tdb_fetch(feed_db, key);
568 if (val.dptr)
569 last_link = strchr(val.dptr, '\001');
570 ret = check_single_feed(b, target, key, NULL, args, last_link ? last_link+1 : NULL, nick);
571 free(val.dptr);
572 if (!ret)
573 privmsg(b, target, "%s: Not updated", nick);
574 free(key.dptr);
577 static void channel_feed_check(struct bio *b, const char *target, int64_t now)
579 int len = strlen(target);
580 int64_t save[] = { now, 0, 0 };
582 TDB_DATA chan, res;
583 if (!feed_db || !chan_db)
584 return;
585 chan.dptr = (char*)target;
586 chan.dsize = len+1;
587 res = tdb_fetch(chan_db, chan);
588 if (res.dptr && res.dsize >= 8) {
589 uint64_t then = *(uint64_t*)res.dptr;
590 if (now - then <= 2000)
591 return;
592 if (res.dsize >= 16)
593 save[1] = ((uint64_t*)res.dptr)[1];
594 if (res.dsize >= 24)
595 save[2] = ((uint64_t*)res.dptr)[2];
597 free(res.dptr);
598 res.dptr = (unsigned char*)save;
599 res.dsize = sizeof(save);
600 if (tdb_store(chan_db, chan, res, 0) < 0) {
601 static int complain_db;
602 if (!complain_db++)
603 privmsg(b, target, "updating database: %s", tdb_errorstr(feed_db));
604 return;
607 for (TDB_DATA d = tdb_firstkey(feed_db); d.dptr;) {
608 TDB_DATA f = tdb_fetch(feed_db, d);
609 TDB_DATA next = tdb_nextkey(feed_db, d);
611 if (!strncmp(d.dptr, target, len) && d.dptr[len] == ',') {
612 const char *url = (char*)d.dptr + len + 1;
613 char *sep;
614 if ((sep = strchr(f.dptr, '\001'))) {
615 *(sep++) = 0;
616 check_single_feed(b, target, d, f.dptr, url, sep, target);
619 free(d.dptr);
620 free(f.dptr);
621 d = next;
625 static void command_unfollow(struct bio *b, const char *nick, const char *host, const char *target, char *args)
627 TDB_DATA key;
628 char *url;
630 if (!feed_db)
631 return;
633 if (!(url = token(&args, ' ')) || (sstrncmp(url, "http://") && sstrncmp(url, "https://"))) {
634 privmsg(b, target, "%s: Invalid url", nick);
635 return;
637 if (target[0] != '#') {
638 privmsg(b, target, "%s: Can only unfollow on channels", nick);
639 return;
641 key.dsize = asprintf((char**)&key.dptr, "%s,%s", target, url)+1;
642 if (tdb_delete(feed_db, key) < 0) {
643 if (tdb_error(feed_db) == TDB_ERR_NOEXIST)
644 privmsg(b, target, "%s: Not following %s on this channel", nick, url);
645 else
646 privmsg(b, target, "%s: Could not delete: %s", nick, tdb_errorstr(feed_db));
647 } else
648 privmsg(b, target, "%s: No longer following %s", nick, url);
649 free(key.dptr);
652 static void command_g(struct bio *b, const char *nick, const char *host, const char *target, char *args)
654 int ret = 0;
655 int64_t g = 0, g_total = 0;
656 TDB_DATA chan, res;
658 if (!chan_db || target[0] != '#')
659 return;
661 chan.dptr = (char*)target;
662 chan.dsize = strlen(chan.dptr)+1;
663 res = tdb_fetch(chan_db, chan);
664 if (res.dptr && res.dsize >= 16) {
665 g = ((int64_t*)res.dptr)[1];
666 ((int64_t*)res.dptr)[1] = 0;
667 if (res.dsize >= 24)
668 g_total = ((int64_t*)res.dptr)[2];
669 ret = tdb_store(chan_db, chan, res, 0);
671 free(res.dptr);
672 if (ret < 0)
673 fprintf(stderr, "updating database: %s", tdb_errorstr(feed_db));
674 else
675 privmsg(b, target, "%s: %"PRIi64" g's since last check, %"PRIi64" total", nick, g, g_total);
678 static void command_feeds(struct bio *b, const char *nick, const char *host, const char *target, char *args)
680 int len = strlen(target), found = 0;
681 if (!feed_db)
682 return;
683 if (target[0] != '#') {
684 privmsg(b, target, "%s: Only useful in channels..", nick);
685 return;
687 for (TDB_DATA d = tdb_firstkey(feed_db); d.dptr;) {
688 TDB_DATA f = tdb_fetch(feed_db, d);
689 TDB_DATA next = tdb_nextkey(feed_db, d);
691 if (!strncmp(d.dptr, target, len) && d.dptr[len] == ',') {
692 privmsg(b, target, "%s: following %s", nick, d.dptr + len + 1);
693 found++;
695 free(d.dptr);
696 free(f.dptr);
697 d = next;
699 if (!found)
700 privmsg(b, target, "%s: not following any feed on %s", nick, target);
703 static void command_feed_get(struct bio *b, const char *nick, const char *host, const char *target, char *args)
705 if (!feed_db)
706 return;
707 for (TDB_DATA d = tdb_firstkey(feed_db); d.dptr;) {
708 TDB_DATA next = tdb_nextkey(feed_db, d);
709 if (!args || strcasestr(d.dptr, args)) {
710 TDB_DATA f = tdb_fetch(feed_db, d);
711 privmsg(b, target, "%s: %s = %s", nick, d.dptr, f.dptr);
712 free(f.dptr);
714 if (strlen(d.dptr)+1 < d.dsize) {
715 privmsg(b, target, "%s: removed buggy entry", nick);
716 tdb_delete(feed_db, d);
718 free(d.dptr);
719 d = next;
723 static void command_feed_set(struct bio *b, const char *nick, const char *host, const char *target, char *args)
725 if (!feed_db)
726 return;
727 TDB_DATA key, val;
728 key.dptr = token(&args, ' ');
729 char *value = token(&args, ' ');
730 if (!key.dptr || !value)
731 return;
732 key.dsize = strlen(key.dptr) + 1;
733 val.dsize = strlen(value) + 2;
734 val.dptr = malloc(val.dsize);
735 strcpy(val.dptr+1, value);
736 val.dptr[0] = '\001';
737 if (tdb_store(feed_db, key, val, 0) < 0)
738 privmsg(b, target, "%s: setting failed: %s", nick, tdb_errorstr(feed_db));
739 else
740 privmsg(b, target, "%s: burp", nick);
741 free(val.dptr);
744 static void command_feed_rem(struct bio *b, const char *nick, const char *host, const char *target, char *args)
746 if (!feed_db || !args)
747 return;
748 TDB_DATA key = { .dptr = (unsigned char*)args, .dsize = strlen(args)+1 };
749 if (tdb_delete(feed_db, key) < 0)
750 privmsg(b, target, "%s: removing failed: %s", nick, tdb_errorstr(feed_db));
751 else
752 privmsg(b, target, "%s: burp", nick);
755 static void command_feed_xxx(struct bio *b, const char *nick, const char *host, const char *target, char *args)
757 if (!feed_db)
758 return;
760 tdb_wipe_all(feed_db);
761 privmsg(b, target, "%s: all evidence erased", nick);
764 static void command_seen_xxx(struct bio *b, const char *nick, const char *host, const char *target, char *args)
766 if (!seen_db)
767 return;
769 tdb_wipe_all(seen_db);
770 privmsg(b, target, "%s: all evidence erased", nick);
773 static void command_feed_counter(struct bio *b, const char *nick, const char *host, const char *target, char *args)
775 if (!chan_db)
776 return;
777 tdb_wipe_all(chan_db);
778 privmsg(b, target, "%s: All update counters reset", nick);
781 static char *get_text_appended(xmlNode *cur)
783 for (; cur; cur = cur->next) {
784 if (cur->type != XML_TEXT_NODE)
785 continue;
786 return strdup(cur->content);
788 return NULL;
791 static char *get_title(struct bio *b, xmlNode *cur_node)
793 for (; cur_node; cur_node = next_link(cur_node)) {
794 if (cur_node->type == XML_ELEMENT_NODE && !strcasecmp(cur_node->name, "title")) {
795 if (!cur_node->children)
796 return NULL;
797 return get_text_appended(cur_node->children);
800 return NULL;
803 static void internal_link(struct bio *b, const char *nick, const char *host, const char *target, char *args, unsigned verbose)
805 CURL *h;
806 struct curl_slist *headers = NULL;
807 char error[CURL_ERROR_SIZE];
808 int success, sent = verbose;
809 struct curl_download_context curl_ctx = {};
811 if (!args)
812 return;
813 int64_t stop, start = get_time(b, target);
815 h = curl_easy_init();
816 headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
817 headers = curl_slist_append(headers, "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
818 headers = curl_slist_append(headers, "Accept-Language: en-us,en;q=0.7");
819 headers = curl_slist_append(headers, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
820 headers = curl_slist_append(headers, "DNT: 1");
821 headers = curl_slist_append(headers, "Connection: keep-alive");
822 curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
823 curl_easy_setopt(h, CURLOPT_URL, args);
824 curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
825 curl_easy_setopt(h, CURLOPT_WRITEDATA, &curl_ctx);
826 curl_easy_setopt(h, CURLOPT_ERRORBUFFER, error);
827 curl_easy_setopt(h, CURLOPT_FOLLOWLOCATION, 1);
828 curl_easy_setopt(h, CURLOPT_MAXREDIRS, 3);
829 curl_easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 0);
830 curl_easy_setopt(h, CURLOPT_TIMEOUT, 8);
831 curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, 8);
832 //curl_easy_setopt(h, CURLOPT_VERBOSE, 1);
833 success = curl_easy_perform(h);
834 curl_easy_cleanup(h);
835 curl_slist_free_all(headers);
836 if (success == CURLE_OK) {
837 magic_t m = magic_open(MAGIC_MIME_TYPE);
838 magic_load(m, NULL);
839 const char *mime = magic_buffer(m, curl_ctx.data, curl_ctx.len);
840 if (strstr(mime, "text/html") || strstr(mime, "application/xml") || strstr(mime, "application/xhtml+xml")) {
841 htmlDocPtr ctx = htmlReadMemory(curl_ctx.data, curl_ctx.len, 0, args, HTML_PARSE_RECOVER|HTML_PARSE_NOERROR|HTML_PARSE_NOWARNING);
842 xmlNode *root_element = xmlDocGetRootElement(ctx);
843 char *title = get_title(b, root_element);
844 if (title) {
845 char *nuke;
846 squash(title);
847 decode_html_entities_utf8(title, NULL);
848 if ((nuke = strstr(title, " on SoundCloud - Create")))
849 *nuke = 0;
850 if (*title) {
851 privmsg(b, target, "%s linked %s", nick, title);
852 sent = 1;
854 free(title);
856 if (verbose && !title)
857 privmsg(b, target, "%s linked %s page with invalid title", nick, mime);
858 xmlFreeDoc(ctx);
859 } else if (verbose) {
860 magic_setflags(m, MAGIC_COMPRESS);
861 const char *desc = magic_buffer(m, curl_ctx.data, curl_ctx.len);
862 privmsg(b, target, "%s linked type %s", nick, desc);
864 magic_close(m);
866 if (verbose && success != CURLE_OK)
867 privmsg(b, target, "Error %s (%u)", error, success);
868 else if (!sent && (stop = get_time(b, target)) - start >= 15) {
869 privmsg(b, target, "Link (%s) by %s timed out, disabling links for 10 seconds", args, nick);
870 commands[strhash("get") % elements(commands)].disabled_until = stop + 10;
872 free(curl_ctx.data);
875 static void command_get(struct bio *b, const char *nick, const char *host, const char *target, char *args)
877 if (!args || (sstrncmp(args, "http://") && sstrncmp(args, "https://")))
878 return;
879 internal_link(b, nick, host, target, token(&args, ' '), 1);
882 static void command_fabric(struct bio *b, const char *nick, const char *host, const char *target, char *args)
884 privmsg(b, target, "Dumb fabric!");
887 static void command_admire(struct bio *b, const char *nick, const char *host, const char *target, char *args)
889 char *arg = token(&args, ' ');
890 privmsg(b, target, "%s: I really like your mane!", arg ? arg : nick);
893 static void command_hugs(struct bio *b, const char *nick, const char *host, const char *target, char *args)
895 action(b, target, "gives a lunar hug to %s", args ? args : nick);
898 static void command_hug(struct bio *b, const char *nick, const char *host, const char *target, char *args)
900 if ((host && !strcmp(host, "life.on.the.moon.is.great.I.know.all.about.it")) ||
901 (args && !sstrncasecmp(args, "lu")))
902 command_hugs(b, nick, host, target, args);
903 else
904 action(b, target, "gives a robotic hug to %s", args ? args : nick);
907 static void command_snuggles(struct bio *b, const char *nick, const char *host, const char *target, char *args)
909 action(b, target, "gives a lunar snuggle to %s", args ? args : nick);
912 static void command_snuggle(struct bio *b, const char *nick, const char *host, const char *target, char *args)
914 if ((host && !strcmp(host, "life.on.the.moon.is.great.I.know.all.about.it")) ||
915 (args && !sstrncasecmp(args, "lu")))
916 command_snuggles(b, nick, host, target, args);
917 else
918 action(b, target, "gives a robotic snuggle to %s", args ? args : nick);
921 static void command_cuddles(struct bio *b, const char *nick, const char *host, const char *target, char *args)
923 action(b, target, "gives cuddles to %s in a lunaresque way", args ? args : nick);
926 static void command_cuddle(struct bio *b, const char *nick, const char *host, const char *target, char *args)
928 if ((host && !strcmp(host, "life.on.the.moon.is.great.I.know.all.about.it")) ||
929 (args && !sstrncasecmp(args, "lu")))
930 command_cuddles(b, nick, host, target, args);
931 else
932 action(b, target, "gives cuddles to %s in a robotic way", args ? args : nick);
936 static void command_cookie(struct bio *b, const char *nick, const char *host, const char *target, char *args)
938 if (args && !strncasecmp(args, nick_self, strlen(nick_self)))
939 action(b, target, "eats the cookie offered by %s", nick);
940 else
941 action(b, target, "hands a metallic looking cookie to %s", args ? args : nick);
944 static void command_derpy(struct bio *b, const char *nick, const char *host, const char *target, char *args)
946 static const char *insults[] = {
947 "accidentally shocks herself",
948 "tumbles down the stairs like a slinky",
949 "whirrrs and clicks in a screeching way",
950 "had problems executing this command",
951 "breaks down entirely",
952 "uses her magic to levitate herself off the ground, then hits it face first"
954 action(b, target, "%s", insults[getrand() % elements(insults)]);
957 static void command_inspect(struct bio *b, const char *nick, const char *host, const char *target, char *args)
959 struct command_hash *c;
960 unsigned leave, crash;
961 char *cmd;
962 if (!args || !(cmd = token(&args, ' ')))
963 return;
965 if (strcmp(cmd, "#")) {
966 c = &commands[strhash(cmd) % elements(commands)];
967 if (!c->string || strcasecmp(c->string, cmd)) {
968 privmsg(b, target, "Command %s not valid", cmd);
969 return;
971 } else
972 c = &command_channel;
974 leave = c->left + (c->cmd == command_inspect);
975 crash = c->enter - leave;
976 if (c->enter != leave)
977 privmsg(b, target, "%s: %u successes and %u crash%s, last crashing command: %s", c->string, leave, crash, crash == 1 ? "" : "es", c->failed_command);
978 else
979 privmsg(b, target, "%s: %u time%s executed succesfully", c->string, leave, leave == 1 ? "" : "s");
982 static void command_rebuild(struct bio *b, const char *nick, const char *host, const char *target, char *args)
984 int ret;
985 char *make[] = { "/usr/bin/make", "-j4", NULL };
986 char *git_reset[] = { "/usr/bin/git", "reset", "--hard", "master", NULL };
987 ret = pipe_command(b, target, nick, 0, 1, git_reset);
988 if (ret) {
989 action(b, target, "could not rebuild");
990 return;
992 ret = pipe_command(b, target, nick, 0, 1, make);
993 if (!ret)
994 kill(getpid(), SIGUSR1);
995 else if (ret > 0)
996 action(b, target, "displays an ominous %i", ret);
999 static void command_swear(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1001 static const char *insults[] = {
1002 "featherbrain",
1003 "ponyfeathers",
1004 "What in the hey?",
1005 "What are you, a dictionary?",
1006 "TAR-DY!",
1007 "[BUY SOME APPLES]",
1008 "{ Your lack of bloodlust on the battlefield is proof positive that you are a soulless automaton! }",
1009 "Your royal snootiness"
1011 privmsg(b, target, "%s: %s", args ? args : nick, insults[getrand() % elements(insults)]);
1014 static const char *perty(int64_t *t)
1016 if (*t >= 14 * 24 * 3600) {
1017 *t /= 7 * 24 * 3600;
1018 return "weeks";
1019 } else if (*t >= 48 * 3600) {
1020 *t /= 24 * 3600;
1021 return "days";
1022 } else if (*t >= 7200) {
1023 *t /= 3600;
1024 return "hours";
1025 } else if (*t >= 120) {
1026 *t /= 60;
1027 return "minutes";
1029 return *t == 1 ? "second" : "seconds";
1032 static void command_timeout(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1034 struct command_hash *c;
1035 int64_t t = get_time(b, target);
1036 int64_t howlong;
1037 if (t < 0)
1038 return;
1039 char *arg = token(&args, ' ');
1040 if (!arg || !args || !(howlong = atoi(args))) {
1041 action(b, target, "pretends to time out");;
1042 return;
1044 c = &commands[strhash(arg) % elements(commands)];
1045 if (c->string && !strcasecmp(c->string, arg)) {
1046 c->disabled_until = t + howlong;
1047 const char *str = perty(&howlong);
1048 action(b, target, "disables %s for %"PRIi64" %s", arg, howlong, str);
1049 } else
1050 action(b, target, "clicks sadly at %s for not being able to find that command", nick);
1053 static void command_mfw(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1055 char error[CURL_ERROR_SIZE], *new_url;
1056 CURL *h = curl_easy_init();
1057 struct curl_slist *headers = NULL;
1058 struct curl_download_context curl_ctx = {};
1059 headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
1060 headers = curl_slist_append(headers, "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
1061 headers = curl_slist_append(headers, "Accept-Language: en-us,en;q=0.7");
1062 headers = curl_slist_append(headers, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
1063 headers = curl_slist_append(headers, "DNT: 1");
1064 headers = curl_slist_append(headers, "Connection: keep-alive");
1065 curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
1066 curl_easy_setopt(h, CURLOPT_URL, "http://mylittlefacewhen.com/random/");
1067 curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
1068 curl_easy_setopt(h, CURLOPT_WRITEDATA, &curl_ctx);
1069 curl_easy_setopt(h, CURLOPT_ERRORBUFFER, error);
1070 curl_easy_setopt(h, CURLOPT_TIMEOUT, 8);
1071 curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT, 8);
1072 //curl_easy_setopt(h, CURLOPT_VERBOSE, 1);
1073 CURLcode ret = curl_easy_perform(h);
1074 if (ret == CURLE_OK && curl_easy_getinfo(h, CURLINFO_REDIRECT_URL, &new_url) == CURLE_OK)
1075 privmsg(b, target, "%s: %s", nick, new_url);
1076 curl_slist_free_all(headers);
1077 curl_easy_cleanup(h);
1078 if (ret != CURLE_OK)
1079 privmsg(b, target, "%s: You have no face", nick);
1082 static TDB_DATA get_mail_key(const char *nick)
1084 TDB_DATA d;
1085 int i;
1086 d.dsize = strlen(nick)+1;
1087 d.dptr = malloc(d.dsize);
1088 for (i = 0; i < d.dsize - 1; ++i)
1089 d.dptr[i] = tolower(nick[i]);
1090 d.dptr[i] = 0;
1091 return d;
1094 static void command_mail(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1096 char *victim, *x = NULL;
1097 size_t len;
1098 int override = 0;
1099 int64_t last_seen = 0;
1101 if (!mail_db || !seen_db)
1102 return;
1103 TDB_DATA key, val;
1104 victim = token(&args, ' ');
1105 if (victim && !strcasecmp(victim, "-seen")) {
1106 victim = token(&args, ' ');
1107 override = 1;
1109 if (!victim || !args || victim[0] == '#' || strchr(victim, '@') || strchr(victim, '.')) {
1110 privmsg(b, target, "%s: Usage: !mail <nick> <message>", nick);
1111 return;
1113 if (!strcasecmp(victim, nick_self)) {
1114 action(b, target, "whirrs and clicks excitedly at the mail she received from %s", nick);
1115 return;
1117 if (!strcasecmp(victim, nick)) {
1118 action(b, target, "echos the words from %s back to them: %s", nick, args);
1119 return;
1121 int64_t now = get_time(b, target);
1122 if (now < 0)
1123 return;
1125 key = get_mail_key(victim);
1126 val = tdb_fetch(seen_db, key);
1127 if (val.dptr && (x = strchr(val.dptr, ','))) {
1128 *(x++) = 0;
1129 last_seen = atoll(val.dptr);
1131 if (x && !admin(host) && (now - last_seen) < 300 && (!sstrncasecmp(x, "in ") || !sstrncasecmp(x, "joining "))) {
1132 action(b, target, "would rather not store mail for someone active so recently");
1133 goto out;
1134 } else if (last_seen && now - last_seen > 14 * 24 * 3600 && !override) {
1135 int64_t delta = now - last_seen;
1136 const char *str = perty(&delta);
1137 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);
1138 return;
1139 } else if (!x && !override) {
1140 privmsg(b, target, "%s: I've never seen \"%s\", use !mail -seen %s <message> to override this check.", nick, victim, victim);
1141 return;
1144 val = tdb_fetch(mail_db, key);
1145 if (!val.dptr)
1146 val.dsize = 0;
1147 else {
1148 unsigned char *cur;
1149 int letters = 0;
1150 for (cur = val.dptr; cur < val.dptr + val.dsize; cur += strlen(cur)+1)
1151 letters++;
1152 if (letters >= 4) {
1153 action(b, target, "looks sadly at %s as she cannot hold any more mail to %s", nick, victim);
1154 goto out;
1157 len = snprintf(NULL, 0, "%"PRIi64 ",%s: %s", now, nick, args) + 1;
1158 val.dptr = realloc(val.dptr, val.dsize + len);
1159 snprintf(val.dptr + val.dsize, len, "%"PRIi64 ",%s: %s", now, nick, args);
1160 val.dsize += len;
1161 if (tdb_store(mail_db, key, val, 0) < 0)
1162 privmsg(b, target, "%s: updating mail returns %s", nick, tdb_errorstr(mail_db));
1163 else
1164 action(b, target, "whirrs and clicks at %s as she stores the mail for %s", nick, victim);
1165 out:
1166 free(val.dptr);
1167 free(key.dptr);
1170 static void single_message(struct bio *b, const char *target, char *cur, int64_t now)
1172 char *endtime, *sep = strchr(cur, ':');
1173 int64_t delta = -1;
1174 if (sep && (endtime = strchr(cur, ',')) && endtime < sep) {
1175 int64_t t = atoll(cur);
1176 if (t > 0)
1177 delta = now - t;
1178 cur = endtime + 1;
1180 if (delta >= 0) {
1181 const char *str = perty(&delta);
1182 privmsg(b, target, "%"PRIi64" %s ago from %s", delta, str, cur);
1183 } else
1184 privmsg(b, target, "From %s", cur);
1187 static void command_deliver(struct bio *b, const char *nick, const char *target)
1189 TDB_DATA key, val;
1190 unsigned char *cur;
1191 static unsigned mail_enter, mail_leave;
1192 if (mail_enter++ != mail_leave)
1193 return;
1195 if (!mail_db)
1196 return;
1197 key = get_mail_key(nick);
1198 val = tdb_fetch(mail_db, key);
1199 if (!val.dptr)
1200 goto end;
1201 int64_t now = get_time(b, NULL);
1202 if (strcasecmp(key.dptr, nick_self)) {
1203 privmsg(b, target, "%s: You've got mail!", nick);
1204 for (cur = val.dptr; cur < val.dptr + val.dsize; cur += strlen(cur)+1)
1205 single_message(b, target, cur, now);
1207 free(val.dptr);
1208 tdb_delete(mail_db, key);
1209 end:
1210 free(key.dptr);
1211 mail_leave++;
1214 static void update_seen(struct bio *b, char *doingwhat, const char *nick)
1216 TDB_DATA key;
1217 key = get_mail_key(nick);
1218 TDB_DATA val = { .dptr = doingwhat, .dsize = strlen(doingwhat)+1 };
1219 if (seen_db)
1220 tdb_store(seen_db, key, val, 0);
1221 free(key.dptr);
1224 static void command_seen(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1226 char *arg = token(&args, ' '), *x;
1227 int64_t now = get_time(b, target);
1228 TDB_DATA key, val;
1229 if (now < 0)
1230 return;
1231 if (!seen_db || !arg) {
1232 privmsg(b, target, "%s: { Error... }", nick);
1233 return;
1235 if (!strcasecmp(arg, nick_self)) {
1236 action(b, target, "whirrs and clicks at %s", nick);
1237 return;
1239 if (!strcasecmp(arg, nick)) {
1240 action(b, target, "circles around %s dancing", nick);
1241 return;
1243 key = get_mail_key(arg);
1244 val = tdb_fetch(seen_db, key);
1245 if (val.dptr && (x = strchr(val.dptr, ','))) {
1246 int64_t delta;
1247 const char *str;
1248 *(x++) = 0;
1249 delta = now - atoll(val.dptr);
1250 str = perty(&delta);
1251 if (delta < 0)
1252 privmsg(b, target, "%s was last seen in the future %s", arg, x);
1253 else
1254 privmsg(b, target, "%s was last seen %"PRIi64" %s ago %s", arg, delta, str, x);
1255 } else
1256 action(b, target, "cannot find any evidence that %s exists", arg);
1257 free(val.dptr);
1260 static void command_mailbag(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1262 char buffer[256];
1263 unsigned rem = sizeof(buffer)-1, first = 2;
1264 if (!mail_db)
1265 return;
1266 buffer[rem] = 0;
1268 for (TDB_DATA f = tdb_firstkey(mail_db); f.dptr;) {
1269 if (f.dsize + 4 > rem) {
1270 privmsg(b, target, "%s: Holding mail for: %s", nick, &buffer[rem]);
1271 first = 2;
1272 rem = sizeof(buffer)-1;
1273 assert(f.dsize + 4 < rem);
1275 if (f.dptr) {
1276 if (first == 2) {
1277 first = 1;
1278 } else if (first) {
1279 rem -= 5;
1280 memcpy(&buffer[rem], " and ", 5);
1281 first = 0;
1282 } else {
1283 rem -= 2;
1284 memcpy(&buffer[rem], ", ", 2);
1286 rem -= f.dsize - 1;
1287 memcpy(&buffer[rem], f.dptr, f.dsize - 1);
1289 TDB_DATA next = tdb_nextkey(mail_db, f);
1290 free(f.dptr);
1291 f = next;
1293 if (first < 2)
1294 privmsg(b, target, "%s: Holding mail for: %s", nick, &buffer[rem]);
1297 static void command_mailread(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1299 TDB_DATA key, val;
1300 char *victim;
1301 if (!mail_db || !(victim = token(&args, ' ')))
1302 return;
1303 key = get_mail_key(victim);
1304 val = tdb_fetch(mail_db, key);
1305 if (!val.dptr)
1306 action(b, target, "ponyshrugs as no mail for %s was found", victim);
1307 else {
1308 unsigned char *cur;
1309 int64_t now = get_time(b, NULL);
1310 action(b, target, "peeks through %s's mail", victim);
1311 for (cur = val.dptr; cur < val.dptr + val.dsize; cur += strlen(cur)+1)
1312 single_message(b, target, cur, now);
1314 free(val.dptr);
1315 free(key.dptr);
1318 static void command_no_deliver(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1320 TDB_DATA key, val;
1321 char *cur;
1322 if (!mail_db || !(cur = token(&args, ' ')))
1323 return;
1324 key = get_mail_key(cur);
1325 val = tdb_fetch(mail_db, key);
1326 if (!val.dptr)
1327 action(b, target, "ponyshrugs as no mail for %s was found", cur);
1328 else {
1329 action(b, target, "deletes all evidence of %s's mail", cur);
1330 tdb_delete(mail_db, key);
1332 free(val.dptr);
1333 free(key.dptr);
1336 static void perform_roll(struct bio *b, const char *nick, const char *target, long sides, long dice, long bonus)
1338 long rem = dice, total = bonus;
1339 while (rem--)
1340 total += 1 + (getrand() % sides);
1341 if (bonus)
1342 action(b, target, "rolls %li %li-sided %s for a total of %li (%+li)", dice, sides, dice == 1 ? "die" : "dice", total, bonus);
1343 else
1344 action(b, target, "rolls %li %li-sided %s for a total of %li", dice, sides, dice == 1 ? "die" : "dice", total);
1347 static void command_roll(struct bio *b, const char *nick, const char *host, const char *target, char *args)
1349 char *cur;
1350 long dice = 1, sides = 20;
1351 if ((cur = token(&args, ' '))) {
1352 char *first = cur;
1353 dice = strtol(first, &cur, 10);
1354 if (first == cur)
1355 dice = 1;
1356 if (*cur && *cur != 'd' && *cur != 'D')
1357 goto syntax;
1359 if (*cur) {
1360 char *last = cur+1;
1361 sides = strtol(last, &cur, 10);
1362 if (last == cur)
1363 goto syntax;
1366 if (dice <= 0 || dice > 10 || sides < 2 || sides > 20)
1367 goto syntax;
1368 perform_roll(b, nick, target, sides, dice, 0);
1369 return;
1371 syntax:
1372 action(b, target, "bleeps at %s in a confused manner", nick);
1375 static void add_g(struct bio *b, const char *target, int g)
1377 int ret = 0;
1378 int64_t total_g = 0;
1379 TDB_DATA chan, res;
1381 if (!chan_db || target[0] != '#')
1382 return;
1384 chan.dptr = (char*)target;
1385 chan.dsize = strlen(chan.dptr)+1;
1386 res = tdb_fetch(chan_db, chan);
1387 if (res.dptr && res.dsize >= 16) {
1388 ((int64_t*)res.dptr)[1] += g;
1389 if (res.dsize >= 24)
1390 total_g = ((int64_t*)res.dptr)[2] += g;
1391 ret = tdb_store(chan_db, chan, res, 0);
1393 free(res.dptr);
1394 if (ret < 0)
1395 fprintf(stderr, "updating database: %s", tdb_errorstr(feed_db));
1396 else if (g < total_g) {
1397 int64_t last_g = total_g - g;
1398 last_g -= last_g % 1000;
1399 if (last_g + 1000 <= total_g)
1400 privmsg(b, target, "g has been said %"PRIi64" times!", total_g);
1404 static int parse_g(const char *cur, int *g)
1406 int this_g = 0;
1407 for (const unsigned char *ptr = cur; *ptr; ptr++) {
1408 if (*ptr >= 0x80)
1409 return 0;
1410 if (*ptr == 'g' || *ptr == 'G')
1411 this_g++;
1412 else if ((*ptr >= 'a' && *ptr <= 'z') || (*ptr >= 'A' && *ptr <= 'Z'))
1413 return 0;
1414 else if (*ptr != '1' && *ptr >= '0' && *ptr <= '9')
1415 return 0;
1417 *g += this_g;
1418 return this_g;
1421 static void channel_msg(struct bio *b, const char *nick, const char *host,
1422 const char *chan, char *msg, int64_t t)
1424 char *cur = NULL, *next;
1425 int is_action = 0;
1426 int g = 0;
1428 int that = 0, what = 0, she = 0;
1430 if (!msg || !strcmp(nick, "`Daring_Do`") ||
1431 !strcmp(nick, "derpy") || !strcmp(nick, "derpy2") || !strcmp(nick, "`Derpy`") ||
1432 !strcmp(nick, "`Luna`") || !strcmp(nick, "`Celestia`") || !sstrncmp(nick, "GitHub") ||
1433 !sstrncmp(nick, "CIA-") || !sstrncmp(nick, "Terminus") || !strcmp(nick, "r0m"))
1434 return;
1436 if (!sstrncasecmp(msg, "\001ACTION ")) {
1437 msg += sizeof("\001ACTION ")-1;
1438 is_action = 1;
1439 asprintf(&cur, "%"PRIi64 ",in %s: * %s %s", t, chan, nick, msg);
1440 } else
1441 asprintf(&cur, "%"PRIi64 ",in %s: <%s> %s", t, chan, nick, msg);
1442 if (t > 0)
1443 update_seen(b, cur, nick);
1444 free(cur);
1445 (void)is_action;
1447 next = msg;
1448 while ((cur = token(&next, ' '))) {
1449 if (!strcasecmp(cur, ">mfw") || !strcasecmp(cur, "mfw")) {
1450 if (!strcasecmp(chan, "#brony") || !ponify)
1451 continue;
1452 if (t < 0 || t > commands[strhash("mfw") % elements(commands)].disabled_until)
1453 command_mfw(b, nick, host, chan, NULL);
1454 return;
1455 } else if (!sstrncasecmp(cur, "http://") || !sstrncasecmp(cur, "https://")) {
1456 static char last_url[512];
1457 char *part;
1458 if (!strcmp(cur, last_url))
1459 return;
1460 strncpy(last_url, cur, sizeof(last_url)-1);
1462 if (!sstrncmp(nick, "EqBot"))
1463 return;
1465 if (t >= 0 && t < commands[strhash("get") % elements(commands)].disabled_until)
1466 return;
1468 else if (strcasestr(cur, "youtube.com/user") && (part = strstr(cur, "#p/"))) {
1469 char *foo;
1470 part = strrchr(part, '/') + 1;
1471 asprintf(&foo, "http://youtube.com/watch?v=%s", part);
1472 if (foo)
1473 internal_link(b, nick, host, chan, foo, 0);
1474 free(foo);
1475 return;
1476 } else if (strcasestr(cur, "twitter.com/") || strcasestr(cur, "mlfw.info") || strcasestr(cur, "mylittlefacewhen.com") || !strcasecmp(chan, "#geek"))
1477 return;
1478 internal_link(b, nick, host, chan, cur, 0);
1479 return;
1481 else if (!sstrncasecmp(cur, "that") || !sstrncasecmp(cur, "dat"))
1482 that = 1;
1483 else if (that && (!sstrncasecmp(cur, "what") || !sstrncasecmp(cur, "wat")))
1484 what = 1;
1485 else if (what && !sstrncasecmp(cur, "she"))
1486 she = 1;
1487 else if (she && !sstrncasecmp(cur, "said")) {
1488 if (t <= 0 || t >= commands[strhash("shesaid") % elements(commands)].disabled_until)
1489 privmsg(b, chan, "%s: \"%s\"", nick, women_quotes[getrand() % elements(women_quotes)]);
1490 return;
1491 } else if (parse_g(cur, &g))
1492 continue;
1494 if (g)
1495 add_g(b, chan, g);
1498 static struct command_hash unhashed[] = {
1499 { "1", command_coinflip },
1500 { "fabric", command_fabric },
1501 { "get", command_get },
1502 { "hug", command_hug },
1503 { "hugs", command_hugs },
1504 { "admire", command_admire },
1505 { "snug", command_snuggle },
1506 { "snugs", command_snuggles },
1507 { "snuggle", command_snuggle },
1508 { "snuggles", command_snuggles },
1509 { "cuddle", command_cuddle },
1510 { "cuddles", command_cuddles },
1511 { "cookie", command_cookie },
1512 { "mfw", command_mfw },
1513 { "swear", command_swear },
1514 { "mail", command_mail },
1515 { "seen", command_seen },
1516 { "derpy", command_derpy },
1517 { "g", command_g },
1518 { "shesaid", command_shesaid },
1519 { "roll", command_roll },
1521 { "rebuild", command_rebuild, 1 },
1522 { "abort", command_abort, 1 },
1523 { "crash", command_crash, 1 },
1524 { "inspect", command_inspect, 1 },
1525 { "timeout", command_timeout, 1 },
1527 { "follow", command_follow },
1528 { "unfollow", command_unfollow },
1529 { "feeds", command_feeds },
1531 // DEBUG
1532 { "feed_get", command_feed_get, 1 },
1533 { "feed_set", command_feed_set, 1 },
1534 { "feed_rem", command_feed_rem, 1 },
1535 { "feed_xxx", command_feed_xxx, 1 },
1536 { "feed_counter", command_feed_counter, 1 },
1537 { "seen_xxx", command_seen_xxx, 1 },
1538 { "mailbag", command_mailbag },
1539 { "mailread", command_mailread, 1 },
1540 { "\"deliver\"", command_no_deliver, 1 },
1543 static void init_hash(struct bio *b, const char *target)
1545 int i;
1546 for (i = 0; i < elements(unhashed); ++i) {
1547 unsigned h = strhash(unhashed[i].string) % elements(commands);
1548 if (commands[h].string)
1549 privmsg(b, target, "%s is a duplicate command with %s", commands[h].string, unhashed[i].string);
1550 else
1551 commands[h] = unhashed[i];
1553 #ifdef local_commands
1554 for (i = 0; i < elements(local_commands); ++i) {
1555 unsigned h = strhash(local_commands[i].string) % elements(commands);
1556 if (commands[h].string)
1557 privmsg(b, target, "%s is a duplicate command with %s", commands[h].string, local_commands[i].string);
1558 else
1559 commands[h] = local_commands[i];
1561 #endif
1564 void init_hook(struct bio *b, const char *target, const char *nick, unsigned is_ponified)
1566 char *cwd, *path = NULL;
1567 nick_self = nick;
1568 static const char *messages[] = {
1569 "feels circuits being activated that weren't before",
1570 "suddenly gets a better feel of her surroundings",
1571 "looks the same, yet there's definitely something different",
1572 "emits a beep as her lights begin to pulse slowly",
1573 "whirrrs and bleeps like never before",
1574 "bleeps a few times happily",
1575 "excitedly peeks at her surroundings"
1577 init_hash(b, target);
1578 ponify = is_ponified;
1580 cwd = getcwd(NULL, 0);
1581 asprintf(&path, "%s/db/feed.tdb", cwd);
1582 feed_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1583 free(path);
1584 if (!feed_db)
1585 privmsg(b, target, "Opening feed db failed: %m");
1587 asprintf(&path, "%s/db/chan.tdb", cwd);
1588 chan_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1589 free(path);
1590 if (!chan_db)
1591 privmsg(b, target, "Opening chan db failed: %m");
1593 asprintf(&path, "%s/db/mail.tdb", cwd);
1594 mail_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1595 free(path);
1596 if (!mail_db)
1597 privmsg(b, target, "Opening mail db failed: %m");
1599 asprintf(&path, "%s/db/seen.tdb", cwd);
1600 seen_db = tdb_open(path, 0, 0, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
1601 free(path);
1602 if (!seen_db)
1603 privmsg(b, target, "Opening seen db failed: %m");
1605 free(cwd);
1606 action(b, target, "%s", messages[getrand() % elements(messages)]);
1609 static void __attribute__((destructor)) shutdown_hook(void)
1611 if (seen_db)
1612 tdb_close(seen_db);
1613 if (mail_db)
1614 tdb_close(mail_db);
1615 if (feed_db)
1616 tdb_close(feed_db);
1617 if (chan_db)
1618 tdb_close(chan_db);
1621 static char *nom_special(char *line)
1623 while (*line) {
1624 if (*line == 0x03) {
1625 line++;
1626 if (*line >= '0' && *line <= '9')
1627 line++;
1628 else continue;
1629 if (*line >= '0' && *line <= '9')
1630 line++;
1631 if (line[0] == ',' && line[1] >= '0' && line[1] <= '9')
1632 line += 2;
1633 else continue;
1634 if (*line >= '0' && *line <= '9')
1635 line++;
1636 } else if (*line != 0x02 && /* BOLD */
1637 *line != 0x1f && /* UNDERLINE */
1638 *line != 0x16 && /* ITALIC */
1639 *line != 0x06 && /* NFI, is this even used? */
1640 *line != 0x07 && /* NFI, is this even used? */
1641 *line != 0x0f) /* NORMAL */
1642 return line;
1643 else
1644 line++;
1646 return line;
1649 static char *cleanup_special(char *line)
1651 char *cur, *start = nom_special(line);
1652 if (!*start)
1653 return NULL;
1654 for (line = cur = start; *line; line = nom_special(line))
1655 *(cur++) = *(line++);
1657 for (cur--; cur >= start; --cur)
1658 if (*cur != ' ' && *cur != '\001')
1659 break;
1661 if (cur < start)
1662 return NULL;
1663 cur[1] = 0;
1664 return start;
1667 static void rss_check(struct bio *b, const char *channel, int64_t t)
1669 static unsigned rss_enter, rss_leave;
1670 if (t >= 0 && rss_enter == rss_leave) {
1671 rss_enter++;
1672 channel_feed_check(b, channel, t);
1673 rss_leave++;
1677 static const char *privileged_command[] = {
1678 "{ Rarity, I love you so much! }",
1679 "{ Rarity, have I ever told you that I love you? }",
1680 "{ Yes, I love my sister, Rarity. }",
1681 "{ Raaaaaaaaaaaaaarity. }",
1682 "{ You do not fool me, Rari...bot! }"
1685 static int cmd_check(struct bio *b, struct command_hash *c, int is_admin, int64_t t, const char *prefix, const char *target)
1687 if (c->left != c->enter)
1688 privmsg(b, target, "Command %s is disabled because of a crash", c->string);
1689 else if (t > 0 && t < c->disabled_until && !is_admin) {
1690 int64_t delta = c->disabled_until - t;
1691 const char *str = perty(&delta);
1692 b->writeline(b, "NOTICE %s :Command %s is on timeout for the next %"PRIi64 " %s", prefix, c->string, delta, str);
1693 } else if (c->admin && !is_admin)
1694 privmsg(b, target, "%s: %s", prefix, privileged_command[getrand() % elements(privileged_command)]);
1695 else
1696 return 1;
1697 return 0;
1700 void privmsg_hook(struct bio *b, const char *prefix, const char *ident, const char *host,
1701 const char *const *args, unsigned nargs)
1703 char *cmd_args, *cmd;
1704 const char *target = args[0][0] == '#' ? args[0] : prefix;
1705 unsigned chan, nick_len;
1706 struct command_hash *c;
1707 int64_t t = get_time(b, target);
1708 int is_admin = admin(host);
1710 chan = args[0][0] == '#';
1711 if (chan) {
1712 rss_check(b, args[0], t);
1713 command_deliver(b, prefix, args[0]);
1715 cmd_args = cleanup_special((char*)args[1]);
1716 if (!cmd_args)
1717 return;
1719 if (ident && (!strcasecmp(ident, "Revolver") || !strcasecmp(ident, "Rev")))
1720 return;
1722 if (chan && cmd_args[0] == '!') {
1723 cmd_args++;
1724 } else if (chan && (nick_len = strlen(nick_self)) &&
1725 !strncasecmp(cmd_args, nick_self, nick_len) &&
1726 (cmd_args[nick_len] == ':' || cmd_args[nick_len] == ',') && cmd_args[nick_len+1] == ' ') {
1727 cmd_args += nick_len + 2;
1728 if (!cmd_args[0])
1729 return;
1730 chan = 2;
1731 } else if (chan) {
1732 if (command_channel.enter == command_channel.left) {
1733 command_channel.enter++;
1734 snprintf(command_channel.failed_command,
1735 sizeof(command_channel) - offsetof(struct command_hash, failed_command) - 1,
1736 "%s:%s (%s@%s) \"#\" %s", target, prefix, ident, host, cmd_args);
1737 channel_msg(b, prefix, host, args[0], cmd_args, t);
1738 command_channel.left++;
1740 return;
1742 cmd = token(&cmd_args, ' ');
1743 if (!chan && cmd_args && cmd_args[0] == '#') {
1744 if (!is_admin) {
1745 privmsg(b, target, "%s: %s", prefix, privileged_command[getrand() % elements(privileged_command)]);
1746 return;
1748 target = token(&cmd_args, ' ');
1751 c = &commands[strhash(cmd) % elements(commands)];
1752 if (c->string && !strcasecmp(c->string, cmd)) {
1753 if (cmd_check(b, c, is_admin, t, prefix, target)) {
1754 c->enter++;
1755 snprintf(c->failed_command, sizeof(*c) - offsetof(struct command_hash, failed_command) - 1,
1756 "%s:%s (%s@%s) \"%s\" %s", target, prefix, ident, host, cmd, cmd_args);
1757 c->cmd(b, prefix, host, target, cmd_args);
1758 c->left++;
1760 return;
1761 } else if (cmd[0] == 'd' && cmd[1] >= '0' && cmd[1] <= '9') {
1762 char *end;
1763 long base;
1764 base = strtol(cmd+1, &end, 10);
1765 if (base > 1 && base <= 20 && !*end) {
1766 long dice = 1, bonus = 0;
1767 char *strdice;
1768 c = &commands[strhash("roll") % elements(commands)];
1769 if (!cmd_check(b, c, is_admin, t, prefix, target))
1770 return;
1771 c->enter++;
1772 snprintf(c->failed_command, sizeof(*c) - offsetof(struct command_hash, failed_command) - 1,
1773 "%s:%s (%s@%s) \"%s\" %s", target, prefix, ident, host, cmd, cmd_args);
1775 strdice = token(&cmd_args, ' ');
1776 if (strdice) {
1777 dice = strtol(strdice, &end, 10);
1778 if (*end || !dice || dice > 10)
1779 goto syntax;
1780 strdice = token(&cmd_args, ' ');
1781 if (strdice) {
1782 bonus = strtol(strdice, &end, 10);
1783 if (*end || bonus > 1000 || bonus < -1000)
1784 goto syntax;
1787 perform_roll(b, prefix, target, base, dice, bonus);
1788 c->left++;
1789 return;
1791 syntax:
1792 c->left++;
1793 action(b, target, "bleeps at %s in a confused manner", prefix);
1794 return;
1797 if (chan == 2 && t > 0) {
1798 static int64_t last_t;
1799 if (t - last_t > 3)
1800 privmsg(b, target, "%s: { I love you! }", prefix);
1801 last_t = t;
1805 void command_hook(struct bio *b, const char *prefix, const char *ident, const char *host,
1806 const char *command, const char *const *args, unsigned nargs)
1808 char *buf = NULL;
1809 int64_t t = -1;
1810 if (!strcasecmp(command, "NOTICE")) {
1811 if (nargs < 2 || args[0][0] == '#')
1812 return;
1813 if (admin(host))
1814 b->writeline(b, "%s", args[1]);
1815 else
1816 fprintf(stderr, "%s: %s\n", prefix, args[1]);
1817 } else if (!strcasecmp(command, "JOIN")) {
1818 t = get_time(b, args[0]);
1819 rss_check(b, args[0], t);
1820 command_deliver(b, prefix, args[0]);
1821 asprintf(&buf, "%"PRIi64",joining %s", t, args[0]);
1822 } else if (!strcasecmp(command, "PART")) {
1823 t = get_time(b, args[0]);
1824 rss_check(b, args[0], t);
1825 asprintf(&buf, "%"PRIi64",leaving %s", t, args[0]);
1826 } else if (!strcasecmp(command, "QUIT")) {
1827 t = get_time(b, NULL);
1828 asprintf(&buf, "%"PRIi64",quitting with the message \"%s\"", t, args[0]);
1829 } else if (!strcasecmp(command, "NICK")) {
1830 t = get_time(b, NULL);
1831 if (t >= 0) {
1832 asprintf(&buf, "%"PRIi64",changing nick from %s", t, prefix);
1833 if (buf)
1834 update_seen(b, buf, args[0]);
1835 free(buf);
1836 buf = NULL;
1838 asprintf(&buf, "%"PRIi64",changing nick to %s", t, args[0]);
1839 } else if (0) {
1840 int i;
1841 fprintf(stderr, ":%s!%s%s %s", prefix, ident, host, command);
1842 for (i = 0; i < nargs; ++i)
1843 fprintf(stderr, " %s", args[i]);
1844 fprintf(stderr, "\n");
1846 if (t >= 0 && buf)
1847 update_seen(b, buf, prefix);
1848 free(buf);
1849 return;