ref: e09ff804102de75826409b6043619d2668d9cef8
dir: /main.c/
/* * This work is dedicated to the public domain. * See COPYING file for more information. */ #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <poll.h> #include <time.h> #include <unistd.h> #include "htable.h" #include "util.c" #define BUFFER_LEN 1024 #define MAX_NICK_LEN 16 #define POLLFD_ADDEND 100 #define NET_ADDEND 10 #define USER_ADDEND 100 #define TIME_OUT 180 typedef struct { int id; /* fd of linker */ int join; /* is joined */ char *name; /* name */ char *symb; /* symbol */ char *host; /* hostname */ char *port; /* port */ char *chan; /* channel */ } Network; /* user defined data for each fd */ struct FdData { int netid; /* net index */ int suffix; /* suffix count */ char *user; /* user nick */ time_t time; }; static struct pollfd *fdset; /* pollfd set */ static struct FdData *fddata; /* user data set */ static int fdslen; /* fdset length */ static int fdscap; /* fdset capacity */ static Network *networks; /* linked list of networks */ static int netlen; /* current network length */ static int netcap; /* total memory allocated */ static Htable *users; /* users-clones hash table */ char msg[BUFFER_LEN]; static int isrunning = 1; /* functions prototype */ void handle_fifo_input(int, char *); void handle_server_output(int); void net_add(char *, char *, char *, char *, char *); void net_del(char *); void net_del_raw(int); void net_update(int); void user_add(char *, int); void user_del(char *, char *); int *user_ids(char *, int); int *euserids(char *); int clone_add(char *, int); int fdset_add(int, int, int, char *); void fdset_del(int); void nick_add_symb(char *, int); void privmsg_update(char *, char *, int); void terminate(int); void print_table(void); void print_htable(void); void print_users(void); void print_border(void); int main(int argc, char *argv[]) { int i, n, timeout_id; time_t last_time, timeout; /* 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 */ fdscap = POLLFD_ADDEND; fdset = ecalloc((size_t)fdscap, sizeof(struct pollfd)); fddata = ecalloc((size_t)fdscap, sizeof(struct FdData)); netcap = NET_ADDEND; networks = ecalloc((size_t)netcap, sizeof(Network)); /* * hash table of users * key -> <nickname> + '[' + <network_symbol> + ']' * value -> array of linked clones fds indexed * corresponding to its connected network */ users = htcreate((KeyLenFn *)strlen, (KeyCmpFn *)strcmp, free, free, USER_ADDEND); /* add fifo_fd */ fdset_add(fifo_open(argv[1]), -1, -1, NULL); /* select loop */ while (isrunning) { /* calculate timeout from fdset */ last_time = time(NULL); for (i = 0; i < fdslen; i++) { if ((fddata[i].netid != -1) /* ignore fifo */ && (fddata[i].time < last_time)) { last_time = fddata[i].time; timeout_id = i; } } timeout = TIME_OUT - (time(NULL) - last_time); if (timeout < 0) timeout = 0; n = poll(fdset, (nfds_t)fdslen, (int)timeout * 1000); if (n == -1) { printf("error: poll: %s\n", strerror(errno)); terminate(1); } else if (n == 0) { snprintf(msg, sizeof(msg), "PING :%s\r\n", networks[fddata[timeout_id].netid].host); writeall(fdset[timeout_id].fd, msg); fddata[timeout_id].time = time(NULL); continue; } for (i = 0; i < fdslen; i++) { if (!(fdset[i].revents & (POLLIN|POLLHUP))) continue; if (fddata[i].netid == -1) handle_fifo_input(i, argv[1]); else handle_server_output(i); fddata[i].time = time(NULL); /* * handle one ready fd at one time because if we * close upcoming ready fd, it cause infinite loop. */ break; } } terminate(0); return 0; } void handle_fifo_input(int id, char *path) { char buffer[BUFFER_LEN]; char *buf; char *cmd; ssize_t n; /* if failed to read data */ if ((n = readline(fdset[id].fd, buffer, sizeof(buffer))) < 1) { if (n == 0) { /* restart again */ fdset_del(id); fdset_add(fifo_open(path), -1, -1, NULL); } else if ((errno != EAGAIN) && (errno != EINTR)) { printf("error: %d: read: %s\n", fdset[id].fd, strerror(errno)); } return; } /* printf("fifo: %s\n", buffer); */ 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(name, symb, host, port, chan); } else if (strcmp(cmd, "netdel") == 0) { char *name = buf; if (!*name) printf("usage: netdel <name>\n"); else net_del(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) { isrunning = 0; } else { printf("error: %s is not a command\n", cmd); } } void handle_server_output(int id) { char buffer [BUFFER_LEN]; char backup [BUFFER_LEN]; char linker_nick [MAX_NICK_LEN]; char *buf; char *cmd; char *nick; int i, netid; ssize_t n; /* if failed to read data */ if ((n = readline(fdset[id].fd, buffer, sizeof(buffer))) < 1) { if (n == 0) { printf("error: %d: connection closed\n", fdset[id].fd); printf("ping: %d : %ld\n", fdset[id].fd, time(0) - fddata[id].time); terminate(1); /* fdset_del(fdset[id].fd); */ } else if ((errno != EAGAIN) && (errno != EINTR)) { printf("error: %d: read: %s\n", fdset[id].fd, strerror(errno)); printf("ping: %d : %ld\n", fdset[id].fd, time(0) - fddata[id].time); terminate(1); } return; } /* 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; netid = fddata[id].netid; /* set linker nick */ strcpy(linker_nick, "linker"); for (i = 0; i < fddata[id].suffix; i++) strcat(linker_nick, "_"); /* 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(fdset[id].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 > MAX_NICK_LEN) { printf("error: cannot append suffix, nick '%s' is too big\n", nick); if (strcmp(nick, linker_nick) == 0) { net_del(networks[netid].name); } else { snprintf(msg, sizeof(msg), "QUIT :nick is too big\r\n"); user_del(nick, msg); } } else { strcat(nick, "_"); fddata[id].suffix++; snprintf(msg, sizeof(msg), "NICK %s\r\n", nick); writeall(fdset[id].fd, msg); } return; } else if (strcmp(cmd, "001") == 0) { snprintf(msg, sizeof(msg), "JOIN %s\r\n", networks[netid].chan); writeall(fdset[id].fd, msg); return; } else if (strcmp(cmd, "PRIVMSG") == 0) { char privmsg[BUFFER_LEN] = ""; int *ids; if (fddata[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(fdset[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(fdset[ids[i]].fd, msg); } return; } /* these messages are handled by linker */ if (fddata[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(netid); while (*(nick = split(&buf, ' ')) != '\0') { if (*nick == '@' || *nick == '&' || *nick == '~' || *nick == '%' || *nick == '+' || *nick == '\\') nick++; if (strcmp(nick, linker_nick) != 0) user_add(nick, netid); } return; } else if (strcmp(cmd, "JOIN") == 0) { if ((strcmp(nick, linker_nick) != 0) && (user_ids(nick, netid) == NULL)) /* if not clone */ user_add(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(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(fdset[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, linker_nick) == 0) { net_del(networks[netid].name); return; } /* delete the user if the message from the same network */ if ((ids = user_ids(user, netid)) == NULL) { nick_add_symb(user, netid); user_del(user, msg); return; } /* close the kicked fd */ writeall(fdset[ids[netid]].fd, msg); fdset_del(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(fdset[networks[i].id].fd, msg); return; } printbuffer: printf("%d: %s\n", fdset[id].fd, backup); } void net_add(char *name, char *symb, char *host, char *port, char *chan) { int i, fd; 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(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; /* send NICK and USER commands */ snprintf(msg, sizeof(msg), "NICK linker\r\n"); writeall(fd, msg); snprintf(msg, sizeof(msg), "USER linker 0 * :linker\r\n"); writeall(fd, msg); /* add a network */ n = &networks[netlen]; n->id = fdset_add(fd, netlen, 0, 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(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(it.node->key, msg); /* this node is deleted */ it = lastit; /* delete the clones */ } else { if (ids[netid] > 0) { writeall(fdset[ids[netid]].fd, msg); fdset_del(ids[netid]); } /* swap last with current one */ ids[netid] = ids[netlen-1]; } lastit = it; } /* set netid of fds with last netid to current netid. */ for (i = 0; i < fdslen; i++) { if (fddata[i].netid == netlen-1) fddata[i].netid = netid; } writeall(fdset[networks[netid].id].fd, msg); fdset_del(networks[netid].id); net_del_raw(netid); printf("%d: network '%s' deleted\n", fdset[networks[netid].id].fd, name); /* swap the network with the last */ networks[netid] = networks[netlen-1]; netlen--; } void net_del_raw(int netid) { Network *n = &networks[netid]; free(n->name); free(n->symb); free(n->host); free(n->port); free(n->chan); } void net_update(int netid) { Htiter it = {0}; while (htiterate(users, &it)) ((int *)it.node->val)[netid] = clone_add(it.node->key, netid); } void user_add(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 > MAX_NICK_LEN) { printf("error: user nick '%s' is too big\n", unick); return; } /* resize hash table if store 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(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); terminate(1); } } void user_del(char *nick, char *msg) { int i; int *ids = euserids(nick); for (i = 0; i < netlen; i++) { if (ids[i] > 0) { writeall(fdset[ids[i]].fd, msg); fdset_del(ids[i]); } } htremove(users, nick); } int * 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) && (fddata[ids[netid]].suffix != (int)suffix)) ids = NULL; /* add suffix back */ if (suffix > 0) nick[strlen(nick)] = '_'; return ids; } /* get user ids */ int * euserids(char *user) { int *ids; if ((ids = htsearch(users, user)) == NULL) { printf("error: cannot find user '%s'\n", user); terminate(1); } return ids; } int clone_add(char *nick, int netid) { int fd; Network *n = &networks[netid]; if ((fd = dial(n->host, n->port)) == -1) return -1; /* send NICK and USER commands */ snprintf(msg, sizeof(msg), "NICK %s\r\n", nick); writeall(fd, msg); snprintf(msg, sizeof(msg), "USER user 0 * :user\r\n"); writeall(fd, msg); return fdset_add(fd, netid, 0, nick); } int fdset_add(int fd, int netid, int suffix, char *user) { if (fdslen == fdscap) { fdset = erecalloc(fdset, (size_t)fdscap, POLLFD_ADDEND, sizeof(struct pollfd)); fddata = erecalloc(fddata, (size_t)fdscap, POLLFD_ADDEND, sizeof(struct FdData)); fdscap += POLLFD_ADDEND; } fdset[fdslen].fd = fd; fdset[fdslen].events = POLLIN; fddata[fdslen].netid = netid; fddata[fdslen].suffix = suffix; fddata[fdslen].user = user; fddata[fdslen].time = time(NULL); return fdslen++; } void fdset_del(int id) { /* set id of last fd to current id */ if (fddata[fdslen-1].user != NULL) euserids(fddata[fdslen-1].user)[fddata[fdslen-1].netid] = id; else if ((fddata[fdslen-1].user == NULL) && (fddata[fdslen-1].netid != -1)) networks[fddata[fdslen-1].netid].id = id; /* set id of removing fd to -2 */ if (fddata[id].user != NULL) euserids(fddata[id].user)[fddata[id].netid] = -2; else if ((fddata[id].user == NULL) && (fddata[id].netid != -1)) networks[fddata[id].netid].id = -2; close(fdset[id].fd); fdset[id] = fdset[fdslen-1]; fddata[id] = fddata[fdslen-1]; fdslen--; } 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 (user_ids(src, netid) != NULL) *strrchr(src, '[') = '\0'; strcat(dst, src); strncat(dst, &d, 1); src = n; } } void terminate(int status) { int i; snprintf(msg, sizeof(msg), "QUIT :linker shutting down\r\n"); for (i = 0; i < fdslen; i++) { if (fddata[i].netid != -1) writeall(fdset[i].fd, msg); fdset_del(i); } /* delete all the users */ htdestroy(users); /* delete all the networks */ for (i = 0; i < netlen; i++) net_del_raw(i); free(networks); free(fdset); free(fddata); 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("Networks\t\t"); for (i = 0; i < netlen; i++) printf("%s(%d)\t", networks[i].symb, fdset[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) && (fddata[ids[i]].suffix > 0)) printf("(%d)", fddata[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"); }