#include #include #include #include #include #include #include "irc.h" IRCC_client client; char *dir = "./"; char *ext = ".txt"; char *fmt = "[%s] %s"; char *host = "127.0.0.1"; char *nick = "historybot"; int port = 6667; int usessl = 0; void die(const char *msg) { fprintf(stderr, "history: %s\n", msg); IRCC_close(&client); exit(1); } void sig_handler(int sig) { fprintf(stderr, "history: recived signal: %d\n", sig); IRCC_close(&client); exit(0); } char *GetFilename(void) { time_t t = time(NULL); struct tm tm = *localtime(&t); size_t filename_size = strlen(client.irc_channel) + (sizeof(tm.tm_year) * 3) + strlen(ext) + 3; char *filename = malloc(filename_size + 1); if (filename == NULL) die("malloc failed"); snprintf(filename, filename_size, "%s_%d-%d-%d%s", client.irc_channel + 1, tm.tm_mday, tm.tm_mon, tm.tm_year, ext); return filename; } void WriteToFile(void) { if (client.irc_msg[1] == '.' || client.irc_channel[0] != '#') return; char *filename = GetFilename(); FILE *fp = fopen(filename, "a"); free(filename); if (fp == NULL) { fprintf(stderr, "history: cant open file: %s\n", client.irc_channel); return; } fprintf(fp, fmt, client.irc_nick, client.irc_msg); fprintf(fp, "\n"); fclose(fp); } int main(int argc, char **argv) { signal(SIGTERM, sig_handler); signal(SIGKILL, sig_handler); int opt; while ((opt = getopt(argc, argv, "h:p:d:n:f:e:t")) != -1) { switch (opt) { case 'h': host = optarg; break; case 'p': port = atoi(optarg); break; case 'd': dir = optarg; break; case 'n': nick = optarg; break; case 'e': ext = optarg; break; case 'f': fmt = optarg; break; case 't': usessl = 1; break; default: printf("history [hpdneft] [\"#channel,key\"]\n\t-t Use ssl\n\t-h HOST Default: %s\n\t-p PORT Default: %d\n\t-d DIR Log dir Default: %s\n\t-n NICK Default: %s\n\t-e EXT File extantion Default: %s\n\t-f FMT Text format Default: %s\n", host, port, dir, nick, ext, fmt); return 0; } } argv += optind; argc -= optind; if (chdir(dir)) die("Cant to change directory"); int status = IRCC_connect(&client, host, port); if (status == IRCC_ERROR) die("connection refused"); if (usessl) { int irc_errno = 0; if (IRCC_initssl(&client, &irc_errno) == IRCC_ERROR) die(IRCC_errno[irc_errno]); } //Register and skip motd if (IRCC_register(&client, nick) == IRCC_DISCONNECTED) die("disconnected"); sleep(5); //Join in channel for (int i = 0; i < argc; i++) { char *key = ""; char *channel = argv[i]; char *p = strchr(channel, ','); if (p != NULL) { p[0] = '\0'; key = p + 1; } IRCC_join(&client, channel, key); } //Recv while (1) { int irc_status = IRCC_recv(&client); if (irc_status == IRCC_DISCONNECTED) die("disconnected"); irc_status = IRCC_parse(&client); if (client.irc_nick != NULL && client.irc_channel != NULL && client.irc_msg != NULL && irc_status == IRCC_PRIVMSG) WriteToFile(); } }