This commit is contained in:
Olaf Rempel 2007-05-15 17:39:34 +02:00
commit d169f4ab47
17 changed files with 1550 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*.o
*.d
torrent-stats
torrent-stats.log

20
Makefile Normal file
View File

@ -0,0 +1,20 @@
CFLAGS := -O2 -pipe -Wall
OBJS := configfile.o event.o linebuffer.o logging.o sockaddr.o tcpsocket.o
all: torrent-stats
torrent-stats: $(OBJS) torrent-stats.o
$(CC) $(CFLAGS) $^ -o $@
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
%.d: %.c
$(CC) $(CFLAGS) -MM -c $< -o $@
clean:
rm -f torrent-stats *.d *.o *.log
DEPS := $(wildcard *.c)
-include $(DEPS:.c=.d)

217
configfile.c Normal file
View File

@ -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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#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(&section->list);
INIT_LIST_HEAD(&section->tupel_list);
section->name = strdup(name);
if (section->name == NULL) {
free(section);
return NULL;
}
list_add_tail(&section->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, &section->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, &section->tupel_list, list) {
list_del(&tupel->list);
free((char *)tupel->option);
free((char *)tupel->parameter);
free(tupel);
}
list_del(&section->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, &section->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, &section->tupel_list, list) {
if (!strcmp(tupel->option, option))
if (callback(tupel->parameter, privdata) == 0)
cnt++;
}
return cnt;
}

15
configfile.h Normal file
View File

@ -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_ */

302
event.c Normal file
View File

@ -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 <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#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);
}

42
event.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef _EVENT_H_
#define _EVENT_H_
#include <sys/time.h>
#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_ */

68
linebuffer.c Normal file
View File

@ -0,0 +1,68 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "linebuffer.h"
struct linebuffer * create_linebuffer(int size)
{
struct linebuffer *retval = malloc(sizeof(struct linebuffer) + size);
if (retval == NULL)
return NULL;
retval->size = size;
retval->pos = 0;
return retval;
}
int linebuffer_read(struct linebuffer *lbuf, int fd)
{
char buf[32];
int len = read(fd, buf, sizeof(buf));
if (len <= 0)
return -1;
int i;
for (i = 0; i < len; i++) {
/* "understand" backspace */
if (buf[i] == 0x08 && lbuf->pos > 0) {
lbuf->pos--;
/* copy */
} else if (buf[i] >= ' ' || buf[i] == '\n') {
lbuf->data[lbuf->pos++] = buf[i];
}
if (lbuf->pos > lbuf->size)
return -1;
}
return 0;
}
char * linebuffer_get(struct linebuffer *lbuf)
{
char *newline = memchr(lbuf->data, '\n', lbuf->pos);
if (newline == NULL)
return NULL;
char *retval = NULL;
*newline = '\0';
int len = newline - lbuf->data;
if (len > 0)
retval = strdup(lbuf->data);
lbuf->pos -= len +1;
memmove(lbuf->data, newline +1, lbuf->pos);
return retval;
}
int linebuffer_clear(struct linebuffer *lbuf)
{
int oldpos = lbuf->pos;
lbuf->pos = 0;
return oldpos;
}

18
linebuffer.h Normal file
View File

@ -0,0 +1,18 @@
#ifndef _LINEBUFFER_H_
#define _LINEBUFFER_H_
struct linebuffer {
int size;
int pos;
char data[0];
};
struct linebuffer * create_linebuffer(int size);
int linebuffer_read(struct linebuffer *lbuf, int fd);
char * linebuffer_get(struct linebuffer *lbuf);
int linebuffer_clear(struct linebuffer *lbuf);
#endif /* _LINEBUFFER_H_ */

268
list.h Normal file
View File

@ -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 <razzor@kopf-tisch.de>
*/
#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_ */

102
logging.c Normal file
View File

@ -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 <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdarg.h>
#include <errno.h>
#include <string.h>
#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;
}

19
logging.h Normal file
View File

@ -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_ */

92
sockaddr.c Normal file
View File

@ -0,0 +1,92 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
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;
}

12
sockaddr.h Normal file
View File

