ref: 889af18831aba0673a2456f05a1987b972d22df6
dir: /main.c/
/*
* This work is dedicated to the public domain.
* See COPYING file for more information.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <time.h>
#include <unistd.h>
#include <picoev.h>
#include "htable.h"
#include "util.c"
#define BUFFER_LEN 1024
#define NICK_LEN 16
#define EVENT_ADDEND 10000
#define NET_ADDEND 10
#define USER_ADDEND 100
#define EVENT_TIMEOUT 10000
#define FIFO_TIMEOUT 5
#define EVENT_FREQUENCY 5
#define UNUSED(x) (void)(x)
struct network {
int id; /* event index */
int join; /* is joined */
char *name; /* name */
char *symb; /* symbol */
char *host; /* hostname */
char *port; /* port */
char *chan; /* channel */
};
struct event {
int fd; /* event fd */
int netid; /* net index */
char *user; /* user nick */
int suffix; /* suffix count */
};
static struct event *events; /* events array */
static int evlen; /* array length */
static int evcap; /* array capacity */
static struct network *networks; /* networks array */
static int netlen; /* array length */
static int netcap; /* array capacity */
/*
* hash table of users
* key -> <user_nick> + '[' + <network_symbol> + ']'
* value -> array of all user's clones event ids indexed
* corresponding to its connected network
*/
static struct Htable *users;
static char msg [BUFFER_LEN];
static int done;
/* functions prototype */
void fifo_event_cb(picoev_loop *, int, int, void *);
void server_event_cb(picoev_loop *, int, int, void *);
void net_add(picoev_loop *, char *, char *, char *, char *, char *);
void net_del(picoev_loop *, char *);
void net_del_raw(int);
void net_update(picoev_loop *, int);
void user_add(picoev_loop *, char *, int);
void user_del(picoev_loop *, char *, char *);
int *user_get_ids(char *);
int *clone_get_user_ids(char *, int);
int clone_add(picoev_loop *, char *, int);
int event_add(picoev_loop *, int, int, char *);
void event_del(picoev_loop *, int);
void nick_add_symb(char *, int);
void privmsg_update(char *, char *, int);
void clean_exit(picoev_loop *, int);
void print_table(void);
void print_htable(void);
void print_users(void);
void print_border(void);
int
main(int argc, char *argv[])
{
picoev_loop *loop;
int fd;
/* set stdout to unbufferd */
setvbuf(stdout, NULL, _IONBF, 0);
/* check arguments */
if (argc != 2) {
printf("usage: %s <fifo>\n", argv[0]);
return 1;
}
/* init global variables */
evcap = EVENT_ADDEND;
netcap = NET_ADDEND;
events = ecalloc((size_t)evcap, sizeof(struct event));
networks = ecalloc((size_t)netcap, sizeof(struct network));
users = htcreate((KeyLenFn *)strlen, (KeyCmpFn *)strcmp, free, free, USER_ADDEND);
/* init picoev */
picoev_init(1000);
/* create loop */
loop = picoev_create_loop(60);
/* get fifo fd */
fd = fifo_open(argv[1]);
/* add fifo fd */
picoev_add(loop, fd, PICOEV_READ, FIFO_TIMEOUT, fifo_event_cb, argv[1]);
/* loop */
while (!done)
picoev_loop_once(loop, 10);
/* clean and exit */
clean_exit(loop, 0);
return 0;
}
void
fifo_event_cb(picoev_loop *loop, int fd, int revents, void *cb_arg)
{
char buffer[BUFFER_LEN];
char *buf;
char *cmd;
ssize_t n;
int i, count = 0;
Htiter it = {0};
if ((revents & PICOEV_TIMEOUT) != 0) {
printf("TIME to add %d more connections\n", EVENT_FREQUENCY);
while (htiterate(users, &it)) {
for (i = 0; i < netlen; i++) {
if (((int *)it.node->val)[i] == 0) {
((int *)it.node->val)[i] = clone_add(loop, it.node->key, i);
count++;
if (count >= 10)
goto return_time;
}
}
}
return_time:
picoev_del(loop, fd);
close(fd);
fd = fifo_open((char *)cb_arg);
picoev_add(loop, fd, PICOEV_READ, FIFO_TIMEOUT, fifo_event_cb, cb_arg);
return;
}
n = readline(fd, buffer, sizeof(buffer));
if (n == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
return;
printf("error: %d: read: %s\n", fd, strerror(errno));
clean_exit(loop, 1);
} else if (n == 0) { /* reopen fifo again */
picoev_del(loop, fd);
close(fd);
fd = fifo_open((char *)cb_arg);
picoev_add(loop, fd, PICOEV_READ, FIFO_TIMEOUT, fifo_event_cb, cb_arg);
return;
}
buf = buffer;
cmd = split(&buf, ' ');
if (strcmp(cmd, "netadd") == 0) {
char *name = split(&buf, ' ');
char *symb = split(&buf, ' ');
char *host = split(&buf, ' ');
char *port = split(&buf, ' ');
char *chan = buf;
if (!*name || !*symb || !*host || !*port || !*chan)
printf("usage: netadd <name> <symbol> <hostname> <port> <channel>\n");
else
net_add(loop, name, symb, host, port, chan);
} else if (strcmp(cmd, "netdel") == 0) {
char *name = buf;
if (!*name)
printf("usage: netdel <name>\n");
else
net_del(loop, name);
} else if (strcmp(cmd, "print") == 0) {
print_table();
} else if (strcmp(cmd, "htable") == 0) {
print_htable();
} else if (strcmp(cmd, "users") == 0) {
print_users();
} else if (strcmp(cmd, "exit") == 0) {
done = 1;
} else {
printf("error: %s is not a command\n", cmd);
}
}
void
server_event_cb(picoev_loop *loop, int fd, int revents, void *cb_arg)
{
char buffer [BUFFER_LEN];
char backup [BUFFER_LEN];
char lnick [NICK_LEN]; /* linker nick */
char *buf;
char *cmd;
char *nick;
int i, id, netid;
ssize_t n;
id = (int)((struct event *)cb_arg - events);
netid = events[id].netid;
if ((revents & PICOEV_WRITE) != 0) {
if (events[id].user == NULL) { /* linker */
snprintf(msg, sizeof(msg), "NICK linker\r\n");
writeall(fd, msg);
snprintf(msg, sizeof(msg), "USER linker 0 * :linker\r\n");
writeall(fd, msg);
} else { /* user */
snprintf(msg, sizeof(msg), "NICK %s\r\n", events[id].user);
writeall(fd, msg);
snprintf(msg, sizeof(msg), "USER user 0 * :user\r\n");
writeall(fd, msg);
}
picoev_set_events(loop, fd, PICOEV_READ);
}
n = readline(fd, buffer, sizeof(buffer));
if (n == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
return;
printf("error: read: %d: %s\n", fd, strerror(errno));
event_del(loop, id);
} else if (n == 0) { /* reopen fifo again */
printf("error: closed: %d\n", fd);
event_del(loop, id);
}
/* remove CRLFs */
for (i = 0; i < (int)strlen(buffer); i++) {
if (buffer[i] == '\r' || buffer[i] == '\n') {
buffer[i] = '\0';
break;
}
}
/* clone the buffer */
strcpy(backup, buffer);
buf = buffer;
/* set linker nick */
strcpy(lnick, "linker");
for (i = 0; i < events[id].suffix; i++)
strcat(lnick, "_");
/* first column */
cmd = split(&buf, ' ');
if (strcmp(cmd, "NOTICE") == 0) {
return;
} else if (strcmp(cmd, "ERROR") == 0) {
goto printbuffer;
} else if (strcmp(cmd, "PING") == 0) {
snprintf(msg, sizeof(msg), "PONG %s\r\n", buf);
writeall(fd, msg);
return;
}
/* strip nick from first column */
nick = split(&cmd, '!');
if (nick[0] == ':')
nick++;
/* second column */
cmd = split(&buf, ' ');
/* ignore all the info messages */
if ((strcmp(cmd, "002") == 0)
|| (strcmp(cmd, "003") == 0)
|| (strcmp(cmd, "004") == 0)
|| (strcmp(cmd, "005") == 0)
|| (strcmp(cmd, "003") == 0)
|| (strcmp(cmd, "251") == 0)
|| (strcmp(cmd, "252") == 0)
|| (strcmp(cmd, "253") == 0) /* unknown connection(s) */
|| (strcmp(cmd, "254") == 0)
|| (strcmp(cmd, "255") == 0)
|| (strcmp(cmd, "265") == 0)
|| (strcmp(cmd, "266") == 0)
|| (strcmp(cmd, "250") == 0)
|| (strcmp(cmd, "375") == 0)
|| (strcmp(cmd, "372") == 0)
|| (strcmp(cmd, "376") == 0)
|| (strcmp(cmd, "396") == 0)
|| (strcmp(cmd, "366") == 0)
|| (strcmp(cmd, "MODE") == 0)
|| (strcmp(cmd, "NOTICE") == 0)) {
return;
} else if (strcmp(cmd, "433") == 0) { /* Nickname already in use */
split(&buf, ' ');
nick = split(&buf, ' ');
if (strlen(nick)+1 > NICK_LEN) {
printf("error: cannot append suffix, nick '%s' is too big\n", nick);
if (strcmp(nick, lnick) == 0) {
net_del(loop, networks[netid].name);
} else {
snprintf(msg, sizeof(msg), "QUIT :nick is too big\r\n");
user_del(loop, nick, msg);
}
} else {
strcat(nick, "_");
events[id].suffix++;
snprintf(msg, sizeof(msg), "NICK %s\r\n", nick);
writeall(fd, msg);
}
return;
} else if (strcmp(cmd, "001") == 0) {
snprintf(msg, sizeof(msg), "JOIN %s\r\n", networks[netid].chan);
writeall(fd, msg);
return;
} else if (strcmp(cmd, "PRIVMSG") == 0) {
char privmsg[BUFFER_LEN] = "";
int *ids;
if (events[id].user == NULL) { /* if linker */
nick_add_symb(nick, netid);
if ((ids = htsearch(users, nick)) == NULL)
return;
split(&buf, ':'); /* set buf to msg */
privmsg_update(privmsg, buf, netid);
for (i = 0; i < netlen; i++) {
if (ids[i] > 0) {
snprintf(msg, sizeof(msg), "PRIVMSG %s :%s\r\n", networks[i].chan, privmsg);
writeall(events[ids[i]].fd, msg);
}
}
} else {
char *netsymb;
char *user = split(&buf, ' ');
/* ignore messages from channel (it is handled by linker) */
if ((user[0] == '#') || (user[0] == '&'))
return;
nick_add_symb(nick, netid);
if ((ids = htsearch(users, nick)) == NULL)
return;
/* split user nick and network symbol */
*strrchr(user, ']') = '\0';
netsymb = strrchr(user, '[');
*netsymb++ = '\0';
/* get the network index */
for (i = 0; i < netlen; i++) {
if (strcmp(netsymb, networks[i].symb) == 0)
break;
}
split(&buf, ':'); /* set buf to msg */
privmsg_update(privmsg, buf, netid);
snprintf(msg, sizeof(msg), "PRIVMSG %s :%s\r\n", user, privmsg);
writeall(events[ids[i]].fd, msg);
}
return;
}
/* these messages are handled by linker */
if (events[id].user != NULL) { /* if clone */
if ((strcmp(cmd, "353") == 0)
|| (strcmp(cmd, "JOIN") == 0)
|| (strcmp(cmd, "QUIT") == 0)
|| (strcmp(cmd, "PART") == 0)
|| (strcmp(cmd, "KICK") == 0)
|| (strcmp(cmd, "NICK") == 0))
return;
} else if (strcmp(cmd, "353") == 0) {
char *nick;
split(&buf, ':');
networks[netid].join = 1;
/* net_update(loop, netid); */
while (*(nick = split(&buf, ' ')) != '\0') {
if (*nick == '@'
|| *nick == '&'
|| *nick == '~'
|| *nick == '%'
|| *nick == '+'
|| *nick == '\\')
nick++;
if (strcmp(nick, lnick) != 0)
user_add(loop, nick, netid);
}
return;
} else if (strcmp(cmd, "JOIN") == 0) {
if ((strcmp(nick, lnick) != 0)
&& (clone_get_user_ids(nick, netid) == NULL)) /* if not clone */
user_add(loop, nick, netid);
return;
} else if ((strcmp(cmd, "QUIT") == 0)
|| (strcmp(cmd, "PART") == 0)) {
snprintf(msg, sizeof(msg), "QUIT :%s\r\n", buf);
nick_add_symb(nick, netid);
if (htsearch(users, nick) != NULL)
user_del(loop, nick, msg);
return;
} else if (strcmp(cmd, "NICK") == 0) {
int *ids, i;
char *newnick;
nick_add_symb(nick, netid);
if ((ids = htsearch(users, nick)) == NULL)
return;
/* set buf to new nick */
split(&buf, ':');
/* allocate a newnick and append the netsym and then replace the old */
newnick = ecalloc(strlen(buf) + strlen(networks[netid].symb) + 2 + 1, sizeof(char));
sprintf(newnick, "%s[%s]", buf, networks[netid].symb);
htsetkey(users, nick, newnick);
snprintf(msg, sizeof(msg), "NICK %s\r\n", newnick);
for (i = 0; i < netlen; i++) {
if (ids[i] > 0)
writeall(events[ids[i]].fd, msg);
}
return;
} else if (strcmp(cmd, "KICK") == 0) {
/* :<nick_which_is_kicking>!~user@host KICK <channel> <nick_which_has_been_kicked> :<kick_msg> */
int *ids;
char *chan = split(&buf, ' ');
char *user = split(&buf, ' ');
/* set the quit msg */
snprintf(msg, sizeof(msg), "QUIT : kicked by %s\r\n", nick);
/* delete whole network if it is the linker */
if (strcmp(user, lnick) == 0) {
net_del(loop, networks[netid].name);
return;
}
/* delete the user if the message from the same network */
if ((ids = clone_get_user_ids(user, netid)) == NULL) {
nick_add_symb(user, netid);
user_del(loop, user, msg);
return;
}
/* close the kicked fd */
writeall(fd, msg);
event_del(loop, id);
/*
* send notice in the channel through linker
*/
/* get the original user netid */
for (i = 0; i < netlen; i++) {
if (ids[i] == -1)
break;
}
/* set buf to msg */
split(&buf, ':');
/* remove netsymb and suffix */
*strrchr(user, '[') = '\0';
/* send notice */
snprintf(msg, sizeof(msg),
"PRIVMSG %s :%s was kicked out by %s from network %s %s [%s]\r\n",
networks[i].chan, user, nick, networks[netid].name, chan, buf);
writeall(events[networks[i].id].fd, msg);
return;
}
printbuffer:
printf("%d: %s\n", fd, backup);
}
void
net_add(picoev_loop *loop, char *name, char *symb, char *host, char *port, char *chan)
{
int i, fd;
struct network *n;
/* if name, symbol or configuration already exists */
for (i = 0; i < netlen; i++) {
if (strcmp(networks[i].name, name) == 0) {
printf("error: network name '%s' already exists\n", name);
return;
}
if (strcmp(networks[i].symb, symb) == 0) {
printf("error: network symbol '%s' already exists\n", symb);
return;
}
if ((strcmp(networks[i].host, host) == 0)
&& (strcmp(networks[i].port, port) == 0)
&& (strcmp(networks[i].chan, chan) == 0)) {
printf("error: network configuration already exists\n");
return;
}
}
/* resize if full */
if (netlen == netcap) {
Htiter it = {0};
networks = erecalloc(networks, (size_t)netcap, NET_ADDEND, sizeof(struct network));
while (htiterate(users, &it))
it.node->val = erecalloc(it.node->val, (size_t)netcap, NET_ADDEND, sizeof(int));
netcap += NET_ADDEND;
}
/* connect */
if ((fd = dial(host, port)) == -1)
return;
/* add a network */
n = &networks[netlen];
n->id = event_add(loop, fd, netlen, NULL);
n->join = 0;
n->name = strdup(name);
n->symb = strdup(symb);
n->host = strdup(host);
n->port = strdup(port);
n->chan = strdup(chan);
netlen++;
printf("%d: network '%s' added\n", fd, name);
}
void
net_del(picoev_loop *loop, char *name)
{
int i, netid, *ids;
Htiter it = {0}; /* current iterator */
Htiter lastit = {0}; /* last iterator */
/* get netid */
netid = -1;
for (i = 0; i < netlen; i++) {
if (strcmp(name, networks[i].name) == 0) {
netid = i;
break;
}
}
if (netid == -1) {
printf("error: network '%s' doesn't exist\n", name);
return;
}
/* set the quit msg */
snprintf(msg, sizeof(msg), "QUIT :unlinking network %s\r\n", name);
/* reconstruct the user-clones table */
while (htiterate(users, &it)) {
ids = (int *)it.node->val;
/* delete all the users of deleting network */
if (ids[netid] == -1) {
user_del(loop, it.node->key, msg);
/* this node is deleted */
it = lastit;
/* delete the clones */
} else {
if (ids[netid] > 0) {
writeall(events[ids[netid]].fd, msg);
event_del(loop, ids[netid]);
}
/* swap last with current one */
ids[netid] = ids[netlen-1];
}
lastit = it;
}
/* set last netid of events to current netid. */
for (i = 0; i < evlen; i++) {
if (events[i].netid == netlen-1)
events[i].netid = netid;
}
writeall(events[networks[netid].id].fd, msg);
event_del(loop, networks[netid].id);
net_del_raw(netid);
printf("%d: network '%s' deleted\n", events[networks[netid].id].fd, name);
/* swap the network with the last */
networks[netid] = networks[netlen-1];
netlen--;
}
void
net_del_raw(int netid)
{
struct network *n = &networks[netid];
free(n->name);
free(n->symb);
free(n->host);
free(n->port);
free(n->chan);
}
void
net_update(picoev_loop *loop, int netid)
{
Htiter it = {0};
while (htiterate(users, &it))
((int *)it.node->val)[netid] = clone_add(loop, it.node->key, netid);
}
void
user_add(picoev_loop *loop, char *unick, int netid)
{
int i, *ids;
size_t len;
char *nick;
len = strlen(unick) + strlen(networks[netid].symb) + 2 + 1;
/* too long nick */
if (len - 1 > NICK_LEN) {
printf("error: user nick '%s' is too big\n", unick);
return;
}
/* resize hash table if storage is low */
if ((users->cap - users->len) < USER_ADDEND)
htresize(users, users->cap + USER_ADDEND);
printf("useradd: %s\n", unick);
/* allocate a new user */
nick = ecalloc(len, sizeof(char));
ids = ecalloc((size_t)netcap, sizeof(int));
sprintf(nick, "%s[%s]", unick, networks[netid].symb);
/* clone the user on all other network */
for (i = 0; i < netlen; i++) {
if (networks[i].join == 0)
continue;
if (i == netid) {
ids[i] = -1;
} else {
/* ids[i] = clone_add(loop, nick, i); */
}
}
/* insert it to the users hash table */
if (htinsert(users, nick, ids) == -1) {
/* this shouldn't happen as it was already checked */
printf("error: user '%s' already exists\n", nick);
clean_exit(loop, 1);
}
}
void
user_del(picoev_loop *loop, char *nick, char *msg)
{
int i;
int *ids = user_get_ids(nick);
for (i = 0; i < netlen; i++) {
if (ids[i] > 0) {
writeall(events[ids[i]].fd, msg);
event_del(loop, ids[i]);
}
}
htremove(users, nick);
}
int *
user_get_ids(char *user)
{
int *ids;
if ((ids = htsearch(users, user)) == NULL) {
printf("error: cannot find user '%s'\n", user);
exit(1);
}
return ids;
}
int *
clone_get_user_ids(char *nick, int netid)
{
unsigned int suffix;
int *ids = NULL;
/* count suffix */
for (suffix = 0; nick[strlen(nick)-suffix-1] == '_'; suffix++);
/* remove suffix */
if (suffix > 0)
nick[strlen(nick)-suffix] = '\0';
ids = htsearch(users, nick);
/* if match but suffix doesn't match */
if ((ids != NULL) && (events[ids[netid]].suffix != (int)suffix))
ids = NULL;
/* add suffix back */
if (suffix > 0)
nick[strlen(nick)] = '_';
return ids;
}
int
clone_add(picoev_loop *loop, char *nick, int netid)
{
int fd;
struct network *n = &networks[netid];
if ((fd = dial(n->host, n->port)) == -1)
return -1;
return event_add(loop, fd, netid, nick);
}
int
event_add(picoev_loop *loop, int fd, int netid, char *user)
{
int i = evlen;
if (evlen == evcap) {
events = erecalloc(events, (size_t)evcap, EVENT_ADDEND, sizeof(struct event));
evcap += EVENT_ADDEND;
}
events[i].fd = fd;
events[i].netid = netid;
events[i].user = user;
events[i].suffix = 0;
picoev_add(loop, fd, PICOEV_WRITE, 0, server_event_cb, &events[i]);
return evlen++;
}
void
event_del(picoev_loop *loop, int id)
{
int *ids;
int l = evlen - 1; /* last id */
/* swap id */
if (events[l].user == NULL) { /* if linker */
networks[events[l].netid].id = id;
} else { /* if user */
ids = user_get_ids(events[l].user);
ids[events[l].netid] = id;
}
/* disable id */
if (events[id].user == NULL) { /* if linker */
networks[events[id].netid].id = -2;
} else { /* if user */
ids = user_get_ids(events[id].user);
ids[events[id].netid] = -2;
}
picoev_del(loop, events[id].fd);
close(events[id].fd);
events[id] = events[l];
events[id] = events[l];
evlen--;
}
void
nick_add_symb(char *nick, int netid)
{
strcat(nick, "[");
strcat(nick, networks[netid].symb);
strcat(nick, "]");
}
/*
* trim all the nicknames to original nick
* src will be destructed
*/
void
privmsg_update(char *dst, char *src, int netid)
{
char d; /* delimiter */
char *n;
while (src != NULL) {
n = strpbrk(src, " :;,<>@&~%+\\");
if (n == NULL) {
d = '\0';
} else {
d = *n;
*n = '\0';
n++;
}
/* check if the word is nick */
if (clone_get_user_ids(src, netid) != NULL)
*strrchr(src, '[') = '\0';
strcat(dst, src);
strncat(dst, &d, 1);
src = n;
}
}
void
clean_exit(picoev_loop *loop, int status)
{
int i;
snprintf(msg, sizeof(msg), "QUIT :linker shutting down\r\n");
for (i = 0; i < evlen; i++) {
writeall(events[i].fd, msg);
event_del(loop, i);
}
picoev_destroy_loop(loop);
picoev_deinit();
/* delete all the users */
htdestroy(users);
/* delete all the networks */
for (i = 0; i < netlen; i++)
net_del_raw(i);
free(networks);
free(events);
if (status == 0) {
printf("exit successfully\n");
exit(0);
} else {
printf("aborted\n");
exit(1);
}
}
void
print_table(void)
{
int i, *ids, diff, tabs;
Htiter it = {0};
char *nick;
if (netlen == 0)
return;
print_border();
/* print networks */
printf("struct networks\t\t");
for (i = 0; i < netlen; i++)
printf("%s(%d)\t", networks[i].symb, events[networks[i].id].fd);
printf("\n");
while (htiterate(users, &it)) {
ids = (int *)it.node->val;
nick = (char *)it.node->key;
/* print tabbed user nick */
printf("%s", nick);
diff = 24 - (int)strlen(nick);
tabs = ((diff / 8) + (diff % 8 > 0));
printf("%.*s", tabs, "\t\t\t");
/* print tabbed clones ids */
for (i = 0; i < netlen; i++) {
printf("%d", ids[i]);
/* print suffix */
if ((ids[i] > 0) && (events[ids[i]].suffix > 0))
printf("(%d)", events[ids[i]].suffix);
printf("\t");
}
printf("\n");
}
print_border();
}
void
print_htable(void)
{
Htiter it = {0};
int index = -1;
print_border();
while (htiterate(users, &it)) {
if (index != (int)it.index) {
/* ignore first new line */
if (index != -1)
printf("\n");
printf("%d", it.index);
index = (int)it.index;
}
printf(" -> %s", (char *)it.node->key);
}
printf("\n");
print_border();
}
void
print_users(void)
{
Htiter it = {0};
int i = 0;
print_border();
while (htiterate(users, &it))
printf("%d: %s\n", i++, (char *)it.node->key);
print_border();
}
void
print_border(void)
{
int i;
for (i = 0; i < 64; i++)
printf("-");
printf("\n");
}