From 0e2ac9360b71a7d054d7e945be575c0d21fa880c Mon Sep 17 00:00:00 2001 From: pk910 Date: Wed, 9 May 2012 11:40:20 +0200 Subject: [PATCH] added IOHandler --- src/ConfigParser.c | 376 ++++++++++++++++++++++++++++++++++++ src/ConfigParser.h | 29 +++ src/IOEngine.h | 39 ++++ src/IOEngine_select.c | 123 ++++++++++++ src/IOHandler.c | 440 ++++++++++++++++++++++++++++++++++++++++++ src/IOHandler.h | 94 +++++++++ src/ServerSocket.c | 75 +++++++ src/ServerSocket.h | 35 ++++ src/UserClient.c | 80 ++++++++ src/UserClient.h | 39 ++++ src/main.c | 53 +++++ src/overall.h | 31 +++ 12 files changed, 1414 insertions(+) create mode 100644 src/ConfigParser.c create mode 100644 src/ConfigParser.h create mode 100644 src/IOEngine.h create mode 100644 src/IOEngine_select.c create mode 100644 src/IOHandler.c create mode 100644 src/IOHandler.h create mode 100644 src/ServerSocket.c create mode 100644 src/ServerSocket.h create mode 100644 src/UserClient.c create mode 100644 src/UserClient.h create mode 100644 src/main.c create mode 100644 src/overall.h diff --git a/src/ConfigParser.c b/src/ConfigParser.c new file mode 100644 index 0000000..03eccaf --- /dev/null +++ b/src/ConfigParser.c @@ -0,0 +1,376 @@ +/* ConfigParser.c - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "ConfigParser.h" + +#define ENTRYTYPE_BLOCK 1 +#define ENTRYTYPE_STRING 2 +#define ENTRYTYPE_INTEGER 3 + +struct ConfigEntry { + char *name; + int type; + void *value; + struct ConfigEntry *next; +}; + +static struct ConfigEntry *root_entry = NULL; + +static char *parse_config_recursive(struct ConfigEntry *centry, char *buffer, int root_element); +static void free_entry_rekursiv(struct ConfigEntry *centry, int is_root_entry); + +int loadConfig(const char *filename) { + FILE *f; + f = fopen(filename, "rb"); + if(!f) return 0; + + // obtain file size: + long lSize; + fseek (f, 0, SEEK_END); + lSize = ftell(f); + rewind(f); + + // allocate memory to contain the whole file: + char *buffer = (char*) malloc (sizeof(char)*lSize + 1); + if (buffer == NULL) { + fclose(f); + return 0; + } + + // copy the file into the buffer: + size_t result = fread (buffer, 1, lSize, f); + if (result != lSize) { + fclose(f); + return 0; + } + buffer[lSize] = '\0'; + + fclose(f); + + // now parse the config file... + if(root_entry) { + free_loaded_config(); + } + root_entry = malloc(sizeof(*root_entry)); + if (!root_entry) return 0; + parse_config_recursive(root_entry, buffer, 1); + + // free the buffer... + free(buffer); + return 1; +} + +#define PARSER_FLAG_ESCAPED 0x01 +#define PARSER_FLAG_BLOCK 0x02 +#define PARSER_FLAG_STRING 0x04 +#define PARSER_FLAG_EXPECT_END 0x08 +#define PARSER_FLAG_NEXTCHAR 0x10 +#define PARSER_FLAG_INTEGER 0x20 +#define PARSER_FLAG_EOBN 0x40 /* End of Block name */ +#define PARSER_FLAG_COMMAND 0x80 +static char *parse_config_recursive(struct ConfigEntry *centry, char *buffer, int root_element) { + int flags = 0; + int type = (root_element ? ENTRYTYPE_BLOCK : 0); + char cbuf[1024]; + int cbufpos = 0; + struct ConfigEntry *sub_entrys = NULL; + while(*buffer) { + if(flags & PARSER_FLAG_NEXTCHAR) { + buffer++; + if(*buffer == '\0') + break; + } + flags |= PARSER_FLAG_NEXTCHAR; + if(flags & PARSER_FLAG_EOBN) { + flags &= ~(PARSER_FLAG_EOBN | PARSER_FLAG_NEXTCHAR); + struct ConfigEntry *new_entry = malloc(sizeof(*new_entry)); + if (!new_entry) return buffer; + new_entry->name = strdup(cbuf); + buffer = parse_config_recursive(new_entry, buffer, 0); + if(sub_entrys) + new_entry->next = sub_entrys; + else + new_entry->next = NULL; + sub_entrys = new_entry; + centry->value = sub_entrys; + } + if(flags & PARSER_FLAG_ESCAPED) { + cbuf[cbufpos++] = *buffer; + flags &= ~PARSER_FLAG_ESCAPED; + continue; + } + if(flags & PARSER_FLAG_EXPECT_END) { + if(*buffer == ';') { + centry->type = type; + return (buffer+1); + } + continue; + } + if(flags & PARSER_FLAG_STRING) { + if(*buffer == '"') { + cbuf[cbufpos] = '\0'; + flags &= ~PARSER_FLAG_STRING; + if(type == ENTRYTYPE_STRING) { + flags |= PARSER_FLAG_EXPECT_END; + centry->value = strdup(cbuf); + } else if(type == ENTRYTYPE_BLOCK) { + flags |= PARSER_FLAG_EOBN; + } + } else if(*buffer == '\\') + flags |= PARSER_FLAG_ESCAPED; + else + cbuf[cbufpos++] = *buffer; + continue; + } + if(flags & PARSER_FLAG_INTEGER) { + if(!isdigit(*buffer)) { + cbuf[cbufpos] = '\0'; + flags &= ~PARSER_FLAG_INTEGER; + if(type == ENTRYTYPE_INTEGER) { + flags |= PARSER_FLAG_EXPECT_END; + int *intbuf = malloc(sizeof(int)); + *intbuf = atoi(cbuf); + centry->value = intbuf; + } + if(*buffer == ';') { + centry->type = type; + return (buffer+1); + } + } else + cbuf[cbufpos++] = *buffer; + continue; + } + if(flags & PARSER_FLAG_COMMAND) { + int found_command = 0; + char *tmp_buffer; + switch(*buffer) { + case '/': + tmp_buffer = buffer; + buffer = strchr(buffer, '\r'); + if(!buffer) + buffer = strchr(tmp_buffer, '\n'); + if(!buffer) + buffer = tmp_buffer + strlen(tmp_buffer)-1; + found_command = 1; + break; + case '*': + //simple search for the next */ + buffer = strstr(buffer, "*/")+1; + found_command = 1; + } + flags &= ~PARSER_FLAG_COMMAND; + if(found_command) + continue; + } + switch(*buffer) { + case '\\': + flags |= PARSER_FLAG_ESCAPED; + break; + case '/': + if(!(flags & PARSER_FLAG_STRING)) { + flags |= PARSER_FLAG_COMMAND; + } + break; + case '{': + flags |= PARSER_FLAG_BLOCK; + type = ENTRYTYPE_BLOCK; + break; + case '}': + if(flags & PARSER_FLAG_BLOCK) + flags &= ~PARSER_FLAG_BLOCK; + flags |= PARSER_FLAG_EXPECT_END; + break; + case '"': + flags |= PARSER_FLAG_STRING; + if(!type) + type = ENTRYTYPE_STRING; + cbufpos = 0; + break; + case ';': + centry->type = type; + return (buffer+1); + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if(!type) + type = ENTRYTYPE_INTEGER; + flags |= PARSER_FLAG_INTEGER; + cbufpos = 0; + cbuf[cbufpos++] = *buffer; + break; + default: + break; + } + } + centry->type = type; + return buffer; //end of the buffer +} + +int get_int_field(char *field_path) { + struct ConfigEntry *centry = root_entry; + char *a, *b = field_path; + struct ConfigEntry *subentry; + while((a = strstr(b, ".")) && centry) { + if(centry->type == ENTRYTYPE_BLOCK) { + int found = 0; + for(subentry = centry->value; subentry; subentry = subentry->next) { + if(!stricmplen(subentry->name, b, a-b)) { + centry = subentry; + found = 1; + break; + } + } + if(!found) + return 0; + } else + return 0; + b = a+1; + } + if(centry->type == ENTRYTYPE_BLOCK) { + int found = 0; + for(subentry = centry->value; subentry; subentry = subentry->next) { + if(!stricmp(subentry->name, b)) { + centry = subentry; + found = 1; + break; + } + } + if(!found) + return 0; + } else + return 0; + if(centry->type == ENTRYTYPE_INTEGER) + return ((int *)centry->value)[0]; + else + return 0; +} + +char *get_string_field(char *field_path) { + struct ConfigEntry *centry = root_entry; + char *a, *b = field_path; + struct ConfigEntry *subentry; + while((a = strstr(b, ".")) && centry) { + if(centry->type == ENTRYTYPE_BLOCK) { + int found = 0; + for(subentry = centry->value; subentry; subentry = subentry->next) { + if(!stricmplen(subentry->name, b, a-b)) { + centry = subentry; + found = 1; + break; + } + } + if(!found) + return NULL; + } else + return NULL; + b = a+1; + } + if(centry->type == ENTRYTYPE_BLOCK) { + int found = 0; + for(subentry = centry->value; subentry; subentry = subentry->next) { + if(!stricmp(subentry->name, b)) { + centry = subentry; + found = 1; + break; + } + } + if(!found) + return NULL; + } else + return NULL; + if(centry->type == ENTRYTYPE_STRING) + return centry->value; + else + return NULL; +} + +char **get_all_fieldnames(char *block_path) { + struct ConfigEntry *centry = root_entry; + char *a, *b = block_path; + struct ConfigEntry *subentry; + while((a = strstr(b, ".")) && centry) { + if(centry->type == ENTRYTYPE_BLOCK) { + int found = 0; + for(subentry = centry->value; subentry; subentry = subentry->next) { + if(!stricmplen(subentry->name, b, a-b)) { + centry = subentry; + found = 1; + break; + } + } + if(!found) + return NULL; + } else + return NULL; + b = a+1; + } + if(centry->type == ENTRYTYPE_BLOCK) { + int found = 0; + for(subentry = centry->value; subentry; subentry = subentry->next) { + if(!stricmp(subentry->name, b)) { + centry = subentry; + found = 1; + break; + } + } + if(!found) + return NULL; + } else + return NULL; + if(centry->type != ENTRYTYPE_BLOCK) return NULL; + int count = 0; + for(subentry = centry->value; subentry; subentry = subentry->next) { + count++; + } + char **fieldnames = calloc(count+1, sizeof(char *)); + count = 0; + for(subentry = centry->value; subentry; subentry = subentry->next) { + fieldnames[count++] = subentry->name; + } + return fieldnames; +} + +void free_loaded_config() { + if(root_entry) { + free_entry_rekursiv(root_entry, 1); + root_entry = NULL; + } +} + +static void free_entry_rekursiv(struct ConfigEntry *centry, int is_root_entry) { + if(centry->type == ENTRYTYPE_BLOCK) { + struct ConfigEntry *subentry, *nextentry; + for(subentry = centry->value; subentry; subentry = nextentry) { + nextentry = subentry->next; + free_entry_rekursiv(subentry, 0); + } + } else if(centry->type == ENTRYTYPE_STRING) { + free(centry->value); + } else if(centry->type == ENTRYTYPE_INTEGER) { + free(centry->value); + } + if(!is_root_entry) + free(centry->name); + free(centry); +} diff --git a/src/ConfigParser.h b/src/ConfigParser.h new file mode 100644 index 0000000..0f2776d --- /dev/null +++ b/src/ConfigParser.h @@ -0,0 +1,29 @@ +/* ConfigParser.h - NeonServ v5.4 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _ConfigParser_h +#define _ConfigParser_h +#include "main.h" + +#ifndef DND_FUNCTIONS +int loadConfig(const char *filename); +/* MODULAR ACCESSIBLE */ int get_int_field(char *field_path); +/* MODULAR ACCESSIBLE */ char *get_string_field(char *field_path); +char **get_all_fieldnames(char *block_path); +void free_loaded_config(); +#endif +#endif diff --git a/src/IOEngine.h b/src/IOEngine.h new file mode 100644 index 0000000..dfcbe98 --- /dev/null +++ b/src/IOEngine.h @@ -0,0 +1,39 @@ +/* IOEngine.h - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#ifndef _IOEngine_h +#define _IOEngine_h +#include "overall.h" + +struct IODescriptor; + +extern struct IODescriptor *first_descriptor; + +struct IOEngine { + const char *name; + int (*init)(void); + void (*add)(struct IODescriptor *iofd); + void (*remove)(struct IODescriptor *iofd); + void (*update)(struct IODescriptor *iofd); + void (*loop)(struct timeval *timeout); + void (*cleanup)(void); +}; + +#define iohandler_wants_writes(IOFD) (IOFD->writebuf.bufpos || IOFD->state == IO_CONNECTING) + +void iohandler_events(struct IODescriptor *iofd, int readable, int writeable); + +#endif diff --git a/src/IOEngine_select.c b/src/IOEngine_select.c new file mode 100644 index 0000000..af919c2 --- /dev/null +++ b/src/IOEngine_select.c @@ -0,0 +1,123 @@ +/* IOEngine_select.c - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include "IOEngine.h" +#include "IOHandler.h" + +static int engine_select_init() { + /* empty */ + return 1; +} + +static void engine_select_add(struct IODescriptor *iofd) { + /* empty */ +} + +static void engine_select_remove(struct IODescriptor *iofd) { + /* empty */ +} + +static void engine_select_update(struct IODescriptor *iofd) { + /* empty */ +} + +static void engine_select_loop(struct timeval *timeout) { + fd_set read_fds; + fd_set write_fds; + unsigned int fds_size = 0; + struct IODescriptor *iofd, *tmp_iofd; + struct timeval now, tdiff; + int select_result; + + gettimeofday(&now, NULL); + + //clear fds + FD_ZERO(&read_fds); + FD_ZERO(&write_fds); + + for(iofd = first_descriptor; iofd; iofd = tmp_iofd) { + tmp_iofd = iofd->next; + if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN) { + if(iofd->fd > fds_size) + fds_size = iofd->fd; + FD_SET(iofd->fd, &read_fds); + if(iohandler_wants_writes(iofd)) + FD_SET(iofd->fd, &write_fds); + } else if(iofd->type == IOTYPE_TIMER) { + tdiff.tv_sec = iofd->timeout.tv_sec - now.tv_sec; + tdiff.tv_usec = iofd->timeout.tv_usec - now.tv_usec; + + if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) { + //exec timer + iofd->state = IO_CLOSED; + iohandler_events(iofd, 1, 0); + iohandler_close(iofd); + continue; + } else if(tdiff.tv_usec < 0) { + tdiff.tv_sec--; + tdiff.tv_usec += 1000000; //1 sec + } + if(timeval_is_smaler(&tdiff, timeout)) { + timeout->tv_sec = tdiff.tv_sec; + timeout->tv_usec = tdiff.tv_usec; + } + } + } + + //select system call + select_result = select(fds_size + 1, &read_fds, &write_fds, NULL, timeout); + + if (select_result < 0) { + if (errno != EINTR) { + //hard fail + return; + } + } + + //check all descriptors + for(iofd = first_descriptor; iofd; iofd = tmp_iofd) { + tmp_iofd = iofd->next; + if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN) { + if(FD_ISSET(iofd->fd, &read_fds) || FD_ISSET(iofd->fd, &write_fds)) { + iohandler_events(iofd, FD_ISSET(iofd->fd, &read_fds), FD_ISSET(iofd->fd, &write_fds)); + } + } else if(iofd->type == IOTYPE_TIMER) { + tdiff.tv_sec = iofd->timeout.tv_sec - now.tv_sec; + tdiff.tv_usec = iofd->timeout.tv_usec - now.tv_usec; + + if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) { + //exec timer + iofd->state = IO_CLOSED; + iohandler_events(iofd, 1, 0); + continue; + } + } + } +} + +static void engine_select_cleanup() { + /* empty */ +} + +struct IOEngine engine_select = { + .name = "select", + .init = engine_select_init, + .add = engine_select_add, + .remove = engine_select_remove, + .update = engine_select_update, + .loop = engine_select_loop, + .cleanup = engine_select_cleanup, +}; diff --git a/src/IOHandler.c b/src/IOHandler.c new file mode 100644 index 0000000..127a99e --- /dev/null +++ b/src/IOHandler.c @@ -0,0 +1,440 @@ +/* IOHandler.c - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +struct IODescriptor *first_descriptor = NULL; + +/* IO Engines */ +extern struct IOEngine engine_select; /* select system call (should always be useable) */ + +struct IOEngine *engine = NULL; + +static void iohandler_init_engine() { + //try other engines + + if(engine) + //found an useable IO engine + else if (engine_select.init()) + engine = &engine_select; + else { + //STDERR: found no useable IO engine + } +} + +struct IODescriptor *iohandler_add(int sockfd, IOType type, iohandler_callback *callback) { + //just add a new IODescriptor + struct IODescriptor *descriptor = calloc(1, sizeof(*descriptor)); + if(!descriptor) return NULL; + descriptor->fd = sockfd; + descriptor->type = type; + descriptor->state = IO_CLOSED; + descriptor->callback = callback; + if(type != IOTYPE_TIMER) { + descriptor->readbuf.buffer = malloc(IOREADBUFLEN + 2); + descriptor->readbuf.bufpos = 0; + descriptor->readbuf.buflen = IOREADBUFLEN; + descriptor->writebuf.buffer = malloc(IOREADBUFLEN + 2); + descriptor->writebuf.bufpos = 0; + descriptor->writebuf.buflen = IOREADBUFLEN; + } + + if(!engine) { + iohandler_init_engine(); + if(!engine) { + return NULL; + } + } + engine->add(descriptor); + + //add IODescriptor to the list + descriptor->prev = NULL; + descriptor->next = first_descriptor; + first_descriptor->prev = descriptor; + first_descriptor = descriptor; + + return descriptor; +} + +static void iohandler_remove(struct IODescriptor *descriptor) { + //remove IODescriptor from the list + if(descriptor->prev) + descriptor->prev->next = descriptor->next; + else + first_descriptor = descriptor->next; + if(descriptor->next) + descriptor->next->prev = descriptor->prev; + engine->remove(descriptor); + if(descriptor->readbuf.buffer) + free(descriptor->readbuf.buffer); + if(descriptor->writebuf.buffer) + free(descriptor->writebuf.buffer); + free(descriptor); +} + +static void iohandler_increase_iobuf(struct IOBuffer *iobuf, size_t required) { + if(iobuf->buflen >= required) return; + char *new_buf = realloc(iobuf->buffer, required + 2); + if(new_buf) { + iobuf->buffer = new_buf; + iobuf->buflen = required; + } +} + +struct IODescriptor *iohandler_timer(timeval timeout, iohandler_callback *callback) { + struct IODescriptor *descriptor; + descriptor = iohandler_add(-1, IOTYPE_TIMER, callback); + if(!descriptor) return NULL; + descriptor->timeout = timeout; + engine->update(descriptor); + return descriptor; +} + +struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, const char *bind, iohandler_callback *callback) { + //non-blocking connect + int sockfd; + struct addrinfo hints, *res, *freeres; + struct sockaddr_in *ip4 = NULL; + struct sockaddr_in6 *ip6 = NULL; + size_t dstaddrlen; + struct sockaddr *dstaddr = NULL; + struct IODescriptor *descriptor; + + memset (&hints, 0, sizeof (hints)); + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags |= AI_CANONNAME; + if (getaddrinfo (hostname, NULL, &hints, &res)) { + return NULL; + } + while (res) { + switch (res->ai_family) { + case AF_INET: + ip4 = (struct sockaddr_in *) res->ai_addr; + break; + case AF_INET6: + ip6 = (struct sockaddr_in6 *) res->ai_addr; + break; + } + freeres = res; + res = res->ai_next; + freeaddrinfo(res); + } + + if(ip6) { + sockfd = socket(AF_INET6, SOCK_STREAM, 0); + if(sockfd == -1) return NULL; + + ip6->sin6_family = AF_INET6; + ip6->sin6_port = htons(port); + + struct sockaddr_in6 *ip6vhost = NULL; + if (bind && !getaddrinfo(bind, NULL, &hints, &res)) { + while (res) { + switch (res->ai_family) { + case AF_INET6: + ip6vhost = (struct sockaddr_in6 *) res->ai_addr; + break; + } + freeres = res; + res = res->ai_next; + freeaddrinfo(res); + } + } + if(ip6vhost) { + ip6vhost->sin6_family = AF_INET6; + ip6vhost->sin6_port = htons(0); + bind(sockfd, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost)); + } + dstaddr = (struct sockaddr*)ip6; + dstaddrlen = sizeof(*ip6); + } else if(ip4) { + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if(sockfd == -1) return NULL; + + ip4->sin_family = AF_INET; + ip4->sin_port = htons(port); + + struct sockaddr_in *ip4vhost = NULL; + if (bind && !getaddrinfo(bind, NULL, &hints, &res)) { + while (res) { + switch (res->ai_family) { + case AF_INET: + ip4vhost = (struct sockaddr_in *) res->ai_addr; + break; + } + freeres = res; + res = res->ai_next; + freeaddrinfo(res); + } + } + if(ip4vhost) { + ip4vhost->sin_family = AF_INET; + ip4vhost->sin_port = htons(0); + bind(sockfd, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost)); + } + dstaddr = (struct sockaddr*)ip4; + dstaddrlen = sizeof(*ip4); + } else + return NULL; + //make sockfd unblocking +#if defined(F_GETFL) + flags = fcntl(sockfd, F_GETFL); + fcntl(sockfd, F_SETFL, flags|O_NONBLOCK); + flags = fcntl(sockfd, F_GETFD); + fcntl(sockfd, F_SETFD, flags|FD_CLOEXEC); +#else + /* I hope you're using the Win32 backend or something else that + * automatically marks the file descriptor non-blocking... + */ + (void)flags; +#endif + descriptor = iohandler_add(sockfd, IOTYPE_CLIENT, callback); + if(!descriptor) { + close(sockfd); + return NULL; + } + connect(sockfd, dstaddr, dstaddrlen); //returns EINPROGRESS here (nonblocking) + descriptor->state = IO_CONNECTING; + descriptor->read_lines = 1; + engine->update(descriptor); +} + +struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback) { + int sockfd; + struct addrinfo hints, *res, *freeres; + struct sockaddr_in *ip4 = NULL; + struct sockaddr_in6 *ip6 = NULL; + struct IODescriptor *descriptor; + unsigned int opt; + + memset (&hints, 0, sizeof (hints)); + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags |= AI_CANONNAME; + if (getaddrinfo (hostname, NULL, &hints, &res)) { + return NULL; + } + while (res) { + switch (res->ai_family) { + case AF_INET: + ip4 = (struct sockaddr_in *) res->ai_addr; + break; + case AF_INET6: + ip6 = (struct sockaddr_in6 *) res->ai_addr; + break; + } + freeres = res; + res = res->ai_next; + freeaddrinfo(res); + } + + if(ip6) { + sockfd = socket(AF_INET6, SOCK_STREAM, 0); + if(sockfd == -1) return NULL; + + opt = 1; + setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt)); + + ip6->sin6_family = AF_INET6; + ip6->sin6_port = htons(port); + + bind(sockfd, (struct sockaddr*)ip6, sizeof(*ip6)); + } else if(ip4) { + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if(sockfd == -1) return NULL; + + opt = 1; + setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt)); + + ip4->sin_family = AF_INET; + ip4->sin_port = htons(port); + + bind(sockfd, (struct sockaddr*)ip4, sizeof(*ip4)); + } else + return NULL; + //make sockfd unblocking +#if defined(F_GETFL) + flags = fcntl(sockfd, F_GETFL); + fcntl(sockfd, F_SETFL, flags|O_NONBLOCK); + flags = fcntl(sockfd, F_GETFD); + fcntl(sockfd, F_SETFD, flags|FD_CLOEXEC); +#else + /* I hope you're using the Win32 backend or something else that + * automatically marks the file descriptor non-blocking... + */ + (void)flags; +#endif + descriptor = iohandler_add(sockfd, IOTYPE_SERVER, callback); + if(!descriptor) { + close(sockfd); + return NULL; + } + listen(sockfd, 1); + descriptor->state = IO_LISTENING; + engine->update(descriptor); +} + +void iohandler_write(struct IODescriptor *iofd, const char *line) { + size_t linelen = strlen(line); + iohandler_send(iofd, line, linelen); +} + +void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen) { + if(iofd->type == IOTYPE_TIMER) return; //can not write to timer? :D + if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) { + iohandler_increase_iobuf(&iofd->writebuf, iofd->writebuf.bufpos + datalen); + if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) + return; + } + memcpy(iofd->writebuf.buffer + iofd->writebuf.bufpos, data, datalen); + engine->update(iofd); +} + +void iohandler_printf(struct IODescriptor *iofd, const char *text, ...) { + va_list arg_list; + char sendBuf[LINELEN]; + int pos; + sendBuf[0] = '\0'; + va_start(arg_list, text); + pos = vsnprintf(sendBuf, LINELEN - 2, text, arg_list); + va_end(arg_list); + if (pos < 0 || pos > (LINELEN - 2)) pos = LINELEN - 2; + sendBuf[pos] = '\n'; + sendBuf[pos+1] = '\0'; + iohandler_send(iofd, sendBuf, pos+1); +} + +void iohandler_try_write(struct IODescriptor *iofd) { + if(!iofd->writebuf.bufpos) return; + int res = send(iofd->fd, iofd->writebuf.buffer, iofd->writebuf.bufpos, 0); + if(res < 0) { + if (errno != EAGAIN) { + //error: could not write + } + } else { + iofd->writebuf.bufpos -= res; + engine->update(iofd); + } +} + +void iohandler_close(struct IODescriptor *iofd) { + //close IODescriptor + if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN) + close(iofd->fd); + iohandler_remove(iofd); +} + +void iohandler_update(struct IODescriptor *iofd) { + engine->update(iofd); +} + +static void iohandler_trigger_event(struct IOEvent *event) { + if(!event->iofd->callback) return; + event->iofd->callback(event); +} + +void iohandler_events(struct IODescriptor *iofd, int readable, int writeable) { + struct IOEvent callback_event; + callback_event.type = IOEVENT_IGNORE; + callback_event.iofd = iofd; + switch(iofd->state) { + case IO_CLOSED: + if(iofd->type == IOTYPE_TIMER) + callback_event.type = IOEVENT_TIMEOUT; + break; + case IO_LISTENING: + callback_event.data.accept_fd = accept(iofd->fd, NULL, 0); + if(callback_event.data.accept_fd < 0) { + //error: could not accept + } else + callback_event.type = IOEVENT_ACCEPT; + break; + case IO_CONNECTING: + if(readable) { //could not connect + callback_event.type = IOEVENT_NOTCONNECTED; + socklen_t arglen; + arglen = sizeof(callback_event.errno); + if (getsockopt(fd->fd, SOL_SOCKET, SO_ERROR, &callback_event.errno, &arglen) < 0) + callback_event.data.errno = errno; + iofd->state = IO_CLOSED; + } else if(writeable) { + callback_event.type = IOEVENT_CONNECTED; + iofd->state = IO_CONNECTED; + engine->update(iofd); + } + break; + case IO_CONNECTED: + if(readable) { + if(iofd->read_lines) { + int bytes = recv(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos, 0); + if(bytes <= 0) { + if (errno != EAGAIN) { + callback_event.type = IOEVENT_CLOSED; + callback_event.data.errno = errno; + } + } else { + int i, used_bytes = 0, buffer_offset = 0; + iofd->readbuf.bufpos += bytes; + callback_event.type = IOEVENT_RECV; + for(i = 0; i < iofd->readbuf.bufpos; i++) { + if(iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] == '\n') + iofd->readbuf.buffer[i] = 0; + else if(iofd->readbuf.buffer[i] == '\n' || iofd->readbuf.buffer[i] == '\r') { + iofd->readbuf.buffer[i] = 0; + callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes; + used_bytes = i+1; + iohandler_trigger_event(&callback_event); + } else if(i + 1 - used_bytes >= LINELEN) { //512 max + iofd->readbuf.buffer[i] = 0; + callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes; + for(; i < iofd->readbuf.bufpos; i++) { //skip the rest of the line + if(iofd->readbuf.buffer[i] == '\n' || (iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] != '\n')) { + break; + } + } + used_bytes = i+1; + iohandler_trigger_event(&callback_event); + } + } + if(used_bytes) { + if(used_bytes == iofd->readbuf.bufpos) + iofd->readbuf.bufpos = 0; + else + memmove(iofd->readbuf.buffer, iofd->readbuf.buffer + used_bytes, iofd->readbuf.bufpos - used_bytes); + } + callback_event.type = IOEVENT_IGNORE; + } + } else + callback_event.type = IOEVENT_READABLE; + } + if(writeable) { + iohandler_try_write(iofd); + } + break; + } + if(callback_event.type != IOEVENT_IGNORE) + iohandler_trigger_event(&callback_event); +} + +void iohandler_poll() { + if(engine) { + struct timeval timeout; + timeout.tv_sec = IO_MAX_TIMEOUT; + timeout.tv_usec = 0; + engine->loop(&timeout); + } +} + diff --git a/src/IOHandler.h b/src/IOHandler.h new file mode 100644 index 0000000..34e49d4 --- /dev/null +++ b/src/IOHandler.h @@ -0,0 +1,94 @@ +/* IOHandler.h - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#ifndef _IOHandler_h +#define _IOHandler_h +#include "overall.h" + +struct IODescriptor; +struct IOEvent; + +#define IOHANDLER_CALLBACK(NAME) void NAME(UNUSED_ARG(struct IOEvent *io_event)) +typedef IOHANDLER_CALLBACK(iohandler_callback); + +enum IOType { + IOTYPE_UNKNOWN, /* ignore descriptor (uninitialized) */ + IOTYPE_SERVER, /* server socket */ + IOTYPE_CLIENT, /* client socket */ + IOTYPE_STDIN, /* stdin */ + IOTYPE_TIMER /* timer */ +}; + +enum IOStatus { + IO_CLOSED, /* descriptor is dead (socket waiting for removal or timer) */ + IO_LISTENING, /* descriptor is waiting for connections (server socket) */ + IO_CONNECTING, /* descriptor is waiting for connection approval (connecting client socket) */ + IO_CONNECTED /* descriptor is connected (connected client socket) */ +}; + +enum IOEventType { + IOEVENT_IGNORE, + IOEVENT_READABLE, /* socket is readable - not read anything yet, could also be disconnect notification */ + IOEVENT_RECV, /* client socket received something (recv_str valid) */ + IOEVENT_CONNECTED, /* client socket connected successful */ + IOEVENT_NOTCONNECTED, /* client socket could not connect (errno valid) */ + IOEVENT_CLOSED, /* client socket lost connection (errno valid) */ + IOEVENT_ACCEPT, /* server socket accepted new connection (accept_fd valid) */ + IOEVENT_TIMEOUT /* timer timed out */ +}; + +struct IOBuffer { + char buffer; + size_t bufpos, buflen; +}; + +struct IODescriptor { + int fd; + IOType type; + IOStatus state; + struct timeval timeout; + iohandler_callback *callback; + struct IOBuffer readbuf; + struct IOBuffer writebuf; + void *data; + int read_lines : 1; + + struct IODescriptor *next, *prev; +}; + +struct IOEvent { + IOEventType type; + struct IODescriptor *iofd; + union { + char *recv_str; + int accept_fd; + int errno; + } data; +}; + +struct IODescriptor *iohandler_add(int sockfd, IOType type, iohandler_callback *callback); +struct IODescriptor *iohandler_timer(timeval timeout, iohandler_callback *callback); +struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, const char *bind, iohandler_callback *callback); +struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback); +void iohandler_write(struct IODescriptor *iofd, const char *line); +void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen); +void iohandler_printf(struct IODescriptor *iofd, const char *text, ...); +void iohandler_close(struct IODescriptor *iofd); +void iohandler_update(struct IODescriptor *iofd); + +void iohandler_poll(); + +#endif diff --git a/src/ServerSocket.c b/src/ServerSocket.c new file mode 100644 index 0000000..0bdec2c --- /dev/null +++ b/src/ServerSocket.c @@ -0,0 +1,75 @@ +/* ServerSocket.c - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include "ServerSocket.h" +#include "IOHandler.h" +#include "UserClient.h" + +static struct ServerSocket *serversockets = NULL; + +static void serversocket_callback(struct IOEvent *event); + +static struct ServerSocket *serversocket_create(struct IODescriptor *iofd) { + struct ServerSocket *sock = malloc(sizeof(*sock)); + sock->iofd = iofd; + sock->clientcount = 0; + + //add ServerSocket to the list + sock->prev = NULL; + sock->next = serversockets; + serversockets->prev = sock; + serversockets = sock; +} + +static void serversocket_delete(struct ServerSocket *server) { + if(server->prev) + server->prev->next = server->next; + else + serversockets = server->next; + if(server->next) + server->next->prev = server->prev; + free(server); +} + +struct ServerSocket *serversocket_listen(char *hostname, int port) { + struct IODescriptor *iofd = iohandler_listen(hostname, port, serversocket_callback); + if(iofd) { + struct ServerSocket *server = serversocket_create(iofd); + return server; + } + return NULL; +} + +void serversocket_close(struct ServerSocket *server, int keep_clients) { + userclient_close_server(server, keep_clients); + iohandler_close(server->iofd); + serversocket_delete(server); +} + +static void serversocket_callback(struct IOEvent *event) { + switch(event->type) { + case IOEVENT_ACCEPT: + struct ServerSocket *server = NULL; + for(server = serversockets; server; server = server->next) { + if(server->iofd == event->iofd) + break; + } + if(server) + userclient_accepted(server, event->accept_fd) + break; + } +} + diff --git a/src/ServerSocket.h b/src/ServerSocket.h new file mode 100644 index 0000000..5e77db1 --- /dev/null +++ b/src/ServerSocket.h @@ -0,0 +1,35 @@ +/* ServerSocket.h - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _ServerSocket_h +#define _ServerSocket_h +#include "overall.h" + +struct IODescriptor; +struct UserClient; + +struct ServerSocket { + struct IODescriptor *iofd; + int clientcount; + + struct ServerSocket *next, *prev; +}; + +struct ServerSocket *serversocket_listen(char *hostname, int port); +void serversocket_close(struct ServerSocket *server, int keep_clients); + +#endif diff --git a/src/UserClient.c b/src/UserClient.c new file mode 100644 index 0000000..c0d3af5 --- /dev/null +++ b/src/UserClient.c @@ -0,0 +1,80 @@ +/* UserClient.c - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include "UserClient.c" +#include "IOHandler.h" + +static void userclient_callback(struct IOEvent *event); + +static struct UserClient *userclients = NULL; + +void userclient_accepted(struct ServerSocket *server, int sockfd) { + struct UserClient *client; + struct IODescriptor *iofd = iohandler_add(sockfd, IOTYPE_CLIENT, userclient_callback); + if(!iofd) return; + iofd->state = IO_CONNECTED; + iofd->read_lines = 1; + iohandler_update(iofd); + client = malloc(sizeof(*client)); + client->iofd = iofd; + client->server = server; + server->clientcount++; + + //add UserClient to the list + sock->prev = NULL; + sock->next = serversockets; + serversockets->prev = sock; + serversockets = sock; + + //let's say hello to the client + iohandler_printf(iofd, "NOTICE AUTH :*** TransparentIRC " TRANSIRC_VERSION " (use /quote transirc for more information)"); +} + +void userclient_close(struct UserClient *client) { + iohandler_close(client->iofd); + client->server->clientcount--; + if(client->prev) + client->prev->next = client->next; + else + userclients = client->next; + if(client->next) + client->next->prev = client->prev; + free(client); +} + +void userclient_close_server(struct ServerSocket *server, int keep_clients) { + struct UserClient *client, *next_client; + for(client = userclients; client; client = next_client) { + if(client->server == server) { + if(keep_clients) + client->server = NULL; + else + userclient_close(client); + } + } +} + +static void userclient_callback(struct IOEvent *event) { + switch(event->type) { + case IOEVENT_RECV: + char *line = event->data.recv_str; + iohandler_printf(event->iofd, "reply: %s", line); + break; + case IOEVENT_CLOSED: + userclient_close(event->iofd); + break; + } +} diff --git a/src/UserClient.h b/src/UserClient.h new file mode 100644 index 0000000..6b95ea1 --- /dev/null +++ b/src/UserClient.h @@ -0,0 +1,39 @@ +/* UserClient.h - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _UserClient_h +#define _UserClient_h +#include "overall.h" + +struct IODescriptor; +struct ServerSocket; +//struct UserSession; + +struct UserClient { + struct IODescriptor *iofd; + struct ServerSocket *server; + + //struct UserSession *user; + + struct UserClient *next, *prev; +}; + +void userclient_accepted(struct ServerSocket *server, int sockfd); +void userclient_close(struct UserClient *client); +void userclient_close_server(struct ServerSocket *server, int keep_clients); + +#endif diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..19e5307 --- /dev/null +++ b/src/main.c @@ -0,0 +1,53 @@ +/* main.c - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "IOHandler.h" +#include "ServerSocket.h" + +char *configFile = "transirc.conf"; + +static void parseParameters(int argc, char *argv[]) { + int c; + struct option options[] = { + {"config", 1, 0, 'c'}, + {0, 0, 0, 0} + }; + while ((c = getopt_long(argc, argv, "s:fvh", options, NULL)) != -1) { + switch (c) { + case 'c': + configFile = strdup(optarg); + break; + } + } +} + +int main(int argc, char *argv[]) { + #ifndef WIN32 + if(geteuid() == 0 || getuid() == 0) { + fprintf(stderr, "TransparentIRC may not be run with super user privileges.\n"); + exit(0); + } + #endif + parseParameters(argc, argv); + + serversocket_listen("0.0.0.0", 9001); + + while(1) { + iohandler_poll(); + } +} + diff --git a/src/overall.h b/src/overall.h new file mode 100644 index 0000000..8797932 --- /dev/null +++ b/src/overall.h @@ -0,0 +1,31 @@ +/* overall.h - TransparentIRC 0.1 + * Copyright (C) 2011-2012 Philipp Kreil (pk910) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _overall_h +#define _overall_h +#include "../config.h" + +#define TRANSIRC_VERSION "0.1" + +#define IO_READ_BUFLEN 1024 +#define IO_MAX_TIMEOUT 10 +#define LINELEN 512 + +#define timeval_is_bigger(x,y) ((x->tv_sec > y->tv_sec) || (x->tv_sec == y->tv_sec && x->tv_usec > y->tv_usec)) +#define timeval_is_smaler(x,y) ((x->tv_sec < y->tv_sec) || (x->tv_sec == y->tv_sec && x->tv_usec < y->tv_usec)) + +#endif -- 2.20.1