@ -0,0 +1,12 @@
#ifndef _SOCKADDR_H_
#define _SOCKADDR_H_
#include <netinet/in.h>
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_ */

118
tcpsocket.c Normal file
View File

@ -0,0 +1,118 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>
#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;
}

12
tcpsocket.h Normal file
View File

@ -0,0 +1,12 @@
#ifndef _TCPSOCKET_H_
#define _TCPSOCKET_H_
#include <netinet/ip.h>
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_

239
torrent-stats.c Normal file
View File

@ -0,0 +1,239 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "configfile.h"
#include "event.h"
#include "linebuffer.h"
#include "list.h"
#include "logging.h"
#include "sockaddr.h"
#include "tcpsocket.h"
/*
startup:
PROTOCOL 0002
CTORRENT -CD0300-0xECFCD73A6132281994AF75C3 1179237904 1179239410 debian-40r0-i386-netinst.iso.torrent
CTSTATUS 0:174/1:5/0 636/636/636 0,1070 169914368,638976 0,0 32
periodic:
CTBW 0,1070 0,0
-------------------------
"SENDDETAIL":
CTDETAIL 166621184 262144 1179239468 1179238848
CTFILES
CTFILE 1 636 636 636 166621184 debian-40r0-i386-netinst.iso
CTFDONE
"CTDETAIL %lld %d %ld %ld",
BTCONTENT.GetTotalFilesLength(),
(int)(BTCONTENT.GetPieceLength()),
(long)now,
(long)(BTCONTENT.GetSeedTime()) );
"CTFILE %d %d %d %d %llu %s",
(int)n,
(int)(BTCONTENT.getFilePieces(n)),
(int)(tmpBitField.Count()),
(int)(tmpavail.Count()),
(unsigned long long)(file->bf_length),
file->bf_filename );
-------------------------
"SENDSTATUS":
CTSTATUS 0:174/1:5/0 636/636/636 0,959 169914368,655360 0,0 32
"CTSTATUS %d:%d/%d:%d/%d %d/%d/%d %d,%d %llu,%llu %d,%d %d",
(int)(m_ctstatus.seeders),
(int)(Tracker.GetSeedsCount() - ((BTCONTENT.pBF->IsFull() && Tracker.GetSeedsCount() > 0) ? 1 : 0)),
(int)(m_ctstatus.leechers),
(int)(Tracker.GetPeersCount() - Tracker.GetSeedsCount() - ((!BTCONTENT.pBF->IsFull() && Tracker.GetPeersCount() > 0) ? 1 : 0)),
(int)(WORLD.GetConnCount()),
(int)(m_ctstatus.nhave),
(int)(m_ctstatus.ntotal),
(int)(WORLD.Pieces_I_Can_Get()),
(int)(m_ctstatus.dlrate),
(int)(m_ctstatus.ulrate),
(unsigned long long)(m_ctstatus.dltotal),
(unsigned long long)(m_ctstatus.ultotal),
(int)(m_ctstatus.dlimit),
(int)(m_ctstatus.ulimit),
(int)(m_ctstatus.cacheused) );
-------------------------
"SENDCONF":
CTCONFIG 0 72 0.000000 100 1 0 16 0
"SENDPEERS":
CTPEERS
CTPEER M3-4-2--bae925c0c070 159.148.184.187 UnUi 0 862 114688 688128 520
CTPDONE
*/
static LIST_HEAD(client_list);
struct client_con {
struct list_head list;
struct sockaddr_in addr;
struct event_timeout *trigger;
struct event_fd *event;
struct linebuffer *lbuf;
int bw_up;
int bw_dn;
unsigned long long total_up;
unsigned long long total_dn;
int chunk_total;
int chunk_avail;
int chunk_have;
};
static void free_client(struct client_con *con)
{
close(event_get_fd(con->event));
event_remove_fd(con->event);
event_remove_timeout(con->trigger);
free(con->lbuf);
free(con);
}
static int trigger_status(void *privdata)
{
struct client_con *con = (struct client_con *)privdata;
write(event_get_fd(con->event), "SENDSTATUS\n", 11);
return 0;
}
static int data_cb(int fd, void *privdata)
{
struct client_con *con = (struct client_con *)privdata;
if (linebuffer_read(con->lbuf, fd) < 0) {
log_print(LOG_WARN, "data_cb(): client %s read", get_sockaddr_buf(&con->addr));
list_del(&con->list);
free_client(con);
return -1;
}
char *line;
while ((line = linebuffer_get(con->lbuf)) != NULL) {
// log_print(LOG_DEBUG, "%s: %s", get_sockaddr_buf(&con->addr), line);
if (strncmp(line, "CTBW ", 5) == 0) {
int bwup, bwdn, liup, lidn;
if (sscanf(line +5, "%d,%d %d,%d", &bwdn, &bwup, &lidn, &liup) == 4) {
con->bw_up = bwup;
con->bw_dn = bwdn;
}
} else if (strncmp(line, "CTSTATUS ", 9) == 0) {
int seeds1 = 0, seeds2 = 0, leech1 = 0, leech2 = 0, count = 0;
int chunk1 = 0, chunk2 = 0, chunk3 = 0, bwdn = 0, bwup = 0;
int lidn = 0, liup = 0, cache = 0;
unsigned long long totdn = 0, totup = 0;
if (sscanf(line +9, "%d:%d/%d:%d/%d %d/%d/%d %d,%d %llu,%llu %d,%d %d",
&seeds1, &seeds2, &leech1, &leech2, &count,
&chunk1, &chunk2, &chunk3,
&bwdn, &bwup, &totdn, &totup,
&lidn, &liup, &cache) == 15) {
con->total_up = totup;
con->total_dn = totdn;
con->chunk_have = chunk1;
con->chunk_total = chunk2;
con->chunk_avail = chunk3;
}
log_print(LOG_INFO, "%s: got %3.2lf%% of %3.2lf%% [down: %llu (%d), up: %llu (%d)] ",
get_sockaddr_buf(&con->addr),
(double)con->chunk_have / (double)con->chunk_total * 100.0,
(double)con->chunk_avail / (double)con->chunk_total * 100.0,
con->total_dn, con->bw_dn, con->total_up, con->bw_up);
}
free(line);
}
return 0;
}
static int accept_cb(int fd, void *privdata)
{
struct client_con *con = malloc(sizeof(struct client_con));
if (con == NULL) {
log_print(LOG_WARN, "accept_cb(): out of memory");
return 0;
}
memset(con, 0, sizeof(struct client_con));
con->lbuf = create_linebuffer(1024);
if (con->lbuf == NULL) {
log_print(LOG_WARN, "accept_cb(): out of memory");
free(con);
return 0;
}
unsigned int i = sizeof(con->addr);
int sockfd = accept(fd, (struct sockaddr *)&con->addr, &i);
if (sockfd < 0) {
log_print(LOG_WARN, "accept_cb(): accept()");
free(con->lbuf);
free(con);
return 0;
}
log_print(LOG_INFO, "new client %s", get_sockaddr_buf(&con->addr));
struct timeval tv = { .tv_sec = 10, .tv_usec = 0 };
con->trigger = event_add_timeout(&tv, trigger_status, con);
con->event = event_add_readfd(NULL, sockfd, data_cb, con);
list_add(&con->list, &client_list);
return 0;
}
static int listen_cb(const char *parameter, void *privdata)
{
struct sockaddr_in addr;
if (parse_sockaddr(parameter, &addr) < 0) {
log_print(LOG_WARN, "listen_cb(): invalid address");
return -1;
}
int sockfd = tcp_listen(&addr);
if (sockfd < 0) {
log_print(LOG_WARN, "listen_cb(): tcp_listen()");
return -1;
}
log_print(LOG_INFO, "listen on %s", get_sockaddr_buf(&addr));
event_add_readfd(NULL, sockfd, accept_cb, NULL);
return 0;
}
int main(int argc, char *argv[])
{
if (config_parse("torrent-stats.conf") < 0)
return 1;
config_get_strings("global", "listen", listen_cb, NULL);
event_loop();
return 0;
}

2
torrent-stats.conf Normal file
View File

@ -0,0 +1,2 @@
[global]
listen 0.0.0.0:2780