From abd29b4728d9ed39b423bbcd5f2f14a35edd5c25 Mon Sep 17 00:00:00 2001 From: Olaf Rempel Date: Wed, 11 Apr 2007 19:37:40 +0200 Subject: [PATCH] initial --- .gitignore | 6 + Makefile | 21 ++++ brarpwatch.c | 111 ++++++++++++++++++ brarpwatch.conf | 7 ++ configfile.c | 217 ++++++++++++++++++++++++++++++++++ configfile.h | 15 +++ datastore.c | 286 +++++++++++++++++++++++++++++++++++++++++++++ datastore.h | 11 ++ event.c | 302 ++++++++++++++++++++++++++++++++++++++++++++++++ event.h | 42 +++++++ list.h | 268 ++++++++++++++++++++++++++++++++++++++++++ logging.c | 102 ++++++++++++++++ logging.h | 19 +++ netlink.c | 95 +++++++++++++++ netlink.h | 7 ++ ulogparse.c | 71 ++++++++++++ ulogparse.h | 6 + 17 files changed, 1586 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 brarpwatch.c create mode 100644 brarpwatch.conf create mode 100644 configfile.c create mode 100644 configfile.h create mode 100644 datastore.c create mode 100644 datastore.h create mode 100644 event.c create mode 100644 event.h create mode 100644 list.h create mode 100644 logging.c create mode 100644 logging.h create mode 100644 netlink.c create mode 100644 netlink.h create mode 100644 ulogparse.c create mode 100644 ulogparse.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9a255c1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*.o +*.d +barpwatch +barpwatch.log + +ebtables* \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2ffaf6e --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +CFLAGS := -O2 -pipe -Wall +LDFLAGS := -lpthread -lnfnetlink -lnetfilter_log + +OBJS := configfile.o datastore.o event.o logging.o netlink.o ulogparse.o + +all: brarpwatch + +brarpwatch: $(OBJS) brarpwatch.o + $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@ + +%.o: %.c + $(CC) $(CFLAGS) -c $< -o $@ + +%.d: %.c + $(CC) $(CFLAGS) -MM -c $< -o $@ + +clean: + rm -f brarpwatch *.d *.o *.log + +DEPS := $(wildcard *.c) +-include $(DEPS:.c=.d) diff --git a/brarpwatch.c b/brarpwatch.c new file mode 100644 index 0000000..d09d47d --- /dev/null +++ b/brarpwatch.c @@ -0,0 +1,111 @@ +#include +#include +#include +#include + +#include + +#include "configfile.h" +#include "datastore.h" +#include "event.h" +#include "logging.h" +#include "netlink.h" + +#define DEFAULT_CONFIG "brarpwatch.conf" +#define DEFAULT_LOGFILE "brarpwatch.log" + +static struct option opts[] = { + {"config", 1, 0, 'c'}, + {"debug", 0, 0, 'd'}, + {"help", 0, 0, 'h'}, + {0, 0, 0, 0} +}; + +int main(int argc, char *argv[]) +{ + char *config = DEFAULT_CONFIG; + int code, arg = 0, debug = 0; + + do { + code = getopt_long(argc, argv, "c:dh", opts, &arg); + + switch (code) { + case 'c': /* config */ + config = optarg; + break; + + case 'd': /* debug */ + debug = 1; + break; + + case 'h': /* help */ + printf("Usage: brarpwatch [options]\n" + "Options: \n" + " --config -c configfile use this configfile\n" + " --debug -d do not fork and log to stderr\n" + " --help -h this help\n" + "\n"); + exit(0); + break; + + case '?': /* error */ + exit(-1); + break; + + default: /* unknown / all options parsed */ + break; + } + } while (code != -1); + + /* parse config file */ + if (config_parse(config)) + exit(1); + + if (datastore_init() < 0) + exit(1); + + if (netlink_init() < 0) { + datastore_close(); + exit(1); + } + +#if 0 + unsigned char mac[6]; + unsigned char mac2[6]; + unsigned char mac3[6]; + unsigned int ip = 0x01000a0a; + unsigned int ip2 = 0x02000a0a; + long stamp = time(NULL); + + // subnet not found + ds_check_update_ip("eth0", ip +1, mac, stamp++); + + // wrong dev not found + ds_check_update_ip("eth1", ip, mac, stamp++); + + // ok + ds_check_update_ip("eth0", ip, mac, stamp++); + + // wrong dev + ds_check_update_ip("eth1", ip, mac, stamp++); + + // update + ds_check_update_ip("eth0", ip, mac, stamp++); + + // warn + ds_check_update_ip("eth0", ip, mac2, stamp++); + + // warn + ds_check_update_ip("eth0", ip, mac3, stamp++); + + // ok + ds_check_update_ip("eth0", ip2, mac, stamp++); + +#endif + + event_loop(); + + netlink_close(); + datastore_close(); + return 0; +} diff --git a/brarpwatch.conf b/brarpwatch.conf new file mode 100644 index 0000000..3267382 --- /dev/null +++ b/brarpwatch.conf @@ -0,0 +1,7 @@ +[global] +hashsize 1021 +hashgc 300 + +netlink_group 1 + +subnet eth0:10.10.0.0/16 diff --git a/configfile.c b/configfile.c new file mode 100644 index 0000000..1314bb3 --- /dev/null +++ b/configfile.c @@ -0,0 +1,217 @@ +/*************************************************************************** + * 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; + const char *name; +}; + +struct conf_tupel { + struct list_head list; + const char *option; + const 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; +} + +void config_free(void) +{ + struct conf_section *section, *section_tmp; + struct conf_tupel *tupel, *tupel_tmp; + + list_for_each_entry_safe(section, section_tmp, &config_list, list) { + list_for_each_entry_safe(tupel, tupel_tmp, §ion->tupel_list, list) { + list_del(&tupel->list); + free((char *)tupel->option); + free((char *)tupel->parameter); + free(tupel); + } + list_del(§ion->list); + free(section); + } +} + +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; +} + +const char * config_get_string(const char *section_str, const char *option, const 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) +{ + const 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..9a2b669 --- /dev/null +++ b/configfile.h @@ -0,0 +1,15 @@ +#ifndef _CONFIG_H_ +#define _CONFIG_H_ + +int config_parse(const char *config); +void config_free(void); + +const char * config_get_string(const char *section_str, const char *option, const 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/datastore.c b/datastore.c new file mode 100644 index 0000000..923caa3 --- /dev/null +++ b/datastore.c @@ -0,0 +1,286 @@ +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "configfile.h" +#include "datastore.h" +#include "event.h" +#include "list.h" +#include "logging.h" + +struct subnet_entry { + struct list_head list; + + uint32_t ip; + uint32_t mask; + + char dev[IFNAMSIZ]; +}; + +struct hash_table { + struct list_head bucket[0]; +}; + +struct ip_entry { + struct list_head list; + + uint32_t ip; + struct subnet_entry *subnet; + + uint8_t mac[6]; + uint32_t timestamp; +}; + +LIST_HEAD(subnet_list); + +static int hashsize; +static struct hash_table *hashtable; +static struct event_timeout *gc_event; + +static int ds_add_subnet(const char *dev, uint32_t ip, uint32_t mask) +{ + struct subnet_entry *entry = malloc(sizeof(struct subnet_entry)); + if (entry == NULL) { + log_print(LOG_ERROR, "ds_add_subnet(): out of memory"); + return -1; + } + + entry->ip = ip; + entry->mask = mask; + strncpy(entry->dev, dev, sizeof(entry->dev)); + + list_add_tail(&entry->list, &subnet_list); + return 0; +} + +static struct subnet_entry * ds_find_subnet(uint32_t ip) +{ + struct subnet_entry *entry; + list_for_each_entry(entry, &subnet_list, list) + if ((ip & entry->mask) == entry->ip) + return entry; + + return NULL; +} + +static int ds_calc_hash(uint32_t ip) +{ + /* TODO: real hash */ + return (ip * 16777219) % hashsize; +} + +static struct ip_entry * ds_find_ip(uint32_t ip) +{ + struct ip_entry *entry; + list_for_each_entry(entry, &(hashtable->bucket[ds_calc_hash(ip)]), list) + if (entry->ip == ip) + return entry; + + return NULL; +} + +static int is_same_mac(uint8_t *a, uint8_t *b) +{ + return ((a[0] ^ b[0]) | (a[1] ^ b[1]) | (a[2] ^ b[2]) | + (a[3] ^ b[3]) | (a[4] ^ b[4]) | (a[5] ^ b[5])) == 0x00; +} + +static void ds_error(struct ip_entry *entry, const char *msg, const char *dev) +{ + char *subnetdev = '\0'; + char ip[16], subnet[16] = {'\0'}, mask[16] = {'\0'}; + + inet_ntop(AF_INET, &entry->ip, ip, sizeof(ip)); + + if (entry->subnet != NULL) { + subnetdev = entry->subnet->dev; + inet_ntop(AF_INET, &entry->subnet->ip, subnet, sizeof(subnet)); + inet_ntop(AF_INET, &entry->subnet->mask, mask, sizeof(mask)); + } + + log_print(LOG_DEBUG, "%s: paket %s: %s[%02x:%02x:%02x:%02x:%02x:%02x] subnet %s: %s/%s", + msg, dev, ip, + entry->mac[0], entry->mac[1], entry->mac[2], + entry->mac[3], entry->mac[4], entry->mac[5], + subnetdev, subnet, mask); +} + +int ds_check_update_ip(const char *dev, uint32_t ip, uint8_t *mac, uint32_t timestamp) +{ + struct ip_entry *entry = ds_find_ip(ip); + if (entry == NULL) { + entry = malloc(sizeof(struct ip_entry)); + if (entry == NULL) { + log_print(LOG_ERROR, "ds_check_update_ip(): out of memory"); + return -1; + } + + entry->ip = ip; + memcpy(entry->mac, mac, 6); + entry->timestamp = timestamp; + + entry->subnet = ds_find_subnet(ip); + if (entry->subnet == NULL) { + ds_error(entry, "NEW: subnet not found", dev); + free(entry); + return -1; + } + + if (strncmp(entry->subnet->dev, dev, sizeof(entry->subnet->dev)) != 0) { + ds_error(entry, "NEW: invalid device", dev); + free(entry); + return -1; + } + + list_add_tail(&entry->list, &(hashtable->bucket[ds_calc_hash(ip)])); + return 0; + + } else if (strncmp(entry->subnet->dev, dev, sizeof(entry->subnet->dev)) != 0) { + ds_error(entry, "UPDATE: invalid device", dev); + return -1; + } + + if (is_same_mac(entry->mac, mac)) { + entry->timestamp = timestamp; + + } else { + char ip[16]; + inet_ntop(AF_INET, &entry->ip, ip, sizeof(ip)); + + log_print(LOG_DEBUG, "UPDATE: %s: %s [%02x:%02x:%02x:%02x:%02x:%02x] -> [%02x:%02x:%02x:%02x:%02x:%02x]", + dev, ip, + entry->mac[0], entry->mac[1], entry->mac[2], + entry->mac[3], entry->mac[4], entry->mac[5], + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + + memcpy(entry->mac, mac, 6); + entry->timestamp = timestamp; + } + return 0; +} + +static int parse_netmask(char *buf, uint32_t *ip, uint32_t *mask) +{ + char *maskstr = strchr(buf, '/'); + if (maskstr == NULL) + return -1; + + *maskstr++ = '\0'; + + if (inet_pton(AF_INET, buf, ip) <= 0) + return -1; + + if (inet_pton(AF_INET, maskstr, mask) <= 0) { + *mask = atoi(maskstr); + if (*mask < 0 || *mask > 32) + return -1; + + *mask = htonl(0xFFFFFFFF << (32 - *mask)); + } + return 0; +} + +static int add_subnet_cb(const char *parameter, void *privdata) +{ + char *dev = strdup(parameter); + + char *ipmask = strchr(dev, ':'); + if (ipmask == NULL) { + log_print(LOG_WARN, "add_subnet_cb(): no ip found"); + free(dev); + return -1; + } + + *ipmask++ = '\0'; + + uint32_t ip, mask; + if (parse_netmask(ipmask, &ip, &mask) != 0) { + log_print(LOG_WARN, "add_subnet_cb(): invalid ip/mask"); + free(dev); + return -1; + } + + char ipstr[16], maskstr[16]; + inet_ntop(AF_INET, &ip, ipstr, sizeof(ipstr)); + inet_ntop(AF_INET, &mask, maskstr, sizeof(maskstr)); + log_print(LOG_INFO, "datastore: adding device %s with subnet %s/%s", dev, ipstr, maskstr); + + ds_add_subnet(dev, ip, mask); + free(dev); + return 0; +} + +static int hash_gc(void *privdata) +{ + uint32_t check = time(NULL) - (int)privdata; + + uint32_t i, total = 0, removed = 0; + for (i = 0; i < hashsize; i++) { + struct ip_entry *entry, *tmp; + list_for_each_entry_safe(entry, tmp, &(hashtable->bucket[i]), list) { + total++; + if (entry->timestamp < check) { + list_del(&entry->list); + free(entry); + removed++; + } + } + } + + log_print(LOG_DEBUG, "garbage collector: %d/%d", removed, total); + return 0; +} + +int datastore_init(void) +{ + hashsize = config_get_int("global", "hashsize", 1021); + hashtable = malloc(sizeof(struct hash_table) + sizeof(struct list_head) * hashsize); + if (hashtable == NULL) { + log_print(LOG_ERROR, "ds_init(): out of memory"); + return -1; + } + + int i; + for (i = 0; i < hashsize; i++) + INIT_LIST_HEAD(&(hashtable->bucket[i])); + + int cnt = config_get_strings("global", "subnet", add_subnet_cb, NULL); + if (cnt <= 0) { + log_print(LOG_ERROR, "ds_init(): no subnets defined"); + free(hashtable); + return -1; + } + + int timeout = config_get_int("global", "hashgc", 300); + struct timeval tv = { .tv_sec = timeout, .tv_usec = 0 }; + gc_event = event_add_timeout(&tv, hash_gc, (void *)timeout); + + return 0; +} + +void datastore_close(void) +{ + struct subnet_entry *entry, *tmp; + list_for_each_entry_safe(entry, tmp, &subnet_list, list) { + list_del(&entry->list); + free(entry); + } + + int i; + for (i = 0; i < hashsize; i++) { + struct ip_entry *entry, *tmp; + list_for_each_entry_safe(entry, tmp, &(hashtable->bucket[i]), list) { + list_del(&entry->list); + free(entry); + } + } + + event_remove_timeout(gc_event); + free(hashtable); +} diff --git a/datastore.h b/datastore.h new file mode 100644 index 0000000..8bd1bf4 --- /dev/null +++ b/datastore.h @@ -0,0 +1,11 @@ +#ifndef _DATASTORE_H_ +#define _DATASTORE_H_ + +#include + +int datastore_init(void); +void datastore_close(void); + +int ds_check_update_ip(const char *dev, uint32_t ip, uint8_t *mac, uint32_t timestamp); + +#endif /* _DATASTORE_H_ */ diff --git a/event.c b/event.c new file mode 100644 index 0000000..8e307e7 --- /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->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; + } + + entry->flags |= EVENT_NEW; + 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) { + 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); + } + } + + 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; + } + } + + 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/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..61dcfcf --- /dev/null +++ b/logging.c @@ -0,0 +1,102 @@ +/*************************************************************************** + * 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 int log_prio = LOG_EVERYTIME; +static char *buffer = NULL; + +int log_print(int prio, const char *fmt, ...) +{ + va_list az; + int len = 0, retval; + + if (prio < log_prio) + return 0; + + if (buffer == NULL) { + buffer = malloc(BUFSIZE); + if (buffer == NULL) { + fprintf(stderr, "log_print(): out of memory\n"); + return -1; + } + } + + if (log_fd != NULL) { + time_t tzgr; + time(&tzgr); + + len += strftime(buffer, BUFSIZE, "%b %d %H:%M:%S :", localtime(&tzgr)); + } + + va_start(az, fmt); + len += vsnprintf(buffer + len, BUFSIZE - len, fmt, az); + va_end(az); + + if (len < 0 || len >= BUFSIZE) { + errno = 0; + return log_print(LOG_ERROR, "log_print: arguments too long"); + } + + if (errno) { + len += snprintf(buffer + len, BUFSIZE - len, ": %s", strerror(errno)); + errno = 0; + } + + retval = fprintf((log_fd ? log_fd : stderr), "%s\n", buffer); + fflush(log_fd); + return retval; +} + +void log_close(void) +{ + if (buffer) + free(buffer); + + if (log_fd) + fclose(log_fd); +} + +int log_init(const char *logfile) +{ + if (log_fd != NULL) + log_close(); + + log_fd = fopen(logfile, "a"); + if (log_fd == NULL) { + fprintf(stderr, "log_init(): can not open logfile"); + return -1; + } + return 0; +} + +void log_setprio(int prio) +{ + log_prio = prio; +} diff --git a/logging.h b/logging.h new file mode 100644 index 0000000..82d028d --- /dev/null +++ b/logging.h @@ -0,0 +1,19 @@ +#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(const char *logfile); +void log_close(void); +void log_setprio(int prio); + +int log_print(int prio, const char *fmt, ... ); + +#endif /* _LOGGING_H_ */ diff --git a/netlink.c b/netlink.c new file mode 100644 index 0000000..c0c992d --- /dev/null +++ b/netlink.c @@ -0,0 +1,95 @@ +#include +#include +#include + +#include +#include + +#include "configfile.h" +#include "event.h" +#include "logging.h" +#include "ulogparse.h" + +static struct event_fd *nl_event; + +#define BUFLEN 65536 +static char buf[BUFLEN]; + +static int netlink_cb(int fd, void *privdata) +{ + int len = recv(fd, buf, BUFLEN, 0); + if (len <= 0) { + log_print(LOG_WARN, "netlink_cb(): recv()"); + return 0; + } + + struct nlmsghdr *nlh = (struct nlmsghdr *)buf; + if (nlh->nlmsg_flags & MSG_TRUNC || len > BUFLEN) { + log_print(LOG_WARN, "netlink_cb(): message truncated"); + return 0; + } + + if (!NLMSG_OK(nlh, BUFLEN)) { + log_print(LOG_WARN, "netlink_cb(): parse error"); + return 0; + } + + while (nlh != NULL) { + parse_ulog_packet(NLMSG_DATA(nlh)); + + if (nlh->nlmsg_flags & NLM_F_MULTI && nlh->nlmsg_type != NLMSG_DONE) { + int remain_len = (len - ((char *)nlh - buf)); + nlh = NLMSG_NEXT(nlh, remain_len); + + } else { + nlh = NULL; + } + } + return 0; +} + +int netlink_init(void) +{ + int fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_NFLOG); + if (fd == 0) { + log_print(LOG_ERROR, "netlink_init(): socket()"); + return -1; + } + + struct sockaddr_nl local; + local.nl_family = AF_NETLINK; + local.nl_pid = 0; + local.nl_groups = 0; + if (bind(fd, (struct sockaddr *)&local, sizeof(local)) < 0) { + log_print(LOG_ERROR, "netlink_init(): bind()"); + close(fd); + return -1; + } + + socklen_t addrlen = sizeof(local); + if (getsockname(fd, (struct sockaddr *)&local, &addrlen) < 0) { + log_print(LOG_ERROR, "netlink_init(): getsockname()"); + close(fd); + return -1; + } + + /* second bind with correct pid (assigned from kernel) */ + local.nl_groups = config_get_int("global", "netlink_group", 1); + if (bind(fd, (struct sockaddr *)&local, sizeof(local)) < 0) { + log_print(LOG_ERROR, "netlink_init(): bind()"); + close(fd); + return -1; + } + + log_print(LOG_INFO, "netlink: listening on group %d", local.nl_groups); + + nl_event = event_add_readfd(NULL, fd, netlink_cb, NULL); + return 0; +} + +void netlink_close(void) +{ + int fd = event_get_fd(nl_event); + event_remove_fd(nl_event); + close(fd); +} diff --git a/netlink.h b/netlink.h new file mode 100644 index 0000000..59e2516 --- /dev/null +++ b/netlink.h @@ -0,0 +1,7 @@ +#ifndef _NETLINK_H_ +#define _NETLINK_H_ + +int netlink_init(void); +void netlink_close(void); + +#endif /* _NETLINK_H_ */ diff --git a/ulogparse.c b/ulogparse.c new file mode 100644 index 0000000..5354a1c --- /dev/null +++ b/ulogparse.c @@ -0,0 +1,71 @@ +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "logging.h" + +#if 0 +static int is_same_mac(uint8_t *a, uint8_t *b) +{ + return ((a[0] ^ b[0]) | (a[1] ^ b[1]) | (a[2] ^ b[2]) | + (a[3] ^ b[3]) | (a[4] ^ b[4]) | (a[5] ^ b[5])) == 0x00; +} + +static int is_null_mac(uint8_t *a) +{ + return (a[0] | a[1] | a[2] | a[3] | a[4] | a[5]) == 0x00; +} + +static int is_broadcast_mac(uint8_t *a) +{ + return (a[0] & a[1] & a[2] & a[3] & a[4] & a[5]) == 0xFF; +} +#endif + +int parse_ulog_packet(void *data) +{ + ebt_ulog_packet_msg_t *pkt = (ebt_ulog_packet_msg_t *)data; + + struct ether_header *eh = (struct ether_header *)pkt->data; + struct ether_arp *ah = (struct ether_arp *)(eh +1); + + /* only ARP packets with ETHER <-> IPv4 */ + if (eh->ether_type != 0x0608 || ah->ea_hdr.ar_hrd != 0x0100 || ah->ea_hdr.ar_pro != 0x0008) + return 0; + + char time_str[40]; + struct tm *ptm = localtime(&pkt->stamp.tv_sec); + strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", ptm); + + char *op = "unknown op "; + if (ah->ea_hdr.ar_op == 0x0100) + op = "ARP Request"; + + else if (ah->ea_hdr.ar_op == 0x0200) + op = "ARP Reply "; + + char sip[16], dip[16]; + inet_ntop(AF_INET, ah->arp_spa, sip, sizeof(sip)); + inet_ntop(AF_INET, ah->arp_tpa, dip, sizeof(dip)); + + log_print(LOG_DEBUG, "%s: %s(%s): %02x:%02x:%02x:%02x:%02x:%02x => %02x:%02x:%02x:%02x:%02x:%02x %s %02x:%02x:%02x:%02x:%02x:%02x (%s) => %02x:%02x:%02x:%02x:%02x:%02x (%s)", + time_str, pkt->indev, pkt->physindev, + eh->ether_shost[0], eh->ether_shost[1], eh->ether_shost[2], + eh->ether_shost[3], eh->ether_shost[4], eh->ether_shost[5], + eh->ether_dhost[0], eh->ether_dhost[1], eh->ether_dhost[2], + eh->ether_dhost[3], eh->ether_dhost[4], eh->ether_dhost[5], + op, + ah->arp_sha[0], ah->arp_sha[1], ah->arp_sha[2], + ah->arp_sha[3], ah->arp_sha[4], ah->arp_sha[5], sip, + ah->arp_tha[0], ah->arp_tha[1], ah->arp_tha[2], + ah->arp_tha[3], ah->arp_tha[4], ah->arp_tha[5], dip); + + return 0; +} diff --git a/ulogparse.h b/ulogparse.h new file mode 100644 index 0000000..3c39e21 --- /dev/null +++ b/ulogparse.h @@ -0,0 +1,6 @@ +#ifndef _ULOGPARSE_H_ +#define _ULOGPARSE_H_ + +int parse_ulog_packet(void *data); + +#endif /* _ULOGPARSE_H_ */