#include "irc.h" #include "cfg.h" #include IRCC_client client; void die(char *msg) { puts(msg); IRCC_close(&client); exit(1); } struct tm GetTime(void) { time_t t = time(NULL); return *localtime(&t); } char *GetFilename(void) { //Get filename + date struct tm tm = GetTime(); size_t filename_size = strlen(client.channel + 1) + (sizeof(tm.tm_year) * 3) + strlen(EXT) + 3; char *filename = malloc(filename_size + 1); if (filename == NULL) die("malloc returned NULL"); snprintf(filename, filename_size, "%s-%d-%d-%d%s", client.channel + 1, tm.tm_year + 1900, tm.tm_mon, tm.tm_mday, EXT); return filename; } void WriteToFile(void) { if (client.msg[1] == '.' || client.channel[0] != '#') return; char *filename = GetFilename(); FILE *fp = fopen(filename, "a"); free(filename); if (fp == NULL) { printf("Cant open file %s\n", client.channel); return; } fprintf(fp, FORMAT, client.nick, client.msg + 1); fclose(fp); } void recvinfo(int ignore) { while (1) { unsigned int irc_status = IRCC_recv(&client); if (irc_status == IRCC_DISCONNECTED) { if (!ignore) die("Disconnected"); return; } else if (client.nick != NULL && client.channel != NULL && client.msg != NULL && irc_status == IRCC_PRIVMSG) WriteToFile(); else if (strstr(client.raw, "No Ident") || irc_status == IRCC_CONNECTED) return; } } int main(void) { if (chdir(DIR)) die("Cant chdir"); //512 - size of raw buffer (max irc) IRCC_init(&client, 512); int status = IRCC_connect(&client, HOST, PORT); if (status == IRCC_ERROR) die("Conn refused"); //Socket timeout struct timeval tv = {5, 5}; if (setsockopt(client.socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) die("setsockopt"); //Register recvinfo(1); IRCC_register(&client, NICK); //Recv motd and join in channel recvinfo(0); sleep(5); for (size_t i = 0; i < sizeof(channels) / sizeof(char *); i++) { if (channels[i] == NULL) break; size_t join_size = strlen("JOIN \r\n") + strlen(channels[i]) + 1; char *tmp = malloc(join_size); if (tmp == NULL) die("malloc retured NULL"); snprintf(tmp, join_size, "JOIN %s\r\n", channels[i]); send(client.socket, tmp, join_size, 0); free(tmp); } recvinfo(0); }