commit 6202fed9e0eed41d64baa1ca3f31a55f1b503227 Author: Olaf Rempel Date: Sat Jun 16 14:22:32 2007 +0200 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..11cccc7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.d +*.o +simpleweb diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..6d3dd52 --- /dev/null +++ b/Makefile @@ -0,0 +1,20 @@ +CFLAGS := -O2 -pipe -Wall + +OBJS := configfile.o event.o http.o logging.o simpleweb.o sockaddr.o tcpsocket.o + +all: simpleweb + +simpleweb: $(OBJS) + $(CC) $(CFLAGS) $^ -o $@ + +%.o: %.c + $(CC) $(CFLAGS) -c $< -o $@ + +%.d: %.c + $(CC) $(CFLAGS) -MM -c $< -o $@ + +clean: + rm -f simpleweb *.d *.o *.log + +DEPS := $(wildcard *.c) +-include $(DEPS:.c=.d) diff --git a/configfile.c b/configfile.c new file mode 100644 index 0000000..73ff3ae --- /dev/null +++ b/configfile.c @@ -0,0 +1,200 @@ +/*************************************************************************** + * Copyright (C) 06/2006 by Olaf Rempel * + * razzor@kopf-tisch.de * + * * + * 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 2 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, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "configfile.h" +#include "list.h" +#include "logging.h" + +#define BUFSIZE 1024 + +struct conf_section { + struct list_head list; + struct list_head tupel_list; + char *name; +}; + +struct conf_tupel { + struct list_head list; + char *option; + char *parameter; +}; + +static LIST_HEAD(config_list); + +static struct conf_section * config_add_section(const char *name) +{ + struct conf_section *section; + section = malloc(sizeof(struct conf_section) + strlen(name)); + if (section == NULL) + return NULL; + + INIT_LIST_HEAD(§ion->list); + INIT_LIST_HEAD(§ion->tupel_list); + + section->name = strdup(name); + if (section->name == NULL) { + free(section); + return NULL; + } + + list_add_tail(§ion->list, &config_list); + return section; +} + +static int config_add_tupel(struct conf_section *section, const char *option, const char *parameter) +{ + struct conf_tupel *tupel = malloc(sizeof(struct conf_tupel)); + if (tupel == NULL) + return -1; + + INIT_LIST_HEAD(&tupel->list); + tupel->option = strdup(option); + tupel->parameter = strdup(parameter); + + if (tupel->option == NULL || tupel->parameter == NULL) { + free(tupel); + return -1; + } + + list_add_tail(&tupel->list, §ion->tupel_list); + return 0; +} + +int config_parse(const char *config) +{ + FILE *fz = fopen(config, "r"); + if (fz == NULL) { + log_print(LOG_ERROR, "config_parse(): %s", config); + return -1; + } + + char *line = malloc(BUFSIZE); + if (line == NULL) { + log_print(LOG_ERROR, "config_parse(): out of memory"); + fclose(fz); + return -1; + } + + int linenum = 0; + struct conf_section *section = NULL; + while (fgets(line, BUFSIZE, fz) != NULL) { + linenum++; + + if (line[0] == '#' || line[0] <= ' ') { + continue; + + } else if (line[0] == '[') { + char *tok = strtok(line +1, " ]\n"); + + if (tok == NULL || (section = config_add_section(tok)) == NULL) { + log_print(LOG_WARN, "config_parse(): invalid section in row %d", linenum); + free(line); + fclose(fz); + return -1; + } + continue; + + } else if (section == NULL) { + log_print(LOG_WARN, "config_parse(): missing section in row %d", linenum); + free(line); + fclose(fz); + return -1; + } + + char *tok = strtok(line, " \n"); + if (tok != NULL) { + char *tok2; + while ((tok2 = strtok(NULL, " \n"))) { + if (config_add_tupel(section, tok, tok2) != 0) + log_print(LOG_WARN, "config_parse(): invalid row %d", linenum); + } + } + } + + fclose(fz); + free(line); + return 0; +} + +static struct conf_section * config_get_section(const char *name) +{ + struct conf_section *section; + + list_for_each_entry(section, &config_list, list) { + if (!strcmp(section->name, name)) + return section; + } + return NULL; +} + +char * config_get_string(const char *section_str, const char *option, char *def) +{ + struct conf_section *section = config_get_section(section_str); + if (section != NULL) { + struct conf_tupel *tupel; + list_for_each_entry(tupel, §ion->tupel_list, list) { + if (!strcmp(tupel->option, option)) + return tupel->parameter; + } + } + + if (def != NULL) + log_print(LOG_WARN, "config [%s:%s] not found, using default: '%s'", + section_str, option, def); + return def; +} + +int config_get_int(const char *section, const char *option, int def) +{ + char *ret = config_get_string(section, option, NULL); + if (ret == NULL) { + log_print(LOG_WARN, "config [%s:%s] not found, using default: '%d'", + section, option, def); + return def; + } + return atoi(ret); +} + +int config_get_strings(const char *section_str, const char *option, + int (*callback)(const char *value, void *privdata), + void *privdata) +{ + struct conf_section *section = config_get_section(section_str); + if (section == NULL) + return -1; + + int cnt = 0; + struct conf_tupel *tupel; + list_for_each_entry(tupel, §ion->tupel_list, list) { + if (!strcmp(tupel->option, option)) + if (callback(tupel->parameter, privdata) == 0) + cnt++; + } + return cnt; +} diff --git a/configfile.h b/configfile.h new file mode 100644 index 0000000..6528459 --- /dev/null +++ b/configfile.h @@ -0,0 +1,16 @@ +#ifndef _CONFIG_H_ +#define _CONFIG_H_ + +#include + +int config_parse(const char *config); + +char * config_get_string(const char *section_str, const char *option, char *def); + +int config_get_int(const char *section, const char *option, int def); + +int config_get_strings(const char *section_str, const char *option, + int (*callback)(const char *value, void *privdata), + void *privdata); + +#endif /* _CONFIG_H_ */ diff --git a/event.c b/event.c new file mode 100644 index 0000000..029c177 --- /dev/null +++ b/event.c @@ -0,0 +1,302 @@ +/*************************************************************************** + * Copyright (C) 10/2006 by Olaf Rempel * + * razzor@kopf-tisch.de * + * * + * 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 2 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, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ +#include +#include +#include + +#include +#include + +#include "list.h" +#include "logging.h" + +#include "event.h" + +static LIST_HEAD(event_fd_list); +static LIST_HEAD(event_timeout_list); + +struct event_fd { + struct list_head list; + unsigned int flags; + int fd; + int (*read_cb)(int fd, void *privdata); + int (*write_cb)(int fd, void *privdata); + void *read_priv; + void *write_priv; +}; + +struct event_timeout { + struct list_head list; + unsigned int flags; + struct timeval intervall; + struct timeval nextrun; + int (*callback)(void *privdata); + void *privdata; +}; + +struct event_fd * event_add_fd( + struct event_fd *entry, + int fd, + int type, + int (*callback)(int fd, void *privdata), + void *privdata) +{ + /* check valid filediskriptor */ + if (fd < 0 || fd > FD_SETSIZE) { + log_print(LOG_ERROR, "event_add_fd(): invalid fd"); + return NULL; + } + + /* check valid type (read/write) */ + if (!(type & FD_TYPES)) { + log_print(LOG_ERROR, "event_add_fd(): invalid type"); + return NULL; + } + + /* create new entry */ + if (entry == NULL) { + entry = malloc(sizeof(struct event_fd)); + if (entry == NULL) { + log_print(LOG_ERROR, "event_add_fd(): out of memory"); + return NULL; + } + + memset(entry, 0, sizeof(struct event_fd)); + entry->flags |= EVENT_NEW; + entry->fd = fd; + + /* put it on the list */ + list_add_tail(&entry->list, &event_fd_list); + } + + if (type & FD_READ) { + entry->flags = (callback != NULL) ? (entry->flags | FD_READ) : (entry->flags & ~FD_READ); + entry->read_cb = callback; + entry->read_priv = privdata; + + } else if (type & FD_WRITE) { + entry->flags = (callback != NULL) ? (entry->flags | FD_WRITE) : (entry->flags & ~FD_WRITE); + entry->write_cb = callback; + entry->write_priv = privdata; + } + + return entry; +} + +int event_get_fd(struct event_fd *entry) +{ + return (entry != NULL) ? entry->fd: -1; +} + +void event_remove_fd(struct event_fd *entry) +{ + /* mark the event as deleted -> remove in select() loop */ + entry->flags |= EVENT_DELETE; +} + +static void add_timeval(struct timeval *ret, struct timeval *a, struct timeval *b) +{ + ret->tv_usec = a->tv_usec + b->tv_usec; + ret->tv_sec = a->tv_sec + b->tv_sec; + + if (ret->tv_usec >= 1000000) { + ret->tv_usec -= 1000000; + ret->tv_sec++; + } +} + +static void sub_timeval(struct timeval *ret, struct timeval *a, struct timeval *b) +{ + ret->tv_usec = a->tv_usec - b->tv_usec; + ret->tv_sec = a->tv_sec - b->tv_sec; + + if (ret->tv_usec < 0) { + ret->tv_usec += 1000000; + ret->tv_sec--; + } +} + +static int cmp_timeval(struct timeval *a, struct timeval *b) +{ + if (a->tv_sec > b->tv_sec) + return -1; + + if (a->tv_sec < b->tv_sec) + return 1; + + if (a->tv_usec > b->tv_usec) + return -1; + + if (a->tv_usec < b->tv_usec) + return 1; + + return 0; +} + +static void schedule_nextrun(struct event_timeout *entry, struct timeval *now) +{ + add_timeval(&entry->nextrun, now, &entry->intervall); + + struct event_timeout *search; + list_for_each_entry(search, &event_timeout_list, list) { + if (search->nextrun.tv_sec > entry->nextrun.tv_sec) { + list_add_tail(&entry->list, &search->list); + return; + + } else if (search->nextrun.tv_sec == entry->nextrun.tv_sec && + search->nextrun.tv_usec > entry->nextrun.tv_usec) { + list_add_tail(&entry->list, &search->list); + return; + } + } + list_add_tail(&entry->list, &event_timeout_list); +} + +struct event_timeout * event_add_timeout( + struct timeval *timeout, + int (*callback)(void *privdata), + void *privdata) +{ + struct event_timeout *entry; + entry = malloc(sizeof(struct event_timeout)); + if (entry == NULL) { + log_print(LOG_ERROR, "event_add_timeout(): out of memory"); + return NULL; + } + + entry->flags = 0; + memcpy(&entry->intervall, timeout, sizeof(entry->intervall)); + entry->callback = callback; + entry->privdata = privdata; + + struct timeval now; + gettimeofday(&now, NULL); + + schedule_nextrun(entry, &now); + return entry; +} + +void event_remove_timeout(struct event_timeout *entry) +{ + /* mark the event as deleted -> remove in select() loop */ + entry->flags |= EVENT_DELETE; +} + +int event_loop(void) +{ + fd_set *fdsets = malloc(sizeof(fd_set) * 2); + if (fdsets == NULL) { + log_print(LOG_ERROR, "event_loop(): out of memory"); + return -1; + } + + while (1) { + struct timeval timeout, *timeout_p = NULL; + if (!list_empty(&event_timeout_list)) { + struct timeval now; + gettimeofday(&now, NULL); + + struct event_timeout *entry, *tmp; + list_for_each_entry_safe(entry, tmp, &event_timeout_list, list) { + if (entry->flags & EVENT_DELETE) { + list_del(&entry->list); + free(entry); + continue; + } + + /* timeout not elapsed, exit search (since list is sorted) */ + if (cmp_timeval(&entry->nextrun, &now) == -1) + break; + + /* remove event from list */ + list_del(&entry->list); + + /* execute callback, when callback returns 0 -> schedule event again */ + if (entry->callback(entry->privdata)) { + free(entry); + + } else { + schedule_nextrun(entry, &now); + } + } + + if (!list_empty(&event_timeout_list)) { + entry = list_entry(event_timeout_list.next, typeof(*entry), list); + + /* calc select() timeout */ + sub_timeval(&timeout, &entry->nextrun, &now); + timeout_p = &timeout; + } + } + + fd_set *readfds = NULL, *writefds = NULL; + struct event_fd *entry, *tmp; + + list_for_each_entry_safe(entry, tmp, &event_fd_list, list) { + entry->flags &= ~EVENT_NEW; + + if (entry->flags & EVENT_DELETE) { + list_del(&entry->list); + free(entry); + + } else if (entry->flags & FD_READ) { + if (readfds == NULL) { + readfds = &fdsets[0]; + FD_ZERO(readfds); + } + FD_SET(entry->fd, readfds); + + } else if (entry->flags & FD_WRITE) { + if (writefds == NULL) { + writefds = &fdsets[1]; + FD_ZERO(writefds); + } + FD_SET(entry->fd, writefds); + } + } + + int i = select(FD_SETSIZE, readfds, writefds, NULL, timeout_p); + if (i <= 0) { + /* On error, -1 is returned, and errno is set + * appropriately; the sets and timeout become + * undefined, so do not rely on their contents + * after an error. + */ + continue; + + } else { + list_for_each_entry(entry, &event_fd_list, list) { + if ((entry->flags & EVENT_NEW) != 0) { + /* entry has just been added, execute it next round */ + continue; + } + + if ((entry->flags & FD_READ) && FD_ISSET(entry->fd, readfds)) + if (entry->read_cb(entry->fd, entry->read_priv) != 0) + entry->flags |= EVENT_DELETE; + + if ((entry->flags & FD_WRITE) && FD_ISSET(entry->fd, writefds)) + if (entry->write_cb(entry->fd, entry->write_priv) != 0) + entry->flags |= EVENT_DELETE; + } + } + } + free(fdsets); +} diff --git a/event.h b/event.h new file mode 100644 index 0000000..05ae63f --- /dev/null +++ b/event.h @@ -0,0 +1,42 @@ +#ifndef _EVENT_H_ +#define _EVENT_H_ + +#include + +#define EVENT_NEW 0x1000 +#define EVENT_DELETE 0x2000 + +#define FD_READ 0x0001 +#define FD_WRITE 0x0002 +#define FD_TYPES (FD_READ | FD_WRITE) + +#define event_add_readfd(entry, fd, callback, privdata) \ + event_add_fd(entry, fd, FD_READ, callback, privdata) + +#define event_add_writefd(entry, fd, callback, privdata) \ + event_add_fd(entry, fd, FD_WRITE, callback, privdata) + +/* inner details are not visible to external users (TODO: size unknown) */ +struct event_fd; +struct event_timeout; + +struct event_fd * event_add_fd( + struct event_fd *entry, + int fd, + int type, + int (*callback)(int fd, void *privdata), + void *privdata); + +int event_get_fd(struct event_fd *entry); +void event_remove_fd(struct event_fd *entry); + +struct event_timeout * event_add_timeout( + struct timeval *timeout, + int (*callback)(void *privdata), + void *privdata); + +void event_remove_timeout(struct event_timeout *entry); + +int event_loop(void); + +#endif /* _EVENT_H_ */ diff --git a/http.c b/http.c new file mode 100644 index 0000000..c2281fa --- /dev/null +++ b/http.c @@ -0,0 +1,233 @@ +#include +#include +#include +#include + +#include +#include +#include + +#include "event.h" +#include "http.h" +#include "list.h" +#include "logging.h" +#include "sockaddr.h" +#include "tcpsocket.h" + +static LIST_HEAD(http_cb_list); + +static void destroy_http_con(struct http_con *con) +{ + close(event_get_fd(con->event)); + event_remove_fd(con->event); + + if (con->req_data != NULL) + free(con->req_data); + + if (con->req_headers != NULL) + free(con->req_headers); + + if (con->req_args != NULL) + free(con->req_args); + + free(con); +} + +int http_send_header(struct http_con *con, char *code, char *type) +{ + char buf[256]; + int len = snprintf(buf, sizeof(buf), "HTTP/1.0 %s\r\nContent-Type: %s\r\nConnection: close\r\n\r\n", code, type); + write(con->fd, buf, len); + return 0; +} + +int http_send_error(struct http_con *con, char *code, char *msg) +{ + http_send_header(con, code, "text/plain"); + write(con->fd, msg, strlen(msg)); + return 0; +} + +static int parse_headers(struct http_con *con) +{ + char *data = con->req_data; + while ((data = strstr(data, "\r\n")) && data < con->req_data + con->req_size) { + con->req_header_cnt++; + data += 2; + } + + con->req_headers = malloc(con->req_header_cnt * sizeof(char *)); + if (con->req_headers == NULL) + return -1; + + int i = 0; + data = con->req_data; + + do { + con->req_headers[i++] = data; + + data = strstr(data, "\r\n"); + if (data == NULL) + break; + + *data++ = '\0'; + *data++ = '\0'; + + } while (data < con->req_data + con->req_size); + return 0; +} + +static int parse_args(struct http_con *con) +{ + /* seperate GET (in req->data) */ + char *req = strchr(con->req_data, ' '); + *req++ = '\0'; + + /* HTTP/1.1 will go to header[0] */ + char *tmp = strchr(req, ' '); + *tmp++ = '\0'; + con->req_headers[0] = tmp; + + /* count args */ + tmp = req; + while (*tmp != '\0' && tmp < con->req_data + con->req_size) { + if (*tmp == '?' || *tmp == '&') + con->req_arg_cnt++; + + tmp++; + } + con->req_arg_cnt++; + + /* alloc args */ + con->req_args = malloc(con->req_arg_cnt * sizeof(char *)); + if (con->req_args == NULL) + return -1; + + int i = 0; + tmp = req; + + con->req_args[i++] = tmp; + while (*tmp != '\0' && tmp < con->req_data + con->req_size) { + if (*tmp == '?' || *tmp == '&') { + *tmp++ = '\0'; + con->req_args[i++] = tmp; + } + tmp++; + } + return 0; +} + +static int http_content_handler(int fd, void *privdata) +{ + struct http_con *con = (struct http_con *)privdata; + + if (ioctl(fd, FIONREAD, &con->req_size) == -1) { + log_print(LOG_WARN, "http_content_handler(): ioctl(FIONREAD)"); + destroy_http_con(con); + return -1; + } + + con->req_data = malloc(con->req_size); + if (con->req_data == NULL) { + log_print(LOG_WARN, "http_content_handler(): out of memory"); + destroy_http_con(con); + return -1; + } + + con->req_size = read(fd, con->req_data, con->req_size); + if (con->req_size <= 0) { + log_print(LOG_WARN, "http_content_handler(): read()"); + destroy_http_con(con); + return -1; + } + + if (strncmp(con->req_data, "GET ", 4) != 0) { + http_send_error(con, "400 Invalid Request", "Not a GET request\r\n"); + destroy_http_con(con); + return -1; + } + + if (parse_headers(con) < 0) { + http_send_error(con, "400 Invalid Request", "Error parsing headers\r\n"); + destroy_http_con(con); + return -1; + } + + if (parse_args(con) < 0) { + http_send_error(con, "400 Invalid Request", "Error parsing arguments\r\n"); + destroy_http_con(con); + return -1; + } + + struct http_callback *entry; + list_for_each_entry(entry, &http_cb_list, list) { + + if ((entry->wildcard == 1 && strncmp(entry->name, con->req_args[0], strlen(entry->name)) == 0) || + (entry->wildcard == 0 && strcmp(entry->name, con->req_args[0]) == 0)) { + + entry->callback(con, entry->privdata); + destroy_http_con(con); + return 0; + } + } + + http_send_error(con, "404 Not Found", "File not found\r\n"); + destroy_http_con(con); + return 0; +} + +int http_listen_handler(int fd, void *privdata) +{ + struct http_con *con = malloc(sizeof(struct http_con)); + if (con == NULL) { + log_print(LOG_WARN, "http_listen_handler(): out of memory"); + return 0; + } + + memset(con, 0, sizeof(struct http_con)); + + unsigned int i = sizeof(con->addr); + con->fd = accept(fd, (struct sockaddr *)&con->addr, &i); + if (con->fd < 0) { + free(con); + return 0; + } + + con->event = event_add_readfd(NULL, con->fd, http_content_handler, con); + return 0; +} + +struct http_callback * http_add_cb(const char *name, + int wildcard, + int (* callback)(struct http_con *con, void *privdata), + void *privdata) +{ + struct http_callback *hcb = malloc(sizeof(struct http_callback)); + if (hcb == NULL) { + log_print(LOG_WARN, "http_create_cb(): out of memory"); + return NULL; + } + + hcb->name = strdup(name); + hcb->wildcard = wildcard; + hcb->callback = callback; + hcb->privdata = privdata; + + list_add_tail(&hcb->list, &http_cb_list); + return hcb; +} + +int http_remove_cb(struct http_callback *hcb) +{ + list_del(&hcb->list); + free(hcb->name); + free(hcb); + return 0; +} + +int http_file_cb(struct http_con *con, void *privdata) +{ + log_print(LOG_DEBUG, "req: %s", con->req_args[0]); + http_send_header(con, "500 NOT OK", "text/plain"); + return 0; +} diff --git a/http.h b/http.h new file mode 100644 index 0000000..dcb51f1 --- /dev/null +++ b/http.h @@ -0,0 +1,44 @@ +#ifndef _HTTP_H_ +#define _HTTP_H_ + +#include + +#include "event.h" +#include "list.h" + +struct http_con { + struct sockaddr_in addr; + struct event_fd *event; + + int fd; + + char *req_data; + unsigned int req_size; + + char **req_headers; + unsigned int req_header_cnt; + + char **req_args; + unsigned int req_arg_cnt; +}; + +struct http_callback { + struct list_head list; + char *name; + int wildcard; + + int (* callback)(struct http_con *con, void *privdata); + void *privdata; +}; + +int http_send_header(struct http_con *con, char *code, char *type); +int http_send_error(struct http_con *con, char *code, char *msg); + +struct http_callback * http_add_cb(const char *name, int flags, int (* cb)(struct http_con *con, void *privdata), void *privdata); +int http_remove_cb(struct http_callback *cb); + +int http_file_cb(struct http_con *con, void *privdata); + +int http_listen_handler(int fd, void *privdata); + +#endif // _HTTP_H_ diff --git a/list.h b/list.h new file mode 100644 index 0000000..61f8d93 --- /dev/null +++ b/list.h @@ -0,0 +1,268 @@ +#ifndef _LIST_H_ +#define _LIST_H_ + +/* + * stolen from linux kernel 2.6.11 (http://kernel.org/) + * linux/include/linux/stddef.h (offsetoff) + * linux/include/linux/kernel.h (container_of) + * linux/include/linux/list.h (*list*) + * linux/include/linux/netfilter_ipv4/listhelp.h (LIST_FIND) + * + * modified by Olaf Rempel + */ +#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) + +#define container_of(ptr, type, member) ({ \ + const typeof( ((type *)0)->member ) *__mptr = (ptr); \ + (type *)( (char *)__mptr - offsetof(type,member) );}) + +struct list_head { + struct list_head *next, *prev; +}; + +#define LIST_HEAD_INIT(name) { &(name), &(name) } + +#define LIST_HEAD(name) \ + struct list_head name = LIST_HEAD_INIT(name) + +#define INIT_LIST_HEAD(ptr) do { \ + (ptr)->next = (ptr); (ptr)->prev = (ptr); \ +} while (0) + +/* + * Insert a new entry between two known consecutive entries. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_add(struct list_head *new, + struct list_head *prev, + struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +/* + * list_add - add a new entry + * @new: new entry to be added + * @head: list head to add it after + * + * Insert a new entry after the specified head. + * This is good for implementing stacks. + */ +static inline void list_add(struct list_head *new, struct list_head *head) +{ + __list_add(new, head, head->next); +} + +/* + * list_add_tail - add a new entry + * @new: new entry to be added + * @head: list head to add it before + * + * Insert a new entry before the specified head. + * This is useful for implementing queues. + */ +static inline void list_add_tail(struct list_head *new, struct list_head *head) +{ + __list_add(new, head->prev, head); +} + +/* + * Delete a list entry by making the prev/next entries + * point to each other. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_del(struct list_head * prev, struct list_head * next) +{ + next->prev = prev; + prev->next = next; +} + +/* + * list_del - deletes entry from list. + * @entry: the element to delete from the list. + * Note: list_empty on entry does not return true after this, the entry is + * in an undefined state. + */ +static inline void list_del(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + entry->next = NULL; + entry->prev = NULL; +} + +/* + * list_del_init - deletes entry from list and reinitialize it. + * entry: the element to delete from the list. + */ +static inline void list_del_init(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + INIT_LIST_HEAD(entry); +} + +/* + * list_move - delete from one list and add as another's head + * @list: the entry to move + * @head: the head that will precede our entry + */ +static inline void list_move(struct list_head *list, struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add(list, head); +} + +/* + * list_move_tail - delete from one list and add as another's tail + * @list: the entry to move + * @head: the head that will follow our entry + */ +static inline void list_move_tail(struct list_head *list, + struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add_tail(list, head); +} + +/* + * list_empty - tests whether a list is empty + * @head: the list to test. + */ +static inline int list_empty(const struct list_head *head) +{ + return head->next == head; +} + +static inline void __list_splice(struct list_head *list, + struct list_head *head) +{ + struct list_head *first = list->next; + struct list_head *last = list->prev; + struct list_head *at = head->next; + + first->prev = head; + head->next = first; + + last->next = at; + at->prev = last; +} + +/* + * list_splice - join two lists + * @list: the new list to add. + * @head: the place to add it in the first list. + */ +static inline void list_splice(struct list_head *list, struct list_head *head) +{ + if (!list_empty(list)) + __list_splice(list, head); +} + +/* + * list_splice_init - join two lists and reinitialise the emptied list. + * @list: the new list to add. + * @head: the place to add it in the first list. + * + * The list at @list is reinitialised + */ +static inline void list_splice_init(struct list_head *list, + struct list_head *head) +{ + if (!list_empty(list)) { + __list_splice(list, head); + INIT_LIST_HEAD(list); + } +} + +/* + * list_entry - get the struct for this entry + * @ptr: the &struct list_head pointer. + * @type: the type of the struct this is embedded in. + * @member: the name of the list_struct within the struct. + */ +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +/* + * list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each(pos, head) \ + for (pos = (head)->next; pos != (head); pos = pos->next) + +/* + * list_for_each_prev - iterate over a list backwards + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each_prev(pos, head) \ + for (pos = (head)->prev; pos != (head); pos = pos->prev) + +/* + * list_for_each_safe - iterate over a list safe against removal of list entry + * @pos: the &struct list_head to use as a loop counter. + * @n: another &struct list_head to use as temporary storage + * @head: the head for your list. + */ +#define list_for_each_safe(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) + +/* + * list_for_each_entry - iterate over list of given type + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) + +/* + * list_for_each_entry_reverse - iterate backwards over list of given type. + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_reverse(pos, head, member) \ + for (pos = list_entry((head)->prev, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.prev, typeof(*pos), member)) + +/* + * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry + * @pos: the type * to use as a loop counter. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_safe(pos, n, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) + + +/* Return pointer to first true entry, if any, or NULL. A macro + required to allow inlining of cmpfn. */ +#define LIST_FIND(head, cmpfn, type, args...) \ +({ \ + const struct list_head *__i, *__j = NULL; \ + \ + list_for_each(__i, (head)) \ + if (cmpfn((const type)__i , ## args)) { \ + __j = __i; \ + break; \ + } \ + (type)__j; \ +}) + +#endif /* _LIST_H_ */ diff --git a/logging.c b/logging.c new file mode 100644 index 0000000..d4fd706 --- /dev/null +++ b/logging.c @@ -0,0 +1,103 @@ +/*************************************************************************** + * Copyright (C) 06/2006 by Olaf Rempel * + * razzor@kopf-tisch.de * + * * + * 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 2 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, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ +#include +#include +#include +#include +#include +#include + +#include "logging.h" + +#define BUFSIZE 8192 + +static FILE *log_fd = NULL; +static char *buffer = NULL; + +void log_print(int prio, const char *fmt, ...) +{ + va_list az; + int len; + + if (buffer == NULL) { + buffer = malloc(BUFSIZE); + if (buffer == NULL) { + fprintf(stderr, "log_print: out of memory\nBailing out!\n"); + exit(-1); + } + } + + va_start(az, fmt); + len = vsnprintf(buffer, BUFSIZE, fmt, az); + va_end(az); + + if (len < 0 || len >= BUFSIZE) { + log_print(LOG_ERROR, "log_print: arguments too long"); + errno = 0; + return; + } + + if (errno) { + strncpy(buffer + len, ": ", BUFSIZE - len); + len += 2; + strncpy(buffer + len, strerror(errno), BUFSIZE - len); + } + + if (log_fd) { + char tbuf[64]; + time_t tzgr; + + time(&tzgr); + strftime(tbuf, sizeof(tbuf), "%b %d %H:%M:%S :", localtime(&tzgr)); + + fprintf(log_fd, "%s %s\n", tbuf, buffer); + fflush(log_fd); + + } else { + fprintf(stderr, "%s\n", buffer); + } + + errno = 0; +} + +static void log_close(void) +{ + if (buffer) + free(buffer); + + fclose(log_fd); +} + +int log_init(char *logfile) +{ + log_fd = fopen(logfile, "a"); + if (log_fd == NULL) { + log_print(LOG_ERROR, "log_open('%s'): %s", logfile); + return 0; + } + + if (atexit(log_close) != 0) { + log_print(LOG_ERROR, "log_open(): atexit()"); + return 0; + } + + log_print(LOG_EVERYTIME, "=========================="); + return 1; +} diff --git a/logging.h b/logging.h new file mode 100644 index 0000000..c6e32c0 --- /dev/null +++ b/logging.h @@ -0,0 +1,16 @@ +#ifndef _LOGGING_H_ +#define _LOGGING_H_ + +#define LOG_DEBUG 5 +#define LOG_INFO 4 +#define LOG_NOTICE 3 +#define LOG_WARN 2 +#define LOG_ERROR 1 +#define LOG_CRIT 0 + +#define LOG_EVERYTIME 0 + +int log_init(char *logfile); +void log_print(int prio, const char *fmt, ... ); + +#endif /* _LOGGING_H_ */ diff --git a/simpleweb.c b/simpleweb.c new file mode 100644 index 0000000..fafefb8 --- /dev/null +++ b/simpleweb.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include + +#include +#include +#include + +#include "configfile.h" +#include "event.h" +#include "http.h" +#include "logging.h" +#include "sockaddr.h" +#include "tcpsocket.h" + +static int listen_init(const char *value, void *privdata) +{ + struct sockaddr_in addr; + + if (parse_sockaddr(value, &addr) == -1) { + log_print(LOG_WARN, "invalid listen addr: '%s'", value); + return -1; + } + + int sock = tcp_listen(&addr); + if (sock < 0) + return -1; + + event_add_readfd(NULL, sock, http_listen_handler, NULL); + log_print(LOG_INFO, "listen on %s", get_sockaddr_buf(&addr)); + return 0; +} + +int main(int argc, char *argv[]) +{ + if (config_parse("simpleweb.conf") == -1) + return -1; + + int cnt = config_get_strings("global", "listen", listen_init, NULL); + if (cnt <= 0) { + log_print(LOG_ERROR, "no listen sockets defined!"); + return -1; + } + + http_add_cb("/", 0, http_file_cb, (void *)"/tmp"); + + event_loop(); + + return 0; +} diff --git a/simpleweb.conf b/simpleweb.conf new file mode 100644 index 0000000..669e2e6 --- /dev/null +++ b/simpleweb.conf @@ -0,0 +1,2 @@ +[global] +listen 0.0.0.0:8080 diff --git a/sockaddr.c b/sockaddr.c new file mode 100644 index 0000000..91a5c20 --- /dev/null +++ b/sockaddr.c @@ -0,0 +1,92 @@ +#include +#include +#include + +#include +#include +#include +#include + +int parse_sockaddr(const char *addr, struct sockaddr_in *sa) +{ + char *buf = strdup(addr); + if (buf == NULL) + return -1; + + char *tmp; + char *ipstr = strtok_r(buf, ":", &tmp); + if (ipstr == NULL) { + free(buf); + return -2; + } + + sa->sin_family = AF_INET; + if (inet_pton(AF_INET, ipstr, &sa->sin_addr) <= 0) { + free(buf); + return -3; + } + + char *portstr = strtok_r(NULL, " \r\n", &tmp); + if (portstr == NULL) { + free(buf); + return -4; + } + + int port = atoi(portstr); + if (port < 0 || port > 65535) { + free(buf); + return -5; + } + + sa->sin_port = htons(port); + free(buf); + return 0; +} + +int parse_subnet(const char *addr, struct in_addr *net, struct in_addr *mask) +{ + char *buf = strdup(addr); + if (buf == NULL) + return -1; + + char *tmp; + char *netstr = strtok_r(buf, "/", &tmp); + if (netstr == NULL) { + free(buf); + return -2; + } + + if (inet_pton(AF_INET, netstr, net) <= 0) { + free(buf); + return -3; + } + + char *maskstr = strtok_r(NULL, " \r\n", &tmp); + if (maskstr == NULL) { + mask->s_addr = ~0; + + } else if (inet_pton(AF_INET, maskstr, mask) <= 0) { + int maskbits = atoi(maskstr); + if (maskbits < 0 || maskbits > 32) { + free(buf); + return -4; + } + + mask->s_addr = htonl(~0 << (32 - maskbits)); + } + + free(buf); + return 0; +} + +int get_sockaddr(char *buf, int size, struct sockaddr_in *addr) +{ + return snprintf(buf, size, "%s:%d", inet_ntoa(addr->sin_addr), ntohs(addr->sin_port)); +} + +char * get_sockaddr_buf(struct sockaddr_in *addr) +{ + static char ret[24]; + get_sockaddr(ret, sizeof(ret), addr); + return ret; +} diff --git a/sockaddr.h b/sockaddr.h new file mode 100644 index 0000000..6345285 --- /dev/null +++ b/sockaddr.h @@ -0,0 +1,12 @@ +#ifndef _SOCKADDR_H_ +#define _SOCKADDR_H_ + +#include + +int parse_sockaddr(const char *addr, struct sockaddr_in *sa); +int parse_subnet(const char *addr, struct in_addr *net, struct in_addr *mask); + +int get_sockaddr(char *buf, int size, struct sockaddr_in *addr); +char * get_sockaddr_buf(struct sockaddr_in *addr); + +#endif /* _SOCKADDR_H_ */ diff --git a/tcpsocket.c b/tcpsocket.c new file mode 100644 index 0000000..4c4a8c1 --- /dev/null +++ b/tcpsocket.c @@ -0,0 +1,118 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "logging.h" +#include "sockaddr.h" + +int tcp_listen(struct sockaddr_in *sa) +{ + int sock = socket(AF_INET, SOCK_STREAM, 0); + if (sock < 0 ) { + log_print(LOG_ERROR, "tcp_listen_socket(): socket()"); + return -1; + } + + int i = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i))) { + log_print(LOG_ERROR, "tcp_listen_socket(): setsockopt(SO_REUSEADDR)"); + close(sock); + return -1; + } + + if (bind(sock, (struct sockaddr *)sa, sizeof(*sa))) { + log_print(LOG_ERROR, "tcp_listen_socket(): bind(%s)", get_sockaddr_buf(sa)); + close(sock); + return -1; + } + + if (listen(sock, 8)) { + log_print(LOG_ERROR, "tcp_listen_socket(): listen()"); + close(sock); + return -1; + } + return sock; +} + +int tcp_connect(struct sockaddr_in *sa) +{ + int sock = socket(AF_INET, SOCK_STREAM, 0); + if (sock < 0 ) { + log_print(LOG_ERROR, "tcp_connect_socket(): socket()"); + return -1; + } + + int ret = connect(sock, (struct sockaddr *)sa, sizeof(*sa)); + if (ret != 0) { + log_print(LOG_ERROR, "tcp_connect(): connect(%s)", get_sockaddr_buf(sa)); + close(sock); + return -1; + } + + return sock; +} + +int tcp_connect_nonblock(struct sockaddr_in *sa) +{ + int sock = socket(AF_INET, SOCK_STREAM, 0); + if (sock < 0 ) { + log_print(LOG_ERROR, "tcp_connect_nonblock(): socket()"); + return -1; + } + + int flags = fcntl(sock, F_GETFL, 0); + if (flags < 0) { + log_print(LOG_ERROR, "tcp_connect_nonblock(): fcntl(F_GETFL)"); + close(sock); + return -1; + } + + /* non-blocking connect() */ + if (fcntl(sock, F_SETFL, flags | O_NONBLOCK)) { + log_print(LOG_ERROR, "tcp_connect_nonblock(): fcntl(F_SETFL)"); + close(sock); + return -1; + } + + int ret = connect(sock, (struct sockaddr *)sa, sizeof(*sa)); + if (ret && errno != EINPROGRESS) { + log_print(LOG_ERROR, "tcp_connect_nonblock(): connect(%s)", get_sockaddr_buf(sa)); + close(sock); + return -1; + } + + /* reset EINPROGRESS */ + errno = 0; + + /* all further actions are blocking */ + if (fcntl(sock, F_SETFL, flags)) { + log_print(LOG_ERROR, "tcp_connect_nonblock(): fcntl(F_SETFL)"); + close(sock); + return -1; + } + + return sock; +} + +int tcp_connect_error(int fd) +{ + int err; + unsigned int err_size = sizeof(err); + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &err_size)) { + log_print(LOG_ERROR, "tcp_connect_error(): getsockopt(SO_ERROR)"); + return -1; + } + + if (err) { + errno = err; + log_print(LOG_ERROR, "tcp_connect_error()"); + return -1; + } + + return 0; +} diff --git a/tcpsocket.h b/tcpsocket.h new file mode 100644 index 0000000..606dbab --- /dev/null +++ b/tcpsocket.h @@ -0,0 +1,12 @@ +#ifndef _TCPSOCKET_H_ +#define _TCPSOCKET_H_ + +#include + +int tcp_listen(struct sockaddr_in *sa); +int tcp_connect(struct sockaddr_in *sa); + +int tcp_connect_nonblock(struct sockaddr_in *sa); +int tcp_connect_error(int fd); + +#endif // _TCPSOCKET_H_