From e4658756229c1bc386516b87dffe32de6ec79613 Mon Sep 17 00:00:00 2001 From: Naim Abda Date: Tue, 20 Nov 2012 15:32:44 +0200 Subject: [PATCH 01/99] Initial Commit --- src/db/database.h | 48 +++++++++ src/db/driver_sqlite.c | 177 +++++++++++++++++++++++++++++++ src/main.c | 52 ++++++++++ src/multiplatform.h | 26 +++++ src/tools.c | 17 +++ src/tools.h | 19 ++++ src/udpTracker.c | 230 +++++++++++++++++++++++++++++++++++++++++ src/udpTracker.h | 89 ++++++++++++++++ 8 files changed, 658 insertions(+) create mode 100644 src/db/database.h create mode 100644 src/db/driver_sqlite.c create mode 100644 src/main.c create mode 100644 src/multiplatform.h create mode 100644 src/tools.c create mode 100644 src/tools.h create mode 100644 src/udpTracker.c create mode 100644 src/udpTracker.h diff --git a/src/db/database.h b/src/db/database.h new file mode 100644 index 0000000..b74c2c2 --- /dev/null +++ b/src/db/database.h @@ -0,0 +1,48 @@ +/* + * database.h + * + * Created on: Nov 18, 2012 + * Author: Naim + * + * This is just a API implementation; Actual management is done in the driver_*.c source. + * + * + */ + +#ifndef DATABASE_H_ +#define DATABASE_H_ + +#include + +typedef struct dbConnection dbConnection; + +int db_open (dbConnection **, char *cStr); +int db_close (dbConnection *); + +typedef struct { + uint8_t *peer_id; + uint64_t downloaded; + uint64_t uploaded; + uint64_t left; + + uint32_t ip; // currently only support IPv4. + uint16_t port; +} db_peerEntry; + +// adds a peer to the torrent's list. +int db_add_peer (dbConnection *, uint8_t [20], db_peerEntry*); + +/* + * lst: pointer to an array whose maximum size is passed to sZ. + * sZ returns the amount of peers returned. + */ +int db_load_peers (dbConnection *, uint8_t [20], db_peerEntry **lst, int *sZ); + +int db_get_stats (dbConnection *, uint8_t [20], uint32_t *seeders, uint32_t *leechers, uint32_t *completed); + +/** + * Calculates Stats, Removes expired data. + */ +int db_cleanup (dbConnection *); + +#endif /* DATABASE_H_ */ diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c new file mode 100644 index 0000000..0ec226b --- /dev/null +++ b/src/db/driver_sqlite.c @@ -0,0 +1,177 @@ +#include "database.h" + +#include +#include +#include +#include +#include + +struct dbConnection +{ + sqlite3 *db; + HANDLE janitor; +}; + +static const char hexadecimal[] = "0123456789abcdef"; + +static void _to_hex_str (uint8_t hash[20], char *data) +{ + int i; + for (i = 0;i < 20;i++) + { + data[i * 2] = hexadecimal[hash[i] / 16]; + data[i * 2 + 1] = hexadecimal[hash[i] % 16]; + } + data[40] = '\0'; +} + +static int _db_make_torrent_table (sqlite3 *db, char *hash) +{ + char sql [2000]; + sql[0] = '\0'; + + strcat(sql, "CREATE TABLE IF NOT EXISTS '"); + strcat(sql, hash); + strcat (sql, "' ("); + + strcat (sql, "peer_id blob(20) UNIQUE," + "ip blob(4)," + "port blob(2)," + "uploaded blob(8)," // uint64 + "downloaded blob(8)," + "left blob(8)," + "last_seen INTEGER(8)"); + + strcat(sql, ")"); + + // create table. + char *err_msg; + int r = sqlite3_exec(db, sql, NULL, NULL, &err_msg); + printf("E:%s\n", err_msg); + + return r; +} + +static void _db_setup (sqlite3 *db) +{ + sqlite3_exec(db, "CREATE TABLE stats (" + "info_hash blob(20)," + "completed INTEGER DEFAULT 0," + "leechers INTEGER DEFAULT 0," + "seeders INTEGER DEFAULT 0" + ")", NULL, NULL, NULL); +} + +int db_open (dbConnection **db, char *cStr) +{ + FILE *f = fopen (cStr, "rb"); + int doSetup = 0; + if (f == NULL) + doSetup = 1; + else + fclose (f); + + *db = malloc (sizeof(struct dbConnection)); + int r = sqlite3_open (cStr, &((*db)->db)); + if (doSetup) + _db_setup((*db)->db); + + + + return r; +} + +int db_close (dbConnection *db) +{ + int r = sqlite3_close(db->db); + free (db); + return r; +} + +int db_add_peer (dbConnection *db, uint8_t info_hash[20], db_peerEntry *pE) +{ + char xHash [50]; // we just need 40 + \0 = 41. + + char *hash = xHash; + _to_hex_str(info_hash, hash); + + _db_make_torrent_table(db->db, hash); + + sqlite3_stmt *stmt; + + char sql [1000]; + sql[0] = '\0'; + strcat(sql, "REPLACE INTO '"); + strcat(sql, hash); + strcat(sql, "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)"); + + sqlite3_prepare(db->db, sql, -1, &stmt, NULL); + + sqlite3_bind_blob(stmt, 1, pE->peer_id, 20, NULL); + sqlite3_bind_blob(stmt, 2, &pE->ip, 4, NULL); + sqlite3_bind_blob(stmt, 3, &pE->port, 2, NULL); + sqlite3_bind_blob(stmt, 4, &pE->uploaded, 8, NULL); + sqlite3_bind_blob(stmt, 5, &pE->downloaded, 8, NULL); + sqlite3_bind_blob(stmt, 6, &pE->left, 8, NULL); + sqlite3_bind_int64(stmt, 7, time(NULL)); + + int r = sqlite3_step(stmt); + sqlite3_finalize(stmt); + + return r; +} + +int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry **lst, int *sZ) +{ + char sql [1000]; + sql[0] = '\0'; + + char hash [50]; + _to_hex_str(info_hash, hash); + + strcat(sql, "SELECT ip,port FROM '"); + strcat(sql, hash); + strcat(sql, "' LIMIT ?"); + + sqlite3_stmt *stmt; + sqlite3_prepare(db->db, sql, -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, *sZ); + + int i = 0; + int r; + + while (1) + { + r = sqlite3_step(stmt); + if (r == SQLITE_ROW) + { + lst[i]->ip = sqlite3_column_int(stmt, 0); + lst[i]->port = sqlite3_column_int(stmt, 1); + i++; + } + else + break; + } + + sqlite3_finalize(stmt); + + *sZ = i; + + return 0; +} + +int db_get_stats (dbConnection *db, uint8_t hash[20], uint32_t *seeders, uint32_t *leechers, uint32_t *completed) +{ + + + return 0; +} + +int db_cleanup (dbConnection *db) +{ + printf("Cleanup...\n"); + + sqlite3_stmt *stmt; + + return 0; +} diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..d6f58cc --- /dev/null +++ b/src/main.c @@ -0,0 +1,52 @@ +/* + ============================================================================ + Name : udpBitTorrentTracker.c + Author : + Version : + Copyright : + Description : Hello World in C, Ansi-style + ============================================================================ + */ + +#include +#include + +//#include +//#include +#include "multiplatform.h" + +#include "udpTracker.h" +#include "tools.h" +#include +#include + +int main(void) +{ + + printf("UDP BitTorrentTracker\t\tCopyright: (C) 2012 Naim Abda.\n\n"); + +#ifdef WIN32 + WSADATA wsadata; + WSAStartup(MAKEWORD(2, 2), &wsadata); +#endif + + udpServerInstance usi; + UDPTracker_init(&usi, 6969, 1); + + if (UDPTracker_start(&usi) != 0) + { + printf("Error While trying to start server."); + return 1; + } + + system("pause"); + printf("\n"); + + UDPTracker_destroy(&usi); + +#ifdef WIN32 + WSACleanup(); +#endif + + return 0; +} diff --git a/src/multiplatform.h b/src/multiplatform.h new file mode 100644 index 0000000..89e0cbe --- /dev/null +++ b/src/multiplatform.h @@ -0,0 +1,26 @@ + +#include + +#ifdef WIN32 +#include +#include +#elif defined (linux) +#include +#include +#include +#include + +#define SOCKET int +#define DWORD uint64_t +typedef struct hostent HOSTENT; +typedef struct sockaddr SOCKADDR; +typedef struct sockaddr_in SOCKADDR_IN; +typedef struct in_addr IN_ADDR; +typedef struct hostent HOSTENT; +typedef void* LPVOID; +typedef void (LPTHREAD_START_ROUTINE)(LPVOID); +typedef void* HANDLE; +#define IPPROTO_UDP 0 // no protocol set.. SOCK_DGRAM is enough. + +#endif + diff --git a/src/tools.c b/src/tools.c new file mode 100644 index 0000000..00910b4 --- /dev/null +++ b/src/tools.c @@ -0,0 +1,17 @@ +#include "tools.h" + +uint64_t m_hton64 (uint64_t n) +{ + uint64_t r = m_hton32 (n & 0xffffffff); + r <<= 32; + r |= m_hton32 (n & 0xffffffff00000000); + return r; +} + +uint32_t m_hton32 (uint32_t n) +{ + uint32_t r = m_hton16 (n & 0xffff); + r <<= 16; + r |= m_hton16 (n & 0xffff0000); + return r; +} diff --git a/src/tools.h b/src/tools.h new file mode 100644 index 0000000..71d3ac3 --- /dev/null +++ b/src/tools.h @@ -0,0 +1,19 @@ +/* + * tools.h + * + * Created on: Nov 18, 2012 + * Author: Naim + */ + +#ifndef TOOLS_H_ +#define TOOLS_H_ + +#include + +#define m_hton16(n) htons(n) + +uint32_t m_hton32 (uint32_t n); + +uint64_t m_hton64 (uint64_t n); + +#endif /* TOOLS_H_ */ diff --git a/src/udpTracker.c b/src/udpTracker.c new file mode 100644 index 0000000..0a302da --- /dev/null +++ b/src/udpTracker.c @@ -0,0 +1,230 @@ + +#include +#include +#include "udpTracker.h" +#include "tools.h" +#include +#include +#include +#include + +#define FLAG_RUNNING 0x01 +#define UDP_BUFFER_SIZE 256 + +static DWORD _thread_start (LPVOID); + +void UDPTracker_init (udpServerInstance *usi, uint16_t port, uint8_t threads) +{ + usi->port = port; + usi->thread_count = threads; + usi->threads = malloc (sizeof(HANDLE) * threads); + usi->flags = 0; +} + +void UDPTracker_destroy (udpServerInstance *usi) +{ + db_close(usi->conn); + free (usi->threads); +} + +int UDPTracker_start (udpServerInstance *usi) +{ + SOCKET sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sock == INVALID_SOCKET) + return 1; + + int r; + + SOCKADDR_IN recvAddr; + + recvAddr.sin_addr.S_un.S_addr = 0L; + recvAddr.sin_family = AF_INET; + recvAddr.sin_port = htons (usi->port); + + BOOL yup = TRUE; + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, sizeof(BOOL)); + + r = bind (sock, (SOCKADDR*)&recvAddr, sizeof(SOCKADDR_IN)); + + if (r == SOCKET_ERROR) + { + closesocket (sock); + return 2; + } + + printf("SOCK=%d\n", sock); + usi->sock = sock; + + db_open(&usi->conn, "tracker.db"); + + usi->flags |= FLAG_RUNNING; + int i; + for (i = 0;i < usi->thread_count; i++) + { + printf("Starting Thread %d of %u\n", (i + 1), usi->thread_count); + usi->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)usi, 0, NULL); + } + + return 0; +} + +static uint64_t _get_connID (SOCKADDR_IN *remote) +{ + int base = time(NULL); + base /= 3600; // changes every day. + + uint64_t x = base; + x += remote->sin_addr.S_un.S_addr; + return x; +} + +static int _send_error (udpServerInstance *usi, SOCKADDR_IN *remote, uint32_t transactionID, char *msg) +{ + struct udp_error_response error; + error.action = htonl(3); + error.transaction_id = transactionID; + error.message = msg; + + + int msg_sz = 4 + 4 + 1 + strlen(msg); + + char buff [msg_sz]; + memcpy(buff, &error, 8); + int i; + for (i = 8;i <= msg_sz;i++) + { + buff[i] = msg[i - 8]; + } + + printf("ERROR SENT\n"); + sendto(usi->sock, buff, msg_sz, 0, (SOCKADDR*)remote, sizeof(*remote)); + + return 0; +} + +static int _handle_connection (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) +{ + ConnectionRequest *req = (ConnectionRequest*)data; + + ConnectionResponse resp; + resp.action = htonl(0); + resp.transaction_id = req->transaction_id; + resp.connection_id = _get_connID(remote); + + int r = sendto(usi->sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + + printf("_h_c=%d\n", r); + + return 0; +} + +static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) +{ + AnnounceRequest *req = (AnnounceRequest*)data; + + if (req->connection_id != _get_connID(remote)) + { + printf("ConnID mismatch.\n"); + return 1; + } + + db_peerEntry pE; + pE.downloaded = req->downloaded; + pE.uploaded = req->uploaded; + pE.left = req->left; + pE.peer_id = req->peer_id; + pE.ip = req->ip_address; + pE.port = req->port; + + db_add_peer(usi->conn, req->info_hash, &pE); + + +// _send_error(usi, remote, req->transaction_id, "Not Implemented :-(."); + + int q = 30; + if (req->num_want >= 1) + q = min (q, req->num_want); + + db_peerEntry *peers = malloc (sizeof(db_peerEntry) * q); + db_load_peers(usi->conn, req->info_hash, &peers, &q); + printf("%d peers found.\n", q); + + int bSize = 20; // header is 20 bytes + bSize += (6 * q); // + 6 bytes per peer. + + uint8_t buff [bSize]; + + AnnounceResponse *resp = (AnnounceResponse*)buff; + resp->action = htonl(1); + resp->interval = htonl ( 1800 ); + resp->leechers = htonl( 1); + resp->seeders = 0; + resp->transaction_id = req->transaction_id; + + int i; + + for (i = 0;i < q;i++) + { + int x = i * 6; + // network byte order!!! + buff[20 + x] = ((peers[i].ip & (0xff << 24)) >> 24); + buff[21 + x] = ((peers[i].ip & (0xff << 16)) >> 16); + buff[22 + x] = ((peers[i].ip & (0xff << 8)) >> 8); + buff[23 + x] = (peers[i].ip & 0xff); + + buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8); + buff[25 + x] = (peers[i].port & 0xff); + + printf("%u.%u.%u.%u:%u\n", buff[20 + x], buff[21 + x], buff[22 + x], buff[23 + x], peers[i].port); + } + + free (peers); + + return sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); +} + +// returns 1 if connection request. returns 2 if announce. returns 3 if scrape. +static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) +{ + ConnectionRequest *cR; + cR = (ConnectionRequest*)data; + + uint32_t action = htonl(cR->action); + + printf("ACTION=%d\n", action); + + if (action == 0) + return _handle_connection(usi, remote, data); + else if (action == 1) + return _handle_announce(usi, remote, data); + else + { + _send_error(usi, remote, cR->transaction_id, "Method not implemented."); + return -1; + } +} + +static DWORD _thread_start (LPVOID arg) +{ + udpServerInstance *usi = arg; + + SOCKADDR_IN remoteAddr; + int addrSz = sizeof (SOCKADDR_IN); + int r; + + char *tmpBuff = malloc (UDP_BUFFER_SIZE); // 98 is the maximum request size. + + while ((usi->flags & FLAG_RUNNING) > 0) + { + fflush(stdout); + // peek into the first 12 bytes of data; determine if connection request or announce request. + r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); + printf("RECV:%d\n", r); + r = _resolve_request(usi, &remoteAddr, tmpBuff); + printf("R=%d\n", r); + } + + free (tmpBuff); + + return 0; +} diff --git a/src/udpTracker.h b/src/udpTracker.h new file mode 100644 index 0000000..b37640f --- /dev/null +++ b/src/udpTracker.h @@ -0,0 +1,89 @@ +/* + * udpTracker.h + * + * Created on: Nov 14, 2012 + * Author: Naim + */ + +#ifndef UDPTRACKER_H_ +#define UDPTRACKER_H_ + +#include +#include "multiplatform.h" +#include "db/database.h" + +struct udp_connection_request +{ + uint64_t connection_id; + uint32_t action; + uint32_t transaction_id; +}; + +struct udp_connection_response +{ + uint32_t action; + uint32_t transaction_id; + uint64_t connection_id; +}; + +struct udp_announce_request +{ + uint64_t connection_id; + uint32_t action; + uint32_t transaction_id; + uint8_t info_hash [20]; + uint8_t peer_id [20]; + uint64_t downloaded; + uint64_t left; + uint64_t uploaded; + uint32_t event; + uint32_t ip_address; + uint32_t key; + int32_t num_want; + uint16_t port; +}; + +struct udp_announce_response +{ + uint32_t action; + uint32_t transaction_id; + uint32_t interval; + uint32_t leechers; + uint32_t seeders; + + uint8_t *peer_list_data; +}; + +struct udp_error_response +{ + uint32_t action; + uint32_t transaction_id; + char *message; +}; + +typedef struct +{ + SOCKET sock; + uint16_t port; + + uint8_t thread_count; + + uint8_t flags; + + HANDLE *threads; + + dbConnection *conn; +} udpServerInstance; + +typedef struct udp_connection_request ConnectionRequest; +typedef struct udp_connection_response ConnectionResponse; +typedef struct udp_announce_request AnnounceRequest; +typedef struct udp_announce_response AnnounceResponse; +typedef struct udp_error_response ErrorResponse; + +void UDPTracker_init (udpServerInstance *, uint16_t port, uint8_t threads); +void UDPTracker_destroy (udpServerInstance *); + +int UDPTracker_start (udpServerInstance *); + +#endif /* UDPTRACKER_H_ */ From 40d2e5f6cef5768bda135e0ffae2daf10486297c Mon Sep 17 00:00:00 2001 From: Naim A Date: Tue, 20 Nov 2012 16:16:33 +0200 Subject: [PATCH 02/99] Linux Compatibility --- src/db/driver_sqlite.c | 2 +- src/main.c | 8 ++++++-- src/multiplatform.h | 11 +++++++++-- src/udpTracker.c | 44 ++++++++++++++++++++++++++++++++---------- 4 files changed, 50 insertions(+), 15 deletions(-) diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c index 0ec226b..db56416 100644 --- a/src/db/driver_sqlite.c +++ b/src/db/driver_sqlite.c @@ -1,5 +1,5 @@ #include "database.h" - +#include "../multiplatform.h" #include #include #include diff --git a/src/main.c b/src/main.c index d6f58cc..d486d99 100644 --- a/src/main.c +++ b/src/main.c @@ -39,10 +39,14 @@ int main(void) return 1; } - system("pause"); +// system("pause"); + printf("Press Any key to exit...\n"); + int i; + for (i = 0;i < usi.thread_count;i++) + pthread_join (usi.threads[i], NULL); printf("\n"); - UDPTracker_destroy(&usi); +// UDPTracker_destroy(&usi); #ifdef WIN32 WSACleanup(); diff --git a/src/multiplatform.h b/src/multiplatform.h index 89e0cbe..df3ea0b 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -8,9 +8,14 @@ #include #include #include +#include +#include +#include #include #define SOCKET int +#define INVALID_SOCKET 0 +#define SOCKET_ERROR -1 #define DWORD uint64_t typedef struct hostent HOSTENT; typedef struct sockaddr SOCKADDR; @@ -19,8 +24,10 @@ typedef struct in_addr IN_ADDR; typedef struct hostent HOSTENT; typedef void* LPVOID; typedef void (LPTHREAD_START_ROUTINE)(LPVOID); -typedef void* HANDLE; -#define IPPROTO_UDP 0 // no protocol set.. SOCK_DGRAM is enough. +typedef pthread_t HANDLE; +//#define IPPROTO_UDP 0 // no protocol set.. SOCK_DGRAM is enough. + +#define min(a,b) (a > b ? b : a) #endif diff --git a/src/udpTracker.c b/src/udpTracker.c index 0a302da..9bd199d 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -1,17 +1,22 @@ -#include -#include +//#include +//#include +#include "multiplatform.h" #include "udpTracker.h" #include "tools.h" #include #include +#include #include -#include -#define FLAG_RUNNING 0x01 -#define UDP_BUFFER_SIZE 256 +#define FLAG_RUNNING 0x01 +#define UDP_BUFFER_SIZE 256 -static DWORD _thread_start (LPVOID); +#ifdef WIN32 +static DWORD _thread_start (LPVOID arg); +#elif defined (linux) +static void* _thread_start (void *arg); +#endif void UDPTracker_init (udpServerInstance *usi, uint16_t port, uint8_t threads) { @@ -36,19 +41,26 @@ int UDPTracker_start (udpServerInstance *usi) int r; SOCKADDR_IN recvAddr; - +#ifdef WIN32 recvAddr.sin_addr.S_un.S_addr = 0L; +#elif defined (linux) + recvAddr.sin_addr.s_addr = 0L; +#endif recvAddr.sin_family = AF_INET; recvAddr.sin_port = htons (usi->port); - BOOL yup = TRUE; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, sizeof(BOOL)); + int yup = 1; + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); r = bind (sock, (SOCKADDR*)&recvAddr, sizeof(SOCKADDR_IN)); if (r == SOCKET_ERROR) { +#ifdef WIN32 closesocket (sock); +#elif defined (linux) + close (sock); +#endif return 2; } @@ -62,7 +74,11 @@ int UDPTracker_start (udpServerInstance *usi) for (i = 0;i < usi->thread_count; i++) { printf("Starting Thread %d of %u\n", (i + 1), usi->thread_count); +#ifdef WIN32 usi->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)usi, 0, NULL); +#elif defined (linux) + pthread_create (&usi->threads[i], NULL, _thread_start, usi); +#endif } return 0; @@ -74,7 +90,11 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) base /= 3600; // changes every day. uint64_t x = base; +#ifdef WIN32 x += remote->sin_addr.S_un.S_addr; +#elif defined (linux) + x += remote->sin_addr.s_addr; +#endif return x; } @@ -204,7 +224,11 @@ static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char * } } +#ifdef WIN32 static DWORD _thread_start (LPVOID arg) +#elif defined (linux) +static void* _thread_start (void *arg) +#endif { udpServerInstance *usi = arg; @@ -218,7 +242,7 @@ static DWORD _thread_start (LPVOID arg) { fflush(stdout); // peek into the first 12 bytes of data; determine if connection request or announce request. - r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); + r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, (unsigned*)&addrSz); printf("RECV:%d\n", r); r = _resolve_request(usi, &remoteAddr, tmpBuff); printf("R=%d\n", r); From 8fdd555d7084c605ab29d1dd4f7b98fd637d0091 Mon Sep 17 00:00:00 2001 From: "Naim A." Date: Tue, 20 Nov 2012 22:19:11 +0200 Subject: [PATCH 03/99] Bug fixes & Additions --- src/db/driver_sqlite.c | 145 +++++++++++++++++++++++++++++++++++----- src/main.c | 17 ++--- src/multiplatform.h | 3 +- src/tools.c | 27 ++++++-- src/tools.h | 11 ++- src/udpTracker.c | 147 +++++++++++++++++++++++++++++------------ src/udpTracker.h | 10 +++ 7 files changed, 282 insertions(+), 78 deletions(-) diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c index db56416..0cb218b 100644 --- a/src/db/driver_sqlite.c +++ b/src/db/driver_sqlite.c @@ -14,7 +14,7 @@ struct dbConnection static const char hexadecimal[] = "0123456789abcdef"; -static void _to_hex_str (uint8_t hash[20], char *data) +static void _to_hex_str (const uint8_t *hash, char *data) { int i; for (i = 0;i < 20;i++) @@ -30,7 +30,7 @@ static int _db_make_torrent_table (sqlite3 *db, char *hash) char sql [2000]; sql[0] = '\0'; - strcat(sql, "CREATE TABLE IF NOT EXISTS '"); + strcat(sql, "CREATE TABLE IF NOT EXISTS 't"); strcat(sql, hash); strcat (sql, "' ("); @@ -40,14 +40,14 @@ static int _db_make_torrent_table (sqlite3 *db, char *hash) "uploaded blob(8)," // uint64 "downloaded blob(8)," "left blob(8)," - "last_seen INTEGER(8)"); + "last_seen INT DEFAULT 0"); strcat(sql, ")"); // create table. char *err_msg; int r = sqlite3_exec(db, sql, NULL, NULL, &err_msg); - printf("E:%s\n", err_msg); +// printf("E:%s\n", err_msg); return r; } @@ -55,10 +55,11 @@ static int _db_make_torrent_table (sqlite3 *db, char *hash) static void _db_setup (sqlite3 *db) { sqlite3_exec(db, "CREATE TABLE stats (" - "info_hash blob(20)," + "info_hash blob(20) UNIQUE," "completed INTEGER DEFAULT 0," "leechers INTEGER DEFAULT 0," - "seeders INTEGER DEFAULT 0" + "seeders INTEGER DEFAULT 0," + "last_mod INTEGER DEFAULT 0" ")", NULL, NULL, NULL); } @@ -101,23 +102,32 @@ int db_add_peer (dbConnection *db, uint8_t info_hash[20], db_peerEntry *pE) char sql [1000]; sql[0] = '\0'; - strcat(sql, "REPLACE INTO '"); + strcat(sql, "REPLACE INTO 't"); strcat(sql, hash); strcat(sql, "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)"); +// printf("IP->%x::%u\n", pE->ip, pE->port); + sqlite3_prepare(db->db, sql, -1, &stmt, NULL); - sqlite3_bind_blob(stmt, 1, pE->peer_id, 20, NULL); - sqlite3_bind_blob(stmt, 2, &pE->ip, 4, NULL); - sqlite3_bind_blob(stmt, 3, &pE->port, 2, NULL); - sqlite3_bind_blob(stmt, 4, &pE->uploaded, 8, NULL); - sqlite3_bind_blob(stmt, 5, &pE->downloaded, 8, NULL); - sqlite3_bind_blob(stmt, 6, &pE->left, 8, NULL); - sqlite3_bind_int64(stmt, 7, time(NULL)); + sqlite3_bind_blob(stmt, 1, (void*)pE->peer_id, 20, NULL); + sqlite3_bind_blob(stmt, 2, (void*)&pE->ip, 4, NULL); + sqlite3_bind_blob(stmt, 3, (void*)&pE->port, 2, NULL); + sqlite3_bind_blob(stmt, 4, (void*)&pE->uploaded, 8, NULL); + sqlite3_bind_blob(stmt, 5, (void*)&pE->downloaded, 8, NULL); + sqlite3_bind_blob(stmt, 6, (void*)&pE->left, 8, NULL); + sqlite3_bind_int(stmt, 7, time(NULL)); int r = sqlite3_step(stmt); sqlite3_finalize(stmt); + strcpy(sql, "REPLACE INTO stats (info_hash,last_mod) VALUES (?,?)"); + sqlite3_prepare (db->db, sql, -1, &stmt, NULL); + sqlite3_bind_blob (stmt, 1, hash, 20, NULL); + sqlite3_bind_int (stmt, 2, time(NULL)); + sqlite3_step (stmt); + sqlite3_finalize (stmt); + return r; } @@ -129,7 +139,7 @@ int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry **lst, char hash [50]; _to_hex_str(info_hash, hash); - strcat(sql, "SELECT ip,port FROM '"); + strcat(sql, "SELECT ip,port FROM 't"); strcat(sql, hash); strcat(sql, "' LIMIT ?"); @@ -145,8 +155,12 @@ int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry **lst, r = sqlite3_step(stmt); if (r == SQLITE_ROW) { - lst[i]->ip = sqlite3_column_int(stmt, 0); - lst[i]->port = sqlite3_column_int(stmt, 1); + const void *ip = sqlite3_column_blob (stmt, 0); + const void *port = sqlite3_column_blob (stmt, 1); + + memcpy(&lst[i]->ip, ip, 4); + memcpy(&lst[i]->port, port, 2); + i++; } else @@ -162,16 +176,113 @@ int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry **lst, int db_get_stats (dbConnection *db, uint8_t hash[20], uint32_t *seeders, uint32_t *leechers, uint32_t *completed) { + *seeders = 0; + *leechers = 0; + *completed = 0; + const char sql[] = "SELECT seeders,leechers,completed FROM 'stats' WHERE info_hash=?"; + + sqlite3_stmt *stmt; + sqlite3_prepare (db->db, sql, -1, &stmt, NULL); + sqlite3_bind_blob (stmt, 1, (void*)hash, 20, NULL); + + if (sqlite3_step(stmt) == SQLITE_ROW) + { + *seeders = sqlite3_column_int (stmt, 0); + *leechers = sqlite3_column_int (stmt, 1); + *completed = sqlite3_column_int (stmt, 2); + } + + sqlite3_finalize (stmt); return 0; } int db_cleanup (dbConnection *db) { + return 0; // TODO: Fix problems and than allow use of this function. printf("Cleanup...\n"); sqlite3_stmt *stmt; + int timeframe = time(NULL); + + // remove "dead" torrents (non-active for two hours). + const char sql[] = "SELECT info_hash FROM stats WHERE last_moddb, sql, -1, &stmt, NULL); + sqlite3_bind_int (stmt, 1, timeframe - 7200); + char hash [50], temp [1000]; + + while (sqlite3_step(stmt) == SQLITE_ROW) + { + _to_hex_str(sqlite3_column_blob(stmt, 0), hash); + + // drop table: + strcpy(temp, "DROP TABLE IF EXISTS 't"); + strcat(temp, hash); + strcat(temp, "'"); + sqlite3_exec(db->db, temp, NULL, NULL, NULL); + } + sqlite3_finalize (stmt); + + // update 'dead' torrents + sqlite3_prepare(db->db, "UPDATE stats SET seeders=0,leechers=0 WHERE last_moddb, "SELECT info_hash FROM stats WHERE last_mod>=?", -1, &stmt, NULL); + sqlite3_bind_int (stmt, 1, timeframe - 7200); + + uint32_t leechers, seeders; + sqlite3_stmt *sTmp, *uStat; + + sqlite3_prepare (db->db, "UPDATE stats SET seeders=?,leechers=?,last_mod=? WHERE info_hash=?", -1, &uStat, NULL); + + while (sqlite3_step(stmt) == SQLITE_ROW) + { + uint8_t *binHash = sqlite3_column_blob(stmt, 0); + _to_hex_str (binHash, hash); + + // total users... + strcpy (temp, "SELECT COUNT(*) FROM 't"); + strcat (temp, hash); + strcat (temp, "'"); + + sqlite3_prepare (db->db, temp, -1, &sTmp, NULL); + if (sqlite3_step(sTmp) == SQLITE_ROW) + { + leechers = sqlite3_column_int (sTmp, 0); + } + sqlite3_finalize (sTmp); + + // seeders... + strcpy (temp, "SELECT COUNT(*) FROM 't"); + strcat (temp, hash); + strcat (temp, "' WHERE left=0"); + + sqlite3_prepare (db->db, temp, -1, &sTmp, NULL); + if (sqlite3_step(sTmp) == SQLITE_ROW) + { + seeders = sqlite3_column_int (sTmp, 0); + } + sqlite3_finalize (sTmp); + + leechers -= seeders; + + sqlite3_bind_int (uStat, 1, seeders); + sqlite3_bind_int (uStat, 2, leechers); + sqlite3_bind_int (uStat, 3, timeframe); + sqlite3_bind_blob (uStat, 4, binHash, 20, NULL); + sqlite3_step (uStat); + sqlite3_reset (uStat); + + printf("%s: %d seeds/%d leechers;\n", hash, seeders, leechers); + } + sqlite3_finalize (stmt); + + sqlite3_finalize (stmt); + return 0; } diff --git a/src/main.c b/src/main.c index d486d99..25dfe46 100644 --- a/src/main.c +++ b/src/main.c @@ -11,8 +11,6 @@ #include #include -//#include -//#include #include "multiplatform.h" #include "udpTracker.h" @@ -22,8 +20,7 @@ int main(void) { - - printf("UDP BitTorrentTracker\t\tCopyright: (C) 2012 Naim Abda.\n\n"); + printf("UDP BitTorrentTracker %s\t\tCopyright: (C) 2012 Naim Abda.\n\n", VERSION); #ifdef WIN32 WSADATA wsadata; @@ -39,14 +36,12 @@ int main(void) return 1; } -// system("pause"); - printf("Press Any key to exit...\n"); - int i; - for (i = 0;i < usi.thread_count;i++) - pthread_join (usi.threads[i], NULL); - printf("\n"); + printf("Press Any key to exit.\n"); -// UDPTracker_destroy(&usi); + getchar (); + + printf("\nGoodbye.\n"); + UDPTracker_destroy(&usi); #ifdef WIN32 WSACleanup(); diff --git a/src/multiplatform.h b/src/multiplatform.h index df3ea0b..32e6526 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -4,6 +4,7 @@ #ifdef WIN32 #include #include +#define VERSION "1.0.0 (Windows)" #elif defined (linux) #include #include @@ -28,6 +29,6 @@ typedef pthread_t HANDLE; //#define IPPROTO_UDP 0 // no protocol set.. SOCK_DGRAM is enough. #define min(a,b) (a > b ? b : a) - +#define VERSION "1.0.0 (Linux)" #endif diff --git a/src/tools.c b/src/tools.c index 00910b4..a259380 100644 --- a/src/tools.c +++ b/src/tools.c @@ -1,17 +1,32 @@ #include "tools.h" +#include "multiplatform.h" + +void m_byteswap (void *dest, void *src, int sz) +{ + int i; + for (i = 0;i < sz;i++) + { + ((char*)dest)[i] = ((char*)src)[(sz - 1) - i]; + } +} + +uint16_t m_hton16(uint16_t n) +{ + uint16_t r; + m_byteswap (&r, &n, 2); + return r; +} uint64_t m_hton64 (uint64_t n) { - uint64_t r = m_hton32 (n & 0xffffffff); - r <<= 32; - r |= m_hton32 (n & 0xffffffff00000000); + uint64_t r; + m_byteswap (&r, &n, 8); return r; } uint32_t m_hton32 (uint32_t n) { - uint32_t r = m_hton16 (n & 0xffff); - r <<= 16; - r |= m_hton16 (n & 0xffff0000); + uint64_t r; + m_byteswap (&r, &n, 4); return r; } diff --git a/src/tools.h b/src/tools.h index 71d3ac3..03ee944 100644 --- a/src/tools.h +++ b/src/tools.h @@ -10,7 +10,16 @@ #include -#define m_hton16(n) htons(n) +/** + * Swaps Bytes: + * example (htons): + * short a = 1234; + * short b; + * m_byteswap (&b, &a, sizeof(a)); + */ +void m_byteswap (void *dest, void *src, int sz); + +uint16_t m_hton16(uint16_t n); uint32_t m_hton32 (uint32_t n); diff --git a/src/udpTracker.c b/src/udpTracker.c index 9bd199d..86a3862 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -1,6 +1,4 @@ -//#include -//#include #include "multiplatform.h" #include "udpTracker.h" #include "tools.h" @@ -10,18 +8,21 @@ #include #define FLAG_RUNNING 0x01 -#define UDP_BUFFER_SIZE 256 +#define UDP_BUFFER_SIZE 2048 +#define CLEANUP_INTERVAL 20 #ifdef WIN32 static DWORD _thread_start (LPVOID arg); +static DWORD _maintainance_start (LPVOID arg); #elif defined (linux) static void* _thread_start (void *arg); +static void* _maintainance_start (void *arg); #endif void UDPTracker_init (udpServerInstance *usi, uint16_t port, uint8_t threads) { usi->port = port; - usi->thread_count = threads; + usi->thread_count = threads + 1; usi->threads = malloc (sizeof(HANDLE) * threads); usi->flags = 0; } @@ -47,7 +48,7 @@ int UDPTracker_start (udpServerInstance *usi) recvAddr.sin_addr.s_addr = 0L; #endif recvAddr.sin_family = AF_INET; - recvAddr.sin_port = htons (usi->port); + recvAddr.sin_port = m_hton16 (usi->port); int yup = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); @@ -71,6 +72,14 @@ int UDPTracker_start (udpServerInstance *usi) usi->flags |= FLAG_RUNNING; int i; + + // create maintainer thread. +#ifdef WIN32 + usi->threads[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_maintainance_start, (LPVOID)usi, 0, NULL); +#elif defined (linux) + pthread_create (&usi->threads[0], NULL, _maintainance_start, usi); +#endif + for (i = 0;i < usi->thread_count; i++) { printf("Starting Thread %d of %u\n", (i + 1), usi->thread_count); @@ -101,7 +110,7 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) static int _send_error (udpServerInstance *usi, SOCKADDR_IN *remote, uint32_t transactionID, char *msg) { struct udp_error_response error; - error.action = htonl(3); + error.action = m_hton32 (3); error.transaction_id = transactionID; error.message = msg; @@ -127,13 +136,11 @@ static int _handle_connection (udpServerInstance *usi, SOCKADDR_IN *remote, char ConnectionRequest *req = (ConnectionRequest*)data; ConnectionResponse resp; - resp.action = htonl(0); + resp.action = m_hton32(0); resp.transaction_id = req->transaction_id; resp.connection_id = _get_connID(remote); - int r = sendto(usi->sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - - printf("_h_c=%d\n", r); + sendto(usi->sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); return 0; } @@ -144,84 +151,116 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * if (req->connection_id != _get_connID(remote)) { - printf("ConnID mismatch.\n"); return 1; } - db_peerEntry pE; - pE.downloaded = req->downloaded; - pE.uploaded = req->uploaded; - pE.left = req->left; - pE.peer_id = req->peer_id; - pE.ip = req->ip_address; - pE.port = req->port; - - db_add_peer(usi->conn, req->info_hash, &pE); + // change byte order: + req->port = m_hton16 (req->port); + req->ip_address = m_hton32 (req->ip_address); + req->downloaded = m_hton64 (req->downloaded); + req->event = m_hton32 (req->event); // doesn't really matter for this tracker + req->uploaded = m_hton64 (req->uploaded); + req->num_want = m_hton32 (req->num_want); + req->left = m_hton64 (req->left); -// _send_error(usi, remote, req->transaction_id, "Not Implemented :-(."); - + // load peers int q = 30; if (req->num_want >= 1) q = min (q, req->num_want); db_peerEntry *peers = malloc (sizeof(db_peerEntry) * q); + db_load_peers(usi->conn, req->info_hash, &peers, &q); - printf("%d peers found.\n", q); +// printf("%d peers found.\n", q); int bSize = 20; // header is 20 bytes bSize += (6 * q); // + 6 bytes per peer. - uint8_t buff [bSize]; + uint32_t seeders, leechers, completed; + db_get_stats (usi->conn, req->info_hash, &seeders, &leechers, &completed); + uint8_t buff [bSize]; AnnounceResponse *resp = (AnnounceResponse*)buff; - resp->action = htonl(1); - resp->interval = htonl ( 1800 ); - resp->leechers = htonl( 1); - resp->seeders = 0; + resp->action = m_hton32(1); + resp->interval = m_hton32 ( 1800 ); + resp->leechers = m_hton32(leechers); + resp->seeders = m_hton32 (seeders); resp->transaction_id = req->transaction_id; int i; - for (i = 0;i < q;i++) { int x = i * 6; // network byte order!!! + + // IP buff[20 + x] = ((peers[i].ip & (0xff << 24)) >> 24); buff[21 + x] = ((peers[i].ip & (0xff << 16)) >> 16); buff[22 + x] = ((peers[i].ip & (0xff << 8)) >> 8); buff[23 + x] = (peers[i].ip & 0xff); + // port buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8); buff[25 + x] = (peers[i].port & 0xff); - printf("%u.%u.%u.%u:%u\n", buff[20 + x], buff[21 + x], buff[22 + x], buff[23 + x], peers[i].port); +// printf("%u.%u.%u.%u:%u\n", buff[20 + x], buff[21 + x], buff[22 + x], buff[23 + x], peers[i].port); } - free (peers); + sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - return sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + // Add peer to list: + db_peerEntry pE; + pE.downloaded = req->downloaded; + pE.uploaded = req->uploaded; + pE.left = req->left; + pE.peer_id = req->peer_id; + if (req->ip_address == 0) // default + { + pE.ip = m_hton32 (remote->sin_addr.s_addr); + } + else + { + pE.ip = req->ip_address; + } + pE.port = req->port; + db_add_peer(usi->conn, req->info_hash, &pE); + + return 0; } -// returns 1 if connection request. returns 2 if announce. returns 3 if scrape. -static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) +static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *data, int len) +{ + ScrapeRequest *sR = (ScrapeRequest*)data; + + _send_error (usi, remote, sR->transaction_id, "Scrape wasn't implemented yet!"); + + return 0; +} + +static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char *data, int r) { ConnectionRequest *cR; cR = (ConnectionRequest*)data; - uint32_t action = htonl(cR->action); + uint32_t action = m_hton32(cR->action); - printf("ACTION=%d\n", action); +// printf(":: %x:%u ACTION=%d\n", remote->sin_addr.s_addr , remote->sin_port, action); - if (action == 0) + if (action == 0 && r >= 16) return _handle_connection(usi, remote, data); - else if (action == 1) + else if (action == 1 && r >= 98) return _handle_announce(usi, remote, data); + else if (action == 2) + return _handle_scrape (usi, remote, data, r); else { - _send_error(usi, remote, cR->transaction_id, "Method not implemented."); + printf("E: action=%d; r=%d\n", action, r); + _send_error(usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); return -1; } + + return 0; } #ifdef WIN32 @@ -243,12 +282,36 @@ static void* _thread_start (void *arg) fflush(stdout); // peek into the first 12 bytes of data; determine if connection request or announce request. r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, (unsigned*)&addrSz); - printf("RECV:%d\n", r); - r = _resolve_request(usi, &remoteAddr, tmpBuff); - printf("R=%d\n", r); +// printf("RECV:%d\n", r); + r = _resolve_request(usi, &remoteAddr, tmpBuff, r); +// printf("R=%d\n", r); } free (tmpBuff); return 0; } + +#ifdef WIN32 +static DWORD _maintainance_start (LPVOID arg); +#elif defined (linux) +static void* _maintainance_start (void *arg) +#endif +{ + udpServerInstance *usi = (udpServerInstance *)arg; + + while ((usi->flags & FLAG_RUNNING) > 0) + { + db_cleanup (usi->conn); + +#ifdef WIN32 + Sleep (CLEANUP_INTERVAL * 1000); // wait 2 minutes between every cleanup. +#elif defined (linux) + sleep (CLEANUP_INTERVAL); +#else +#error Unsupported OS. +#endif + } + + return 0; +} diff --git a/src/udpTracker.h b/src/udpTracker.h index b37640f..ad659c3 100644 --- a/src/udpTracker.h +++ b/src/udpTracker.h @@ -54,6 +54,15 @@ struct udp_announce_response uint8_t *peer_list_data; }; +struct udp_scrape_request +{ + uint64_t connection_id; + uint32_t action; + uint32_t transaction_id; + + uint8_t *torrent_list_data; +}; + struct udp_error_response { uint32_t action; @@ -79,6 +88,7 @@ typedef struct udp_connection_request ConnectionRequest; typedef struct udp_connection_response ConnectionResponse; typedef struct udp_announce_request AnnounceRequest; typedef struct udp_announce_response AnnounceResponse; +typedef struct udp_scrape_request ScrapeRequest; typedef struct udp_error_response ErrorResponse; void UDPTracker_init (udpServerInstance *, uint16_t port, uint8_t threads); From 00a68330cd695a73865a387f29e334719f8328fd Mon Sep 17 00:00:00 2001 From: Naim Abda Date: Fri, 23 Nov 2012 16:07:42 +0200 Subject: [PATCH 04/99] Oops... --- src/udpTracker.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/udpTracker.c b/src/udpTracker.c index 86a3862..6472230 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -281,7 +281,7 @@ static void* _thread_start (void *arg) { fflush(stdout); // peek into the first 12 bytes of data; determine if connection request or announce request. - r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, (unsigned*)&addrSz); + r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); // printf("RECV:%d\n", r); r = _resolve_request(usi, &remoteAddr, tmpBuff, r); // printf("R=%d\n", r); @@ -293,7 +293,7 @@ static void* _thread_start (void *arg) } #ifdef WIN32 -static DWORD _maintainance_start (LPVOID arg); +static DWORD _maintainance_start (LPVOID arg) #elif defined (linux) static void* _maintainance_start (void *arg) #endif From ce247fc7d59ccc195c7e1c0e49861c443b8d526c Mon Sep 17 00:00:00 2001 From: Naim A Date: Mon, 26 Nov 2012 23:33:12 +0200 Subject: [PATCH 05/99] Various changes. SEGFAULT fixed. --- src/db/database.h | 4 +- src/db/driver_sqlite.c | 48 +++++++++++++++++++----- src/main.c | 29 ++++++++++++++- src/multiplatform.h | 1 + src/udpTracker.c | 84 ++++++++++++++++++++++++++++++++++-------- src/udpTracker.h | 15 +++++++- 6 files changed, 151 insertions(+), 30 deletions(-) diff --git a/src/db/database.h b/src/db/database.h index b74c2c2..f175ec4 100644 --- a/src/db/database.h +++ b/src/db/database.h @@ -36,7 +36,7 @@ int db_add_peer (dbConnection *, uint8_t [20], db_peerEntry*); * lst: pointer to an array whose maximum size is passed to sZ. * sZ returns the amount of peers returned. */ -int db_load_peers (dbConnection *, uint8_t [20], db_peerEntry **lst, int *sZ); +int db_load_peers (dbConnection *, uint8_t [20], db_peerEntry *lst, int *sZ); int db_get_stats (dbConnection *, uint8_t [20], uint32_t *seeders, uint32_t *leechers, uint32_t *completed); @@ -45,4 +45,6 @@ int db_get_stats (dbConnection *, uint8_t [20], uint32_t *seeders, uint32_t *lee */ int db_cleanup (dbConnection *); +int db_remove_peer (dbConnection *, uint8_t hash [20], db_peerEntry *); + #endif /* DATABASE_H_ */ diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c index 0cb218b..b7c0294 100644 --- a/src/db/driver_sqlite.c +++ b/src/db/driver_sqlite.c @@ -14,7 +14,7 @@ struct dbConnection static const char hexadecimal[] = "0123456789abcdef"; -static void _to_hex_str (const uint8_t *hash, char *data) +void _to_hex_str (const uint8_t *hash, char *data) { int i; for (i = 0;i < 20;i++) @@ -34,7 +34,7 @@ static int _db_make_torrent_table (sqlite3 *db, char *hash) strcat(sql, hash); strcat (sql, "' ("); - strcat (sql, "peer_id blob(20) UNIQUE," + strcat (sql, "peer_id blob(20)," "ip blob(4)," "port blob(2)," "uploaded blob(8)," // uint64 @@ -42,12 +42,12 @@ static int _db_make_torrent_table (sqlite3 *db, char *hash) "left blob(8)," "last_seen INT DEFAULT 0"); - strcat(sql, ")"); + strcat(sql, ", CONSTRAINT c1 UNIQUE (ip,port) ON CONFLICT REPLACE)"); // create table. char *err_msg; int r = sqlite3_exec(db, sql, NULL, NULL, &err_msg); -// printf("E:%s\n", err_msg); + printf("E:%s\n", err_msg); return r; } @@ -131,7 +131,7 @@ int db_add_peer (dbConnection *db, uint8_t info_hash[20], db_peerEntry *pE) return r; } -int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry **lst, int *sZ) +int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry *lst, int *sZ) { char sql [1000]; sql[0] = '\0'; @@ -150,16 +150,16 @@ int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry **lst, int i = 0; int r; - while (1) + while (*sZ > i) { r = sqlite3_step(stmt); if (r == SQLITE_ROW) { - const void *ip = sqlite3_column_blob (stmt, 0); - const void *port = sqlite3_column_blob (stmt, 1); + const char *ip = (const char*)sqlite3_column_blob (stmt, 0); + const char *port = (const char*)sqlite3_column_blob (stmt, 1); - memcpy(&lst[i]->ip, ip, 4); - memcpy(&lst[i]->port, port, 2); + memcpy(&lst[i].ip, ip, 4); + memcpy(&lst[i].port, port, 2); i++; } @@ -167,6 +167,8 @@ int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry **lst, break; } + printf("%d Clients Dumped.\n", i); + sqlite3_finalize(stmt); *sZ = i; @@ -286,3 +288,29 @@ int db_cleanup (dbConnection *db) return 0; } + +int db_remove_peer (dbConnection *db, uint8_t hash[20], db_peerEntry *pE) +{ + char sql [1000]; + char xHash [50]; + + _to_hex_str (hash, xHash); + + strcpy (sql, "DELETE FROM 't"); + strcat (sql, xHash); + strcat (sql, "' WHERE ip=? AND port=? AND peer_id=?"); + + sqlite3_stmt *stmt; + + sqlite3_prepare (db->db, sql, -1, &stmt, NULL); + + sqlite3_bind_blob(stmt, 0, (const void*)&pE->ip, 4, NULL); + sqlite3_bind_blob(stmt, 1, (const void*)&pE->port, 2, NULL); + sqlite3_bind_blob(stmt, 2, (const void*)pE->peer_id, 20, NULL); + + sqlite3_step(stmt); + + sqlite3_finalize(stmt); + + return 0; +} diff --git a/src/main.c b/src/main.c index 25dfe46..9f342f5 100644 --- a/src/main.c +++ b/src/main.c @@ -18,17 +18,42 @@ #include #include -int main(void) +int main(int argc, char *argv[]) { printf("UDP BitTorrentTracker %s\t\tCopyright: (C) 2012 Naim Abda.\n\n", VERSION); +#ifdef linux + if (argc > 1) + { + if (strcmp(argv[1], "d") == 0) + { + pid_t pid; + pid = fork (); + + if (pid < 0) + { + printf ("Failed to start daemon.\n"); + exit (EXIT_FAILURE); + } + if (pid > 0) + { + printf("Daemon Started; pid=%d.\n", pid); + fclose (stdin); + fclose (stdout); + fclose (stderr); + exit (EXIT_SUCCESS); + } + } + } +#endif + #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); #endif udpServerInstance usi; - UDPTracker_init(&usi, 6969, 1); + UDPTracker_init(&usi, 6969, 5); if (UDPTracker_start(&usi) != 0) { diff --git a/src/multiplatform.h b/src/multiplatform.h index 32e6526..5a21192 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -18,6 +18,7 @@ #define INVALID_SOCKET 0 #define SOCKET_ERROR -1 #define DWORD uint64_t +#define closesocket(s) close(s) typedef struct hostent HOSTENT; typedef struct sockaddr SOCKADDR; typedef struct sockaddr_in SOCKADDR_IN; diff --git a/src/udpTracker.c b/src/udpTracker.c index 6472230..4f1ff6e 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -145,6 +145,30 @@ static int _handle_connection (udpServerInstance *usi, SOCKADDR_IN *remote, char return 0; } +static int _is_good_peer (uint32_t ip, uint16_t port) +{ + SOCKADDR_IN addr; + addr.sin_family = AF_INET; +#ifdef WIN32 + addr.sin_addr.S_un.S_addr = htonl( ip ); +#elif defined (linux) + addr.sin_addr.s_addr = htonl( ip ); +#endif + addr.sin_port = htons (port); + + SOCKET cli = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (cli == INVALID_SOCKET) + return 1; + if (connect(cli, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN)) == SOCKET_ERROR) + { + closesocket (cli); + return 1; + } + printf ("Client Verified.\n"); + closesocket (cli); + return 0; +} + static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) { AnnounceRequest *req = (AnnounceRequest*)data; @@ -162,20 +186,36 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * req->uploaded = m_hton64 (req->uploaded); req->num_want = m_hton32 (req->num_want); req->left = m_hton64 (req->left); + if (req->ip_address == 0) // default + { + req->ip_address = m_hton32 (remote->sin_addr.s_addr); + } +// if (_is_good_peer(req->ip_address, req->port) != 0) +// { +// _send_error (usi, remote, req->transaction_id, "Couldn't verify your client."); +// return 0; +// } // load peers int q = 30; if (req->num_want >= 1) q = min (q, req->num_want); - db_peerEntry *peers = malloc (sizeof(db_peerEntry) * q); - - db_load_peers(usi->conn, req->info_hash, &peers, &q); -// printf("%d peers found.\n", q); - + db_peerEntry *peers = NULL; int bSize = 20; // header is 20 bytes - bSize += (6 * q); // + 6 bytes per peer. + + if (req->event == 3) // stopped; they don't need anymore peers! + { + q = 0; // don't need any peers! + } + else + { + peers = malloc (sizeof(db_peerEntry) * q); + db_load_peers(usi->conn, req->info_hash, peers, &q); + } + + bSize += (6 * q); // + 6 bytes per peer (ip->4, port->2). uint32_t seeders, leechers, completed; db_get_stats (usi->conn, req->info_hash, &seeders, &leechers, &completed); @@ -206,24 +246,29 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * // printf("%u.%u.%u.%u:%u\n", buff[20 + x], buff[21 + x], buff[22 + x], buff[23 + x], peers[i].port); } - free (peers); + + if (peers != NULL) + free (peers); + sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + // Add peer to list: db_peerEntry pE; pE.downloaded = req->downloaded; pE.uploaded = req->uploaded; pE.left = req->left; pE.peer_id = req->peer_id; - if (req->ip_address == 0) // default - { - pE.ip = m_hton32 (remote->sin_addr.s_addr); - } - else - { - pE.ip = req->ip_address; - } + pE.ip = req->ip_address; pE.port = req->port; + + if (req->event == 3) // stopped + { + // just remove client from swarm, and return empty peer list... + db_remove_peer(usi->conn, req->info_hash, &pE); + return 0; + } + db_add_peer(usi->conn, req->info_hash, &pE); return 0; @@ -233,7 +278,14 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da { ScrapeRequest *sR = (ScrapeRequest*)data; - _send_error (usi, remote, sR->transaction_id, "Scrape wasn't implemented yet!"); +// _send_error (usi, remote, sR->transaction_id, "Scrape wasn't implemented yet!"); + + ScrapeResponse resp; + resp.resp_part = NULL; + resp.action = 2; + resp.transaction_id = sR->transaction_id; + + sendto (usi->sock, (const char*)&resp, 8, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); return 0; } diff --git a/src/udpTracker.h b/src/udpTracker.h index ad659c3..f910c26 100644 --- a/src/udpTracker.h +++ b/src/udpTracker.h @@ -59,8 +59,20 @@ struct udp_scrape_request uint64_t connection_id; uint32_t action; uint32_t transaction_id; + struct reqD { + uint8_t info_hash [20]; + } *req_part; +}; - uint8_t *torrent_list_data; +struct udp_scrape_response +{ + uint32_t action; + uint32_t transaction_id; + struct respD { + uint32_t seeders; + uint32_t completed; + uint32_t leechers; + } *resp_part; }; struct udp_error_response @@ -89,6 +101,7 @@ typedef struct udp_connection_response ConnectionResponse; typedef struct udp_announce_request AnnounceRequest; typedef struct udp_announce_response AnnounceResponse; typedef struct udp_scrape_request ScrapeRequest; +typedef struct udp_scrape_response ScrapeResponse; typedef struct udp_error_response ErrorResponse; void UDPTracker_init (udpServerInstance *, uint16_t port, uint8_t threads); From 7266aa2f5a75adf665f7efaf377542a0e9e7ead8 Mon Sep 17 00:00:00 2001 From: Naim A Date: Tue, 27 Nov 2012 16:01:40 +0200 Subject: [PATCH 06/99] Git changes... --- src/db/database.h | 2 +- src/db/driver_sqlite.c | 15 ++--- src/tools.c | 14 +++++ src/tools.h | 2 + src/udpTracker.c | 138 ++++++++++++++++++++--------------------- src/udpTracker.h | 12 ++-- 6 files changed, 96 insertions(+), 87 deletions(-) diff --git a/src/db/database.h b/src/db/database.h index f175ec4..19db4a8 100644 --- a/src/db/database.h +++ b/src/db/database.h @@ -38,7 +38,7 @@ int db_add_peer (dbConnection *, uint8_t [20], db_peerEntry*); */ int db_load_peers (dbConnection *, uint8_t [20], db_peerEntry *lst, int *sZ); -int db_get_stats (dbConnection *, uint8_t [20], uint32_t *seeders, uint32_t *leechers, uint32_t *completed); +int db_get_stats (dbConnection *, uint8_t [20], int32_t *seeders, int32_t *leechers, int32_t *completed); /** * Calculates Stats, Removes expired data. diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c index b7c0294..5decb65 100644 --- a/src/db/driver_sqlite.c +++ b/src/db/driver_sqlite.c @@ -1,5 +1,6 @@ #include "database.h" #include "../multiplatform.h" +#include "../tools.h" #include #include #include @@ -11,7 +12,7 @@ struct dbConnection sqlite3 *db; HANDLE janitor; }; - + static const char hexadecimal[] = "0123456789abcdef"; void _to_hex_str (const uint8_t *hash, char *data) @@ -24,7 +25,7 @@ void _to_hex_str (const uint8_t *hash, char *data) } data[40] = '\0'; } - + static int _db_make_torrent_table (sqlite3 *db, char *hash) { char sql [2000]; @@ -94,7 +95,7 @@ int db_add_peer (dbConnection *db, uint8_t info_hash[20], db_peerEntry *pE) char xHash [50]; // we just need 40 + \0 = 41. char *hash = xHash; - _to_hex_str(info_hash, hash); + to_hex_str(info_hash, hash); _db_make_torrent_table(db->db, hash); @@ -137,7 +138,7 @@ int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry *lst, i sql[0] = '\0'; char hash [50]; - _to_hex_str(info_hash, hash); + to_hex_str(info_hash, hash); strcat(sql, "SELECT ip,port FROM 't"); strcat(sql, hash); @@ -176,7 +177,7 @@ int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry *lst, i return 0; } -int db_get_stats (dbConnection *db, uint8_t hash[20], uint32_t *seeders, uint32_t *leechers, uint32_t *completed) +int db_get_stats (dbConnection *db, uint8_t hash[20], int32_t *seeders, int32_t *leechers, int32_t *completed) { *seeders = 0; *leechers = 0; @@ -217,7 +218,7 @@ int db_cleanup (dbConnection *db) while (sqlite3_step(stmt) == SQLITE_ROW) { - _to_hex_str(sqlite3_column_blob(stmt, 0), hash); + to_hex_str(sqlite3_column_blob(stmt, 0), hash); // drop table: strcpy(temp, "DROP TABLE IF EXISTS 't"); @@ -245,7 +246,7 @@ int db_cleanup (dbConnection *db) while (sqlite3_step(stmt) == SQLITE_ROW) { uint8_t *binHash = sqlite3_column_blob(stmt, 0); - _to_hex_str (binHash, hash); + to_hex_str (binHash, hash); // total users... strcpy (temp, "SELECT COUNT(*) FROM 't"); diff --git a/src/tools.c b/src/tools.c index a259380..8c776b1 100644 --- a/src/tools.c +++ b/src/tools.c @@ -30,3 +30,17 @@ uint32_t m_hton32 (uint32_t n) m_byteswap (&r, &n, 4); return r; } + + +static const char hexadecimal[] = "0123456789abcdef"; + +void to_hex_str (const uint8_t *hash, char *data) +{ + int i; + for (i = 0;i < 20;i++) + { + data[i * 2] = hexadecimal[hash[i] / 16]; + data[i * 2 + 1] = hexadecimal[hash[i] % 16]; + } + data[40] = '\0'; +} diff --git a/src/tools.h b/src/tools.h index 03ee944..adae247 100644 --- a/src/tools.h +++ b/src/tools.h @@ -25,4 +25,6 @@ uint32_t m_hton32 (uint32_t n); uint64_t m_hton64 (uint64_t n); +void to_hex_str (const uint8_t *hash, char *data); + #endif /* TOOLS_H_ */ diff --git a/src/udpTracker.c b/src/udpTracker.c index 4f1ff6e..34653bc 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -10,6 +10,7 @@ #define FLAG_RUNNING 0x01 #define UDP_BUFFER_SIZE 2048 #define CLEANUP_INTERVAL 20 +#define TRACKER_INTERVAL 60 // normally 1800 #ifdef WIN32 static DWORD _thread_start (LPVOID arg); @@ -114,7 +115,6 @@ static int _send_error (udpServerInstance *usi, SOCKADDR_IN *remote, uint32_t tr error.transaction_id = transactionID; error.message = msg; - int msg_sz = 4 + 4 + 1 + strlen(msg); char buff [msg_sz]; @@ -125,7 +125,6 @@ static int _send_error (udpServerInstance *usi, SOCKADDR_IN *remote, uint32_t tr buff[i] = msg[i - 8]; } - printf("ERROR SENT\n"); sendto(usi->sock, buff, msg_sz, 0, (SOCKADDR*)remote, sizeof(*remote)); return 0; @@ -145,30 +144,6 @@ static int _handle_connection (udpServerInstance *usi, SOCKADDR_IN *remote, char return 0; } -static int _is_good_peer (uint32_t ip, uint16_t port) -{ - SOCKADDR_IN addr; - addr.sin_family = AF_INET; -#ifdef WIN32 - addr.sin_addr.S_un.S_addr = htonl( ip ); -#elif defined (linux) - addr.sin_addr.s_addr = htonl( ip ); -#endif - addr.sin_port = htons (port); - - SOCKET cli = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (cli == INVALID_SOCKET) - return 1; - if (connect(cli, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN)) == SOCKET_ERROR) - { - closesocket (cli); - return 1; - } - printf ("Client Verified.\n"); - closesocket (cli); - return 0; -} - static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) { AnnounceRequest *req = (AnnounceRequest*)data; @@ -186,44 +161,28 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * req->uploaded = m_hton64 (req->uploaded); req->num_want = m_hton32 (req->num_want); req->left = m_hton64 (req->left); - if (req->ip_address == 0) // default - { - req->ip_address = m_hton32 (remote->sin_addr.s_addr); - } -// if (_is_good_peer(req->ip_address, req->port) != 0) -// { -// _send_error (usi, remote, req->transaction_id, "Couldn't verify your client."); -// return 0; -// } // load peers int q = 30; if (req->num_want >= 1) q = min (q, req->num_want); - db_peerEntry *peers = NULL; + db_peerEntry *peers = malloc (sizeof(db_peerEntry) * q); + + db_load_peers(usi->conn, req->info_hash, peers, &q); +// printf("%d peers found.\n", q); + int bSize = 20; // header is 20 bytes + bSize += (6 * q); // + 6 bytes per peer. - if (req->event == 3) // stopped; they don't need anymore peers! - { - q = 0; // don't need any peers! - } - else - { - peers = malloc (sizeof(db_peerEntry) * q); - db_load_peers(usi->conn, req->info_hash, peers, &q); - } - - bSize += (6 * q); // + 6 bytes per peer (ip->4, port->2). - - uint32_t seeders, leechers, completed; + int32_t seeders, leechers, completed; db_get_stats (usi->conn, req->info_hash, &seeders, &leechers, &completed); uint8_t buff [bSize]; AnnounceResponse *resp = (AnnounceResponse*)buff; resp->action = m_hton32(1); - resp->interval = m_hton32 ( 1800 ); + resp->interval = m_hton32 ( TRACKER_INTERVAL ); resp->leechers = m_hton32(leechers); resp->seeders = m_hton32 (seeders); resp->transaction_id = req->transaction_id; @@ -246,29 +205,24 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * // printf("%u.%u.%u.%u:%u\n", buff[20 + x], buff[21 + x], buff[22 + x], buff[23 + x], peers[i].port); } - - if (peers != NULL) - free (peers); - + free (peers); sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - // Add peer to list: db_peerEntry pE; pE.downloaded = req->downloaded; pE.uploaded = req->uploaded; pE.left = req->left; pE.peer_id = req->peer_id; - pE.ip = req->ip_address; - pE.port = req->port; - - if (req->event == 3) // stopped + if (req->ip_address == 0) // default { - // just remove client from swarm, and return empty peer list... - db_remove_peer(usi->conn, req->info_hash, &pE); - return 0; + pE.ip = m_hton32 (remote->sin_addr.s_addr); } - + else + { + pE.ip = req->ip_address; + } + pE.port = req->port; db_add_peer(usi->conn, req->info_hash, &pE); return 0; @@ -280,12 +234,52 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da // _send_error (usi, remote, sR->transaction_id, "Scrape wasn't implemented yet!"); - ScrapeResponse resp; - resp.resp_part = NULL; - resp.action = 2; - resp.transaction_id = sR->transaction_id; + // validate request length: + int v = len - 16; + if (v < 0 || v % 20 != 0) + { + printf("BAD SCRAPE: len=%d\n", len); + _send_error (usi, remote, sR->transaction_id, "Bad scrape request."); + return 0; + } - sendto (usi->sock, (const char*)&resp, 8, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + // get torrent count. + int c = v / 20; + + uint8_t hash [20]; + char xHash [50]; + + uint8_t buffer [8 + (12 * c)]; + ScrapeResponse *resp = (ScrapeResponse*)buffer; + resp->action = m_hton32 (2); + resp->transaction_id = sR->transaction_id; + + int i, j; + printf("Scrape: (%d) \n", c); + for (i = 0;i < c;i++) + { + for (j = 0; j < 20;j++) + hash[j] = data[j + (i*20)+16]; + + to_hex_str (hash, xHash); + + printf("\t%s\n", xHash); + + int32_t *seeders = (int32_t*)&buffer[i*12+8]; + int32_t *completed = (int32_t*)&buffer[i*12+12]; + int32_t *leechers = (int32_t*)&buffer[i*12+16]; + + int32_t s, c, l; + + db_get_stats (usi->conn, hash, &s, &l, &c); + + *seeders = m_hton32 (s); + *completed = m_hton32 (c); + *leechers = m_hton32 (l); + } + fflush (stdout); + + sendto (usi->sock, buffer, sizeof(buffer), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); return 0; } @@ -297,7 +291,7 @@ static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char * uint32_t action = m_hton32(cR->action); -// printf(":: %x:%u ACTION=%d\n", remote->sin_addr.s_addr , remote->sin_port, action); + printf(":: %x:%u ACTION=%d\n", remote->sin_addr.s_addr , remote->sin_port, action); if (action == 0 && r >= 16) return _handle_connection(usi, remote, data); @@ -333,7 +327,9 @@ static void* _thread_start (void *arg) { fflush(stdout); // peek into the first 12 bytes of data; determine if connection request or announce request. - r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); + r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, (unsigned*)&addrSz); + if (r <= 0) + continue; // bad request... // printf("RECV:%d\n", r); r = _resolve_request(usi, &remoteAddr, tmpBuff, r); // printf("R=%d\n", r); @@ -345,7 +341,7 @@ static void* _thread_start (void *arg) } #ifdef WIN32 -static DWORD _maintainance_start (LPVOID arg) +static DWORD _maintainance_start (LPVOID arg); #elif defined (linux) static void* _maintainance_start (void *arg) #endif diff --git a/src/udpTracker.h b/src/udpTracker.h index f910c26..8accf31 100644 --- a/src/udpTracker.h +++ b/src/udpTracker.h @@ -59,20 +59,16 @@ struct udp_scrape_request uint64_t connection_id; uint32_t action; uint32_t transaction_id; - struct reqD { - uint8_t info_hash [20]; - } *req_part; + + uint8_t *torrent_list_data; }; struct udp_scrape_response { uint32_t action; uint32_t transaction_id; - struct respD { - uint32_t seeders; - uint32_t completed; - uint32_t leechers; - } *resp_part; + + uint8_t *data; }; struct udp_error_response From 311006d635c87ac00fc76c9cd4588824cdd39e80 Mon Sep 17 00:00:00 2001 From: Naim A Date: Tue, 4 Dec 2012 00:44:30 +0200 Subject: [PATCH 07/99] Added Copyright license; Fixed memory leaks with threads. --- README | 9 + gpl.txt | 674 +++++++++++++++++++++++++++++++++++++++++ src/db/database.h | 16 +- src/db/driver_sqlite.c | 21 +- src/main.c | 68 ++--- src/multiplatform.h | 18 ++ src/tools.c | 19 ++ src/tools.h | 18 +- src/udpTracker.c | 66 +++- src/udpTracker.h | 18 +- 10 files changed, 872 insertions(+), 55 deletions(-) create mode 100644 README create mode 100644 gpl.txt diff --git a/README b/README new file mode 100644 index 0000000..7a5ec2d --- /dev/null +++ b/README @@ -0,0 +1,9 @@ + +README for the UDPT project. + +Licensed under GNU GPLv3. +The license file is attached under the name gpl.txt. + +This software currently uses the Sqlite3 Library (public domain). + +Developed by Naim A. . diff --git a/gpl.txt b/gpl.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/gpl.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/src/db/database.h b/src/db/database.h index 19db4a8..a9a40a0 100644 --- a/src/db/database.h +++ b/src/db/database.h @@ -1,12 +1,20 @@ /* - * database.h + * Copyright © 2012 Naim A. * - * Created on: Nov 18, 2012 - * Author: Naim + * This file is part of UDPT. * - * This is just a API implementation; Actual management is done in the driver_*.c source. + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * + * UDPT 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 UDPT. If not, see . */ #ifndef DATABASE_H_ diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c index 5decb65..9521643 100644 --- a/src/db/driver_sqlite.c +++ b/src/db/driver_sqlite.c @@ -1,3 +1,22 @@ +/* + * Copyright © 2012 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + #include "database.h" #include "../multiplatform.h" #include "../tools.h" @@ -245,7 +264,7 @@ int db_cleanup (dbConnection *db) while (sqlite3_step(stmt) == SQLITE_ROW) { - uint8_t *binHash = sqlite3_column_blob(stmt, 0); + uint8_t *binHash = (uint8_t*)sqlite3_column_blob(stmt, 0); to_hex_str (binHash, hash); // total users... diff --git a/src/main.c b/src/main.c index 9f342f5..ea13bbd 100644 --- a/src/main.c +++ b/src/main.c @@ -1,11 +1,20 @@ /* - ============================================================================ - Name : udpBitTorrentTracker.c - Author : - Version : - Copyright : - Description : Hello World in C, Ansi-style - ============================================================================ + * Copyright © 2012 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . */ #include @@ -17,35 +26,11 @@ #include "tools.h" #include #include +#include int main(int argc, char *argv[]) { - printf("UDP BitTorrentTracker %s\t\tCopyright: (C) 2012 Naim Abda.\n\n", VERSION); - -#ifdef linux - if (argc > 1) - { - if (strcmp(argv[1], "d") == 0) - { - pid_t pid; - pid = fork (); - - if (pid < 0) - { - printf ("Failed to start daemon.\n"); - exit (EXIT_FAILURE); - } - if (pid > 0) - { - printf("Daemon Started; pid=%d.\n", pid); - fclose (stdin); - fclose (stdout); - fclose (stderr); - exit (EXIT_SUCCESS); - } - } - } -#endif + printf("UDP Tracker (UDPT) %s\tCopyright: (C) 2012 Naim Abda \n\n", VERSION); #ifdef WIN32 WSADATA wsadata; @@ -55,9 +40,22 @@ int main(int argc, char *argv[]) udpServerInstance usi; UDPTracker_init(&usi, 6969, 5); - if (UDPTracker_start(&usi) != 0) + int r = UDPTracker_start(&usi); + if (r != 0) { - printf("Error While trying to start server."); + printf("Error While trying to start server.\n"); + switch (r) + { + case 1: + printf("Failed to create socket.\n"); + break; + case 2: + printf("Failed to bind socket.\n"); + break; + default: + printf ("Unknown Error\n"); + break; + } return 1; } diff --git a/src/multiplatform.h b/src/multiplatform.h index 5a21192..202f662 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -1,3 +1,21 @@ +/* + * Copyright © 2012 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ #include diff --git a/src/tools.c b/src/tools.c index 8c776b1..01a0ecd 100644 --- a/src/tools.c +++ b/src/tools.c @@ -1,3 +1,22 @@ +/* + * Copyright © 2012 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + #include "tools.h" #include "multiplatform.h" diff --git a/src/tools.h b/src/tools.h index adae247..09e7c21 100644 --- a/src/tools.h +++ b/src/tools.h @@ -1,8 +1,20 @@ /* - * tools.h + * Copyright © 2012 Naim A. * - * Created on: Nov 18, 2012 - * Author: Naim + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . */ #ifndef TOOLS_H_ diff --git a/src/udpTracker.c b/src/udpTracker.c index 34653bc..426ae9b 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -1,3 +1,21 @@ +/* + * Copyright © 2012 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ #include "multiplatform.h" #include "udpTracker.h" @@ -24,16 +42,42 @@ void UDPTracker_init (udpServerInstance *usi, uint16_t port, uint8_t threads) { usi->port = port; usi->thread_count = threads + 1; - usi->threads = malloc (sizeof(HANDLE) * threads); + usi->threads = malloc (sizeof(HANDLE) * usi->thread_count); usi->flags = 0; + usi->conn = NULL; } void UDPTracker_destroy (udpServerInstance *usi) { - db_close(usi->conn); + usi->flags = (!(FLAG_RUNNING)) & usi->flags; + + + // drop listener connection to continue thread loops. + // wait for request to finish (1 second max; allot of time for a computer!). + +#ifdef linux + close (usi->sock); + + sleep (1); +#elif defined (WIN32) + closesocket (usi->sock); + + Sleep (1000); +#endif + + int i; + for (i = 0;i < usi->thread_count;i++) + { + pthread_detach (usi->threads[i]); + pthread_cancel (usi->threads[i]); + printf ("Thread (%d/%u) terminated.\n", i + 1, usi->thread_count); + } + if (usi->conn != NULL) + db_close(usi->conn); free (usi->threads); } + int UDPTracker_start (udpServerInstance *usi) { SOCKET sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); @@ -78,16 +122,17 @@ int UDPTracker_start (udpServerInstance *usi) #ifdef WIN32 usi->threads[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_maintainance_start, (LPVOID)usi, 0, NULL); #elif defined (linux) + printf("Starting maintenance thread (1/6)...\n"); pthread_create (&usi->threads[0], NULL, _maintainance_start, usi); #endif - for (i = 0;i < usi->thread_count; i++) + for (i = 1;i < usi->thread_count; i++) { - printf("Starting Thread %d of %u\n", (i + 1), usi->thread_count); + printf("Starting Thread (%d/%u)\n", (i + 1), usi->thread_count); #ifdef WIN32 usi->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)usi, 0, NULL); #elif defined (linux) - pthread_create (&usi->threads[i], NULL, _thread_start, usi); + pthread_create (&(usi->threads[i]), NULL, _thread_start, usi); #endif } @@ -238,7 +283,7 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da int v = len - 16; if (v < 0 || v % 20 != 0) { - printf("BAD SCRAPE: len=%d\n", len); +// printf("BAD SCRAPE: len=%d\n", len); _send_error (usi, remote, sR->transaction_id, "Bad scrape request."); return 0; } @@ -255,7 +300,7 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da resp->transaction_id = sR->transaction_id; int i, j; - printf("Scrape: (%d) \n", c); +// printf("Scrape: (%d) \n", c); for (i = 0;i < c;i++) { for (j = 0; j < 20;j++) @@ -321,7 +366,9 @@ static void* _thread_start (void *arg) int addrSz = sizeof (SOCKADDR_IN); int r; - char *tmpBuff = malloc (UDP_BUFFER_SIZE); // 98 is the maximum request size. +// char *tmpBuff = malloc (UDP_BUFFER_SIZE); // 98 is the maximum request size. + + char tmpBuff [UDP_BUFFER_SIZE]; while ((usi->flags & FLAG_RUNNING) > 0) { @@ -335,8 +382,9 @@ static void* _thread_start (void *arg) // printf("R=%d\n", r); } - free (tmpBuff); +// free (tmpBuff); + pthread_exit (NULL); return 0; } diff --git a/src/udpTracker.h b/src/udpTracker.h index 8accf31..7ffb1e1 100644 --- a/src/udpTracker.h +++ b/src/udpTracker.h @@ -1,8 +1,20 @@ /* - * udpTracker.h + * Copyright © 2012 Naim A. * - * Created on: Nov 14, 2012 - * Author: Naim + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . */ #ifndef UDPTRACKER_H_ From 8da6a3ee43fbc4e248bdd83ce5a82feb3aef3ed6 Mon Sep 17 00:00:00 2001 From: Naim Abda Date: Tue, 4 Dec 2012 09:52:31 +0200 Subject: [PATCH 08/99] Fixes for Windows --- src/udpTracker.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/udpTracker.c b/src/udpTracker.c index 426ae9b..e3ee9f8 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -68,8 +68,12 @@ void UDPTracker_destroy (udpServerInstance *usi) int i; for (i = 0;i < usi->thread_count;i++) { +#ifdef WIN32 + TerminateThread (usi->threads[0], 0x00); +#elif defined (linux) pthread_detach (usi->threads[i]); pthread_cancel (usi->threads[i]); +#endif printf ("Thread (%d/%u) terminated.\n", i + 1, usi->thread_count); } if (usi->conn != NULL) @@ -383,13 +387,14 @@ static void* _thread_start (void *arg) } // free (tmpBuff); - +#ifdef linux pthread_exit (NULL); +#endif return 0; } #ifdef WIN32 -static DWORD _maintainance_start (LPVOID arg); +static DWORD _maintainance_start (LPVOID arg) #elif defined (linux) static void* _maintainance_start (void *arg) #endif From a4c2f83979de280c316ac8763a0210e9a44ee0a2 Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 6 Dec 2012 04:11:20 +0200 Subject: [PATCH 09/99] Bugfix #1: Listening port is now configurable. Default port is 6969. --- src/main.c | 21 +++++++++++++++++++-- src/udpTracker.c | 1 - 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main.c b/src/main.c index ea13bbd..4534c95 100644 --- a/src/main.c +++ b/src/main.c @@ -28,17 +28,34 @@ #include #include +static void _print_usage () +{ + printf ("Usage: udpt \n" + "\tDefault port is 6969.\n"); +} + int main(int argc, char *argv[]) { - printf("UDP Tracker (UDPT) %s\tCopyright: (C) 2012 Naim Abda \n\n", VERSION); + printf("UDP Tracker (UDPT) %s\nCopyright: (C) 2012 Naim Abda \n\n", VERSION); #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); #endif + uint16_t port = 6969; + if (argc <= 1) + { + _print_usage (); + } + else if (argc == 2) + { + port = atoi(argv[1]); + printf("selected port=%u\n", port); + } + udpServerInstance usi; - UDPTracker_init(&usi, 6969, 5); + UDPTracker_init(&usi, port, 5); int r = UDPTracker_start(&usi); if (r != 0) diff --git a/src/udpTracker.c b/src/udpTracker.c index e3ee9f8..d2c4583 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -114,7 +114,6 @@ int UDPTracker_start (udpServerInstance *usi) return 2; } - printf("SOCK=%d\n", sock); usi->sock = sock; db_open(&usi->conn, "tracker.db"); From 0ef79d37aa02b6d0ba28c4414b4e78730b55b6f4 Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 7 Dec 2012 03:39:01 +0200 Subject: [PATCH 10/99] Added Makefile for Linux & MinGW; Allowing people to build easily from source. --- Makefile | 40 ++++++++++++++++++++++++++++++++++++++++ README | 14 ++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c0f2704 --- /dev/null +++ b/Makefile @@ -0,0 +1,40 @@ +# +# Copyright © 2012 Naim A. +# +# This file is part of UDPT. +# +# UDPT is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# UDPT 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 UDPT. If not, see . +# + +win32: main.o tools.o udpTracker.o driver_sqlite.o + gcc -static -O3 -o udpt.exe main.o tools.o udpTracker.o driver_sqlite.o -lsqlite3 -lws2_32 + +linux: main.o tools.o udpTracker.o driver_sqlite.o + gcc -static -O3 -o udpt main.o tools.o udpTracker.o driver_sqlite.o -lsqlite3 -lpthreads + +main.o: + gcc -c -O3 -o main.o src/main.c + +tools.o: + gcc -c -O3 -o tools.o src/tools.c + +udpTracker.o: + gcc -c -O3 -o udpTracker.o src/udpTracker.c + +driver_sqlite.o: + gcc -O3 -c -o driver_sqlite.o src/db/driver_sqlite.c + +.PHONY: clean +clean: + rm -f udpt.exe main.o tools.o udpTracker.o driver_sqlite.o udpt \ No newline at end of file diff --git a/README b/README index 7a5ec2d..5110a8f 100644 --- a/README +++ b/README @@ -4,6 +4,20 @@ README for the UDPT project. Licensed under GNU GPLv3. The license file is attached under the name gpl.txt. +Compiling under linux or linux environment (MinGW): + +For Windows (with Linux environment): +$ make win32 + +For Linux: +$ make linux + +Running: +$ ./udpt + +Cleaning: +$ make clean + This software currently uses the Sqlite3 Library (public domain). Developed by Naim A. . From fda15157c2cc8ece5a7dce31208e7330e57c9101 Mon Sep 17 00:00:00 2001 From: Naim A Date: Mon, 10 Dec 2012 04:54:43 +0200 Subject: [PATCH 11/99] Adding configuration reader/writer. --- src/settings.c | 335 +++++++++++++++++++++++++++++++++++++++++++++++++ src/settings.h | 53 ++++++++ 2 files changed, 388 insertions(+) create mode 100644 src/settings.c create mode 100644 src/settings.h diff --git a/src/settings.c b/src/settings.c new file mode 100644 index 0000000..0b899c4 --- /dev/null +++ b/src/settings.c @@ -0,0 +1,335 @@ +/* + * + * Copyright © 2012 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "settings.h" +#include +#include +#include +#include + +static +SettingClass* settings_get_class (Settings *s, char *classname) +{ + if (s == NULL || classname == NULL) + return NULL; + int i; + for (i = 0;i < s->class_count;i++) + { + if (strcmp(classname, s->classes[i].classname) == 0) + { + return &s->classes[i]; + } + } + + return NULL; +} + +void settings_init (Settings *s, char *filename) +{ + s->buffer = NULL; + s->filename = filename; + s->classes = NULL; + s->class_count = s->class_size = 0; +} + +static +void _settings_clean_string (char **str) +{ + int len = strlen(*str); + + //strip leading whitespaces. + int i, offset = 0; + for (i = 0;i < len;i++) + { + if (isspace(*str[i]) == 0) + break; + offset++; + } + + *str += offset; + len -= offset; + + for (i = len - 1;i >= 0;i--) + { + if (isspace( (*str)[i] ) != 0) + { + *str[i] = '\0'; + } + else + break; + } +} + +static +void _settings_parser (Settings *s, char *data, int len) +{ + char *className = NULL; + char *key = NULL; + char *value = NULL; + int i, cil = 0; // cil = Chars in line. + char c; + for (i = 0;i < len;i++) + { + c = data[i]; + if (c == '\n') + { + cil = 0; + continue; + } + if (cil == 0 && c == ';') + { + while (i < len) + { + if (data[i] == '\n') + break; + i++; + } + continue; + } + if (isspace(c) != 0 && cil == 0) + { + continue; + } + if (cil == 0 && c == '[') + { + className = (char*)(i + data + 1); + while (i < len) + { + if (data[i] != ']') + { + i++; + continue; + } + data[i] = '\0'; + break; + } + continue; + } + + if (isgraph(c) != 0 && cil == 0) // must be a key. + { + key = (char*)(i + data); + while (i < len) + { + if (data[i] == '\n') + { + key = NULL; + break; + } + if (data[i] == '=') + { + data[i] = '\0'; + value = (char*)(data + i + 1); + while (i < len) + { + if (data[i] == '\n') + { + data[i] = '\0'; + + _settings_clean_string(&key); + _settings_clean_string(&value); + +// printf("KEY: '%s'\tVALUE: '%s'\n", key, value); + + // add to settings... + settings_set(s, className, key, value); + + cil = 0; + break; + } + i++; + } + break; + } + i++; + } + continue; + } + + if (isgraph(c) != 0) + { + cil++; + } + } +} + +int settings_load (Settings *s) +{ + if (s->buffer != NULL) + { + free (s->buffer); + s->buffer = NULL; + } + + // ini file format. + FILE *f = fopen(s->filename, "rb"); + if (f == NULL) + return 1; + fseek (f, 0, SEEK_END); + int len = ftell(f); + fseek(f, 0, SEEK_SET); + + s->buffer = malloc (len); + char *buffer = s->buffer; + + char tmp [512]; + int r = 0, offset = 0; + while (!feof(f) && !ferror(f)) + { + r = fread (tmp, 1, 512, f); + int i; + for (i = 0;i < r;i++) + { + buffer[offset + i] = tmp[i]; + } + offset += r; + } + + fclose (f); +// printf("File loaded into buffer. size=%d\n", len); + _settings_parser (s, buffer, len); + + return 0; +} + +int settings_save (Settings *s) +{ + char buffer [2048]; + + FILE *f = fopen(s->filename, "wb"); + fprintf(f, "; udpt Settings File - Created Automatically.\n"); + setbuf(f, buffer); + + int c, e; + SettingClass *class; + for (c = 0;c < s->class_count;c++) + { + class = &s->classes[c]; + fprintf(f, "[%s]\n", class->classname); + + for (e = 0;e < class->entry_count;e++) + { + fprintf(f, "%s=%s\n", class->entries[e].key, class->entries[e].values); + } + + fprintf(f, "\n"); + } + + fclose (f); + + return 0; +} + +void settings_destroy (Settings *s) +{ + if (s->classes != NULL) + { + + int i; + for (i = 0;i < s->class_count;i++) + { + if (s->classes[i].entries != NULL) + free (s->classes[i].entries); + } + + free (s->classes); + } + if (s->buffer != NULL) + { + free (s->buffer); + s->buffer = NULL; + } +} + +char* settings_get (Settings *s, char *class, char *name) +{ + if (s == NULL || class == NULL || name == NULL) + return NULL; + + SettingClass *c = settings_get_class (s, class); + if (c == NULL) + return NULL; + + KeyValue *kv; + int i; + for (i = 0;i < c->entry_count;i++) + { + kv = &c->entries[i]; + if (strcmp(kv->key, name) == 0) + return kv->values; + } + return NULL; +} + +int settings_set (Settings *s, char *class, char *name, char *value) +{ + if (s == NULL || class == NULL || name == NULL) + return 1; + + SettingClass *c = settings_get_class (s, class); + if (c == NULL) + { + if (s->class_count + 1 >= s->class_size) + { + int ns = s->class_size + 1; + SettingClass *sc = realloc (s->classes, sizeof(SettingClass) * ns); + if (sc == NULL) + return 1; + s->classes = sc; + s->class_size = ns; + } + + c = &s->classes[s->class_count]; + s->class_count++; + + c->classname = class; + c->entries = NULL; + c->entry_size = c->entry_count = 0; + + } + + int i; + for (i = 0;i < c->entry_count;i++) + { + if (strcmp(name, c->entries[i].key) == 0) + { + c->entries[i].values = value; + return 0; + } + } + + if (c->entry_count + 1 >= c->entry_size) + { + int ns = c->entry_size + 5; + KeyValue *n = realloc (c->entries, sizeof(KeyValue) * ns); + if (n == NULL) + return 1; + c->entries = n; + c->entry_size = ns; + } + + int ni = c->entry_count; + c->entry_count++; + + c->entries[ni].key = name; + c->entries[ni].values = value; + + return 0; +} diff --git a/src/settings.h b/src/settings.h new file mode 100644 index 0000000..72b91f9 --- /dev/null +++ b/src/settings.h @@ -0,0 +1,53 @@ +/* + * + * Copyright © 2012 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include + +typedef struct { + char *key; + char *values; +} KeyValue; + +typedef struct { + char *classname; + KeyValue *entries; + uint32_t entry_count, entry_size; +} SettingClass; + +typedef struct { + char *filename; + + SettingClass *classes; + uint32_t class_count, class_size; + + char *buffer; +} Settings; + +void settings_init (Settings *, char *filename); + +int settings_load (Settings *); + +int settings_save (Settings *); + +void settings_destroy (Settings *); + +char* settings_get (Settings *, char *class, char *name); + +int settings_set (Settings *, char *class, char *name, char *value); From 0c32025590945d2d1d16b71fb705cca01b60f975 Mon Sep 17 00:00:00 2001 From: Naim A Date: Mon, 10 Dec 2012 18:31:54 +0200 Subject: [PATCH 12/99] Added documentation to some functions; Fixed possible memory leak. --- src/db/database.h | 68 +++++++++++++++++++++++++++++++++++++---------- src/main.c | 5 ++-- src/settings.h | 46 +++++++++++++++++++++++++++----- src/udpTracker.h | 22 ++++++++++++--- 4 files changed, 116 insertions(+), 25 deletions(-) diff --git a/src/db/database.h b/src/db/database.h index a9a40a0..d13c299 100644 --- a/src/db/database.h +++ b/src/db/database.h @@ -24,8 +24,20 @@ typedef struct dbConnection dbConnection; -int db_open (dbConnection **, char *cStr); -int db_close (dbConnection *); +/** + * Opens a database connection. + * @param pdb Pointer to database instance. + * @param cStr Connection string for the active driver. + * @return 0 on success; otherwise non-zero. + */ +int db_open (dbConnection **pdb, char *cStr); + +/** + * Closes the database connection. + * @param db Database instance. + * @return 0 on success; otherwise non-zero. + */ +int db_close (dbConnection *db); typedef struct { uint8_t *peer_id; @@ -37,22 +49,50 @@ typedef struct { uint16_t port; } db_peerEntry; -// adds a peer to the torrent's list. -int db_add_peer (dbConnection *, uint8_t [20], db_peerEntry*); - -/* - * lst: pointer to an array whose maximum size is passed to sZ. - * sZ returns the amount of peers returned. +/** + * Adds/Updates the list of peers. + * @param db The database's instance. + * @param hash The info_hash of the torrent. + * @param pE Peer's information. + * @return 0 on success; otherwise non-zero. */ -int db_load_peers (dbConnection *, uint8_t [20], db_peerEntry *lst, int *sZ); - -int db_get_stats (dbConnection *, uint8_t [20], int32_t *seeders, int32_t *leechers, int32_t *completed); +int db_add_peer (dbConnection *db, uint8_t hash[20], db_peerEntry *pE); /** - * Calculates Stats, Removes expired data. + * Loads peers for the requested torrent. + * @param db Database instance. + * @param hash The info_hash of the requested torrent. + * @param lst A allocated array to store results in. + * @param sZ in: The maximum amount of entries to load. out: Amount of loaded entries. + * @return 0 on success; otherwise non-zero. */ -int db_cleanup (dbConnection *); +int db_load_peers (dbConnection *db, uint8_t hash[20], db_peerEntry *lst, int *sZ); -int db_remove_peer (dbConnection *, uint8_t hash [20], db_peerEntry *); +/** + * Gets stats for the requested torrent. + * @param db The Database connection + * @param hash info_hash of the torrent. + * @param seeders Returns the Seeders for the requested torrent. + * @param leechers Returns the Leechers for the requested torrent. + * @param completed Returns the count of completed downloaded reported. + * @return 0 on success, otherwise non-zero. + */ +int db_get_stats (dbConnection *db, uint8_t hash[20], int32_t *seeders, int32_t *leechers, int32_t *completed); + +/** + * Maintenance routine, Calculates stats & releases space from old entries. + * @param db The database connection. + * @return 0 on success; otherwise non-zero. + */ +int db_cleanup (dbConnection *db); + +/** + * Deletes a peer from the database. + * @param db Database connection + * @param hash info_hash of the torrent. + * @param pE The peer's information. + * @return 0 on success; otherwise non-zero. + */ +int db_remove_peer (dbConnection *db, uint8_t hash [20], db_peerEntry *pE); #endif /* DATABASE_H_ */ diff --git a/src/main.c b/src/main.c index 4534c95..4549ac1 100644 --- a/src/main.c +++ b/src/main.c @@ -21,7 +21,6 @@ #include #include "multiplatform.h" - #include "udpTracker.h" #include "tools.h" #include @@ -73,14 +72,16 @@ int main(int argc, char *argv[]) printf ("Unknown Error\n"); break; } - return 1; + goto cleanup; } printf("Press Any key to exit.\n"); getchar (); +cleanup: printf("\nGoodbye.\n"); + UDPTracker_destroy(&usi); #ifdef WIN32 diff --git a/src/settings.h b/src/settings.h index 72b91f9..f015248 100644 --- a/src/settings.h +++ b/src/settings.h @@ -40,14 +40,48 @@ typedef struct { char *buffer; } Settings; -void settings_init (Settings *, char *filename); +/** + * Initializes the settings type. + * @param s Pointer to settings to initialize. + * @param filename the settings filename. + */ +void settings_init (Settings *s, char *filename); -int settings_load (Settings *); +/** + * Loads settings from file + * @param s pointer to settings type + * @return 0 on success, otherwise non-zero. + */ +int settings_load (Settings *s); -int settings_save (Settings *); +/** + * Saves settings to file. + * @param s Pointer to settings. + * @return 0 on success; otherwise non-zero. + */ +int settings_save (Settings *s); -void settings_destroy (Settings *); +/** + * Destroys the settings "object" + * @param s Pointer to settings. + */ +void settings_destroy (Settings *s); -char* settings_get (Settings *, char *class, char *name); +/** + * Gets a setting from a Settings type. + * @param s Pointer to a setting type. + * @param class The class of the requested setting. + * @param name The name of the requested setting. + * @return The value for the requested setting, NULL if not available. + */ +char* settings_get (Settings *s, char *class, char *name); -int settings_set (Settings *, char *class, char *name, char *value); +/** + * Sets a setting in a settings type. + * @param s Pointer to settings type. + * @param class The class of the setting. + * @param name The name of the setting. + * @param value The value to set for the setting. + * @return 0 on success, otherwise non-zero. + */ +int settings_set (Settings *s, char *class, char *name, char *value); diff --git a/src/udpTracker.h b/src/udpTracker.h index 7ffb1e1..9ad9d3a 100644 --- a/src/udpTracker.h +++ b/src/udpTracker.h @@ -112,9 +112,25 @@ typedef struct udp_scrape_request ScrapeRequest; typedef struct udp_scrape_response ScrapeResponse; typedef struct udp_error_response ErrorResponse; -void UDPTracker_init (udpServerInstance *, uint16_t port, uint8_t threads); -void UDPTracker_destroy (udpServerInstance *); +/** + * Initializes the UDP Tracker. + * @param usi The Instancfe to initialize. + * @param port The port to bind the server to + * @param threads Amount of threads to start the server with. + */ +void UDPTracker_init (udpServerInstance *usi, uint16_t port, uint8_t threads); -int UDPTracker_start (udpServerInstance *); +/** + * Destroys resources that were created by UDPTracker_init. + * @param usi Instance to destroy. + */ +void UDPTracker_destroy (udpServerInstance *usi); + +/** + * Starts the Initialized instance. + * @param usi Instance to start + * @return 0 on success, otherwise non-zero. + */ +int UDPTracker_start (udpServerInstance *usi); #endif /* UDPTRACKER_H_ */ From fdfc36f736fe274d07b99f5b18f29494175c1945 Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 13 Dec 2012 13:52:55 +0200 Subject: [PATCH 13/99] Settings are now made via the configuration file; Option to block IANA reserved IPs (against DOS attacks) --- src/main.c | 36 +++++++++++++------ src/multiplatform.h | 3 +- src/settings.c | 4 +-- src/settings.h | 2 ++ src/udpTracker.c | 84 ++++++++++++++++++++++++++++++++++++++++++--- src/udpTracker.h | 11 +++++- 6 files changed, 121 insertions(+), 19 deletions(-) diff --git a/src/main.c b/src/main.c index 4549ac1..e5b777d 100644 --- a/src/main.c +++ b/src/main.c @@ -26,35 +26,51 @@ #include #include #include +#include "settings.h" static void _print_usage () { - printf ("Usage: udpt \n" - "\tDefault port is 6969.\n"); + printf ("Usage: udpt []\n"); } int main(int argc, char *argv[]) { - printf("UDP Tracker (UDPT) %s\nCopyright: (C) 2012 Naim Abda \n\n", VERSION); + printf("UDP Tracker (UDPT) %s\nCopyright: (C) 2012 Naim Abda \n", VERSION); + printf("Build Date: %s\n\n", __DATE__); #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); #endif - uint16_t port = 6969; + char *config_file = "udpt.conf"; + if (argc <= 1) { _print_usage (); } - else if (argc == 2) + + Settings settings; + udpServerInstance usi; + + settings_init (&settings, config_file); + if (settings_load (&settings) != 0) { - port = atoi(argv[1]); - printf("selected port=%u\n", port); + // set default settings: + + settings_set (&settings, "database", "driver", "sqlite3"); + settings_set (&settings, "database", "file", "tracker.db"); + + settings_set (&settings, "tracker", "port", "6969"); + settings_set (&settings, "tracker", "threads", "5"); + settings_set (&settings, "tracker", "allow_remotes", "yes"); + settings_set (&settings, "tracker", "allow_iana_ips", "yes"); + + settings_save (&settings); + printf("Failed to read from '%s'. Using default settings.\n", config_file); } - udpServerInstance usi; - UDPTracker_init(&usi, port, 5); + UDPTracker_init(&usi, &settings); int r = UDPTracker_start(&usi); if (r != 0) @@ -81,7 +97,7 @@ int main(int argc, char *argv[]) cleanup: printf("\nGoodbye.\n"); - + settings_destroy (&settings); UDPTracker_destroy(&usi); #ifdef WIN32 diff --git a/src/multiplatform.h b/src/multiplatform.h index 202f662..87d746c 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -45,9 +45,8 @@ typedef struct hostent HOSTENT; typedef void* LPVOID; typedef void (LPTHREAD_START_ROUTINE)(LPVOID); typedef pthread_t HANDLE; -//#define IPPROTO_UDP 0 // no protocol set.. SOCK_DGRAM is enough. #define min(a,b) (a > b ? b : a) -#define VERSION "1.0.0 (Linux)" +#define VERSION "1.0.0-alpha (Linux)" #endif diff --git a/src/settings.c b/src/settings.c index 0b899c4..359097b 100644 --- a/src/settings.c +++ b/src/settings.c @@ -63,14 +63,14 @@ void _settings_clean_string (char **str) offset++; } - *str += offset; + (*str) += offset; len -= offset; for (i = len - 1;i >= 0;i--) { if (isspace( (*str)[i] ) != 0) { - *str[i] = '\0'; + (*str)[i] = '\0'; } else break; diff --git a/src/settings.h b/src/settings.h index f015248..49d80ce 100644 --- a/src/settings.h +++ b/src/settings.h @@ -18,6 +18,8 @@ * along with UDPT. If not, see . */ +#pragma once + #include typedef struct { diff --git a/src/udpTracker.c b/src/udpTracker.c index d2c4583..95474d6 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -38,13 +38,65 @@ static void* _thread_start (void *arg); static void* _maintainance_start (void *arg); #endif -void UDPTracker_init (udpServerInstance *usi, uint16_t port, uint8_t threads) +static int _isTrue (char *str) { + if (str == NULL) + return -1; + int i; + int len = strlen (str); + for (i = 0;i < len;i++) + { + if (str[i] >= 'A' && str[i] <= 'Z') + { + str[i] = (str[i] - 'A' + 'a'); + } + } + if (strcmp(str, "yes") == 0) + return 1; + if (strcmp(str, "no") == 0) + return 0; + if (strcmp(str, "true") == 0) + return 1; + if (strcmp(str, "false") == 0) + return 0; + if (strcmp(str, "1") == 0) + return 1; + if (strcmp(str, "0") == 0) + return 0; + return -1; +} + +void UDPTracker_init (udpServerInstance *usi, Settings *settings) +{ + int r; + int port = 6969; + int threads = 5; + uint8_t n_settings = 0; + + char *s_port = settings_get(settings, "tracker", "port"); + char *s_threads = settings_get(settings, "tracker", "threads"); + char *s_allow_remotes = settings_get (settings, "tracker", "allow_remotes"); + char *s_allow_iana_ip = settings_get (settings, "tracker", "allow_iana_ips"); + + r = _isTrue(s_allow_remotes); + if (r == 1) + n_settings |= UDPT_ALLOW_REMOTE_IP; + r = _isTrue(s_allow_iana_ip); + if (r != 0) + n_settings |= UDPT_ALLOW_IANA_IP; + + if (s_port != NULL) + port = atoi (s_port); + if (s_threads != NULL) + threads = atoi (s_threads); + usi->port = port; usi->thread_count = threads + 1; usi->threads = malloc (sizeof(HANDLE) * usi->thread_count); usi->flags = 0; usi->conn = NULL; + usi->settings = n_settings; + usi->o_settings = settings; } void UDPTracker_destroy (udpServerInstance *usi) @@ -81,7 +133,6 @@ void UDPTracker_destroy (udpServerInstance *usi) free (usi->threads); } - int UDPTracker_start (udpServerInstance *usi) { SOCKET sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); @@ -116,7 +167,11 @@ int UDPTracker_start (udpServerInstance *usi) usi->sock = sock; - db_open(&usi->conn, "tracker.db"); + char *dbname = settings_get (usi->o_settings, "database", "file"); + if (dbname == NULL) + dbname = "tracker.db"; + + db_open(&usi->conn, dbname); usi->flags |= FLAG_RUNNING; int i; @@ -125,7 +180,7 @@ int UDPTracker_start (udpServerInstance *usi) #ifdef WIN32 usi->threads[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_maintainance_start, (LPVOID)usi, 0, NULL); #elif defined (linux) - printf("Starting maintenance thread (1/6)...\n"); + printf("Starting maintenance thread (1/%u)...\n", usi->thread_count); pthread_create (&usi->threads[0], NULL, _maintainance_start, usi); #endif @@ -210,6 +265,11 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * req->num_want = m_hton32 (req->num_want); req->left = m_hton64 (req->left); + if ((usi->settings & UDPT_ALLOW_REMOTE_IP) == 0 && req->ip_address != 0) + { + _send_error (usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); + return 0; + } // load peers int q = 30; @@ -332,6 +392,14 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da return 0; } +static int _isIANA_IP (uint32_t ip) +{ + uint8_t x = (ip % 256); + if (x == 0 || x == 10 || x == 127 || x >= 224) + return 1; + return 0; +} + static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char *data, int r) { ConnectionRequest *cR; @@ -339,6 +407,14 @@ static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char * uint32_t action = m_hton32(cR->action); + if ((usi->settings & UDPT_ALLOW_IANA_IP) > 0) + { + if (_isIANA_IP (remote->sin_addr.s_addr)) + { + return 0; // Access Denied: IANA reserved IP. + } + } + printf(":: %x:%u ACTION=%d\n", remote->sin_addr.s_addr , remote->sin_port, action); if (action == 0 && r >= 16) diff --git a/src/udpTracker.h b/src/udpTracker.h index 9ad9d3a..2f6f4d1 100644 --- a/src/udpTracker.h +++ b/src/udpTracker.h @@ -23,6 +23,7 @@ #include #include "multiplatform.h" #include "db/database.h" +#include "settings.h" struct udp_connection_request { @@ -90,6 +91,12 @@ struct udp_error_response char *message; }; +#define UDPT_DYNAMIC 0x01 // Track Any info_hash? +#define UDPT_ALLOW_REMOTE_IP 0x02 // Allow client's to send other IPs? +#define UDPT_ALLOW_IANA_IP 0x04 // allow IP's like 127.0.0.1 or other IANA reserved IPs? +#define UDPT_VALIDATE_CLIENT 0x08 // validate client before adding to Database? (check if connection is open?) + + typedef struct { SOCKET sock; @@ -98,9 +105,11 @@ typedef struct uint8_t thread_count; uint8_t flags; + uint8_t settings; HANDLE *threads; + Settings *o_settings; dbConnection *conn; } udpServerInstance; @@ -118,7 +127,7 @@ typedef struct udp_error_response ErrorResponse; * @param port The port to bind the server to * @param threads Amount of threads to start the server with. */ -void UDPTracker_init (udpServerInstance *usi, uint16_t port, uint8_t threads); +void UDPTracker_init (udpServerInstance *usi, Settings *); /** * Destroys resources that were created by UDPTracker_init. From 3d88d5ea3e772fef28733f89a1c23c26407932ab Mon Sep 17 00:00:00 2001 From: Naim A Date: Tue, 18 Dec 2012 19:28:45 +0200 Subject: [PATCH 14/99] minor change in settings. --- src/settings.c | 37 ++++++++++++++++++++++++------------- src/settings.h | 12 ++++++++++++ 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/src/settings.c b/src/settings.c index 359097b..278332d 100644 --- a/src/settings.c +++ b/src/settings.c @@ -24,7 +24,6 @@ #include #include -static SettingClass* settings_get_class (Settings *s, char *classname) { if (s == NULL || classname == NULL) @@ -264,18 +263,7 @@ char* settings_get (Settings *s, char *class, char *name) return NULL; SettingClass *c = settings_get_class (s, class); - if (c == NULL) - return NULL; - - KeyValue *kv; - int i; - for (i = 0;i < c->entry_count;i++) - { - kv = &c->entries[i]; - if (strcmp(kv->key, name) == 0) - return kv->values; - } - return NULL; + return settingclass_get (c, name); } int settings_set (Settings *s, char *class, char *name, char *value) @@ -284,6 +272,7 @@ int settings_set (Settings *s, char *class, char *name, char *value) return 1; SettingClass *c = settings_get_class (s, class); + if (c == NULL) { if (s->class_count + 1 >= s->class_size) @@ -305,6 +294,28 @@ int settings_set (Settings *s, char *class, char *name, char *value) } + return settingclass_set (c, name, value); +} + +char* settingclass_get (SettingClass *c, char *name) +{ + if (c == NULL) + return NULL; + + KeyValue *kv; + int i; + for (i = 0;i < c->entry_count;i++) + { + kv = &c->entries[i]; + if (strcmp(kv->key, name) == 0) + return kv->values; + } + return NULL; +} + +int settingclass_set (SettingClass *c, char *name, char *value) +{ + int i; for (i = 0;i < c->entry_count;i++) { diff --git a/src/settings.h b/src/settings.h index 49d80ce..971e6c8 100644 --- a/src/settings.h +++ b/src/settings.h @@ -69,6 +69,18 @@ int settings_save (Settings *s); */ void settings_destroy (Settings *s); +/** + * Gets the requested SettingClass. + * @param s Settings Object. + * @param classname The name of the class to find (case sensitive). + * @return a pointer to the found class, or NULL if not found. + */ +SettingClass* settings_get_class (Settings *s, char *classname); + +char* settingclass_get (SettingClass *s, char *name); + +int settingclass_set (SettingClass *s, char *name, char *value); + /** * Gets a setting from a Settings type. * @param s Pointer to a setting type. From bc56edda7ee4c861b61f1ef9127a8211c374a48a Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 20 Dec 2012 01:58:59 +0200 Subject: [PATCH 15/99] It is now possible to change announce/cleanup interval; Minor changes with settings; --- src/main.c | 16 +++++++++------ src/settings.c | 22 ++++++++++---------- src/settings.h | 12 +++++------ src/udpTracker.c | 53 +++++++++++++++++++----------------------------- src/udpTracker.h | 3 +++ 5 files changed, 51 insertions(+), 55 deletions(-) diff --git a/src/main.c b/src/main.c index e5b777d..1bc4598 100644 --- a/src/main.c +++ b/src/main.c @@ -56,15 +56,19 @@ int main(int argc, char *argv[]) settings_init (&settings, config_file); if (settings_load (&settings) != 0) { + const char strDATABASE[] = "database"; + const char strTRACKER[] = "tracker"; // set default settings: - settings_set (&settings, "database", "driver", "sqlite3"); - settings_set (&settings, "database", "file", "tracker.db"); + settings_set (&settings, strDATABASE, "driver", "sqlite3"); + settings_set (&settings, strDATABASE, "file", "tracker.db"); - settings_set (&settings, "tracker", "port", "6969"); - settings_set (&settings, "tracker", "threads", "5"); - settings_set (&settings, "tracker", "allow_remotes", "yes"); - settings_set (&settings, "tracker", "allow_iana_ips", "yes"); + settings_set (&settings, strTRACKER, "port", "6969"); + settings_set (&settings, strTRACKER, "threads", "5"); + settings_set (&settings, strTRACKER, "allow_remotes", "yes"); + settings_set (&settings, strTRACKER, "allow_iana_ips", "yes"); + settings_set (&settings, strTRACKER, "announce_interval", "1800"); + settings_set (&settings, strTRACKER, "cleanup_interval", "120"); settings_save (&settings); printf("Failed to read from '%s'. Using default settings.\n", config_file); diff --git a/src/settings.c b/src/settings.c index 278332d..4effdd1 100644 --- a/src/settings.c +++ b/src/settings.c @@ -24,7 +24,7 @@ #include #include -SettingClass* settings_get_class (Settings *s, char *classname) +SettingClass* settings_get_class (Settings *s, const char *classname) { if (s == NULL || classname == NULL) return NULL; @@ -40,10 +40,10 @@ SettingClass* settings_get_class (Settings *s, char *classname) return NULL; } -void settings_init (Settings *s, char *filename) +void settings_init (Settings *s, const char *filename) { s->buffer = NULL; - s->filename = filename; + s->filename = (char*)filename; s->classes = NULL; s->class_count = s->class_size = 0; } @@ -257,7 +257,7 @@ void settings_destroy (Settings *s) } } -char* settings_get (Settings *s, char *class, char *name) +char* settings_get (Settings *s, const char *class, const char *name) { if (s == NULL || class == NULL || name == NULL) return NULL; @@ -266,7 +266,7 @@ char* settings_get (Settings *s, char *class, char *name) return settingclass_get (c, name); } -int settings_set (Settings *s, char *class, char *name, char *value) +int settings_set (Settings *s, const char *class, const char *name, const char *value) { if (s == NULL || class == NULL || name == NULL) return 1; @@ -288,7 +288,7 @@ int settings_set (Settings *s, char *class, char *name, char *value) c = &s->classes[s->class_count]; s->class_count++; - c->classname = class; + c->classname = (char*)class; c->entries = NULL; c->entry_size = c->entry_count = 0; @@ -297,7 +297,7 @@ int settings_set (Settings *s, char *class, char *name, char *value) return settingclass_set (c, name, value); } -char* settingclass_get (SettingClass *c, char *name) +char* settingclass_get (SettingClass *c, const char *name) { if (c == NULL) return NULL; @@ -313,7 +313,7 @@ char* settingclass_get (SettingClass *c, char *name) return NULL; } -int settingclass_set (SettingClass *c, char *name, char *value) +int settingclass_set (SettingClass *c, const char *name, const char *value) { int i; @@ -321,7 +321,7 @@ int settingclass_set (SettingClass *c, char *name, char *value) { if (strcmp(name, c->entries[i].key) == 0) { - c->entries[i].values = value; + c->entries[i].values = (char*)value; return 0; } } @@ -339,8 +339,8 @@ int settingclass_set (SettingClass *c, char *name, char *value) int ni = c->entry_count; c->entry_count++; - c->entries[ni].key = name; - c->entries[ni].values = value; + c->entries[ni].key = (char*)name; + c->entries[ni].values = (char*)value; return 0; } diff --git a/src/settings.h b/src/settings.h index 971e6c8..5117c6a 100644 --- a/src/settings.h +++ b/src/settings.h @@ -47,7 +47,7 @@ typedef struct { * @param s Pointer to settings to initialize. * @param filename the settings filename. */ -void settings_init (Settings *s, char *filename); +void settings_init (Settings *s, const char *filename); /** * Loads settings from file @@ -75,11 +75,11 @@ void settings_destroy (Settings *s); * @param classname The name of the class to find (case sensitive). * @return a pointer to the found class, or NULL if not found. */ -SettingClass* settings_get_class (Settings *s, char *classname); +SettingClass* settings_get_class (Settings *s, const char *classname); -char* settingclass_get (SettingClass *s, char *name); +char* settingclass_get (SettingClass *s, const char *name); -int settingclass_set (SettingClass *s, char *name, char *value); +int settingclass_set (SettingClass *s, const char *name, const char *value); /** * Gets a setting from a Settings type. @@ -88,7 +88,7 @@ int settingclass_set (SettingClass *s, char *name, char *value); * @param name The name of the requested setting. * @return The value for the requested setting, NULL if not available. */ -char* settings_get (Settings *s, char *class, char *name); +char* settings_get (Settings *s, const char *class, const char *name); /** * Sets a setting in a settings type. @@ -98,4 +98,4 @@ char* settings_get (Settings *s, char *class, char *name); * @param value The value to set for the setting. * @return 0 on success, otherwise non-zero. */ -int settings_set (Settings *s, char *class, char *name, char *value); +int settings_set (Settings *s, const char *class, const char *name, const char *value); diff --git a/src/udpTracker.c b/src/udpTracker.c index 95474d6..08a0201 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -20,6 +20,7 @@ #include "multiplatform.h" #include "udpTracker.h" #include "tools.h" +#include "settings.h" #include #include #include @@ -27,8 +28,6 @@ #define FLAG_RUNNING 0x01 #define UDP_BUFFER_SIZE 2048 -#define CLEANUP_INTERVAL 20 -#define TRACKER_INTERVAL 60 // normally 1800 #ifdef WIN32 static DWORD _thread_start (LPVOID arg); @@ -68,31 +67,30 @@ static int _isTrue (char *str) void UDPTracker_init (udpServerInstance *usi, Settings *settings) { - int r; - int port = 6969; - int threads = 5; + SettingClass *sc_tracker; + sc_tracker = settings_get_class (settings, "tracker"); uint8_t n_settings = 0; - char *s_port = settings_get(settings, "tracker", "port"); - char *s_threads = settings_get(settings, "tracker", "threads"); - char *s_allow_remotes = settings_get (settings, "tracker", "allow_remotes"); - char *s_allow_iana_ip = settings_get (settings, "tracker", "allow_iana_ips"); + char *s_port = settingclass_get(sc_tracker, "port"); + char *s_threads = settingclass_get(sc_tracker, "threads"); + char *s_allow_remotes = settingclass_get (sc_tracker, "allow_remotes"); + char *s_allow_iana_ip = settingclass_get (sc_tracker, "allow_iana_ips"); + char *s_int_announce = settingclass_get (sc_tracker, "announce_interval"); + char *s_int_cleanup = settingclass_get (sc_tracker, "cleanup_interval"); - r = _isTrue(s_allow_remotes); - if (r == 1) + if (_isTrue(s_allow_remotes) == 1) n_settings |= UDPT_ALLOW_REMOTE_IP; - r = _isTrue(s_allow_iana_ip); - if (r != 0) + + if (_isTrue(s_allow_iana_ip) != 0) n_settings |= UDPT_ALLOW_IANA_IP; - if (s_port != NULL) - port = atoi (s_port); - if (s_threads != NULL) - threads = atoi (s_threads); + usi->announce_interval = (s_int_announce == NULL ? 1800 : atoi (s_int_announce)); + usi->cleanup_interval = (s_int_cleanup == NULL ? 120 : atoi (s_int_cleanup)); + usi->port = (s_port == NULL ? 6969 : atoi (s_port)); + usi->thread_count = (s_threads == NULL ? 5 : atoi (s_threads)) + 1; - usi->port = port; - usi->thread_count = threads + 1; usi->threads = malloc (sizeof(HANDLE) * usi->thread_count); + usi->flags = 0; usi->conn = NULL; usi->settings = n_settings; @@ -290,7 +288,7 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * uint8_t buff [bSize]; AnnounceResponse *resp = (AnnounceResponse*)buff; resp->action = m_hton32(1); - resp->interval = m_hton32 ( TRACKER_INTERVAL ); + resp->interval = m_hton32 ( usi->announce_interval ); resp->leechers = m_hton32(leechers); resp->seeders = m_hton32 (seeders); resp->transaction_id = req->transaction_id; @@ -311,7 +309,6 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8); buff[25 + x] = (peers[i].port & 0xff); -// printf("%u.%u.%u.%u:%u\n", buff[20 + x], buff[21 + x], buff[22 + x], buff[23 + x], peers[i].port); } free (peers); sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); @@ -340,13 +337,10 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da { ScrapeRequest *sR = (ScrapeRequest*)data; -// _send_error (usi, remote, sR->transaction_id, "Scrape wasn't implemented yet!"); - // validate request length: int v = len - 16; if (v < 0 || v % 20 != 0) { -// printf("BAD SCRAPE: len=%d\n", len); _send_error (usi, remote, sR->transaction_id, "Bad scrape request."); return 0; } @@ -363,7 +357,7 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da resp->transaction_id = sR->transaction_id; int i, j; -// printf("Scrape: (%d) \n", c); + for (i = 0;i < c;i++) { for (j = 0; j < 20;j++) @@ -445,8 +439,6 @@ static void* _thread_start (void *arg) int addrSz = sizeof (SOCKADDR_IN); int r; -// char *tmpBuff = malloc (UDP_BUFFER_SIZE); // 98 is the maximum request size. - char tmpBuff [UDP_BUFFER_SIZE]; while ((usi->flags & FLAG_RUNNING) > 0) @@ -456,12 +448,9 @@ static void* _thread_start (void *arg) r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, (unsigned*)&addrSz); if (r <= 0) continue; // bad request... -// printf("RECV:%d\n", r); r = _resolve_request(usi, &remoteAddr, tmpBuff, r); -// printf("R=%d\n", r); } -// free (tmpBuff); #ifdef linux pthread_exit (NULL); #endif @@ -481,9 +470,9 @@ static void* _maintainance_start (void *arg) db_cleanup (usi->conn); #ifdef WIN32 - Sleep (CLEANUP_INTERVAL * 1000); // wait 2 minutes between every cleanup. + Sleep (usi->cleanup_interval * 1000); // wait 2 minutes between every cleanup. #elif defined (linux) - sleep (CLEANUP_INTERVAL); + sleep (usi->cleanup_interval); #else #error Unsupported OS. #endif diff --git a/src/udpTracker.h b/src/udpTracker.h index 2f6f4d1..e148765 100644 --- a/src/udpTracker.h +++ b/src/udpTracker.h @@ -109,6 +109,9 @@ typedef struct HANDLE *threads; + uint32_t announce_interval; + uint32_t cleanup_interval; + Settings *o_settings; dbConnection *conn; } udpServerInstance; From 632e88444c9845fa75c5343fe51cd10788db7b0d Mon Sep 17 00:00:00 2001 From: Naim A Date: Tue, 15 Jan 2013 01:55:25 +0200 Subject: [PATCH 16/99] Bufix #2. --- src/multiplatform.h | 1 - 1 file changed, 1 deletion(-) diff --git a/src/multiplatform.h b/src/multiplatform.h index 87d746c..2931621 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -41,7 +41,6 @@ typedef struct hostent HOSTENT; typedef struct sockaddr SOCKADDR; typedef struct sockaddr_in SOCKADDR_IN; typedef struct in_addr IN_ADDR; -typedef struct hostent HOSTENT; typedef void* LPVOID; typedef void (LPTHREAD_START_ROUTINE)(LPVOID); typedef pthread_t HANDLE; From 06f51a10680e6340d8dae17a72a80f655d693be7 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 17 Feb 2013 15:21:17 +0200 Subject: [PATCH 17/99] Change code style to be compatible with MSVC Moving all decleration to top of functions. Added Macro _WIN32 to support MSVC --- src/db/driver_sqlite.c | 55 ++++++++------ src/multiplatform.h | 4 ++ src/settings.c | 87 ++++++++++++++-------- src/settings.h | 4 +- src/udpTracker.c | 159 ++++++++++++++++++++++++++--------------- 5 files changed, 196 insertions(+), 113 deletions(-) diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c index 9521643..ac93c5f 100644 --- a/src/db/driver_sqlite.c +++ b/src/db/driver_sqlite.c @@ -48,6 +48,9 @@ void _to_hex_str (const uint8_t *hash, char *data) static int _db_make_torrent_table (sqlite3 *db, char *hash) { char sql [2000]; + char *err_msg; + int r; + sql[0] = '\0'; strcat(sql, "CREATE TABLE IF NOT EXISTS 't"); @@ -65,8 +68,7 @@ static int _db_make_torrent_table (sqlite3 *db, char *hash) strcat(sql, ", CONSTRAINT c1 UNIQUE (ip,port) ON CONFLICT REPLACE)"); // create table. - char *err_msg; - int r = sqlite3_exec(db, sql, NULL, NULL, &err_msg); + r = sqlite3_exec(db, sql, NULL, NULL, &err_msg); printf("E:%s\n", err_msg); return r; @@ -85,20 +87,22 @@ static void _db_setup (sqlite3 *db) int db_open (dbConnection **db, char *cStr) { - FILE *f = fopen (cStr, "rb"); - int doSetup = 0; + FILE *f; + int doSetup, // check if to build DB, or it already exists? + r; + + f = fopen (cStr, "rb"); + doSetup = 0; if (f == NULL) doSetup = 1; else fclose (f); *db = malloc (sizeof(struct dbConnection)); - int r = sqlite3_open (cStr, &((*db)->db)); + r = sqlite3_open (cStr, &((*db)->db)); if (doSetup) _db_setup((*db)->db); - - return r; } @@ -112,15 +116,16 @@ int db_close (dbConnection *db) int db_add_peer (dbConnection *db, uint8_t info_hash[20], db_peerEntry *pE) { char xHash [50]; // we just need 40 + \0 = 41. + sqlite3_stmt *stmt; + char sql [1000]; + int r; char *hash = xHash; to_hex_str(info_hash, hash); _db_make_torrent_table(db->db, hash); - sqlite3_stmt *stmt; - char sql [1000]; sql[0] = '\0'; strcat(sql, "REPLACE INTO 't"); strcat(sql, hash); @@ -138,7 +143,7 @@ int db_add_peer (dbConnection *db, uint8_t info_hash[20], db_peerEntry *pE) sqlite3_bind_blob(stmt, 6, (void*)&pE->left, 8, NULL); sqlite3_bind_int(stmt, 7, time(NULL)); - int r = sqlite3_step(stmt); + r = sqlite3_step(stmt); sqlite3_finalize(stmt); strcpy(sql, "REPLACE INTO stats (info_hash,last_mod) VALUES (?,?)"); @@ -154,22 +159,23 @@ int db_add_peer (dbConnection *db, uint8_t info_hash[20], db_peerEntry *pE) int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry *lst, int *sZ) { char sql [1000]; + char hash [50]; + sqlite3_stmt *stmt; + int r, + i; + sql[0] = '\0'; - char hash [50]; to_hex_str(info_hash, hash); strcat(sql, "SELECT ip,port FROM 't"); strcat(sql, hash); strcat(sql, "' LIMIT ?"); - sqlite3_stmt *stmt; sqlite3_prepare(db->db, sql, -1, &stmt, NULL); sqlite3_bind_int(stmt, 1, *sZ); - int i = 0; - int r; - + i = 0; while (*sZ > i) { r = sqlite3_step(stmt); @@ -198,13 +204,14 @@ int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry *lst, i int db_get_stats (dbConnection *db, uint8_t hash[20], int32_t *seeders, int32_t *leechers, int32_t *completed) { + const char sql[] = "SELECT seeders,leechers,completed FROM 'stats' WHERE info_hash=?"; + sqlite3_stmt *stmt; + *seeders = 0; *leechers = 0; *completed = 0; - const char sql[] = "SELECT seeders,leechers,completed FROM 'stats' WHERE info_hash=?"; - sqlite3_stmt *stmt; sqlite3_prepare (db->db, sql, -1, &stmt, NULL); sqlite3_bind_blob (stmt, 1, (void*)hash, 20, NULL); @@ -222,18 +229,21 @@ int db_get_stats (dbConnection *db, uint8_t hash[20], int32_t *seeders, int32_t int db_cleanup (dbConnection *db) { + const char sql[] = "SELECT info_hash FROM stats WHERE last_moddb, sql, -1, &stmt, NULL); sqlite3_bind_int (stmt, 1, timeframe - 7200); - char hash [50], temp [1000]; while (sqlite3_step(stmt) == SQLITE_ROW) { @@ -313,6 +323,7 @@ int db_remove_peer (dbConnection *db, uint8_t hash[20], db_peerEntry *pE) { char sql [1000]; char xHash [50]; + sqlite3_stmt *stmt; _to_hex_str (hash, xHash); @@ -320,8 +331,6 @@ int db_remove_peer (dbConnection *db, uint8_t hash[20], db_peerEntry *pE) strcat (sql, xHash); strcat (sql, "' WHERE ip=? AND port=? AND peer_id=?"); - sqlite3_stmt *stmt; - sqlite3_prepare (db->db, sql, -1, &stmt, NULL); sqlite3_bind_blob(stmt, 0, (const void*)&pE->ip, 4, NULL); diff --git a/src/multiplatform.h b/src/multiplatform.h index 2931621..427c5be 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -19,6 +19,10 @@ #include +#if defined (_WIN32) && !defined (WIN32) +#define WIN32 +#endif + #ifdef WIN32 #include #include diff --git a/src/settings.c b/src/settings.c index 4effdd1..d8d7882 100644 --- a/src/settings.c +++ b/src/settings.c @@ -26,9 +26,11 @@ SettingClass* settings_get_class (Settings *s, const char *classname) { + int i; + if (s == NULL || classname == NULL) return NULL; - int i; + for (i = 0;i < s->class_count;i++) { if (strcmp(classname, s->classes[i].classname) == 0) @@ -51,10 +53,14 @@ void settings_init (Settings *s, const char *filename) static void _settings_clean_string (char **str) { - int len = strlen(*str); + int len, + i, + offset; + + len = strlen(*str); //strip leading whitespaces. - int i, offset = 0; + offset = 0; for (i = 0;i < len;i++) { if (isspace(*str[i]) == 0) @@ -79,11 +85,14 @@ void _settings_clean_string (char **str) static void _settings_parser (Settings *s, char *data, int len) { - char *className = NULL; - char *key = NULL; - char *value = NULL; - int i, cil = 0; // cil = Chars in line. + char *className, *key, *value; + int i, + cil; // cil = Chars in line. char c; + + className = key = value = NULL; + cil = 0; + for (i = 0;i < len;i++) { c = data[i]; @@ -171,6 +180,13 @@ void _settings_parser (Settings *s, char *data, int len) int settings_load (Settings *s) { + FILE *f; + int len, + r, + offset; // file length + char *buffer; + char tmp [512]; + if (s->buffer != NULL) { free (s->buffer); @@ -178,22 +194,21 @@ int settings_load (Settings *s) } // ini file format. - FILE *f = fopen(s->filename, "rb"); + f = fopen(s->filename, "rb"); if (f == NULL) return 1; fseek (f, 0, SEEK_END); - int len = ftell(f); + len = ftell(f); fseek(f, 0, SEEK_SET); - s->buffer = malloc (len); - char *buffer = s->buffer; + s->buffer = (char*)malloc (len); + buffer = s->buffer; - char tmp [512]; - int r = 0, offset = 0; + r = offset = 0; while (!feof(f) && !ferror(f)) { - r = fread (tmp, 1, 512, f); int i; + r = fread (tmp, 1, 512, f); for (i = 0;i < r;i++) { buffer[offset + i] = tmp[i]; @@ -211,21 +226,22 @@ int settings_load (Settings *s) int settings_save (Settings *s) { char buffer [2048]; + SettingClass *sclass; + FILE *f; + int c, e; - FILE *f = fopen(s->filename, "wb"); + f = fopen(s->filename, "wb"); fprintf(f, "; udpt Settings File - Created Automatically.\n"); setbuf(f, buffer); - int c, e; - SettingClass *class; for (c = 0;c < s->class_count;c++) { - class = &s->classes[c]; - fprintf(f, "[%s]\n", class->classname); + sclass = &s->classes[c]; + fprintf(f, "[%s]\n", sclass->classname); - for (e = 0;e < class->entry_count;e++) + for (e = 0;e < sclass->entry_count;e++) { - fprintf(f, "%s=%s\n", class->entries[e].key, class->entries[e].values); + fprintf(f, "%s=%s\n", sclass->entries[e].key, sclass->entries[e].values); } fprintf(f, "\n"); @@ -240,7 +256,6 @@ void settings_destroy (Settings *s) { if (s->classes != NULL) { - int i; for (i = 0;i < s->class_count;i++) { @@ -259,19 +274,23 @@ void settings_destroy (Settings *s) char* settings_get (Settings *s, const char *class, const char *name) { + SettingClass *c; + if (s == NULL || class == NULL || name == NULL) return NULL; - SettingClass *c = settings_get_class (s, class); + c = settings_get_class (s, class); return settingclass_get (c, name); } int settings_set (Settings *s, const char *class, const char *name, const char *value) { + SettingClass *c; + if (s == NULL || class == NULL || name == NULL) return 1; - SettingClass *c = settings_get_class (s, class); + c = settings_get_class (s, class); if (c == NULL) { @@ -299,11 +318,12 @@ int settings_set (Settings *s, const char *class, const char *name, const char * char* settingclass_get (SettingClass *c, const char *name) { + KeyValue *kv; + int i; + if (c == NULL) return NULL; - KeyValue *kv; - int i; for (i = 0;i < c->entry_count;i++) { kv = &c->entries[i]; @@ -316,7 +336,9 @@ char* settingclass_get (SettingClass *c, const char *name) int settingclass_set (SettingClass *c, const char *name, const char *value) { - int i; + int i, + ni; + for (i = 0;i < c->entry_count;i++) { if (strcmp(name, c->entries[i].key) == 0) @@ -328,15 +350,20 @@ int settingclass_set (SettingClass *c, const char *name, const char *value) if (c->entry_count + 1 >= c->entry_size) { - int ns = c->entry_size + 5; - KeyValue *n = realloc (c->entries, sizeof(KeyValue) * ns); + int ns; + KeyValue *n; + + ns = c->entry_size + 5; + n = realloc (c->entries, sizeof(KeyValue) * ns); + if (n == NULL) return 1; + c->entries = n; c->entry_size = ns; } - int ni = c->entry_count; + ni = c->entry_count; c->entry_count++; c->entries[ni].key = (char*)name; diff --git a/src/settings.h b/src/settings.h index 5117c6a..0a67e8a 100644 --- a/src/settings.h +++ b/src/settings.h @@ -88,7 +88,7 @@ int settingclass_set (SettingClass *s, const char *name, const char *value); * @param name The name of the requested setting. * @return The value for the requested setting, NULL if not available. */ -char* settings_get (Settings *s, const char *class, const char *name); +char* settings_get (Settings *s, const char *classn, const char *name); /** * Sets a setting in a settings type. @@ -98,4 +98,4 @@ char* settings_get (Settings *s, const char *class, const char *name); * @param value The value to set for the setting. * @return 0 on success, otherwise non-zero. */ -int settings_set (Settings *s, const char *class, const char *name, const char *value); +int settings_set (Settings *s, const char *classn, const char *name, const char *value); diff --git a/src/udpTracker.c b/src/udpTracker.c index 08a0201..e0d4a5b 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -39,10 +39,12 @@ static void* _maintainance_start (void *arg); static int _isTrue (char *str) { + int i, // loop index + len; // string's length + if (str == NULL) return -1; - int i; - int len = strlen (str); + len = strlen (str); for (i = 0;i < len;i++) { if (str[i] >= 'A' && str[i] <= 'Z') @@ -68,15 +70,22 @@ static int _isTrue (char *str) void UDPTracker_init (udpServerInstance *usi, Settings *settings) { SettingClass *sc_tracker; - sc_tracker = settings_get_class (settings, "tracker"); uint8_t n_settings = 0; + char *s_port, // port + *s_threads, // threads + *s_allow_remotes, // remotes allowed? + *s_allow_iana_ip, // IANA IPs allowed? + *s_int_announce, // announce interval + *s_int_cleanup; // cleanup interval - char *s_port = settingclass_get(sc_tracker, "port"); - char *s_threads = settingclass_get(sc_tracker, "threads"); - char *s_allow_remotes = settingclass_get (sc_tracker, "allow_remotes"); - char *s_allow_iana_ip = settingclass_get (sc_tracker, "allow_iana_ips"); - char *s_int_announce = settingclass_get (sc_tracker, "announce_interval"); - char *s_int_cleanup = settingclass_get (sc_tracker, "cleanup_interval"); + sc_tracker = settings_get_class (settings, "tracker"); + + s_port = settingclass_get(sc_tracker, "port"); + s_threads = settingclass_get(sc_tracker, "threads"); + s_allow_remotes = settingclass_get (sc_tracker, "allow_remotes"); + s_allow_iana_ip = settingclass_get (sc_tracker, "allow_iana_ips"); + s_int_announce = settingclass_get (sc_tracker, "announce_interval"); + s_int_cleanup = settingclass_get (sc_tracker, "cleanup_interval"); if (_isTrue(s_allow_remotes) == 1) n_settings |= UDPT_ALLOW_REMOTE_IP; @@ -89,7 +98,7 @@ void UDPTracker_init (udpServerInstance *usi, Settings *settings) usi->port = (s_port == NULL ? 6969 : atoi (s_port)); usi->thread_count = (s_threads == NULL ? 5 : atoi (s_threads)) + 1; - usi->threads = malloc (sizeof(HANDLE) * usi->thread_count); + usi->threads = (HANDLE*)malloc (sizeof(HANDLE) * usi->thread_count); usi->flags = 0; usi->conn = NULL; @@ -99,6 +108,8 @@ void UDPTracker_init (udpServerInstance *usi, Settings *settings) void UDPTracker_destroy (udpServerInstance *usi) { + int i; // loop index + usi->flags = (!(FLAG_RUNNING)) & usi->flags; @@ -115,7 +126,6 @@ void UDPTracker_destroy (udpServerInstance *usi) Sleep (1000); #endif - int i; for (i = 0;i < usi->thread_count;i++) { #ifdef WIN32 @@ -133,13 +143,17 @@ void UDPTracker_destroy (udpServerInstance *usi) int UDPTracker_start (udpServerInstance *usi) { - SOCKET sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); + SOCKET sock; + SOCKADDR_IN recvAddr; + int r, // saves results + i, // loop index + yup; // just to set TRUE + char *dbname;// saves the Database name. + + sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == INVALID_SOCKET) return 1; - int r; - - SOCKADDR_IN recvAddr; #ifdef WIN32 recvAddr.sin_addr.S_un.S_addr = 0L; #elif defined (linux) @@ -148,7 +162,7 @@ int UDPTracker_start (udpServerInstance *usi) recvAddr.sin_family = AF_INET; recvAddr.sin_port = m_hton16 (usi->port); - int yup = 1; + yup = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); r = bind (sock, (SOCKADDR*)&recvAddr, sizeof(SOCKADDR_IN)); @@ -165,14 +179,13 @@ int UDPTracker_start (udpServerInstance *usi) usi->sock = sock; - char *dbname = settings_get (usi->o_settings, "database", "file"); + dbname = settings_get (usi->o_settings, "database", "file"); if (dbname == NULL) dbname = "tracker.db"; db_open(&usi->conn, dbname); usi->flags |= FLAG_RUNNING; - int i; // create maintainer thread. #ifdef WIN32 @@ -197,10 +210,13 @@ int UDPTracker_start (udpServerInstance *usi) static uint64_t _get_connID (SOCKADDR_IN *remote) { - int base = time(NULL); + int base; + uint64_t x; + + base = time(NULL); base /= 3600; // changes every day. - uint64_t x = base; + x = base; #ifdef WIN32 x += remote->sin_addr.S_un.S_addr; #elif defined (linux) @@ -212,15 +228,17 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) static int _send_error (udpServerInstance *usi, SOCKADDR_IN *remote, uint32_t transactionID, char *msg) { struct udp_error_response error; + int msg_sz, // message size to send. + i; // copy loop + char buff [1024]; // more than reasonable message size... + error.action = m_hton32 (3); error.transaction_id = transactionID; error.message = msg; - int msg_sz = 4 + 4 + 1 + strlen(msg); + msg_sz = 4 + 4 + 1 + strlen(msg); - char buff [msg_sz]; memcpy(buff, &error, 8); - int i; for (i = 8;i <= msg_sz;i++) { buff[i] = msg[i - 8]; @@ -233,9 +251,11 @@ static int _send_error (udpServerInstance *usi, SOCKADDR_IN *remote, uint32_t tr static int _handle_connection (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) { - ConnectionRequest *req = (ConnectionRequest*)data; - + ConnectionRequest *req; ConnectionResponse resp; + + req = (ConnectionRequest*)data; + resp.action = m_hton32(0); resp.transaction_id = req->transaction_id; resp.connection_id = _get_connID(remote); @@ -247,7 +267,19 @@ static int _handle_connection (udpServerInstance *usi, SOCKADDR_IN *remote, char static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) { - AnnounceRequest *req = (AnnounceRequest*)data; + AnnounceRequest *req; + AnnounceResponse *resp; + int q, // peer counts + bSize, // message size + i; // loop index + db_peerEntry *peers; + int32_t seeders, + leechers, + completed; + db_peerEntry pE; // info for DB + uint8_t buff [1028]; // Reasonable buffer size. (header+168 peers) + + req = (AnnounceRequest*)data; if (req->connection_id != _get_connID(remote)) { @@ -270,30 +302,27 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * } // load peers - int q = 30; + q = 30; if (req->num_want >= 1) q = min (q, req->num_want); - db_peerEntry *peers = malloc (sizeof(db_peerEntry) * q); + peers = (db_peerEntry*)malloc (sizeof(db_peerEntry) * q); db_load_peers(usi->conn, req->info_hash, peers, &q); // printf("%d peers found.\n", q); - int bSize = 20; // header is 20 bytes + bSize = 20; // header is 20 bytes bSize += (6 * q); // + 6 bytes per peer. - int32_t seeders, leechers, completed; db_get_stats (usi->conn, req->info_hash, &seeders, &leechers, &completed); - uint8_t buff [bSize]; - AnnounceResponse *resp = (AnnounceResponse*)buff; + resp = (AnnounceResponse*)buff; resp->action = m_hton32(1); resp->interval = m_hton32 ( usi->announce_interval ); resp->leechers = m_hton32(leechers); resp->seeders = m_hton32 (seeders); resp->transaction_id = req->transaction_id; - int i; for (i = 0;i < q;i++) { int x = i * 6; @@ -314,7 +343,6 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); // Add peer to list: - db_peerEntry pE; pE.downloaded = req->downloaded; pE.uploaded = req->uploaded; pE.left = req->left; @@ -335,10 +363,21 @@ static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char * static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *data, int len) { - ScrapeRequest *sR = (ScrapeRequest*)data; + ScrapeRequest *sR; + int v, // validation helper + c, // torrent counter + i, // loop counter + j; // loop counter + uint8_t hash [20]; + char xHash [50]; + ScrapeResponse *resp; + uint8_t buffer [1024]; // up to 74 torrents can be scraped at once (17*74+8) < 1024 + + + sR = (ScrapeRequest*)data; // validate request length: - int v = len - 16; + v = len - 16; if (v < 0 || v % 20 != 0) { _send_error (usi, remote, sR->transaction_id, "Bad scrape request."); @@ -346,20 +385,19 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da } // get torrent count. - int c = v / 20; + c = v / 20; - uint8_t hash [20]; - char xHash [50]; - - uint8_t buffer [8 + (12 * c)]; - ScrapeResponse *resp = (ScrapeResponse*)buffer; + resp = (ScrapeResponse*)buffer; resp->action = m_hton32 (2); resp->transaction_id = sR->transaction_id; - int i, j; - for (i = 0;i < c;i++) { + int32_t s, c, l; + int32_t *seeders, + *completed, + *leechers; + for (j = 0; j < 20;j++) hash[j] = data[j + (i*20)+16]; @@ -367,11 +405,9 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da printf("\t%s\n", xHash); - int32_t *seeders = (int32_t*)&buffer[i*12+8]; - int32_t *completed = (int32_t*)&buffer[i*12+12]; - int32_t *leechers = (int32_t*)&buffer[i*12+16]; - - int32_t s, c, l; + seeders = (int32_t*)&buffer[i*12+8]; + completed = (int32_t*)&buffer[i*12+12]; + leechers = (int32_t*)&buffer[i*12+16]; db_get_stats (usi->conn, hash, &s, &l, &c); @@ -381,7 +417,7 @@ static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *da } fflush (stdout); - sendto (usi->sock, buffer, sizeof(buffer), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + sendto (usi->sock, (const char*)buffer, sizeof(buffer), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); return 0; } @@ -397,9 +433,11 @@ static int _isIANA_IP (uint32_t ip) static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char *data, int r) { ConnectionRequest *cR; + uint32_t action; + cR = (ConnectionRequest*)data; - uint32_t action = m_hton32(cR->action); + action = m_hton32(cR->action); if ((usi->settings & UDPT_ALLOW_IANA_IP) > 0) { @@ -409,7 +447,7 @@ static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char * } } - printf(":: %x:%u ACTION=%d\n", remote->sin_addr.s_addr , remote->sin_port, action); + printf(":: %x:%u ACTION=%d\n", (unsigned int)remote->sin_addr.s_addr , remote->sin_port, action); if (action == 0 && r >= 16) return _handle_connection(usi, remote, data); @@ -433,14 +471,17 @@ static DWORD _thread_start (LPVOID arg) static void* _thread_start (void *arg) #endif { - udpServerInstance *usi = arg; - + udpServerInstance *usi; SOCKADDR_IN remoteAddr; - int addrSz = sizeof (SOCKADDR_IN); - int r; - + int addrSz, + r; char tmpBuff [UDP_BUFFER_SIZE]; + usi = arg; + + addrSz = sizeof (SOCKADDR_IN); + + while ((usi->flags & FLAG_RUNNING) > 0) { fflush(stdout); @@ -463,7 +504,9 @@ static DWORD _maintainance_start (LPVOID arg) static void* _maintainance_start (void *arg) #endif { - udpServerInstance *usi = (udpServerInstance *)arg; + udpServerInstance *usi; + + usi = (udpServerInstance *)arg; while ((usi->flags & FLAG_RUNNING) > 0) { From 5ae54cd8d677d30ea237f2956fe819037c622731 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 17 Feb 2013 17:07:05 +0200 Subject: [PATCH 18/99] Copyright headers updated, Compiles on MSVC now! --- src/db/database.h | 2 +- src/db/driver_sqlite.c | 8 +++----- src/main.c | 18 ++++++++++-------- src/multiplatform.h | 2 +- src/settings.c | 2 +- src/settings.h | 2 +- src/tools.c | 2 +- src/tools.h | 2 +- src/udpTracker.c | 2 +- src/udpTracker.h | 2 +- 10 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/db/database.h b/src/db/database.h index d13c299..61b25d5 100644 --- a/src/db/database.h +++ b/src/db/database.h @@ -1,5 +1,5 @@ /* - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c index ac93c5f..15611cd 100644 --- a/src/db/driver_sqlite.c +++ b/src/db/driver_sqlite.c @@ -1,5 +1,5 @@ /* - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * @@ -234,11 +234,12 @@ int db_cleanup (dbConnection *db) temp [1000]; sqlite3_stmt *stmt; int timeframe; + uint32_t leechers, seeders; + sqlite3_stmt *sTmp, *uStat; return 0; // TODO: Fix problems and than allow use of this function. printf("Cleanup...\n"); - timeframe = time(NULL); // remove "dead" torrents (non-active for two hours). @@ -267,9 +268,6 @@ int db_cleanup (dbConnection *db) sqlite3_prepare(db->db, "SELECT info_hash FROM stats WHERE last_mod>=?", -1, &stmt, NULL); sqlite3_bind_int (stmt, 1, timeframe - 7200); - uint32_t leechers, seeders; - sqlite3_stmt *sTmp, *uStat; - sqlite3_prepare (db->db, "UPDATE stats SET seeders=?,leechers=?,last_mod=? WHERE info_hash=?", -1, &uStat, NULL); while (sqlite3_step(stmt) == SQLITE_ROW) diff --git a/src/main.c b/src/main.c index 1bc4598..485830d 100644 --- a/src/main.c +++ b/src/main.c @@ -1,5 +1,5 @@ /* - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * @@ -35,24 +35,26 @@ static void _print_usage () int main(int argc, char *argv[]) { - printf("UDP Tracker (UDPT) %s\nCopyright: (C) 2012 Naim Abda \n", VERSION); - printf("Build Date: %s\n\n", __DATE__); + Settings settings; + udpServerInstance usi; + char *config_file; + int r; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); #endif - char *config_file = "udpt.conf"; + printf("UDP Tracker (UDPT) %s\nCopyright: (C) 2012 Naim Abda \n", VERSION); + printf("Build Date: %s\n\n", __DATE__); + + config_file = "udpt.conf"; if (argc <= 1) { _print_usage (); } - Settings settings; - udpServerInstance usi; - settings_init (&settings, config_file); if (settings_load (&settings) != 0) { @@ -76,7 +78,7 @@ int main(int argc, char *argv[]) UDPTracker_init(&usi, &settings); - int r = UDPTracker_start(&usi); + r = UDPTracker_start(&usi); if (r != 0) { printf("Error While trying to start server.\n"); diff --git a/src/multiplatform.h b/src/multiplatform.h index 427c5be..cc2acbb 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -1,5 +1,5 @@ /* - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * diff --git a/src/settings.c b/src/settings.c index d8d7882..dfdbf76 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,6 +1,6 @@ /* * - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * diff --git a/src/settings.h b/src/settings.h index 0a67e8a..21604a4 100644 --- a/src/settings.h +++ b/src/settings.h @@ -1,6 +1,6 @@ /* * - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * diff --git a/src/tools.c b/src/tools.c index 01a0ecd..e47098d 100644 --- a/src/tools.c +++ b/src/tools.c @@ -1,5 +1,5 @@ /* - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * diff --git a/src/tools.h b/src/tools.h index 09e7c21..f265038 100644 --- a/src/tools.h +++ b/src/tools.h @@ -1,5 +1,5 @@ /* - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * diff --git a/src/udpTracker.c b/src/udpTracker.c index e0d4a5b..95e969b 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -1,5 +1,5 @@ /* - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * diff --git a/src/udpTracker.h b/src/udpTracker.h index e148765..7402bf0 100644 --- a/src/udpTracker.h +++ b/src/udpTracker.h @@ -1,5 +1,5 @@ /* - * Copyright © 2012 Naim A. + * Copyright © 2012,2013 Naim A. * * This file is part of UDPT. * From 84ab27bfde87b718f3fa29daeb7f246052361630 Mon Sep 17 00:00:00 2001 From: Naim A Date: Tue, 26 Feb 2013 03:13:52 +0200 Subject: [PATCH 19/99] Small changes --- src/udpTracker.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/udpTracker.c b/src/udpTracker.c index 95e969b..0b59548 100644 --- a/src/udpTracker.c +++ b/src/udpTracker.c @@ -110,8 +110,7 @@ void UDPTracker_destroy (udpServerInstance *usi) { int i; // loop index - usi->flags = (!(FLAG_RUNNING)) & usi->flags; - + usi->flags &= ~FLAG_RUNNING; // drop listener connection to continue thread loops. // wait for request to finish (1 second max; allot of time for a computer!). @@ -217,11 +216,7 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) base /= 3600; // changes every day. x = base; -#ifdef WIN32 - x += remote->sin_addr.S_un.S_addr; -#elif defined (linux) x += remote->sin_addr.s_addr; -#endif return x; } From 51e2c80ba715678d684a2b0e29a68e7f1cb8bf2c Mon Sep 17 00:00:00 2001 From: Naim A Date: Tue, 26 Feb 2013 21:02:50 +0200 Subject: [PATCH 20/99] Moving from C to C++... Some progress... --- src/db/database.h | 9 +- src/db/driver_sqlite.c | 2 +- src/main.c | 114 --------- src/main.cpp | 115 +++++++++ src/settings.c | 373 ----------------------------- src/settings.cpp | 294 +++++++++++++++++++++++ src/settings.h | 101 -------- src/settings.hpp | 145 ++++++++++++ src/tools.h | 8 + src/udpTracker.c | 520 ----------------------------------------- src/udpTracker.cpp | 516 ++++++++++++++++++++++++++++++++++++++++ src/udpTracker.h | 148 ------------ src/udpTracker.hpp | 166 +++++++++++++ 13 files changed, 1253 insertions(+), 1258 deletions(-) delete mode 100644 src/main.c create mode 100644 src/main.cpp delete mode 100644 src/settings.c create mode 100644 src/settings.cpp delete mode 100644 src/settings.h create mode 100644 src/settings.hpp delete mode 100644 src/udpTracker.c create mode 100644 src/udpTracker.cpp delete mode 100644 src/udpTracker.h create mode 100644 src/udpTracker.hpp diff --git a/src/db/database.h b/src/db/database.h index 61b25d5..f731eea 100644 --- a/src/db/database.h +++ b/src/db/database.h @@ -22,6 +22,10 @@ #include +#ifdef __cplusplus +extern "C" { +#endif + typedef struct dbConnection dbConnection; /** @@ -30,7 +34,7 @@ typedef struct dbConnection dbConnection; * @param cStr Connection string for the active driver. * @return 0 on success; otherwise non-zero. */ -int db_open (dbConnection **pdb, char *cStr); +int db_open (dbConnection **pdb, const char *cStr); /** * Closes the database connection. @@ -95,4 +99,7 @@ int db_cleanup (dbConnection *db); */ int db_remove_peer (dbConnection *db, uint8_t hash [20], db_peerEntry *pE); +#ifdef __cplusplus +} +#endif #endif /* DATABASE_H_ */ diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c index 15611cd..56aef7a 100644 --- a/src/db/driver_sqlite.c +++ b/src/db/driver_sqlite.c @@ -85,7 +85,7 @@ static void _db_setup (sqlite3 *db) ")", NULL, NULL, NULL); } -int db_open (dbConnection **db, char *cStr) +int db_open (dbConnection **db, const char *cStr) { FILE *f; int doSetup, // check if to build DB, or it already exists? diff --git a/src/main.c b/src/main.c deleted file mode 100644 index 485830d..0000000 --- a/src/main.c +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright © 2012,2013 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include -#include - -#include "multiplatform.h" -#include "udpTracker.h" -#include "tools.h" -#include -#include -#include -#include "settings.h" - -static void _print_usage () -{ - printf ("Usage: udpt []\n"); -} - -int main(int argc, char *argv[]) -{ - Settings settings; - udpServerInstance usi; - char *config_file; - int r; - -#ifdef WIN32 - WSADATA wsadata; - WSAStartup(MAKEWORD(2, 2), &wsadata); -#endif - - printf("UDP Tracker (UDPT) %s\nCopyright: (C) 2012 Naim Abda \n", VERSION); - printf("Build Date: %s\n\n", __DATE__); - - config_file = "udpt.conf"; - - if (argc <= 1) - { - _print_usage (); - } - - settings_init (&settings, config_file); - if (settings_load (&settings) != 0) - { - const char strDATABASE[] = "database"; - const char strTRACKER[] = "tracker"; - // set default settings: - - settings_set (&settings, strDATABASE, "driver", "sqlite3"); - settings_set (&settings, strDATABASE, "file", "tracker.db"); - - settings_set (&settings, strTRACKER, "port", "6969"); - settings_set (&settings, strTRACKER, "threads", "5"); - settings_set (&settings, strTRACKER, "allow_remotes", "yes"); - settings_set (&settings, strTRACKER, "allow_iana_ips", "yes"); - settings_set (&settings, strTRACKER, "announce_interval", "1800"); - settings_set (&settings, strTRACKER, "cleanup_interval", "120"); - - settings_save (&settings); - printf("Failed to read from '%s'. Using default settings.\n", config_file); - } - - UDPTracker_init(&usi, &settings); - - r = UDPTracker_start(&usi); - if (r != 0) - { - printf("Error While trying to start server.\n"); - switch (r) - { - case 1: - printf("Failed to create socket.\n"); - break; - case 2: - printf("Failed to bind socket.\n"); - break; - default: - printf ("Unknown Error\n"); - break; - } - goto cleanup; - } - - printf("Press Any key to exit.\n"); - - getchar (); - -cleanup: - printf("\nGoodbye.\n"); - settings_destroy (&settings); - UDPTracker_destroy(&usi); - -#ifdef WIN32 - WSACleanup(); -#endif - - return 0; -} diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..4baba4e --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,115 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include + +#include "multiplatform.h" +#include "udpTracker.hpp" +#include "settings.hpp" + +using namespace std; +using namespace UDPT; + +static void _print_usage () +{ + cout << "Usage: udpt []" << endl; +} + +int main(int argc, char *argv[]) +{ + Settings *settings = NULL; + UDPTracker *usi = NULL; + string config_file; + int r; + +#ifdef WIN32 + WSADATA wsadata; + WSAStartup(MAKEWORD(2, 2), &wsadata); +#endif + + cout << "UDP Tracker (UDPT) " << VERSION << endl; + cout << "Copyright 2012,2013 Naim Abda \n\tReleased under the GPLv3 License." << endl; + cout << "Build Date: " << __DATE__ << endl << endl; + + config_file = "udpt.conf"; + + if (argc <= 1) + { + _print_usage (); + } + + settings = new Settings (config_file); + + if (!settings->load()) + { + const char strDATABASE[] = "database"; + const char strTRACKER[] = "tracker"; + // set default settings: + + settings->set (strDATABASE, "driver", "sqlite3"); + settings->set (strDATABASE, "file", "tracker.db"); + + settings->set (strTRACKER, "port", "6969"); + settings->set (strTRACKER, "threads", "5"); + settings->set (strTRACKER, "allow_remotes", "yes"); + settings->set (strTRACKER, "allow_iana_ips", "yes"); + settings->set (strTRACKER, "announce_interval", "1800"); + settings->set (strTRACKER, "cleanup_interval", "120"); + + settings->save(); + cout << "Failed to read from '" << config_file.c_str() << "'. Using default settings." << endl; + } + + usi = new UDPTracker (settings); + + r = usi->start(); + if (r != UDPTracker::START_OK) + { + cout << "Error While trying to start server." << endl; + switch (r) + { + case UDPTracker::START_ESOCKET_FAILED: + cout << "Failed to create socket." << endl; + break; + case UDPTracker::START_EBIND_FAILED: + cout << "Failed to bind socket." << endl; + break; + default: + cout << "Unknown Error" << endl; + break; + } + goto cleanup; + } + + cout << "Press Any key to exit." << endl; + + cin.get(); + +cleanup: + cout << endl << "Goodbye." << endl; + + delete usi; + delete settings; + +#ifdef WIN32 + WSACleanup(); +#endif + + return 0; +} diff --git a/src/settings.c b/src/settings.c deleted file mode 100644 index dfdbf76..0000000 --- a/src/settings.c +++ /dev/null @@ -1,373 +0,0 @@ -/* - * - * Copyright © 2012,2013 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include "settings.h" -#include -#include -#include -#include - -SettingClass* settings_get_class (Settings *s, const char *classname) -{ - int i; - - if (s == NULL || classname == NULL) - return NULL; - - for (i = 0;i < s->class_count;i++) - { - if (strcmp(classname, s->classes[i].classname) == 0) - { - return &s->classes[i]; - } - } - - return NULL; -} - -void settings_init (Settings *s, const char *filename) -{ - s->buffer = NULL; - s->filename = (char*)filename; - s->classes = NULL; - s->class_count = s->class_size = 0; -} - -static -void _settings_clean_string (char **str) -{ - int len, - i, - offset; - - len = strlen(*str); - - //strip leading whitespaces. - offset = 0; - for (i = 0;i < len;i++) - { - if (isspace(*str[i]) == 0) - break; - offset++; - } - - (*str) += offset; - len -= offset; - - for (i = len - 1;i >= 0;i--) - { - if (isspace( (*str)[i] ) != 0) - { - (*str)[i] = '\0'; - } - else - break; - } -} - -static -void _settings_parser (Settings *s, char *data, int len) -{ - char *className, *key, *value; - int i, - cil; // cil = Chars in line. - char c; - - className = key = value = NULL; - cil = 0; - - for (i = 0;i < len;i++) - { - c = data[i]; - if (c == '\n') - { - cil = 0; - continue; - } - if (cil == 0 && c == ';') - { - while (i < len) - { - if (data[i] == '\n') - break; - i++; - } - continue; - } - if (isspace(c) != 0 && cil == 0) - { - continue; - } - if (cil == 0 && c == '[') - { - className = (char*)(i + data + 1); - while (i < len) - { - if (data[i] != ']') - { - i++; - continue; - } - data[i] = '\0'; - break; - } - continue; - } - - if (isgraph(c) != 0 && cil == 0) // must be a key. - { - key = (char*)(i + data); - while (i < len) - { - if (data[i] == '\n') - { - key = NULL; - break; - } - if (data[i] == '=') - { - data[i] = '\0'; - value = (char*)(data + i + 1); - while (i < len) - { - if (data[i] == '\n') - { - data[i] = '\0'; - - _settings_clean_string(&key); - _settings_clean_string(&value); - -// printf("KEY: '%s'\tVALUE: '%s'\n", key, value); - - // add to settings... - settings_set(s, className, key, value); - - cil = 0; - break; - } - i++; - } - break; - } - i++; - } - continue; - } - - if (isgraph(c) != 0) - { - cil++; - } - } -} - -int settings_load (Settings *s) -{ - FILE *f; - int len, - r, - offset; // file length - char *buffer; - char tmp [512]; - - if (s->buffer != NULL) - { - free (s->buffer); - s->buffer = NULL; - } - - // ini file format. - f = fopen(s->filename, "rb"); - if (f == NULL) - return 1; - fseek (f, 0, SEEK_END); - len = ftell(f); - fseek(f, 0, SEEK_SET); - - s->buffer = (char*)malloc (len); - buffer = s->buffer; - - r = offset = 0; - while (!feof(f) && !ferror(f)) - { - int i; - r = fread (tmp, 1, 512, f); - for (i = 0;i < r;i++) - { - buffer[offset + i] = tmp[i]; - } - offset += r; - } - - fclose (f); -// printf("File loaded into buffer. size=%d\n", len); - _settings_parser (s, buffer, len); - - return 0; -} - -int settings_save (Settings *s) -{ - char buffer [2048]; - SettingClass *sclass; - FILE *f; - int c, e; - - f = fopen(s->filename, "wb"); - fprintf(f, "; udpt Settings File - Created Automatically.\n"); - setbuf(f, buffer); - - for (c = 0;c < s->class_count;c++) - { - sclass = &s->classes[c]; - fprintf(f, "[%s]\n", sclass->classname); - - for (e = 0;e < sclass->entry_count;e++) - { - fprintf(f, "%s=%s\n", sclass->entries[e].key, sclass->entries[e].values); - } - - fprintf(f, "\n"); - } - - fclose (f); - - return 0; -} - -void settings_destroy (Settings *s) -{ - if (s->classes != NULL) - { - int i; - for (i = 0;i < s->class_count;i++) - { - if (s->classes[i].entries != NULL) - free (s->classes[i].entries); - } - - free (s->classes); - } - if (s->buffer != NULL) - { - free (s->buffer); - s->buffer = NULL; - } -} - -char* settings_get (Settings *s, const char *class, const char *name) -{ - SettingClass *c; - - if (s == NULL || class == NULL || name == NULL) - return NULL; - - c = settings_get_class (s, class); - return settingclass_get (c, name); -} - -int settings_set (Settings *s, const char *class, const char *name, const char *value) -{ - SettingClass *c; - - if (s == NULL || class == NULL || name == NULL) - return 1; - - c = settings_get_class (s, class); - - if (c == NULL) - { - if (s->class_count + 1 >= s->class_size) - { - int ns = s->class_size + 1; - SettingClass *sc = realloc (s->classes, sizeof(SettingClass) * ns); - if (sc == NULL) - return 1; - s->classes = sc; - s->class_size = ns; - } - - c = &s->classes[s->class_count]; - s->class_count++; - - c->classname = (char*)class; - c->entries = NULL; - c->entry_size = c->entry_count = 0; - - } - - return settingclass_set (c, name, value); -} - -char* settingclass_get (SettingClass *c, const char *name) -{ - KeyValue *kv; - int i; - - if (c == NULL) - return NULL; - - for (i = 0;i < c->entry_count;i++) - { - kv = &c->entries[i]; - if (strcmp(kv->key, name) == 0) - return kv->values; - } - return NULL; -} - -int settingclass_set (SettingClass *c, const char *name, const char *value) -{ - - int i, - ni; - - for (i = 0;i < c->entry_count;i++) - { - if (strcmp(name, c->entries[i].key) == 0) - { - c->entries[i].values = (char*)value; - return 0; - } - } - - if (c->entry_count + 1 >= c->entry_size) - { - int ns; - KeyValue *n; - - ns = c->entry_size + 5; - n = realloc (c->entries, sizeof(KeyValue) * ns); - - if (n == NULL) - return 1; - - c->entries = n; - c->entry_size = ns; - } - - ni = c->entry_count; - c->entry_count++; - - c->entries[ni].key = (char*)name; - c->entries[ni].values = (char*)value; - - return 0; -} diff --git a/src/settings.cpp b/src/settings.cpp new file mode 100644 index 0000000..2a7ea99 --- /dev/null +++ b/src/settings.cpp @@ -0,0 +1,294 @@ +/* + * + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "settings.hpp" +#include // still primitive - need for strlen() +#include // need for isspace() + +#include +#include + +using namespace std; + +namespace UDPT +{ + Settings::SettingClass* Settings::getClass(const string classname) + { + if (classname == "") + return NULL; + + map::iterator it; + it = this->classes.find(classname); + + if (it == this->classes.end()) + return NULL; + else + return it->second; + + return NULL; + } + + Settings::Settings (const string filename) + { + this->filename = filename; + this->classes.clear(); + } + +static +void _settings_clean_string (char **str) +{ + int len, + i, + offset; + + len = strlen(*str); + + //strip leading whitespaces. + offset = 0; + for (i = 0;i < len;i++) + { + if (isspace(*str[i]) == 0) + break; + offset++; + } + + (*str) += offset; + len -= offset; + + for (i = len - 1;i >= 0;i--) + { + if (isspace( (*str)[i] ) != 0) + { + (*str)[i] = '\0'; + } + else + break; + } +} + + void Settings::parseSettings (char *data, int len) + { + char *className, *key, *value; + int i, + cil; // cil = Chars in line. + char c; + + className = key = value = NULL; + cil = 0; + + for (i = 0;i < len;i++) + { + c = data[i]; + if (c == '\n') + { + cil = 0; + continue; + } + if (cil == 0 && c == ';') + { + while (i < len) + { + if (data[i] == '\n') + break; + i++; + } + continue; + } + if (isspace(c) != 0 && cil == 0) + { + continue; + } + if (cil == 0 && c == '[') + { + className = (char*)(i + data + 1); + while (i < len) + { + if (data[i] != ']') + { + i++; + continue; + } + data[i] = '\0'; + break; + } + continue; + } + + if (isgraph(c) != 0 && cil == 0) // must be a key. + { + key = (char*)(i + data); + while (i < len) + { + if (data[i] == '\n') + { + key = NULL; + break; + } + if (data[i] == '=') + { + data[i] = '\0'; + value = (char*)(data + i + 1); + while (i < len) + { + if (data[i] == '\n') + { + data[i] = '\0'; + + _settings_clean_string(&key); + _settings_clean_string(&value); + + // printf("KEY: '%s'\tVALUE: '%s'\n", key, value); + + // add to settings... + this->set (className, key, value); + + cil = 0; + break; + } + i++; + } + break; + } + i++; + } + continue; + } + + if (isgraph(c) != 0) + { + cil++; + } + } + } + + bool Settings::load() + { + int len; + char *buffer; + + fstream cfg; + cfg.open(this->filename.c_str(), ios::in | ios::binary); + + if (!cfg.is_open()) + return false; + + cfg.seekg(0, ios::end); + len = cfg.tellg(); + cfg.seekg(0, ios::beg); + + buffer = new char [len]; + cfg.read(buffer, len); + cfg.close(); + + this->parseSettings(buffer, len); + + delete[] buffer; + + return true; + } + + bool Settings::save () + { + SettingClass *sclass; + + fstream cfg (this->filename.c_str(), ios::binary | ios::out); + if (!cfg.is_open()) + return false; + + cfg << "; udpt Settings File - Created Automatically.\n"; + + map::iterator it; + for (it = this->classes.begin();it != this->classes.end();it++) + { + sclass = it->second; + cfg << "[" << it->first.c_str() << "]\n"; + + map::iterator rec; + for (rec = sclass->entries.begin();rec != sclass->entries.end();rec++) + { + cfg << rec->first.c_str() << "=" << rec->second.c_str() << "\n"; + } + + cfg << "\n"; + } + cfg.close(); + + return 0; + } + + Settings::~Settings() + { + map::iterator it; + for (it = this->classes.begin();it != this->classes.end();it++) + { + SettingClass *sc = it->second; + delete sc; + } + this->classes.clear(); + } + + string Settings::get (const string classN, const string name) + { + SettingClass *c; + + c = this->getClass(classN); + return c->get(name); + } + + bool Settings::set (const string classN, const string name, const string value) + { + SettingClass *c; + + if (classN == "" || name == "") + return false; + + c = this->getClass (classN); + + if (c == NULL) + { + c = new SettingClass(classN); + this->classes.insert(pair(classN, c)); + } + + return c->set (name, value); + } + + Settings::SettingClass::SettingClass(const string cn) + { + this->className = cn; + } + + string Settings::SettingClass::get (const string name) + { + return this->entries[name]; + } + + bool Settings::SettingClass::set (const string name, const string value) + { + pair::iterator, bool> r; + r = this->entries.insert(pair(name, value)); + if (!r.second) + { + r.first->second = value; + } + + return true; + } +}; diff --git a/src/settings.h b/src/settings.h deleted file mode 100644 index 21604a4..0000000 --- a/src/settings.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * - * Copyright © 2012,2013 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#pragma once - -#include - -typedef struct { - char *key; - char *values; -} KeyValue; - -typedef struct { - char *classname; - KeyValue *entries; - uint32_t entry_count, entry_size; -} SettingClass; - -typedef struct { - char *filename; - - SettingClass *classes; - uint32_t class_count, class_size; - - char *buffer; -} Settings; - -/** - * Initializes the settings type. - * @param s Pointer to settings to initialize. - * @param filename the settings filename. - */ -void settings_init (Settings *s, const char *filename); - -/** - * Loads settings from file - * @param s pointer to settings type - * @return 0 on success, otherwise non-zero. - */ -int settings_load (Settings *s); - -/** - * Saves settings to file. - * @param s Pointer to settings. - * @return 0 on success; otherwise non-zero. - */ -int settings_save (Settings *s); - -/** - * Destroys the settings "object" - * @param s Pointer to settings. - */ -void settings_destroy (Settings *s); - -/** - * Gets the requested SettingClass. - * @param s Settings Object. - * @param classname The name of the class to find (case sensitive). - * @return a pointer to the found class, or NULL if not found. - */ -SettingClass* settings_get_class (Settings *s, const char *classname); - -char* settingclass_get (SettingClass *s, const char *name); - -int settingclass_set (SettingClass *s, const char *name, const char *value); - -/** - * Gets a setting from a Settings type. - * @param s Pointer to a setting type. - * @param class The class of the requested setting. - * @param name The name of the requested setting. - * @return The value for the requested setting, NULL if not available. - */ -char* settings_get (Settings *s, const char *classn, const char *name); - -/** - * Sets a setting in a settings type. - * @param s Pointer to settings type. - * @param class The class of the setting. - * @param name The name of the setting. - * @param value The value to set for the setting. - * @return 0 on success, otherwise non-zero. - */ -int settings_set (Settings *s, const char *classn, const char *name, const char *value); diff --git a/src/settings.hpp b/src/settings.hpp new file mode 100644 index 0000000..8e9ec51 --- /dev/null +++ b/src/settings.hpp @@ -0,0 +1,145 @@ +/* + * + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#pragma once + +#include +#include +#include +using namespace std; + +namespace UDPT +{ + class Settings + { + public: + class SettingClass + { + public: + SettingClass (const string className); + bool set (const string key, const string value); + string get (const string key); + private: + friend class Settings; + string className; + map entries; + }; + + /** + * Initializes the settings type. + * @param filename the settings filename. + */ + Settings (const string filename); + + /** + * Gets a setting from a Settings type. + * @param class The class of the requested setting. + * @param name The name of the requested setting. + * @return The value for the requested setting, NULL if not available. + */ + SettingClass* getClass (const string name); + + /** + * Loads settings from file + * @return true on success, otherwise false. + */ + bool load (); + + /** + * Saves settings to file. + * @return true on success; otherwise false. + */ + bool save (); + + /** + * Sets a setting in a settings type. + * @param className The class of the setting. + * @param key The name of the setting. + * @param value The value to set for the setting. + * @return true on success, otherwise false. + */ + bool set (const string className, const string key, const string value); + + /** + * Gets the requested SettingClass. + * @param classname The name of the class to find (case sensitive). + * @return a pointer to the found class, or NULL if not found. + */ + string get (const string className, const string key); + + /** + * Destroys the settings "object" + */ + virtual ~Settings (); + private: + string filename; + map classes; + + void parseSettings (char *data, int len); + }; +}; + +//#ifdef __cplusplus +//extern "C" { +//#endif +// +//typedef struct { +// char *key; +// char *values; +//} KeyValue; +// +//typedef struct { +// char *classname; +// KeyValue *entries; +// uint32_t entry_count, entry_size; +//} SettingClass; +// +//typedef struct { +// char *filename; +// +// SettingClass *classes; +// uint32_t class_count, class_size; +// +// char *buffer; +//} Settings; +// +// +//void settings_init (Settings *s, const char *filename); +// +//int settings_load (Settings *s); +// +//int settings_save (Settings *s); +// +//void settings_destroy (Settings *s); +// +//SettingClass* settings_get_class (Settings *s, const char *classname); +// +//char* settingclass_get (SettingClass *s, const char *name); +// +//int settingclass_set (SettingClass *s, const char *name, const char *value); +// +//char* settings_get (Settings *s, const char *classn, const char *name); +// +// +//int settings_set (Settings *s, const char *classn, const char *name, const char *value); +// +//#ifdef __cplusplus +//} +//#endif diff --git a/src/tools.h b/src/tools.h index f265038..be0afc5 100644 --- a/src/tools.h +++ b/src/tools.h @@ -22,6 +22,10 @@ #include +#ifdef __cplusplus +extern "C" { +#endif + /** * Swaps Bytes: * example (htons): @@ -39,4 +43,8 @@ uint64_t m_hton64 (uint64_t n); void to_hex_str (const uint8_t *hash, char *data); +#ifdef __cplusplus +} +#endif + #endif /* TOOLS_H_ */ diff --git a/src/udpTracker.c b/src/udpTracker.c deleted file mode 100644 index 0b59548..0000000 --- a/src/udpTracker.c +++ /dev/null @@ -1,520 +0,0 @@ -/* - * Copyright © 2012,2013 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include "multiplatform.h" -#include "udpTracker.h" -#include "tools.h" -#include "settings.h" -#include -#include -#include -#include - -#define FLAG_RUNNING 0x01 -#define UDP_BUFFER_SIZE 2048 - -#ifdef WIN32 -static DWORD _thread_start (LPVOID arg); -static DWORD _maintainance_start (LPVOID arg); -#elif defined (linux) -static void* _thread_start (void *arg); -static void* _maintainance_start (void *arg); -#endif - -static int _isTrue (char *str) -{ - int i, // loop index - len; // string's length - - if (str == NULL) - return -1; - len = strlen (str); - for (i = 0;i < len;i++) - { - if (str[i] >= 'A' && str[i] <= 'Z') - { - str[i] = (str[i] - 'A' + 'a'); - } - } - if (strcmp(str, "yes") == 0) - return 1; - if (strcmp(str, "no") == 0) - return 0; - if (strcmp(str, "true") == 0) - return 1; - if (strcmp(str, "false") == 0) - return 0; - if (strcmp(str, "1") == 0) - return 1; - if (strcmp(str, "0") == 0) - return 0; - return -1; -} - -void UDPTracker_init (udpServerInstance *usi, Settings *settings) -{ - SettingClass *sc_tracker; - uint8_t n_settings = 0; - char *s_port, // port - *s_threads, // threads - *s_allow_remotes, // remotes allowed? - *s_allow_iana_ip, // IANA IPs allowed? - *s_int_announce, // announce interval - *s_int_cleanup; // cleanup interval - - sc_tracker = settings_get_class (settings, "tracker"); - - s_port = settingclass_get(sc_tracker, "port"); - s_threads = settingclass_get(sc_tracker, "threads"); - s_allow_remotes = settingclass_get (sc_tracker, "allow_remotes"); - s_allow_iana_ip = settingclass_get (sc_tracker, "allow_iana_ips"); - s_int_announce = settingclass_get (sc_tracker, "announce_interval"); - s_int_cleanup = settingclass_get (sc_tracker, "cleanup_interval"); - - if (_isTrue(s_allow_remotes) == 1) - n_settings |= UDPT_ALLOW_REMOTE_IP; - - if (_isTrue(s_allow_iana_ip) != 0) - n_settings |= UDPT_ALLOW_IANA_IP; - - usi->announce_interval = (s_int_announce == NULL ? 1800 : atoi (s_int_announce)); - usi->cleanup_interval = (s_int_cleanup == NULL ? 120 : atoi (s_int_cleanup)); - usi->port = (s_port == NULL ? 6969 : atoi (s_port)); - usi->thread_count = (s_threads == NULL ? 5 : atoi (s_threads)) + 1; - - usi->threads = (HANDLE*)malloc (sizeof(HANDLE) * usi->thread_count); - - usi->flags = 0; - usi->conn = NULL; - usi->settings = n_settings; - usi->o_settings = settings; -} - -void UDPTracker_destroy (udpServerInstance *usi) -{ - int i; // loop index - - usi->flags &= ~FLAG_RUNNING; - - // drop listener connection to continue thread loops. - // wait for request to finish (1 second max; allot of time for a computer!). - -#ifdef linux - close (usi->sock); - - sleep (1); -#elif defined (WIN32) - closesocket (usi->sock); - - Sleep (1000); -#endif - - for (i = 0;i < usi->thread_count;i++) - { -#ifdef WIN32 - TerminateThread (usi->threads[0], 0x00); -#elif defined (linux) - pthread_detach (usi->threads[i]); - pthread_cancel (usi->threads[i]); -#endif - printf ("Thread (%d/%u) terminated.\n", i + 1, usi->thread_count); - } - if (usi->conn != NULL) - db_close(usi->conn); - free (usi->threads); -} - -int UDPTracker_start (udpServerInstance *usi) -{ - SOCKET sock; - SOCKADDR_IN recvAddr; - int r, // saves results - i, // loop index - yup; // just to set TRUE - char *dbname;// saves the Database name. - - sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (sock == INVALID_SOCKET) - return 1; - -#ifdef WIN32 - recvAddr.sin_addr.S_un.S_addr = 0L; -#elif defined (linux) - recvAddr.sin_addr.s_addr = 0L; -#endif - recvAddr.sin_family = AF_INET; - recvAddr.sin_port = m_hton16 (usi->port); - - yup = 1; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); - - r = bind (sock, (SOCKADDR*)&recvAddr, sizeof(SOCKADDR_IN)); - - if (r == SOCKET_ERROR) - { -#ifdef WIN32 - closesocket (sock); -#elif defined (linux) - close (sock); -#endif - return 2; - } - - usi->sock = sock; - - dbname = settings_get (usi->o_settings, "database", "file"); - if (dbname == NULL) - dbname = "tracker.db"; - - db_open(&usi->conn, dbname); - - usi->flags |= FLAG_RUNNING; - - // create maintainer thread. -#ifdef WIN32 - usi->threads[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_maintainance_start, (LPVOID)usi, 0, NULL); -#elif defined (linux) - printf("Starting maintenance thread (1/%u)...\n", usi->thread_count); - pthread_create (&usi->threads[0], NULL, _maintainance_start, usi); -#endif - - for (i = 1;i < usi->thread_count; i++) - { - printf("Starting Thread (%d/%u)\n", (i + 1), usi->thread_count); -#ifdef WIN32 - usi->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)usi, 0, NULL); -#elif defined (linux) - pthread_create (&(usi->threads[i]), NULL, _thread_start, usi); -#endif - } - - return 0; -} - -static uint64_t _get_connID (SOCKADDR_IN *remote) -{ - int base; - uint64_t x; - - base = time(NULL); - base /= 3600; // changes every day. - - x = base; - x += remote->sin_addr.s_addr; - return x; -} - -static int _send_error (udpServerInstance *usi, SOCKADDR_IN *remote, uint32_t transactionID, char *msg) -{ - struct udp_error_response error; - int msg_sz, // message size to send. - i; // copy loop - char buff [1024]; // more than reasonable message size... - - error.action = m_hton32 (3); - error.transaction_id = transactionID; - error.message = msg; - - msg_sz = 4 + 4 + 1 + strlen(msg); - - memcpy(buff, &error, 8); - for (i = 8;i <= msg_sz;i++) - { - buff[i] = msg[i - 8]; - } - - sendto(usi->sock, buff, msg_sz, 0, (SOCKADDR*)remote, sizeof(*remote)); - - return 0; -} - -static int _handle_connection (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) -{ - ConnectionRequest *req; - ConnectionResponse resp; - - req = (ConnectionRequest*)data; - - resp.action = m_hton32(0); - resp.transaction_id = req->transaction_id; - resp.connection_id = _get_connID(remote); - - sendto(usi->sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - - return 0; -} - -static int _handle_announce (udpServerInstance *usi, SOCKADDR_IN *remote, char *data) -{ - AnnounceRequest *req; - AnnounceResponse *resp; - int q, // peer counts - bSize, // message size - i; // loop index - db_peerEntry *peers; - int32_t seeders, - leechers, - completed; - db_peerEntry pE; // info for DB - uint8_t buff [1028]; // Reasonable buffer size. (header+168 peers) - - req = (AnnounceRequest*)data; - - if (req->connection_id != _get_connID(remote)) - { - return 1; - } - - // change byte order: - req->port = m_hton16 (req->port); - req->ip_address = m_hton32 (req->ip_address); - req->downloaded = m_hton64 (req->downloaded); - req->event = m_hton32 (req->event); // doesn't really matter for this tracker - req->uploaded = m_hton64 (req->uploaded); - req->num_want = m_hton32 (req->num_want); - req->left = m_hton64 (req->left); - - if ((usi->settings & UDPT_ALLOW_REMOTE_IP) == 0 && req->ip_address != 0) - { - _send_error (usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); - return 0; - } - - // load peers - q = 30; - if (req->num_want >= 1) - q = min (q, req->num_want); - - peers = (db_peerEntry*)malloc (sizeof(db_peerEntry) * q); - - db_load_peers(usi->conn, req->info_hash, peers, &q); -// printf("%d peers found.\n", q); - - bSize = 20; // header is 20 bytes - bSize += (6 * q); // + 6 bytes per peer. - - db_get_stats (usi->conn, req->info_hash, &seeders, &leechers, &completed); - - resp = (AnnounceResponse*)buff; - resp->action = m_hton32(1); - resp->interval = m_hton32 ( usi->announce_interval ); - resp->leechers = m_hton32(leechers); - resp->seeders = m_hton32 (seeders); - resp->transaction_id = req->transaction_id; - - for (i = 0;i < q;i++) - { - int x = i * 6; - // network byte order!!! - - // IP - buff[20 + x] = ((peers[i].ip & (0xff << 24)) >> 24); - buff[21 + x] = ((peers[i].ip & (0xff << 16)) >> 16); - buff[22 + x] = ((peers[i].ip & (0xff << 8)) >> 8); - buff[23 + x] = (peers[i].ip & 0xff); - - // port - buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8); - buff[25 + x] = (peers[i].port & 0xff); - - } - free (peers); - sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - - // Add peer to list: - pE.downloaded = req->downloaded; - pE.uploaded = req->uploaded; - pE.left = req->left; - pE.peer_id = req->peer_id; - if (req->ip_address == 0) // default - { - pE.ip = m_hton32 (remote->sin_addr.s_addr); - } - else - { - pE.ip = req->ip_address; - } - pE.port = req->port; - db_add_peer(usi->conn, req->info_hash, &pE); - - return 0; -} - -static int _handle_scrape (udpServerInstance *usi, SOCKADDR_IN *remote, char *data, int len) -{ - ScrapeRequest *sR; - int v, // validation helper - c, // torrent counter - i, // loop counter - j; // loop counter - uint8_t hash [20]; - char xHash [50]; - ScrapeResponse *resp; - uint8_t buffer [1024]; // up to 74 torrents can be scraped at once (17*74+8) < 1024 - - - sR = (ScrapeRequest*)data; - - // validate request length: - v = len - 16; - if (v < 0 || v % 20 != 0) - { - _send_error (usi, remote, sR->transaction_id, "Bad scrape request."); - return 0; - } - - // get torrent count. - c = v / 20; - - resp = (ScrapeResponse*)buffer; - resp->action = m_hton32 (2); - resp->transaction_id = sR->transaction_id; - - for (i = 0;i < c;i++) - { - int32_t s, c, l; - int32_t *seeders, - *completed, - *leechers; - - for (j = 0; j < 20;j++) - hash[j] = data[j + (i*20)+16]; - - to_hex_str (hash, xHash); - - printf("\t%s\n", xHash); - - seeders = (int32_t*)&buffer[i*12+8]; - completed = (int32_t*)&buffer[i*12+12]; - leechers = (int32_t*)&buffer[i*12+16]; - - db_get_stats (usi->conn, hash, &s, &l, &c); - - *seeders = m_hton32 (s); - *completed = m_hton32 (c); - *leechers = m_hton32 (l); - } - fflush (stdout); - - sendto (usi->sock, (const char*)buffer, sizeof(buffer), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - - return 0; -} - -static int _isIANA_IP (uint32_t ip) -{ - uint8_t x = (ip % 256); - if (x == 0 || x == 10 || x == 127 || x >= 224) - return 1; - return 0; -} - -static int _resolve_request (udpServerInstance *usi, SOCKADDR_IN *remote, char *data, int r) -{ - ConnectionRequest *cR; - uint32_t action; - - cR = (ConnectionRequest*)data; - - action = m_hton32(cR->action); - - if ((usi->settings & UDPT_ALLOW_IANA_IP) > 0) - { - if (_isIANA_IP (remote->sin_addr.s_addr)) - { - return 0; // Access Denied: IANA reserved IP. - } - } - - printf(":: %x:%u ACTION=%d\n", (unsigned int)remote->sin_addr.s_addr , remote->sin_port, action); - - if (action == 0 && r >= 16) - return _handle_connection(usi, remote, data); - else if (action == 1 && r >= 98) - return _handle_announce(usi, remote, data); - else if (action == 2) - return _handle_scrape (usi, remote, data, r); - else - { - printf("E: action=%d; r=%d\n", action, r); - _send_error(usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); - return -1; - } - - return 0; -} - -#ifdef WIN32 -static DWORD _thread_start (LPVOID arg) -#elif defined (linux) -static void* _thread_start (void *arg) -#endif -{ - udpServerInstance *usi; - SOCKADDR_IN remoteAddr; - int addrSz, - r; - char tmpBuff [UDP_BUFFER_SIZE]; - - usi = arg; - - addrSz = sizeof (SOCKADDR_IN); - - - while ((usi->flags & FLAG_RUNNING) > 0) - { - fflush(stdout); - // peek into the first 12 bytes of data; determine if connection request or announce request. - r = recvfrom(usi->sock, tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, (unsigned*)&addrSz); - if (r <= 0) - continue; // bad request... - r = _resolve_request(usi, &remoteAddr, tmpBuff, r); - } - -#ifdef linux - pthread_exit (NULL); -#endif - return 0; -} - -#ifdef WIN32 -static DWORD _maintainance_start (LPVOID arg) -#elif defined (linux) -static void* _maintainance_start (void *arg) -#endif -{ - udpServerInstance *usi; - - usi = (udpServerInstance *)arg; - - while ((usi->flags & FLAG_RUNNING) > 0) - { - db_cleanup (usi->conn); - -#ifdef WIN32 - Sleep (usi->cleanup_interval * 1000); // wait 2 minutes between every cleanup. -#elif defined (linux) - sleep (usi->cleanup_interval); -#else -#error Unsupported OS. -#endif - } - - return 0; -} diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp new file mode 100644 index 0000000..55efe2b --- /dev/null +++ b/src/udpTracker.cpp @@ -0,0 +1,516 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "multiplatform.h" +#include "udpTracker.hpp" +#include "tools.h" +#include +#include + +#include +using namespace std; + +#define UDP_BUFFER_SIZE 2048 + +namespace UDPT +{ + inline static int _isTrue (string str) + { + int i, // loop index + len; // string's length + + if (str == "") + return -1; + len = str.length(); + for (i = 0;i < len;i++) + { + if (str[i] >= 'A' && str[i] <= 'Z') + { + str[i] = (str[i] - 'A' + 'a'); + } + } + if (str.compare ("yes") == 0) + return 1; + if (str.compare ("no") == 0) + return 0; + if (str.compare("true") == 0) + return 1; + if (str.compare ("false") == 0) + return 0; + if (str.compare("1") == 0) + return 1; + if (str.compare ("0") == 0) + return 0; + return -1; + } + + UDPTracker::UDPTracker (Settings *settings) + { + Settings::SettingClass *sc_tracker; + uint8_t n_settings = 0; + string s_port, // port + s_threads, // threads + s_allow_remotes, // remotes allowed? + s_allow_iana_ip, // IANA IPs allowed? + s_int_announce, // announce interval + s_int_cleanup; // cleanup interval + + sc_tracker = settings->getClass("tracker"); + + s_port = sc_tracker->get ("port"); + s_threads = sc_tracker->get ("threads"); + s_allow_remotes = sc_tracker->get ("allow_remotes"); + s_allow_iana_ip = sc_tracker->get ("allow_iana_ips"); + s_int_announce = sc_tracker->get ("announce_interval"); + s_int_cleanup = sc_tracker-> get ("cleanup_interval"); + + if (_isTrue(s_allow_remotes) == 1) + n_settings |= UDPT_ALLOW_REMOTE_IP; + + if (_isTrue(s_allow_iana_ip) != 0) + n_settings |= UDPT_ALLOW_IANA_IP; + + this->announce_interval = (s_int_announce == "" ? 1800 : atoi (s_int_announce.c_str())); + this->cleanup_interval = (s_int_cleanup == "" ? 120 : atoi (s_int_cleanup.c_str())); + this->port = (s_port == "" ? 6969 : atoi (s_port.c_str())); + this->thread_count = (s_threads == "" ? 5 : atoi (s_threads.c_str())) + 1; + + cout << "port=" << this->port << endl; + + this->threads = new HANDLE[this->thread_count]; + + this->isRunning = false; + this->conn = NULL; + this->settings = n_settings; + this->o_settings = settings; + } + + UDPTracker::~UDPTracker () + { + int i; // loop index + + this->isRunning = false; + + // drop listener connection to continue thread loops. + // wait for request to finish (1 second max; allot of time for a computer!). + + #ifdef linux + close (this->sock); + + sleep (1); + #elif defined (WIN32) + closesocket (this->sock); + + Sleep (1000); + #endif + + for (i = 0;i < this->thread_count;i++) + { + #ifdef WIN32 + TerminateThread (this->threads[i], 0x00); + #elif defined (linux) + pthread_detach (usi->threads[i]); + pthread_cancel (usi->threads[i]); + #endif + cout << "Thread (" << ( i + 1) << "/" << ((int)this->thread_count) << ") terminated." << endl; + } + if (this->conn != NULL) + db_close(this->conn); + delete[] this->threads; + } + + enum UDPTracker::StartStatus UDPTracker::start () + { + SOCKET sock; + SOCKADDR_IN recvAddr; + int r, // saves results + i, // loop index + yup; // just to set TRUE + string dbname;// saves the Database name. + + sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sock == INVALID_SOCKET) + return START_ESOCKET_FAILED; + + #ifdef WIN32 + recvAddr.sin_addr.S_un.S_addr = 0L; + #elif defined (linux) + recvAddr.sin_addr.s_addr = 0L; + #endif + recvAddr.sin_family = AF_INET; + recvAddr.sin_port = m_hton16 (this->port); + + yup = 1; + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); + + r = bind (sock, (SOCKADDR*)&recvAddr, sizeof(SOCKADDR_IN)); + + if (r == SOCKET_ERROR) + { + #ifdef WIN32 + closesocket (sock); + #elif defined (linux) + close (sock); + #endif + return START_EBIND_FAILED; + } + + this->sock = sock; + + dbname = this->o_settings->get ("database", "file"); + if (dbname == "") + dbname = "tracker.db"; + + db_open(&this->conn, dbname.c_str()); + + this->isRunning = true; + cout << "Starting maintenance thread (1/" << ((int)this->thread_count) << ")" << endl; + + // create maintainer thread. + #ifdef WIN32 + this->threads[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_maintainance_start, (LPVOID)this, 0, NULL); + #elif defined (linux) + pthread_create (&usi->threads[0], NULL, _maintainance_start, usi); + #endif + + for (i = 1;i < this->thread_count; i++) + { + cout << "Starting thread (" << (i + 1) << "/" << ((int)this->thread_count) << ")" << endl; + #ifdef WIN32 + this->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)this, 0, NULL); + #elif defined (linux) + pthread_create (&(this->threads[i]), NULL, _thread_start, this); + #endif + } + + return START_OK; + } + +static uint64_t _get_connID (SOCKADDR_IN *remote) +{ + int base; + uint64_t x; + + base = time(NULL); + base /= 3600; // changes every hour. + + x = base; + x += remote->sin_addr.s_addr; + return x; +} + + int UDPTracker::sendError (UDPTracker *usi, SOCKADDR_IN *remote, uint32_t transactionID, const string &msg) + { + struct udp_error_response error; + int msg_sz, // message size to send. + i; // copy loop + char buff [1024]; // more than reasonable message size... + + error.action = m_hton32 (3); + error.transaction_id = transactionID; + error.message = (char*)msg.c_str(); + + msg_sz = 4 + 4 + 1 + msg.length(); + + memcpy(buff, &error, 8); + for (i = 8;i <= msg_sz;i++) + { + buff[i] = msg[i - 8]; + } + + sendto(usi->sock, buff, msg_sz, 0, (SOCKADDR*)remote, sizeof(*remote)); + + return 0; + } + + int UDPTracker::handleConnection (UDPTracker *usi, SOCKADDR_IN *remote, char *data) + { + ConnectionRequest *req; + ConnectionResponse resp; + + req = (ConnectionRequest*)data; + + resp.action = m_hton32(0); + resp.transaction_id = req->transaction_id; + resp.connection_id = _get_connID(remote); + + sendto(usi->sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + + return 0; + } + + int UDPTracker::handleAnnounce (UDPTracker *usi, SOCKADDR_IN *remote, char *data) + { + AnnounceRequest *req; + AnnounceResponse *resp; + int q, // peer counts + bSize, // message size + i; // loop index + db_peerEntry *peers; + int32_t seeders, + leechers, + completed; + db_peerEntry pE; // info for DB + uint8_t buff [1028]; // Reasonable buffer size. (header+168 peers) + + req = (AnnounceRequest*)data; + + if (req->connection_id != _get_connID(remote)) + { + return 1; + } + + // change byte order: + req->port = m_hton16 (req->port); + req->ip_address = m_hton32 (req->ip_address); + req->downloaded = m_hton64 (req->downloaded); + req->event = m_hton32 (req->event); // doesn't really matter for this tracker + req->uploaded = m_hton64 (req->uploaded); + req->num_want = m_hton32 (req->num_want); + req->left = m_hton64 (req->left); + + if ((usi->settings & UDPT_ALLOW_REMOTE_IP) == 0 && req->ip_address != 0) + { + UDPTracker::sendError (usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); + return 0; + } + + // load peers + q = 30; + if (req->num_want >= 1) + q = min (q, req->num_want); + + peers = (db_peerEntry*)malloc (sizeof(db_peerEntry) * q); + + db_load_peers(usi->conn, req->info_hash, peers, &q); + + bSize = 20; // header is 20 bytes + bSize += (6 * q); // + 6 bytes per peer. + + db_get_stats (usi->conn, req->info_hash, &seeders, &leechers, &completed); + + resp = (AnnounceResponse*)buff; + resp->action = m_hton32(1); + resp->interval = m_hton32 ( usi->announce_interval ); + resp->leechers = m_hton32(leechers); + resp->seeders = m_hton32 (seeders); + resp->transaction_id = req->transaction_id; + + for (i = 0;i < q;i++) + { + int x = i * 6; + // network byte order!!! + + // IP + buff[20 + x] = ((peers[i].ip & (0xff << 24)) >> 24); + buff[21 + x] = ((peers[i].ip & (0xff << 16)) >> 16); + buff[22 + x] = ((peers[i].ip & (0xff << 8)) >> 8); + buff[23 + x] = (peers[i].ip & 0xff); + + // port + buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8); + buff[25 + x] = (peers[i].port & 0xff); + + } + free (peers); + sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + + // Add peer to list: + pE.downloaded = req->downloaded; + pE.uploaded = req->uploaded; + pE.left = req->left; + pE.peer_id = req->peer_id; + if (req->ip_address == 0) // default + { + pE.ip = m_hton32 (remote->sin_addr.s_addr); + } + else + { + pE.ip = req->ip_address; + } + pE.port = req->port; + db_add_peer(usi->conn, req->info_hash, &pE); + + return 0; + } + + int UDPTracker::handleScrape (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len) + { + ScrapeRequest *sR; + int v, // validation helper + c, // torrent counter + i, // loop counter + j; // loop counter + uint8_t hash [20]; + char xHash [50]; + ScrapeResponse *resp; + uint8_t buffer [1024]; // up to 74 torrents can be scraped at once (17*74+8) < 1024 + + + sR = (ScrapeRequest*)data; + + // validate request length: + v = len - 16; + if (v < 0 || v % 20 != 0) + { + UDPTracker::sendError (usi, remote, sR->transaction_id, "Bad scrape request."); + return 0; + } + + // get torrent count. + c = v / 20; + + resp = (ScrapeResponse*)buffer; + resp->action = m_hton32 (2); + resp->transaction_id = sR->transaction_id; + + for (i = 0;i < c;i++) + { + int32_t s, c, l; + int32_t *seeders, + *completed, + *leechers; + + for (j = 0; j < 20;j++) + hash[j] = data[j + (i*20)+16]; + + to_hex_str (hash, xHash); + + cout << "\t" << xHash << endl; + + seeders = (int32_t*)&buffer[i*12+8]; + completed = (int32_t*)&buffer[i*12+12]; + leechers = (int32_t*)&buffer[i*12+16]; + + db_get_stats (usi->conn, hash, &s, &l, &c); + + *seeders = m_hton32 (s); + *completed = m_hton32 (c); + *leechers = m_hton32 (l); + } + cout.flush(); + + sendto (usi->sock, (const char*)buffer, sizeof(buffer), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + + return 0; + } + +static int _isIANA_IP (uint32_t ip) +{ + uint8_t x = (ip % 256); + if (x == 0 || x == 10 || x == 127 || x >= 224) + return 1; + return 0; +} + + int UDPTracker::resolveRequest (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r) + { + ConnectionRequest *cR; + uint32_t action; + + cR = (ConnectionRequest*)data; + + action = m_hton32(cR->action); + + if ((usi->settings & UDPT_ALLOW_IANA_IP) == 0) + { + if (_isIANA_IP (remote->sin_addr.s_addr)) + { + return 0; // Access Denied: IANA reserved IP. + } + } + + cout << ":: " << (void*)remote->sin_addr.s_addr << ": " << remote->sin_port << " ACTION=" << action << endl; + + if (action == 0 && r >= 16) + return UDPTracker::handleConnection (usi, remote, data); + else if (action == 1 && r >= 98) + return UDPTracker::handleAnnounce (usi, remote, data); + else if (action == 2) + return UDPTracker::handleScrape (usi, remote, data, r); + else + { + cout << "E: action=" << action << ", r=" << r << endl; + UDPTracker::sendError (usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); + return -1; + } + + return 0; + } + +#ifdef WIN32 + DWORD UDPTracker::_thread_start (LPVOID arg) +#elif defined (linux) + void* UDPTracker::_thread_start (void *arg) +#endif + { + UDPTracker *usi; + SOCKADDR_IN remoteAddr; + int addrSz, + r; + char tmpBuff [UDP_BUFFER_SIZE]; + + usi = (UDPTracker*)arg; + + addrSz = sizeof (SOCKADDR_IN); + + + while (usi->isRunning) + { + cout.flush(); + // peek into the first 12 bytes of data; determine if connection request or announce request. + r = recvfrom(usi->sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); + if (r <= 0) + continue; // bad request... + r = UDPTracker::resolveRequest (usi, &remoteAddr, tmpBuff, r); + } + + #ifdef linux + pthread_exit (NULL); + #endif + return 0; + } + +#ifdef WIN32 + DWORD UDPTracker::_maintainance_start (LPVOID arg) +#elif defined (linux) + void* UDPTracker::_maintainance_start (void *arg) +#endif + { + UDPTracker *usi; + + usi = (UDPTracker *)arg; + + while (usi->isRunning) + { + db_cleanup (usi->conn); + +#ifdef WIN32 + Sleep (usi->cleanup_interval * 1000); // wait 2 minutes between every cleanup. +#elif defined (linux) + sleep (usi->cleanup_interval); +#else +#error Unsupported OS. +#endif + } + + return 0; + } + +}; diff --git a/src/udpTracker.h b/src/udpTracker.h deleted file mode 100644 index 7402bf0..0000000 --- a/src/udpTracker.h +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright © 2012,2013 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#ifndef UDPTRACKER_H_ -#define UDPTRACKER_H_ - -#include -#include "multiplatform.h" -#include "db/database.h" -#include "settings.h" - -struct udp_connection_request -{ - uint64_t connection_id; - uint32_t action; - uint32_t transaction_id; -}; - -struct udp_connection_response -{ - uint32_t action; - uint32_t transaction_id; - uint64_t connection_id; -}; - -struct udp_announce_request -{ - uint64_t connection_id; - uint32_t action; - uint32_t transaction_id; - uint8_t info_hash [20]; - uint8_t peer_id [20]; - uint64_t downloaded; - uint64_t left; - uint64_t uploaded; - uint32_t event; - uint32_t ip_address; - uint32_t key; - int32_t num_want; - uint16_t port; -}; - -struct udp_announce_response -{ - uint32_t action; - uint32_t transaction_id; - uint32_t interval; - uint32_t leechers; - uint32_t seeders; - - uint8_t *peer_list_data; -}; - -struct udp_scrape_request -{ - uint64_t connection_id; - uint32_t action; - uint32_t transaction_id; - - uint8_t *torrent_list_data; -}; - -struct udp_scrape_response -{ - uint32_t action; - uint32_t transaction_id; - - uint8_t *data; -}; - -struct udp_error_response -{ - uint32_t action; - uint32_t transaction_id; - char *message; -}; - -#define UDPT_DYNAMIC 0x01 // Track Any info_hash? -#define UDPT_ALLOW_REMOTE_IP 0x02 // Allow client's to send other IPs? -#define UDPT_ALLOW_IANA_IP 0x04 // allow IP's like 127.0.0.1 or other IANA reserved IPs? -#define UDPT_VALIDATE_CLIENT 0x08 // validate client before adding to Database? (check if connection is open?) - - -typedef struct -{ - SOCKET sock; - uint16_t port; - - uint8_t thread_count; - - uint8_t flags; - uint8_t settings; - - HANDLE *threads; - - uint32_t announce_interval; - uint32_t cleanup_interval; - - Settings *o_settings; - dbConnection *conn; -} udpServerInstance; - -typedef struct udp_connection_request ConnectionRequest; -typedef struct udp_connection_response ConnectionResponse; -typedef struct udp_announce_request AnnounceRequest; -typedef struct udp_announce_response AnnounceResponse; -typedef struct udp_scrape_request ScrapeRequest; -typedef struct udp_scrape_response ScrapeResponse; -typedef struct udp_error_response ErrorResponse; - -/** - * Initializes the UDP Tracker. - * @param usi The Instancfe to initialize. - * @param port The port to bind the server to - * @param threads Amount of threads to start the server with. - */ -void UDPTracker_init (udpServerInstance *usi, Settings *); - -/** - * Destroys resources that were created by UDPTracker_init. - * @param usi Instance to destroy. - */ -void UDPTracker_destroy (udpServerInstance *usi); - -/** - * Starts the Initialized instance. - * @param usi Instance to start - * @return 0 on success, otherwise non-zero. - */ -int UDPTracker_start (udpServerInstance *usi); - -#endif /* UDPTRACKER_H_ */ diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp new file mode 100644 index 0000000..864886f --- /dev/null +++ b/src/udpTracker.hpp @@ -0,0 +1,166 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#ifndef UDPTRACKER_H_ +#define UDPTRACKER_H_ + + +#include +#include "multiplatform.h" +#include "db/database.h" +#include "settings.hpp" + +#include +using namespace std; + +#define UDPT_DYNAMIC 0x01 // Track Any info_hash? +#define UDPT_ALLOW_REMOTE_IP 0x02 // Allow client's to send other IPs? +#define UDPT_ALLOW_IANA_IP 0x04 // allow IP's like 127.0.0.1 or other IANA reserved IPs? +#define UDPT_VALIDATE_CLIENT 0x08 // validate client before adding to Database? (check if connection is open?) + + +namespace UDPT +{ + class UDPTracker + { + public: + typedef struct udp_connection_request + { + uint64_t connection_id; + uint32_t action; + uint32_t transaction_id; + } ConnectionRequest; + + typedef struct udp_connection_response + { + uint32_t action; + uint32_t transaction_id; + uint64_t connection_id; + } ConnectionResponse; + + typedef struct udp_announce_request + { + uint64_t connection_id; + uint32_t action; + uint32_t transaction_id; + uint8_t info_hash [20]; + uint8_t peer_id [20]; + uint64_t downloaded; + uint64_t left; + uint64_t uploaded; + uint32_t event; + uint32_t ip_address; + uint32_t key; + int32_t num_want; + uint16_t port; + } AnnounceRequest; + + typedef struct udp_announce_response + { + uint32_t action; + uint32_t transaction_id; + uint32_t interval; + uint32_t leechers; + uint32_t seeders; + + uint8_t *peer_list_data; + } AnnounceResponse; + + typedef struct udp_scrape_request + { + uint64_t connection_id; + uint32_t action; + uint32_t transaction_id; + + uint8_t *torrent_list_data; + } ScrapeRequest; + + typedef struct udp_scrape_response + { + uint32_t action; + uint32_t transaction_id; + + uint8_t *data; + } ScrapeResponse; + + typedef struct udp_error_response + { + uint32_t action; + uint32_t transaction_id; + char *message; + } ErrorResponse; + + enum StartStatus + { + START_OK = 0, + START_ESOCKET_FAILED = 1, + START_EBIND_FAILED = 2 + }; + + /** + * Initializes the UDP Tracker. + * @param settings Settings to start server with + */ + UDPTracker (Settings *); + + /** + * Starts the Initialized instance. + * @return 0 on success, otherwise non-zero. + */ + enum StartStatus start (); + + /** + * Destroys resources that were created by constructor + * @param usi Instance to destroy. + */ + virtual ~UDPTracker (); + + private: + SOCKET sock; + uint16_t port; + uint8_t thread_count; + bool isRunning; + HANDLE *threads; + uint32_t announce_interval; + uint32_t cleanup_interval; + + uint8_t settings; + Settings *o_settings; + dbConnection *conn; + +#ifdef WIN32 + static DWORD _thread_start (LPVOID arg); + static DWORD _maintainance_start (LPVOID arg); +#elif defined (linux) + static void* _thread_start (void *arg); + static void* _maintainance_start (void *arg); +#endif + + static int resolveRequest (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r); + + static int handleConnection (UDPTracker *usi, SOCKADDR_IN *remote, char *data); + static int handleAnnounce (UDPTracker *usi, SOCKADDR_IN *remote, char *data); + static int handleScrape (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len); + + static int sendError (UDPTracker *, SOCKADDR_IN *remote, uint32_t transId, const string &); + + }; +}; + +#endif /* UDPTRACKER_H_ */ From d1c49c6b6f361685371f8babfb2af0e920ba1055 Mon Sep 17 00:00:00 2001 From: Naim A Date: Mon, 4 Mar 2013 00:54:48 +0200 Subject: [PATCH 21/99] New Database Interface, The Ability to add more Database Drivers. --- src/db/database.cpp | 121 +++++++++++ src/db/database.h | 105 ---------- src/db/database.hpp | 173 ++++++++++++++++ src/db/driver_sqlite.c | 343 ------------------------------- src/db/driver_sqlite.cpp | 430 +++++++++++++++++++++++++++++++++++++++ src/db/driver_sqlite.hpp | 55 +++++ src/udpTracker.cpp | 140 +++++++------ src/udpTracker.hpp | 4 +- 8 files changed, 860 insertions(+), 511 deletions(-) create mode 100644 src/db/database.cpp delete mode 100644 src/db/database.h create mode 100644 src/db/database.hpp delete mode 100644 src/db/driver_sqlite.c create mode 100644 src/db/driver_sqlite.cpp create mode 100644 src/db/driver_sqlite.hpp diff --git a/src/db/database.cpp b/src/db/database.cpp new file mode 100644 index 0000000..a521a9f --- /dev/null +++ b/src/db/database.cpp @@ -0,0 +1,121 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "database.hpp" + +namespace UDPT +{ + namespace Data + { + DatabaseDriver::DatabaseDriver(Settings::SettingClass *sc, bool isDynamic) + { + this->dClass = sc; + this->is_dynamic = isDynamic; + } + + bool DatabaseDriver::addTorrent(uint8_t hash [20]) + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + bool DatabaseDriver::removeTorrent(uint8_t hash[20]) + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + bool DatabaseDriver::isDynamic() + { + return this->is_dynamic; + } + + bool DatabaseDriver::genConnectionId(uint64_t *cid, uint32_t ip, uint16_t port) + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + bool DatabaseDriver::verifyConnectionId(uint64_t cid, uint32_t ip, uint16_t port) + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + bool DatabaseDriver::updatePeer(uint8_t peer_id [20], uint8_t info_hash [20], + uint32_t ip, uint16_t port, + int64_t downloaded, int64_t left, int64_t uploaded, + enum TrackerEvents event) + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + bool DatabaseDriver::removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port) + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + bool DatabaseDriver::getTorrentInfo (TorrentEntry *e) + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + bool DatabaseDriver::getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe) + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + void DatabaseDriver::cleanup() + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + bool DatabaseDriver::isTorrentAllowed(uint8_t info_hash[20]) + { + throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); + } + + DatabaseDriver::~DatabaseDriver() + { + } + + /*-- Exceptions --*/ + static const char *EMessages[] = { + "Unknown Error", + "Not Implemented", + "Failed to connect to database" + }; + + DatabaseException::DatabaseException() + { + this->errorNum = E_UNKNOWN; + } + + DatabaseException::DatabaseException(enum EType e) + { + this->errorNum = e; + } + + enum DatabaseException::EType DatabaseException::getErrorType() + { + return this->errorNum; + } + + const char* DatabaseException::getErrorMessage() + { + return EMessages[this->errorNum]; + } + }; +}; diff --git a/src/db/database.h b/src/db/database.h deleted file mode 100644 index f731eea..0000000 --- a/src/db/database.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright © 2012,2013 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#ifndef DATABASE_H_ -#define DATABASE_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct dbConnection dbConnection; - -/** - * Opens a database connection. - * @param pdb Pointer to database instance. - * @param cStr Connection string for the active driver. - * @return 0 on success; otherwise non-zero. - */ -int db_open (dbConnection **pdb, const char *cStr); - -/** - * Closes the database connection. - * @param db Database instance. - * @return 0 on success; otherwise non-zero. - */ -int db_close (dbConnection *db); - -typedef struct { - uint8_t *peer_id; - uint64_t downloaded; - uint64_t uploaded; - uint64_t left; - - uint32_t ip; // currently only support IPv4. - uint16_t port; -} db_peerEntry; - -/** - * Adds/Updates the list of peers. - * @param db The database's instance. - * @param hash The info_hash of the torrent. - * @param pE Peer's information. - * @return 0 on success; otherwise non-zero. - */ -int db_add_peer (dbConnection *db, uint8_t hash[20], db_peerEntry *pE); - -/** - * Loads peers for the requested torrent. - * @param db Database instance. - * @param hash The info_hash of the requested torrent. - * @param lst A allocated array to store results in. - * @param sZ in: The maximum amount of entries to load. out: Amount of loaded entries. - * @return 0 on success; otherwise non-zero. - */ -int db_load_peers (dbConnection *db, uint8_t hash[20], db_peerEntry *lst, int *sZ); - -/** - * Gets stats for the requested torrent. - * @param db The Database connection - * @param hash info_hash of the torrent. - * @param seeders Returns the Seeders for the requested torrent. - * @param leechers Returns the Leechers for the requested torrent. - * @param completed Returns the count of completed downloaded reported. - * @return 0 on success, otherwise non-zero. - */ -int db_get_stats (dbConnection *db, uint8_t hash[20], int32_t *seeders, int32_t *leechers, int32_t *completed); - -/** - * Maintenance routine, Calculates stats & releases space from old entries. - * @param db The database connection. - * @return 0 on success; otherwise non-zero. - */ -int db_cleanup (dbConnection *db); - -/** - * Deletes a peer from the database. - * @param db Database connection - * @param hash info_hash of the torrent. - * @param pE The peer's information. - * @return 0 on success; otherwise non-zero. - */ -int db_remove_peer (dbConnection *db, uint8_t hash [20], db_peerEntry *pE); - -#ifdef __cplusplus -} -#endif -#endif /* DATABASE_H_ */ diff --git a/src/db/database.hpp b/src/db/database.hpp new file mode 100644 index 0000000..ac4f9e5 --- /dev/null +++ b/src/db/database.hpp @@ -0,0 +1,173 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#ifndef DATABASE_HPP_ +#define DATABASE_HPP_ + +#include "../settings.hpp" + +namespace UDPT +{ + namespace Data + { + class DatabaseException + { + public: + enum EType { + E_UNKNOWN = 0, // Unknown error + E_NOT_IMPLEMENTED = 1, // not implemented + E_CONNECTION_FAILURE = 2 + }; + + DatabaseException (); + DatabaseException (EType); + EType getErrorType (); + const char* getErrorMessage (); + private: + EType errorNum; + }; + + class DatabaseDriver + { + public: + typedef struct { + uint8_t *info_hash; + int32_t seeders; + int32_t leechers; + int32_t completed; + } TorrentEntry; + typedef struct { + uint32_t ip; + uint16_t port; + } PeerEntry; + + enum TrackerEvents { + EVENT_UNSPEC = 0, + EVENT_COMPLETE = 1, + EVENT_START = 2, + EVENT_STOP = 3 + }; + + /** + * Opens the DB's connection + * @param dClass Settings class ('database' class). + */ + DatabaseDriver (Settings::SettingClass *dClass, bool isDynamic = false); + + /** + * Adds a torrent to the Database. automatically done if in dynamic mode. + * @param hash The info_hash of the torrent. + * @return true on success. false on failure. + */ + virtual bool addTorrent (uint8_t hash[20]); + + /** + * Removes a torrent from the database. should be used only for non-dynamic trackers or by cleanup. + * @param hash The info_hash to drop. + * @return true if torrent's database was dropped or no longer exists. otherwise false (shouldn't happen - critical) + */ + virtual bool removeTorrent (uint8_t hash[20]); + + /** + * Checks if the Database is acting as a dynamic tracker DB. + * @return true if dynamic. otherwise false. + */ + bool isDynamic (); + + /** + * Checks if the torrent can be used in the tracker. + * @param info_hash The torrent's info_hash. + * @return true if allowed. otherwise false. + */ + virtual bool isTorrentAllowed (uint8_t info_hash [20]); + + /** + * Generate a Connection ID for the peer. + * @param connectionId (Output) the generated connection ID. + * @param ip The peer's IP (requesting peer. not remote) + * @param port The peer's IP (remote port if tracker accepts) + * @return + */ + virtual bool genConnectionId (uint64_t *connectionId, uint32_t ip, uint16_t port); + + virtual bool verifyConnectionId (uint64_t connectionId, uint32_t ip, uint16_t port); + + /** + * Updates/Adds a peer to/in the database. + * @param peer_id the peer's peer_id + * @param info_hash the torrent info_hash + * @param ip IP of peer (remote ip if tracker accepts) + * @param port TCP port of peer (remote port if tracker accepts) + * @param downloaded total Bytes downloaded + * @param left total bytes left + * @param uploaded total bytes uploaded + * @return true on success, false on failure. + */ + virtual bool updatePeer (uint8_t peer_id [20], uint8_t info_hash [20], + uint32_t ip, uint16_t port, + int64_t downloaded, int64_t left, int64_t uploaded, + enum TrackerEvents event); + + /** + * Remove a peer from a torrent (if stop action occurred, or if peer is inactive in cleanup) + * @param peer_id The peer's peer_id + * @param info_hash Torrent's info_hash + * @param ip The IP of the peer (remote IP if tracker accepts) + * @param port The TCP port (remote port if tracker accepts) + * @return true on success. false on failure (shouldn't happen - critical) + */ + virtual bool removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port); + + /** + * Gets stats on a torrent + * @param e TorrentEntry, only this info_hash has to be set + * @return true on success, false on failure. + */ + virtual bool getTorrentInfo (TorrentEntry *e); + + /** + * Gets a list of peers from the database. + * @param info_hash The torrent's info_hash + * @param max_count The maximum amount of peers to load from the database. The amount of loaded peers is returned through this variable. + * @param pe The list of peers. Must be pre-allocated to the size of max_count. + * @return true on success, otherwise false (shouldn't happen). + */ + virtual bool getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe); + + /** + * Cleanup the database. + * Other actions may be locked when using this depending on the driver. + */ + virtual void cleanup (); + + /** + * Closes the connections, and releases all other resources. + */ + virtual ~DatabaseDriver (); + + protected: + Settings::SettingClass *dClass; + private: + bool is_dynamic; + }; + }; +}; + + +#endif /* DATABASE_HPP_ */ diff --git a/src/db/driver_sqlite.c b/src/db/driver_sqlite.c deleted file mode 100644 index 56aef7a..0000000 --- a/src/db/driver_sqlite.c +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright © 2012,2013 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include "database.h" -#include "../multiplatform.h" -#include "../tools.h" -#include -#include -#include -#include -#include - -struct dbConnection -{ - sqlite3 *db; - HANDLE janitor; -}; - -static const char hexadecimal[] = "0123456789abcdef"; - -void _to_hex_str (const uint8_t *hash, char *data) -{ - int i; - for (i = 0;i < 20;i++) - { - data[i * 2] = hexadecimal[hash[i] / 16]; - data[i * 2 + 1] = hexadecimal[hash[i] % 16]; - } - data[40] = '\0'; -} - -static int _db_make_torrent_table (sqlite3 *db, char *hash) -{ - char sql [2000]; - char *err_msg; - int r; - - sql[0] = '\0'; - - strcat(sql, "CREATE TABLE IF NOT EXISTS 't"); - strcat(sql, hash); - strcat (sql, "' ("); - - strcat (sql, "peer_id blob(20)," - "ip blob(4)," - "port blob(2)," - "uploaded blob(8)," // uint64 - "downloaded blob(8)," - "left blob(8)," - "last_seen INT DEFAULT 0"); - - strcat(sql, ", CONSTRAINT c1 UNIQUE (ip,port) ON CONFLICT REPLACE)"); - - // create table. - r = sqlite3_exec(db, sql, NULL, NULL, &err_msg); - printf("E:%s\n", err_msg); - - return r; -} - -static void _db_setup (sqlite3 *db) -{ - sqlite3_exec(db, "CREATE TABLE stats (" - "info_hash blob(20) UNIQUE," - "completed INTEGER DEFAULT 0," - "leechers INTEGER DEFAULT 0," - "seeders INTEGER DEFAULT 0," - "last_mod INTEGER DEFAULT 0" - ")", NULL, NULL, NULL); -} - -int db_open (dbConnection **db, const char *cStr) -{ - FILE *f; - int doSetup, // check if to build DB, or it already exists? - r; - - f = fopen (cStr, "rb"); - doSetup = 0; - if (f == NULL) - doSetup = 1; - else - fclose (f); - - *db = malloc (sizeof(struct dbConnection)); - r = sqlite3_open (cStr, &((*db)->db)); - if (doSetup) - _db_setup((*db)->db); - - return r; -} - -int db_close (dbConnection *db) -{ - int r = sqlite3_close(db->db); - free (db); - return r; -} - -int db_add_peer (dbConnection *db, uint8_t info_hash[20], db_peerEntry *pE) -{ - char xHash [50]; // we just need 40 + \0 = 41. - sqlite3_stmt *stmt; - char sql [1000]; - int r; - - char *hash = xHash; - to_hex_str(info_hash, hash); - - _db_make_torrent_table(db->db, hash); - - - sql[0] = '\0'; - strcat(sql, "REPLACE INTO 't"); - strcat(sql, hash); - strcat(sql, "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)"); - -// printf("IP->%x::%u\n", pE->ip, pE->port); - - sqlite3_prepare(db->db, sql, -1, &stmt, NULL); - - sqlite3_bind_blob(stmt, 1, (void*)pE->peer_id, 20, NULL); - sqlite3_bind_blob(stmt, 2, (void*)&pE->ip, 4, NULL); - sqlite3_bind_blob(stmt, 3, (void*)&pE->port, 2, NULL); - sqlite3_bind_blob(stmt, 4, (void*)&pE->uploaded, 8, NULL); - sqlite3_bind_blob(stmt, 5, (void*)&pE->downloaded, 8, NULL); - sqlite3_bind_blob(stmt, 6, (void*)&pE->left, 8, NULL); - sqlite3_bind_int(stmt, 7, time(NULL)); - - r = sqlite3_step(stmt); - sqlite3_finalize(stmt); - - strcpy(sql, "REPLACE INTO stats (info_hash,last_mod) VALUES (?,?)"); - sqlite3_prepare (db->db, sql, -1, &stmt, NULL); - sqlite3_bind_blob (stmt, 1, hash, 20, NULL); - sqlite3_bind_int (stmt, 2, time(NULL)); - sqlite3_step (stmt); - sqlite3_finalize (stmt); - - return r; -} - -int db_load_peers (dbConnection *db, uint8_t info_hash[20], db_peerEntry *lst, int *sZ) -{ - char sql [1000]; - char hash [50]; - sqlite3_stmt *stmt; - int r, - i; - - sql[0] = '\0'; - - to_hex_str(info_hash, hash); - - strcat(sql, "SELECT ip,port FROM 't"); - strcat(sql, hash); - strcat(sql, "' LIMIT ?"); - - sqlite3_prepare(db->db, sql, -1, &stmt, NULL); - sqlite3_bind_int(stmt, 1, *sZ); - - i = 0; - while (*sZ > i) - { - r = sqlite3_step(stmt); - if (r == SQLITE_ROW) - { - const char *ip = (const char*)sqlite3_column_blob (stmt, 0); - const char *port = (const char*)sqlite3_column_blob (stmt, 1); - - memcpy(&lst[i].ip, ip, 4); - memcpy(&lst[i].port, port, 2); - - i++; - } - else - break; - } - - printf("%d Clients Dumped.\n", i); - - sqlite3_finalize(stmt); - - *sZ = i; - - return 0; -} - -int db_get_stats (dbConnection *db, uint8_t hash[20], int32_t *seeders, int32_t *leechers, int32_t *completed) -{ - const char sql[] = "SELECT seeders,leechers,completed FROM 'stats' WHERE info_hash=?"; - sqlite3_stmt *stmt; - - *seeders = 0; - *leechers = 0; - *completed = 0; - - - sqlite3_prepare (db->db, sql, -1, &stmt, NULL); - sqlite3_bind_blob (stmt, 1, (void*)hash, 20, NULL); - - if (sqlite3_step(stmt) == SQLITE_ROW) - { - *seeders = sqlite3_column_int (stmt, 0); - *leechers = sqlite3_column_int (stmt, 1); - *completed = sqlite3_column_int (stmt, 2); - } - - sqlite3_finalize (stmt); - - return 0; -} - -int db_cleanup (dbConnection *db) -{ - const char sql[] = "SELECT info_hash FROM stats WHERE last_moddb, sql, -1, &stmt, NULL); - sqlite3_bind_int (stmt, 1, timeframe - 7200); - - while (sqlite3_step(stmt) == SQLITE_ROW) - { - to_hex_str(sqlite3_column_blob(stmt, 0), hash); - - // drop table: - strcpy(temp, "DROP TABLE IF EXISTS 't"); - strcat(temp, hash); - strcat(temp, "'"); - sqlite3_exec(db->db, temp, NULL, NULL, NULL); - } - sqlite3_finalize (stmt); - - // update 'dead' torrents - sqlite3_prepare(db->db, "UPDATE stats SET seeders=0,leechers=0 WHERE last_moddb, "SELECT info_hash FROM stats WHERE last_mod>=?", -1, &stmt, NULL); - sqlite3_bind_int (stmt, 1, timeframe - 7200); - - sqlite3_prepare (db->db, "UPDATE stats SET seeders=?,leechers=?,last_mod=? WHERE info_hash=?", -1, &uStat, NULL); - - while (sqlite3_step(stmt) == SQLITE_ROW) - { - uint8_t *binHash = (uint8_t*)sqlite3_column_blob(stmt, 0); - to_hex_str (binHash, hash); - - // total users... - strcpy (temp, "SELECT COUNT(*) FROM 't"); - strcat (temp, hash); - strcat (temp, "'"); - - sqlite3_prepare (db->db, temp, -1, &sTmp, NULL); - if (sqlite3_step(sTmp) == SQLITE_ROW) - { - leechers = sqlite3_column_int (sTmp, 0); - } - sqlite3_finalize (sTmp); - - // seeders... - strcpy (temp, "SELECT COUNT(*) FROM 't"); - strcat (temp, hash); - strcat (temp, "' WHERE left=0"); - - sqlite3_prepare (db->db, temp, -1, &sTmp, NULL); - if (sqlite3_step(sTmp) == SQLITE_ROW) - { - seeders = sqlite3_column_int (sTmp, 0); - } - sqlite3_finalize (sTmp); - - leechers -= seeders; - - sqlite3_bind_int (uStat, 1, seeders); - sqlite3_bind_int (uStat, 2, leechers); - sqlite3_bind_int (uStat, 3, timeframe); - sqlite3_bind_blob (uStat, 4, binHash, 20, NULL); - sqlite3_step (uStat); - sqlite3_reset (uStat); - - printf("%s: %d seeds/%d leechers;\n", hash, seeders, leechers); - } - sqlite3_finalize (stmt); - - sqlite3_finalize (stmt); - - return 0; -} - -int db_remove_peer (dbConnection *db, uint8_t hash[20], db_peerEntry *pE) -{ - char sql [1000]; - char xHash [50]; - sqlite3_stmt *stmt; - - _to_hex_str (hash, xHash); - - strcpy (sql, "DELETE FROM 't"); - strcat (sql, xHash); - strcat (sql, "' WHERE ip=? AND port=? AND peer_id=?"); - - sqlite3_prepare (db->db, sql, -1, &stmt, NULL); - - sqlite3_bind_blob(stmt, 0, (const void*)&pE->ip, 4, NULL); - sqlite3_bind_blob(stmt, 1, (const void*)&pE->port, 2, NULL); - sqlite3_bind_blob(stmt, 2, (const void*)pE->peer_id, 20, NULL); - - sqlite3_step(stmt); - - sqlite3_finalize(stmt); - - return 0; -} diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp new file mode 100644 index 0000000..8d6f83e --- /dev/null +++ b/src/db/driver_sqlite.cpp @@ -0,0 +1,430 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "driver_sqlite.hpp" +#include "../multiplatform.h" +#include "../tools.h" +#include +#include +#include +#include +#include +#include + +using namespace std; + +namespace UDPT +{ + namespace Data + { + static const char hexadecimal[] = "0123456789abcdef"; + + static char* _to_hex_str (const uint8_t *hash, char *data) + { + int i; + for (i = 0;i < 20;i++) + { + data[i * 2] = hexadecimal[hash[i] / 16]; + data[i * 2 + 1] = hexadecimal[hash[i] % 16]; + } + data[40] = '\0'; + return data; + } + + static uint8_t* _hash_to_bin (const char *hash, uint8_t *data) + { + for (int i = 0;i < 20;i++) + { + data [i] = 0; + char a = hash[i * 2]; + char b = hash[i * 2 + 1]; + + assert ( (a >= 'a' && a <= 'f') || (a >= '0' && a <= '9') ); + assert ( (b >= 'a' && b <= 'f') || (b >= '0' && b <= '9') ); + + data[i] = ( (a >= '0' && a <= 'f') ? (a - '0') : (a - 'f' + 10) ); + data[i] <<= 4; + data[i] = ( (b >= '0' && b <= 'f') ? (b - '0') : (b - 'f' + 10) ); + } + + return data; + } + + SQLite3Driver::SQLite3Driver (Settings::SettingClass *sc, bool isDyn) : DatabaseDriver(sc, isDyn) + { + int r; + bool doSetup; + + fstream fCheck; + string filename = sc->get("file"); + + fCheck.open(filename.c_str(), ios::binary | ios::in); + if (fCheck.is_open()) + { + doSetup = false; + fCheck.close(); + } + else + doSetup = true; + + r = sqlite3_open(filename.c_str(), &this->db); + if (r != SQLITE_OK) + { + sqlite3_close(this->db); + throw DatabaseException (DatabaseException::E_CONNECTION_FAILURE); + } + + if (doSetup) + this->doSetup(); + } + + void SQLite3Driver::doSetup() + { +// cout << "Creating DB..." << endl; + char *eMsg = NULL; + // for quicker stats. + sqlite3_exec(this->db, "CREATE TABLE stats (" + "info_hash blob(20) UNIQUE," + "completed INTEGER DEFAULT 0," + "leechers INTEGER DEFAULT 0," + "seeders INTEGER DEFAULT 0," + "last_mod INTEGER DEFAULT 0" + ")", NULL, NULL, &eMsg); +// cout << "stats: " << (eMsg == NULL ? "OK" : eMsg) << endl; + // for non-Dynamic trackers + sqlite3_exec(this->db, "CREATE TABLE torrents (" + "info_hash blob(20) UNIQUE," + "created INTEGER" + ")", NULL, NULL, &eMsg); +// cout << "torrents: " << (eMsg == NULL ? "OK" : eMsg) << endl; + } + + bool SQLite3Driver::getTorrentInfo(TorrentEntry *e) + { + bool gotInfo = false; + + const char sql[] = "SELECT seeders,leechers,completed FROM 'stats' WHERE info_hash=?"; + sqlite3_stmt *stmt; + + e->seeders = 0; + e->leechers = 0; + e->completed = 0; + + + sqlite3_prepare (this->db, sql, -1, &stmt, NULL); + sqlite3_bind_blob (stmt, 1, (void*)e->info_hash, 20, NULL); + + if (sqlite3_step(stmt) == SQLITE_ROW) + { + e->seeders = sqlite3_column_int (stmt, 0); + e->leechers = sqlite3_column_int (stmt, 1); + e->completed = sqlite3_column_int (stmt, 2); + + gotInfo = true; + } + + sqlite3_finalize (stmt); + + return gotInfo; + } + + bool SQLite3Driver::getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe) + { + char sql [1000]; + char hash [50]; + sqlite3_stmt *stmt; + int r, + i; + + sql[0] = '\0'; + + to_hex_str(info_hash, hash); + + strcat(sql, "SELECT ip,port FROM 't"); + strcat(sql, hash); + strcat(sql, "' LIMIT ?"); + + sqlite3_prepare(this->db, sql, -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, *max_count); + + i = 0; + while (*max_count > i) + { + r = sqlite3_step(stmt); + if (r == SQLITE_ROW) + { + const char *ip = (const char*)sqlite3_column_blob (stmt, 0); + const char *port = (const char*)sqlite3_column_blob (stmt, 1); + + memcpy(&pe[i].ip, ip, 4); + memcpy(&pe[i].port, port, 2); + + i++; + } + else + { + break; + } + } + + printf("%d Clients Dumped.\n", i); + + sqlite3_finalize(stmt); + + *max_count = i; + + return true; + } + + bool SQLite3Driver::updatePeer(uint8_t peer_id[20], uint8_t info_hash[20], uint32_t ip, uint16_t port, int64_t downloaded, int64_t left, int64_t uploaded, enum TrackerEvents event) + { + char xHash [50]; // we just need 40 + \0 = 41. + sqlite3_stmt *stmt; + char sql [1000]; + int r; + + char *hash = xHash; + to_hex_str(info_hash, hash); + + addTorrent (info_hash); + + + sql[0] = '\0'; + strcat(sql, "REPLACE INTO 't"); + strcat(sql, hash); + strcat(sql, "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)"); + + // printf("IP->%x::%u\n", pE->ip, pE->port); + + sqlite3_prepare(this->db, sql, -1, &stmt, NULL); + + sqlite3_bind_blob(stmt, 1, (void*)peer_id, 20, NULL); + sqlite3_bind_blob(stmt, 2, (void*)&ip, 4, NULL); + sqlite3_bind_blob(stmt, 3, (void*)&port, 2, NULL); + sqlite3_bind_blob(stmt, 4, (void*)&uploaded, 8, NULL); + sqlite3_bind_blob(stmt, 5, (void*)&downloaded, 8, NULL); + sqlite3_bind_blob(stmt, 6, (void*)&left, 8, NULL); + sqlite3_bind_int(stmt, 7, time(NULL)); + + r = sqlite3_step(stmt); + sqlite3_finalize(stmt); + + strcpy(sql, "REPLACE INTO stats (info_hash,last_mod) VALUES (?,?)"); + sqlite3_prepare (this->db, sql, -1, &stmt, NULL); + sqlite3_bind_blob (stmt, 1, hash, 20, NULL); + sqlite3_bind_int (stmt, 2, time(NULL)); + sqlite3_step (stmt); + sqlite3_finalize (stmt); + + return r; + } + + bool SQLite3Driver::addTorrent (uint8_t info_hash[20]) + { + char xHash [41]; + char *err_msg; + int r; + + _to_hex_str(info_hash, xHash); + + // if non-dynamic, called only when adding to DB. + if (!this->isDynamic()) + { + sqlite3_stmt *stmt; + sqlite3_prepare(this->db, "INSERT INTO torrents (info_hash,created) VALUES (?,?)", -1, &stmt, NULL); + sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); + sqlite3_bind_int(stmt, 1, time(NULL)); + sqlite3_step(stmt); + sqlite3_finalize(stmt); + } + + string sql = "CREATE TABLE IF NOT EXISTS 't"; + sql += xHash; + sql += "' ("; + sql += "peer_id blob(20)," + "ip blob(4)," + "port blob(2)," + "uploaded blob(8)," // uint64 + "downloaded blob(8)," + "left blob(8)," + "last_seen INT DEFAULT 0"; + + sql += ", CONSTRAINT c1 UNIQUE (ip,port) ON CONFLICT REPLACE)"; + + // create table. + r = sqlite3_exec(this->db, sql.c_str(), NULL, NULL, &err_msg); + printf("E:%s\n", err_msg); + + return (r == SQLITE_OK); + } + + bool SQLite3Driver::isTorrentAllowed(uint8_t info_hash[20]) + { + if (this->isDynamic()) + return true; + sqlite3_stmt *stmt; + sqlite3_prepare(this->db, "SELECT COUNT(*) FROM torrents WHERE info_hash=?", -1, &stmt, NULL); + sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); + sqlite3_step(stmt); + + int n = sqlite3_column_int(stmt, 1); + sqlite3_finalize(stmt); + return (n == 1); + } + + void SQLite3Driver::cleanup() + { + int exp = time (NULL) - 7200; // 2 hours, expired. + + // drop all peers with no activity for 2 hours. + sqlite3_stmt *getTables; + // torrent table names: t + sqlite3_prepare(this->db, "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 't________________________________________'", -1, &getTables, NULL); + + uint8_t buff [20]; + sqlite3_stmt *updateStats; + assert (sqlite3_prepare(this->db, "REPLACE INTO stats (info_hash,seeders,leechers,last_mod) VALUES (?,?,?,?)", -1, &updateStats, NULL) == SQLITE_OK); + + + while (sqlite3_step(getTables) == SQLITE_ROW) + { + char* tblN = (char*)sqlite3_column_text(getTables, 0); + stringstream sStr; + sStr << "DELETE FROM " << tblN << " WHERE last_seen<" << exp; + + assert (sqlite3_exec(this->db, sStr.str().c_str(), NULL, NULL, NULL) == SQLITE_OK); + + sStr.str (string()); + sStr << "SELECT left,COUNT(*) FROM " << tblN << " GROUP BY left==0"; + + sqlite3_stmt *collectStats; + + sqlite3_prepare(this->db, sStr.str().c_str(), sStr.str().length(), &collectStats, NULL); + cout << "[" << sqlite3_errmsg(this->db) << "]" << endl; + int seeders = 0, leechers = 0; + while (sqlite3_step(collectStats) == SQLITE_ROW) // expecting two results. + { + if (sqlite3_column_int(collectStats, 0) == 0) + seeders = sqlite3_column_int (collectStats, 1); + else + leechers = sqlite3_column_int (collectStats, 1); + } + sqlite3_finalize(collectStats); + + sqlite3_bind_blob(updateStats, 1, _hash_to_bin((const char*)(tblN + 1), buff), 20, NULL); + sqlite3_bind_int(updateStats, 2, seeders); + sqlite3_bind_int(updateStats, 3, leechers); + sqlite3_bind_int(updateStats, 4, time (NULL)); + + sqlite3_step(updateStats); + sqlite3_reset (updateStats); + } + sqlite3_finalize(updateStats); + sqlite3_finalize(getTables); + } + + bool SQLite3Driver::removeTorrent(uint8_t info_hash[20]) + { + // if non-dynamic, remove from table + if (!this->isDynamic()) + { + sqlite3_stmt *stmt; + sqlite3_prepare(this->db, "DELETE FROM torrents WHERE info_hash=?", -1, &stmt, NULL); + sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); + sqlite3_step(stmt); + sqlite3_finalize(stmt); + } + + // remove from stats + sqlite3_stmt *rmS; + if (sqlite3_prepare(this->db, "DELETE FROM stats WHERE info_hash=?", -1, &rmS, NULL) != SQLITE_OK) + { + sqlite3_finalize(rmS); + return false; + } + sqlite3_bind_blob(rmS, 1, (const void*)info_hash, 20, NULL); + sqlite3_step(rmS); + sqlite3_finalize(rmS); + + // remove table + string str = "DROP TABLE IF EXISTS 't"; + char buff [41]; + str += _to_hex_str(info_hash, buff); + str += "'"; + + sqlite3_exec(this->db, str.c_str(), NULL, NULL, NULL); + + return true; + } + + bool SQLite3Driver::removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port) + { + char sql [1000]; + char xHash [50]; + sqlite3_stmt *stmt; + + _to_hex_str (info_hash, xHash); + + strcpy (sql, "DELETE FROM 't"); + strcat (sql, xHash); + strcat (sql, "' WHERE ip=? AND port=? AND peer_id=?"); + + sqlite3_prepare (this->db, sql, -1, &stmt, NULL); + + sqlite3_bind_blob(stmt, 0, (const void*)&ip, 4, NULL); + sqlite3_bind_blob(stmt, 1, (const void*)&port, 2, NULL); + sqlite3_bind_blob(stmt, 2, (const void*)peer_id, 20, NULL); + + sqlite3_step(stmt); + + sqlite3_finalize(stmt); + + return true; + } + + static uint64_t _genCiD (uint32_t ip, uint16_t port) + { + uint64_t x; + x = (time(NULL) / 3600) * port; // x will probably overload. + x = (ip ^ port); + x <<= 16; + x |= (~port); + return x; + } + + bool SQLite3Driver::genConnectionId (uint64_t *connectionId, uint32_t ip, uint16_t port) + { + *connectionId = _genCiD(ip, port); + return true; + } + + bool SQLite3Driver::verifyConnectionId(uint64_t cId, uint32_t ip, uint16_t port) + { + if (cId == _genCiD(ip, port)) + return true; + else + return false; + } + + SQLite3Driver::~SQLite3Driver() + { + sqlite3_close(this->db); + } + }; +}; diff --git a/src/db/driver_sqlite.hpp b/src/db/driver_sqlite.hpp new file mode 100644 index 0000000..34b28d9 --- /dev/null +++ b/src/db/driver_sqlite.hpp @@ -0,0 +1,55 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#ifndef DATABASE_H_ +#define DATABASE_H_ + +#include +#include "database.hpp" +#include + +namespace UDPT +{ + namespace Data + { + class SQLite3Driver : public DatabaseDriver + { + public: + SQLite3Driver (Settings::SettingClass *sc, bool isDyn = false); + bool addTorrent (uint8_t info_hash[20]); + bool removeTorrent (uint8_t info_hash[20]); + bool genConnectionId (uint64_t *connId, uint32_t ip, uint16_t port); + bool verifyConnectionId (uint64_t connId, uint32_t ip, uint16_t port); + bool updatePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port, int64_t downloaded, int64_t left, int64_t uploaded, enum TrackerEvents event); + bool removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port); + bool getTorrentInfo (TorrentEntry *e); + bool isTorrentAllowed (uint8_t info_hash[20]); + bool getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe); + void cleanup (); + + ~SQLite3Driver (); + private: + sqlite3 *db; + + void doSetup (); + }; + }; +}; + +#endif /* DATABASE_H_ */ diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index 55efe2b..391a80f 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -25,6 +25,7 @@ #include using namespace std; +using namespace UDPT::Data; #define UDP_BUFFER_SIZE 2048 @@ -91,8 +92,6 @@ namespace UDPT this->port = (s_port == "" ? 6969 : atoi (s_port.c_str())); this->thread_count = (s_threads == "" ? 5 : atoi (s_threads.c_str())) + 1; - cout << "port=" << this->port << endl; - this->threads = new HANDLE[this->thread_count]; this->isRunning = false; @@ -131,7 +130,7 @@ namespace UDPT cout << "Thread (" << ( i + 1) << "/" << ((int)this->thread_count) << ") terminated." << endl; } if (this->conn != NULL) - db_close(this->conn); + delete this->conn; delete[] this->threads; } @@ -148,11 +147,7 @@ namespace UDPT if (sock == INVALID_SOCKET) return START_ESOCKET_FAILED; - #ifdef WIN32 - recvAddr.sin_addr.S_un.S_addr = 0L; - #elif defined (linux) recvAddr.sin_addr.s_addr = 0L; - #endif recvAddr.sin_family = AF_INET; recvAddr.sin_port = m_hton16 (this->port); @@ -173,11 +168,7 @@ namespace UDPT this->sock = sock; - dbname = this->o_settings->get ("database", "file"); - if (dbname == "") - dbname = "tracker.db"; - - db_open(&this->conn, dbname.c_str()); + this->conn = new Data::SQLite3Driver (this->o_settings->getClass("database"), true); this->isRunning = true; cout << "Starting maintenance thread (1/" << ((int)this->thread_count) << ")" << endl; @@ -186,7 +177,7 @@ namespace UDPT #ifdef WIN32 this->threads[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_maintainance_start, (LPVOID)this, 0, NULL); #elif defined (linux) - pthread_create (&usi->threads[0], NULL, _maintainance_start, usi); + pthread_create (&usi->threads[0], NULL, _maintainance_start, (void*)this); #endif for (i = 1;i < this->thread_count; i++) @@ -195,26 +186,13 @@ namespace UDPT #ifdef WIN32 this->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)this, 0, NULL); #elif defined (linux) - pthread_create (&(this->threads[i]), NULL, _thread_start, this); + pthread_create (&(this->threads[i]), NULL, _thread_start, (void*)this); #endif } return START_OK; } -static uint64_t _get_connID (SOCKADDR_IN *remote) -{ - int base; - uint64_t x; - - base = time(NULL); - base /= 3600; // changes every hour. - - x = base; - x += remote->sin_addr.s_addr; - return x; -} - int UDPTracker::sendError (UDPTracker *usi, SOCKADDR_IN *remote, uint32_t transactionID, const string &msg) { struct udp_error_response error; @@ -248,7 +226,13 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) resp.action = m_hton32(0); resp.transaction_id = req->transaction_id; - resp.connection_id = _get_connID(remote); + + if (!usi->conn->genConnectionId(&resp.connection_id, + m_hton32(remote->sin_addr.s_addr), + m_hton16(remote->sin_port))) + { + return 1; + } sendto(usi->sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); @@ -262,16 +246,16 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) int q, // peer counts bSize, // message size i; // loop index - db_peerEntry *peers; - int32_t seeders, - leechers, - completed; - db_peerEntry pE; // info for DB + DatabaseDriver::PeerEntry *peers; + DatabaseDriver::TorrentEntry tE; + uint8_t buff [1028]; // Reasonable buffer size. (header+168 peers) req = (AnnounceRequest*)data; - if (req->connection_id != _get_connID(remote)) + if (!usi->conn->verifyConnectionId(req->connection_id, + m_hton32(remote->sin_addr.s_addr), + m_hton16(remote->sin_port))) { return 1; } @@ -291,25 +275,54 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) return 0; } + if (!usi->conn->isTorrentAllowed(req->info_hash)) + { + UDPTracker::sendError(usi, remote, req->transaction_id, "info_hash not registered."); + return 0; + } + // load peers q = 30; if (req->num_want >= 1) q = min (q, req->num_want); - peers = (db_peerEntry*)malloc (sizeof(db_peerEntry) * q); + peers = new DatabaseDriver::PeerEntry [q]; - db_load_peers(usi->conn, req->info_hash, peers, &q); + + DatabaseDriver::TrackerEvents event; + switch (req->event) + { + case 1: + event = DatabaseDriver::EVENT_COMPLETE; + break; + case 2: + event = DatabaseDriver::EVENT_START; + break; + case 3: + event = DatabaseDriver::EVENT_STOP; + break; + default: + event = DatabaseDriver::EVENT_UNSPEC; + break; + } + + if (event == DatabaseDriver::EVENT_STOP) + q = 0; // no need for peers when stopping. + + if (q > 0) + usi->conn->getPeers(req->info_hash, &q, peers); bSize = 20; // header is 20 bytes bSize += (6 * q); // + 6 bytes per peer. - db_get_stats (usi->conn, req->info_hash, &seeders, &leechers, &completed); + tE.info_hash = req->info_hash; + usi->conn->getTorrentInfo(&tE); resp = (AnnounceResponse*)buff; resp->action = m_hton32(1); resp->interval = m_hton32 ( usi->announce_interval ); - resp->leechers = m_hton32(leechers); - resp->seeders = m_hton32 (seeders); + resp->leechers = m_hton32(tE.leechers); + resp->seeders = m_hton32 (tE.seeders); resp->transaction_id = req->transaction_id; for (i = 0;i < q;i++) @@ -328,24 +341,17 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) buff[25 + x] = (peers[i].port & 0xff); } - free (peers); + delete[] peers; sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - // Add peer to list: - pE.downloaded = req->downloaded; - pE.uploaded = req->uploaded; - pE.left = req->left; - pE.peer_id = req->peer_id; + // update DB. + uint32_t ip; if (req->ip_address == 0) // default - { - pE.ip = m_hton32 (remote->sin_addr.s_addr); - } + ip = m_hton32 (remote->sin_addr.s_addr); else - { - pE.ip = req->ip_address; - } - pE.port = req->port; - db_add_peer(usi->conn, req->info_hash, &pE); + ip = req->ip_address; + usi->conn->updatePeer(req->peer_id, req->info_hash, ip, req->port, + req->downloaded, req->left, req->uploaded, event); return 0; } @@ -373,6 +379,13 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) return 0; } + if (!usi->conn->verifyConnectionId(sR->connection_id, + m_hton32(remote->sin_addr.s_addr), + m_hton16(remote->sin_port))) + { + return 1; + } + // get torrent count. c = v / 20; @@ -382,7 +395,6 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) for (i = 0;i < c;i++) { - int32_t s, c, l; int32_t *seeders, *completed, *leechers; @@ -398,11 +410,17 @@ static uint64_t _get_connID (SOCKADDR_IN *remote) completed = (int32_t*)&buffer[i*12+12]; leechers = (int32_t*)&buffer[i*12+16]; - db_get_stats (usi->conn, hash, &s, &l, &c); + DatabaseDriver::TorrentEntry tE; + tE.info_hash = hash; + if (!usi->conn->getTorrentInfo(&tE)) + { + sendError(usi, remote, sR->transaction_id, "Scrape Failed: couldn't retrieve torrent data"); + return 0; + } - *seeders = m_hton32 (s); - *completed = m_hton32 (c); - *leechers = m_hton32 (l); + *seeders = m_hton32 (tE.seeders); + *completed = m_hton32 (tE.completed); + *leechers = m_hton32 (tE.leechers); } cout.flush(); @@ -436,7 +454,7 @@ static int _isIANA_IP (uint32_t ip) } } - cout << ":: " << (void*)remote->sin_addr.s_addr << ": " << remote->sin_port << " ACTION=" << action << endl; + cout << ":: " << (void*)m_hton32(remote->sin_addr.s_addr) << ": " << m_hton16(remote->sin_port) << " ACTION=" << action << endl; if (action == 0 && r >= 16) return UDPTracker::handleConnection (usi, remote, data); @@ -499,10 +517,10 @@ static int _isIANA_IP (uint32_t ip) while (usi->isRunning) { - db_cleanup (usi->conn); + usi->conn->cleanup(); #ifdef WIN32 - Sleep (usi->cleanup_interval * 1000); // wait 2 minutes between every cleanup. + Sleep (usi->cleanup_interval * 1000); #elif defined (linux) sleep (usi->cleanup_interval); #else diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 864886f..f0bd18e 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -23,7 +23,7 @@ #include #include "multiplatform.h" -#include "db/database.h" +#include "db/driver_sqlite.hpp" #include "settings.hpp" #include @@ -142,7 +142,7 @@ namespace UDPT uint8_t settings; Settings *o_settings; - dbConnection *conn; + Data::DatabaseDriver *conn; #ifdef WIN32 static DWORD _thread_start (LPVOID arg); From 08870bb524b8aca8c6e2f2d52cb16436de5cdd22 Mon Sep 17 00:00:00 2001 From: Naim A Date: Wed, 6 Mar 2013 00:55:29 +0200 Subject: [PATCH 22/99] The start of HTTP API development --- src/http/httpserver.cpp | 203 ++++++++++++++++++++++++++++++++++++++++ src/http/httpserver.hpp | 110 ++++++++++++++++++++++ 2 files changed, 313 insertions(+) create mode 100644 src/http/httpserver.cpp create mode 100644 src/http/httpserver.hpp diff --git a/src/http/httpserver.cpp b/src/http/httpserver.cpp new file mode 100644 index 0000000..8c67baf --- /dev/null +++ b/src/http/httpserver.cpp @@ -0,0 +1,203 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "httpserver.hpp" +#include "../tools.h" + +namespace UDPT +{ + namespace API + { + HTTPServer::HTTPServer (uint16_t port, int threads) + { + int r; + + this->thread_count = threads; + this->threads = new HANDLE [threads]; + + SOCKADDR_IN endpoint; + endpoint.sin_family = AF_INET; + endpoint.sin_port = m_hton16(port); + endpoint.sin_addr.s_addr = 0L; + + this->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (this->sock == INVALID_SOCKET) + throw APIException("Invalid Socket"); + + r = bind(this->sock, (SOCKADDR*)&endpoint, sizeof(SOCKADDR_IN)); + if (r == SOCKET_ERROR) + throw APIException("Failed to bind port."); + + this->isRunning = true; + + this->rootNode.name = ""; + this->rootNode.children.clear(); + this->rootNode.callback = NULL; + + for (int i = 0;i < threads;i++) + { +#ifdef WIN32 + this->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&HTTPServer::doServe, (LPVOID)this, 0, NULL); +#else + pthread_create (&this->threads[0], NULL, HTTPServer::doServe, (void*)this); +#endif + } + } + +#ifdef WIN32 + DWORD HTTPServer::doServe (LPVOID arg) +#else + void* HTTPServer::doServe (void* arg) +#endif + { + HTTPServer *srv = (HTTPServer*)arg; + int r; + SOCKADDR addr; + int addrSz = sizeof (addr); + SOCKET conn; + + while (srv->isRunning) + { + r = listen (srv->sock, SOMAXCONN); + if (r == SOCKET_ERROR) + throw APIException("Failed to listen"); + + addrSz = sizeof (addr); + + conn = accept(srv->sock, &addr, &addrSz); + if (conn == INVALID_SOCKET) + { + continue; + } + cout << "A" << endl; + + Request req = Request (conn, &addr); + Response resp = Response (conn); + + HTTPServer::handleConnection(srv, &req, &resp); + closesocket(conn); + } + +#ifdef WIN32 + return 0; +#else + return NULL; +#endif + } + + void HTTPServer::handleConnection (HTTPServer *srv, Request *req, Response *resp) + { + // follow path... + serveNode *cNode = &srv->rootNode; + list::iterator it; + for (it = req->path.begin();(it != req->path.end() && cNode != NULL);it++) + { + if ((*it).length() == 0) + continue; // same node. + + map::iterator np; + np = cNode->children.find((*it)); + if (np == srv->rootNode.children.end()) + { + cNode = NULL; + break; + } + else + cNode = &np->second; + } + + if (cNode->callback != NULL) + cNode->callback (req, resp); + else + { + // TODO: add HTTP error handler (404 NOT FOUND...) + cout << "Page Not Found" << endl; + } + } + + list HTTPServer::split (const string str, const string del) + { + list lst; + + unsigned s, e; + s = e = 0; + + while (true) + { + e = str.find(del, s); + + if (e == string::npos) + e = str.length(); + + if (e == str.length()) + break; + s = e + del.length(); + } + + return lst; + } + + void HTTPServer::addApplication (const string path, srvCallback *callback) + { + list p = split (path, "/"); + list::iterator it; + + serveNode *node = &this->rootNode; + + for (it = p.begin();it != p.end();it++) + { + if ((*it).length() == 0) + continue; // same node... + + node = &node->children[*it]; + node->name = *it; + } + node->callback = callback; + } + + HTTPServer::~HTTPServer() + { + this->isRunning = false; + closesocket(this->sock); + for (int i = 0;i < this->thread_count;i++) + { +#ifdef WIN32 + TerminateThread(this->threads[i], 0); +#else + pthread_detach (this->threads[i]); + pthread_cancel (this->threads[i]); +#endif + } + delete[] this->threads; + } + + + HTTPServer::Request::Request(SOCKET sock, const SOCKADDR *sa) + { + this->sock = sock; + this->sock_addr = sa; + } + + HTTPServer::Response::Response(SOCKET sock) + { + + } + + }; +}; diff --git a/src/http/httpserver.hpp b/src/http/httpserver.hpp new file mode 100644 index 0000000..eb42412 --- /dev/null +++ b/src/http/httpserver.hpp @@ -0,0 +1,110 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#ifndef HTTPSERVER_HPP_ +#define HTTPSERVER_HPP_ + +#include +#include +#include +#include +#include +#include "../multiplatform.h" + +using namespace std; + +namespace UDPT +{ + namespace API + { + class APIException + { + public: + inline + APIException (const string msg) + { + this->msg = msg; + } + + private: + string msg; + }; + + class HTTPServer + { + public: + class Request + { + public: + Request (SOCKET sock, const SOCKADDR *sock_addr); + private: + friend class HTTPServer; + + SOCKET sock; + multimap headers; + list path; // /some/path + map query; // a=b&c=d + const SOCKADDR *sock_addr; // IP address+family + + void loadAndParse (); + }; + class Response + { + public: + Response (SOCKET sock); + + private: + friend class HTTPServer; + }; + + typedef int (srvCallback) (Request *, Response *); + + HTTPServer (uint16_t port, int threads); + + void addApplication (const string path, srvCallback *callback); + + virtual ~HTTPServer (); + + + static list split (const string str, const string del); + private: + typedef struct _serve_node { + string name; // part of path name + map children; + srvCallback *callback; + } serveNode; + + bool isRunning; + serveNode rootNode; + SOCKET sock; + int thread_count; + HANDLE *threads; + +#ifdef WIN32 + static DWORD doServe (LPVOID arg); +#else + static void* doServe (void* arg); +#endif + + static void handleConnection (HTTPServer *, Request *, Response *); + }; + }; +}; + +#endif /* HTTPSERVER_HPP_ */ From 485b490b9aad53530a19d3883fd856495f69996e Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 7 Mar 2013 17:37:31 +0200 Subject: [PATCH 23/99] minor Linux fixes --- src/db/driver_sqlite.cpp | 48 ++++++++++++++++++---------------------- src/multiplatform.h | 5 +++++ src/udpTracker.cpp | 25 +++++++++++++-------- 3 files changed, 43 insertions(+), 35 deletions(-) diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp index 8d6f83e..5f75429 100644 --- a/src/db/driver_sqlite.cpp +++ b/src/db/driver_sqlite.cpp @@ -18,14 +18,14 @@ */ #include "driver_sqlite.hpp" -#include "../multiplatform.h" #include "../tools.h" -#include -#include +#include +#include #include #include -#include #include +#include // memcpy +#include "../multiplatform.h" using namespace std; @@ -146,21 +146,18 @@ namespace UDPT bool SQLite3Driver::getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe) { - char sql [1000]; + string sql; char hash [50]; sqlite3_stmt *stmt; - int r, - i; - - sql[0] = '\0'; + int r, i; to_hex_str(info_hash, hash); - strcat(sql, "SELECT ip,port FROM 't"); - strcat(sql, hash); - strcat(sql, "' LIMIT ?"); + sql = "SELECT ip,port FROM 't"; + sql += hash; + sql += "' LIMIT ?"; - sqlite3_prepare(this->db, sql, -1, &stmt, NULL); + sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL); sqlite3_bind_int(stmt, 1, *max_count); i = 0; @@ -196,7 +193,7 @@ namespace UDPT { char xHash [50]; // we just need 40 + \0 = 41. sqlite3_stmt *stmt; - char sql [1000]; + string sql; int r; char *hash = xHash; @@ -205,14 +202,13 @@ namespace UDPT addTorrent (info_hash); - sql[0] = '\0'; - strcat(sql, "REPLACE INTO 't"); - strcat(sql, hash); - strcat(sql, "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)"); + sql = "REPLACE INTO 't"; + sql += hash; + sql += "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)"; // printf("IP->%x::%u\n", pE->ip, pE->port); - sqlite3_prepare(this->db, sql, -1, &stmt, NULL); + sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL); sqlite3_bind_blob(stmt, 1, (void*)peer_id, 20, NULL); sqlite3_bind_blob(stmt, 2, (void*)&ip, 4, NULL); @@ -225,8 +221,8 @@ namespace UDPT r = sqlite3_step(stmt); sqlite3_finalize(stmt); - strcpy(sql, "REPLACE INTO stats (info_hash,last_mod) VALUES (?,?)"); - sqlite3_prepare (this->db, sql, -1, &stmt, NULL); + sql = "REPLACE INTO stats (info_hash,last_mod) VALUES (?,?)"; + sqlite3_prepare (this->db, sql.c_str(), sql.length(), &stmt, NULL); sqlite3_bind_blob (stmt, 1, hash, 20, NULL); sqlite3_bind_int (stmt, 2, time(NULL)); sqlite3_step (stmt); @@ -375,17 +371,17 @@ namespace UDPT bool SQLite3Driver::removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port) { - char sql [1000]; + string sql; char xHash [50]; sqlite3_stmt *stmt; _to_hex_str (info_hash, xHash); - strcpy (sql, "DELETE FROM 't"); - strcat (sql, xHash); - strcat (sql, "' WHERE ip=? AND port=? AND peer_id=?"); + sql += "DELETE FROM 't"; + sql += xHash; + sql += "' WHERE ip=? AND port=? AND peer_id=?"; - sqlite3_prepare (this->db, sql, -1, &stmt, NULL); + sqlite3_prepare (this->db, sql.c_str(), sql.length(), &stmt, NULL); sqlite3_bind_blob(stmt, 0, (const void*)&ip, 4, NULL); sqlite3_bind_blob(stmt, 1, (const void*)&port, 2, NULL); diff --git a/src/multiplatform.h b/src/multiplatform.h index cc2acbb..97b5d4c 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -16,6 +16,9 @@ * You should have received a copy of the GNU General Public License * along with UDPT. If not, see . */ +/* + * NOTE: keep this header after standard C/C++ headers + */ #include @@ -49,7 +52,9 @@ typedef void* LPVOID; typedef void (LPTHREAD_START_ROUTINE)(LPVOID); typedef pthread_t HANDLE; +#ifndef min #define min(a,b) (a > b ? b : a) +#endif #define VERSION "1.0.0-alpha (Linux)" #endif diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index 391a80f..555fb51 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -17,13 +17,14 @@ * along with UDPT. If not, see . */ -#include "multiplatform.h" #include "udpTracker.hpp" #include "tools.h" -#include -#include - +#include // atoi +#include +#include #include +#include "multiplatform.h" + using namespace std; using namespace UDPT::Data; @@ -124,8 +125,8 @@ namespace UDPT #ifdef WIN32 TerminateThread (this->threads[i], 0x00); #elif defined (linux) - pthread_detach (usi->threads[i]); - pthread_cancel (usi->threads[i]); + pthread_detach (this->threads[i]); + pthread_cancel (this->threads[i]); #endif cout << "Thread (" << ( i + 1) << "/" << ((int)this->thread_count) << ") terminated." << endl; } @@ -177,7 +178,7 @@ namespace UDPT #ifdef WIN32 this->threads[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_maintainance_start, (LPVOID)this, 0, NULL); #elif defined (linux) - pthread_create (&usi->threads[0], NULL, _maintainance_start, (void*)this); + pthread_create (&this->threads[0], NULL, _maintainance_start, (void*)this); #endif for (i = 1;i < this->thread_count; i++) @@ -480,8 +481,14 @@ static int _isIANA_IP (uint32_t ip) { UDPTracker *usi; SOCKADDR_IN remoteAddr; - int addrSz, - r; + +#ifdef linux + socklen_t addrSz; +#else + int addrSz; +#endif + + int r; char tmpBuff [UDP_BUFFER_SIZE]; usi = (UDPTracker*)arg; From 6666d795e3332f9e6b761185ef60b38a29895d50 Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 8 Mar 2013 02:42:02 +0200 Subject: [PATCH 24/99] HTTP API comming soon... --- src/http/httpserver.cpp | 146 +++++++++++++++++++++++++++++++++++++--- src/http/httpserver.hpp | 27 +++++++- src/main.cpp | 12 ++++ src/multiplatform.h | 7 +- src/settings.cpp | 4 ++ 5 files changed, 181 insertions(+), 15 deletions(-) diff --git a/src/http/httpserver.cpp b/src/http/httpserver.cpp index 8c67baf..1ab35f8 100644 --- a/src/http/httpserver.cpp +++ b/src/http/httpserver.cpp @@ -18,8 +18,12 @@ */ #include "httpserver.hpp" +#include +#include #include "../tools.h" +#define REQBUFFSZ 2048 // enough for all headers. + namespace UDPT { namespace API @@ -69,7 +73,14 @@ namespace UDPT HTTPServer *srv = (HTTPServer*)arg; int r; SOCKADDR addr; - int addrSz = sizeof (addr); + +#ifdef linux + socklen_t addrSz; +#else + int addrSz; +#endif + + addrSz = sizeof (addr); SOCKET conn; while (srv->isRunning) @@ -85,12 +96,15 @@ namespace UDPT { continue; } - cout << "A" << endl; - Request req = Request (conn, &addr); - Response resp = Response (conn); + try { + Request req = Request (conn, &addr); + Response resp = Response (conn); - HTTPServer::handleConnection(srv, &req, &resp); + HTTPServer::handleConnection(srv, &req, &resp); + } catch (...) { + cout << "ERR OCC" << endl; + } closesocket(conn); } @@ -131,7 +145,7 @@ namespace UDPT } } - list HTTPServer::split (const string str, const string del) + list HTTPServer::split (const string str, const string del, int limit) { list lst; @@ -142,12 +156,15 @@ namespace UDPT { e = str.find(del, s); - if (e == string::npos) + if (e == string::npos || limit - 1 == 0) e = str.length(); - if (e == str.length()) + lst.push_back(str.substr(s, e - s)); + + if (e >= str.length() || limit - 1 == 0) break; s = e + del.length(); + limit--; } return lst; @@ -185,6 +202,7 @@ namespace UDPT #endif } delete[] this->threads; + cout << "ST" << endl; } @@ -192,12 +210,122 @@ namespace UDPT { this->sock = sock; this->sock_addr = sa; + + this->loadAndParse(); + } + + void HTTPServer::Request::loadAndParse () + { + char buffer [REQBUFFSZ]; + int r; + + this->httpVersion.major = 0; + this->httpVersion.minor = 0; + this->requestMethod = RM_UNKNOWN; + this->path.clear(); + this->headers.clear(); + this->query.clear (); + this->str_requestMethod = ""; + + r = recv (this->sock, buffer, REQBUFFSZ, 0); + if (r <= 0) + throw APIException("No data received from client."); + + string request = string (buffer); + list lines = HTTPServer::split(request, "\r\n"); + list::iterator it, begin, end; + begin = lines.begin(); + end = lines.end(); + for (it = begin;it != end;it++) + { + if (it == begin) + { + list hLine = HTTPServer::split(*it, " "); + if (hLine.size() < 3) + throw APIException("Bad Request"); + this->str_requestMethod = hLine.front(); + string httpVersion = hLine.back(); + if (strncmp(httpVersion.c_str(), "HTTP/", 5) != 0) + throw APIException("Unsupported HTTP Version"); + string vn = httpVersion.substr(5); + this->httpVersion.major = atoi (vn.substr(0, vn.find('.')).c_str()); + this->httpVersion.minor = atoi (vn.substr(vn.find('.') + 1).c_str()); + + hLine.pop_front(); + hLine.pop_back(); + string path; + bool isF = true; + while (!hLine.empty()) + { + if (isF) + isF = false; + else + path.append(" "); + path.append(hLine.front()); + hLine.pop_front(); + } + + list parts = HTTPServer::split(path, "?", 2); + if (!parts.empty()) + { + this->path = HTTPServer::split(parts.front(), "/"); + parts.pop_front(); + } + if (!parts.empty()) + { + string qData = parts.front(); + parts.pop_front(); + + string::size_type sK, sV, eK, eV; + sK = sV = eK = eV = 0; + + while (sK < qData.length()) + { + eK = qData.find('=', sK); + if (eK == string::npos) // not valid key + break; + sV = eK + 1; + eV = qData.find('&', sV); + if (eV == string::npos) + eV = qData.length(); + + this->query [qData.substr(sK, eK - sK)] = qData.substr(sV, eV - sV); + + if (eV >= qData.length()) + break; + sK = eV + 1; + } + } + } + else + { + string::size_type p = (*it).find(": "); + if (p == string::npos) + continue; + this->headers.insert(pair( + (*it).substr(0, p), + (*it).substr(p+2) + )); + } + } } HTTPServer::Response::Response(SOCKET sock) { - + this->sock = sock; + this->isHeaderSent = false; + setStatus(200, "OK"); } + void HTTPServer::Response::setStatus (int code, string msg) + { + this->statusCode = code; + this->statusMsg = msg; + } + + void HTTPServer::Response::sendRaw (void *data, int sz) + { + send (this->sock, (const char*)data, sz, 0); + } }; }; diff --git a/src/http/httpserver.hpp b/src/http/httpserver.hpp index eb42412..6e30dca 100644 --- a/src/http/httpserver.hpp +++ b/src/http/httpserver.hpp @@ -42,6 +42,12 @@ namespace UDPT this->msg = msg; } + inline + const string& getMessage () + { + return this->msg; + } + private: string msg; }; @@ -52,10 +58,21 @@ namespace UDPT class Request { public: + enum RequestMethod { + RM_UNKNOWN = 0, + RM_GET = 1 + }; + Request (SOCKET sock, const SOCKADDR *sock_addr); private: friend class HTTPServer; + enum RequestMethod requestMethod; + string str_requestMethod; + struct { + unsigned int major; + unsigned int minor; + } httpVersion; SOCKET sock; multimap headers; list path; // /some/path @@ -64,13 +81,21 @@ namespace UDPT void loadAndParse (); }; + class Response { public: Response (SOCKET sock); + void sendRaw (void*, int); + void setStatus (int code, string msg); + private: friend class HTTPServer; + SOCKET sock; + bool isHeaderSent; + string statusMsg; + int statusCode; }; typedef int (srvCallback) (Request *, Response *); @@ -82,7 +107,7 @@ namespace UDPT virtual ~HTTPServer (); - static list split (const string str, const string del); + static list split (const string str, const string del, int limit = -1); private: typedef struct _serve_node { string name; // part of path name diff --git a/src/main.cpp b/src/main.cpp index 4baba4e..8f5a5df 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -22,6 +22,7 @@ #include "multiplatform.h" #include "udpTracker.hpp" #include "settings.hpp" +#include "http/httpserver.hpp" using namespace std; using namespace UDPT; @@ -78,6 +79,8 @@ int main(int argc, char *argv[]) usi = new UDPTracker (settings); + API::HTTPServer *apiSrv = NULL; + r = usi->start(); if (r != UDPTracker::START_OK) { @@ -97,6 +100,14 @@ int main(int argc, char *argv[]) goto cleanup; } + try{ + apiSrv = new API::HTTPServer(6969, 2); + } catch (API::APIException &ex) + { + cerr << "APIException: " << ex.getMessage() << endl; + goto cleanup; + } + cout << "Press Any key to exit." << endl; cin.get(); @@ -106,6 +117,7 @@ cleanup: delete usi; delete settings; + delete apiSrv; #ifdef WIN32 WSACleanup(); diff --git a/src/multiplatform.h b/src/multiplatform.h index 97b5d4c..8b9c7a4 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -29,7 +29,7 @@ #ifdef WIN32 #include #include -#define VERSION "1.0.0 (Windows)" +#define VERSION "1.0.0-beta (Windows)" #elif defined (linux) #include #include @@ -52,9 +52,6 @@ typedef void* LPVOID; typedef void (LPTHREAD_START_ROUTINE)(LPVOID); typedef pthread_t HANDLE; -#ifndef min -#define min(a,b) (a > b ? b : a) -#endif -#define VERSION "1.0.0-alpha (Linux)" +#define VERSION "1.0.0-beta (Linux)" #endif diff --git a/src/settings.cpp b/src/settings.cpp index 2a7ea99..4253678 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -249,6 +249,8 @@ void _settings_clean_string (char **str) SettingClass *c; c = this->getClass(classN); + if (c == NULL) + return ""; return c->get(name); } @@ -277,6 +279,8 @@ void _settings_clean_string (char **str) string Settings::SettingClass::get (const string name) { + if (this->entries.find(name) == this->entries.end()) + return ""; return this->entries[name]; } From 471c8d8dbaa84a9d15fd1a2ea32565bacc745a90 Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 8 Mar 2013 16:04:49 +0200 Subject: [PATCH 25/99] New Makefile for Linux based systems --- Makefile | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/Makefile b/Makefile index c0f2704..82c89ed 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ # -# Copyright © 2012 Naim A. +# Copyright © 2012,2013 Naim A. # # This file is part of UDPT. # @@ -17,24 +17,26 @@ # along with UDPT. If not, see . # -win32: main.o tools.o udpTracker.o driver_sqlite.o - gcc -static -O3 -o udpt.exe main.o tools.o udpTracker.o driver_sqlite.o -lsqlite3 -lws2_32 +objects = main.o udpTracker.o database.o driver_sqlite.o \ + settings.o tools.o +target = udpt -linux: main.o tools.o udpTracker.o driver_sqlite.o - gcc -static -O3 -o udpt main.o tools.o udpTracker.o driver_sqlite.o -lsqlite3 -lpthreads - -main.o: - gcc -c -O3 -o main.o src/main.c +%.o: src/%.c + $(CC) -c -o $@ $< $(CFLAGS) +%.o: src/%.cpp + $(CXX) -c -o $@ $< $(CXXFLAGS) +%.o: src/db/%.cpp + $(CXX) -c -o $@ $< $(CXXFLAGS) +all: $(target) -tools.o: - gcc -c -O3 -o tools.o src/tools.c - -udpTracker.o: - gcc -c -O3 -o udpTracker.o src/udpTracker.c - -driver_sqlite.o: - gcc -O3 -c -o driver_sqlite.o src/db/driver_sqlite.c - -.PHONY: clean +$(target): $(objects) + @echo Linking... + $(CXX) $(LDFLAGS) -O3 -o $(target) $(objects) -lsqlite3 + @echo Done. clean: - rm -f udpt.exe main.o tools.o udpTracker.o driver_sqlite.o udpt \ No newline at end of file + @echo Cleaning Up... + $(RM) $(objects) $(target) + @echo Done. + +install: $(target) + @echo Installing $(target) to '$(exec_prefix)/bin'... From 876f2da5b715b6e7697051c382ede7dc94728119 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 10 Mar 2013 23:18:37 +0200 Subject: [PATCH 26/99] Recreated HTTP server... --- src/http/httpserver.cpp | 833 ++++++++++++++++++++++++---------------- src/http/httpserver.hpp | 292 +++++++------- src/main.cpp | 9 +- 3 files changed, 664 insertions(+), 470 deletions(-) diff --git a/src/http/httpserver.cpp b/src/http/httpserver.cpp index 1ab35f8..d3fa533 100644 --- a/src/http/httpserver.cpp +++ b/src/http/httpserver.cpp @@ -1,331 +1,502 @@ -/* - * Copyright © 2012,2013 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include "httpserver.hpp" -#include -#include -#include "../tools.h" - -#define REQBUFFSZ 2048 // enough for all headers. - -namespace UDPT -{ - namespace API - { - HTTPServer::HTTPServer (uint16_t port, int threads) - { - int r; - - this->thread_count = threads; - this->threads = new HANDLE [threads]; - - SOCKADDR_IN endpoint; - endpoint.sin_family = AF_INET; - endpoint.sin_port = m_hton16(port); - endpoint.sin_addr.s_addr = 0L; - - this->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (this->sock == INVALID_SOCKET) - throw APIException("Invalid Socket"); - - r = bind(this->sock, (SOCKADDR*)&endpoint, sizeof(SOCKADDR_IN)); - if (r == SOCKET_ERROR) - throw APIException("Failed to bind port."); - - this->isRunning = true; - - this->rootNode.name = ""; - this->rootNode.children.clear(); - this->rootNode.callback = NULL; - - for (int i = 0;i < threads;i++) - { -#ifdef WIN32 - this->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&HTTPServer::doServe, (LPVOID)this, 0, NULL); -#else - pthread_create (&this->threads[0], NULL, HTTPServer::doServe, (void*)this); -#endif - } - } - -#ifdef WIN32 - DWORD HTTPServer::doServe (LPVOID arg) -#else - void* HTTPServer::doServe (void* arg) -#endif - { - HTTPServer *srv = (HTTPServer*)arg; - int r; - SOCKADDR addr; - -#ifdef linux - socklen_t addrSz; -#else - int addrSz; -#endif - - addrSz = sizeof (addr); - SOCKET conn; - - while (srv->isRunning) - { - r = listen (srv->sock, SOMAXCONN); - if (r == SOCKET_ERROR) - throw APIException("Failed to listen"); - - addrSz = sizeof (addr); - - conn = accept(srv->sock, &addr, &addrSz); - if (conn == INVALID_SOCKET) - { - continue; - } - - try { - Request req = Request (conn, &addr); - Response resp = Response (conn); - - HTTPServer::handleConnection(srv, &req, &resp); - } catch (...) { - cout << "ERR OCC" << endl; - } - closesocket(conn); - } - -#ifdef WIN32 - return 0; -#else - return NULL; -#endif - } - - void HTTPServer::handleConnection (HTTPServer *srv, Request *req, Response *resp) - { - // follow path... - serveNode *cNode = &srv->rootNode; - list::iterator it; - for (it = req->path.begin();(it != req->path.end() && cNode != NULL);it++) - { - if ((*it).length() == 0) - continue; // same node. - - map::iterator np; - np = cNode->children.find((*it)); - if (np == srv->rootNode.children.end()) - { - cNode = NULL; - break; - } - else - cNode = &np->second; - } - - if (cNode->callback != NULL) - cNode->callback (req, resp); - else - { - // TODO: add HTTP error handler (404 NOT FOUND...) - cout << "Page Not Found" << endl; - } - } - - list HTTPServer::split (const string str, const string del, int limit) - { - list lst; - - unsigned s, e; - s = e = 0; - - while (true) - { - e = str.find(del, s); - - if (e == string::npos || limit - 1 == 0) - e = str.length(); - - lst.push_back(str.substr(s, e - s)); - - if (e >= str.length() || limit - 1 == 0) - break; - s = e + del.length(); - limit--; - } - - return lst; - } - - void HTTPServer::addApplication (const string path, srvCallback *callback) - { - list p = split (path, "/"); - list::iterator it; - - serveNode *node = &this->rootNode; - - for (it = p.begin();it != p.end();it++) - { - if ((*it).length() == 0) - continue; // same node... - - node = &node->children[*it]; - node->name = *it; - } - node->callback = callback; - } - - HTTPServer::~HTTPServer() - { - this->isRunning = false; - closesocket(this->sock); - for (int i = 0;i < this->thread_count;i++) - { -#ifdef WIN32 - TerminateThread(this->threads[i], 0); -#else - pthread_detach (this->threads[i]); - pthread_cancel (this->threads[i]); -#endif - } - delete[] this->threads; - cout << "ST" << endl; - } - - - HTTPServer::Request::Request(SOCKET sock, const SOCKADDR *sa) - { - this->sock = sock; - this->sock_addr = sa; - - this->loadAndParse(); - } - - void HTTPServer::Request::loadAndParse () - { - char buffer [REQBUFFSZ]; - int r; - - this->httpVersion.major = 0; - this->httpVersion.minor = 0; - this->requestMethod = RM_UNKNOWN; - this->path.clear(); - this->headers.clear(); - this->query.clear (); - this->str_requestMethod = ""; - - r = recv (this->sock, buffer, REQBUFFSZ, 0); - if (r <= 0) - throw APIException("No data received from client."); - - string request = string (buffer); - list lines = HTTPServer::split(request, "\r\n"); - list::iterator it, begin, end; - begin = lines.begin(); - end = lines.end(); - for (it = begin;it != end;it++) - { - if (it == begin) - { - list hLine = HTTPServer::split(*it, " "); - if (hLine.size() < 3) - throw APIException("Bad Request"); - this->str_requestMethod = hLine.front(); - string httpVersion = hLine.back(); - if (strncmp(httpVersion.c_str(), "HTTP/", 5) != 0) - throw APIException("Unsupported HTTP Version"); - string vn = httpVersion.substr(5); - this->httpVersion.major = atoi (vn.substr(0, vn.find('.')).c_str()); - this->httpVersion.minor = atoi (vn.substr(vn.find('.') + 1).c_str()); - - hLine.pop_front(); - hLine.pop_back(); - string path; - bool isF = true; - while (!hLine.empty()) - { - if (isF) - isF = false; - else - path.append(" "); - path.append(hLine.front()); - hLine.pop_front(); - } - - list parts = HTTPServer::split(path, "?", 2); - if (!parts.empty()) - { - this->path = HTTPServer::split(parts.front(), "/"); - parts.pop_front(); - } - if (!parts.empty()) - { - string qData = parts.front(); - parts.pop_front(); - - string::size_type sK, sV, eK, eV; - sK = sV = eK = eV = 0; - - while (sK < qData.length()) - { - eK = qData.find('=', sK); - if (eK == string::npos) // not valid key - break; - sV = eK + 1; - eV = qData.find('&', sV); - if (eV == string::npos) - eV = qData.length(); - - this->query [qData.substr(sK, eK - sK)] = qData.substr(sV, eV - sV); - - if (eV >= qData.length()) - break; - sK = eV + 1; - } - } - } - else - { - string::size_type p = (*it).find(": "); - if (p == string::npos) - continue; - this->headers.insert(pair( - (*it).substr(0, p), - (*it).substr(p+2) - )); - } - } - } - - HTTPServer::Response::Response(SOCKET sock) - { - this->sock = sock; - this->isHeaderSent = false; - setStatus(200, "OK"); - } - - void HTTPServer::Response::setStatus (int code, string msg) - { - this->statusCode = code; - this->statusMsg = msg; - } - - void HTTPServer::Response::sendRaw (void *data, int sz) - { - send (this->sock, (const char*)data, sz, 0); - } - }; -}; +/* + * Copyright © 2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include +#include +#include +#include +#include +#include "httpserver.hpp" + +using namespace std; + +namespace UDPT +{ + namespace Server + { + /* HTTPServer */ + HTTPServer::HTTPServer (uint16_t port, int threads) + { + int r; + SOCKADDR_IN sa; + + this->thread_count = threads; + this->threads = new HANDLE[threads]; + this->isRunning = false; + + this->rootNode.callback = NULL; + + this->srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (this->srv == INVALID_SOCKET) + { + throw ServerException (1, "Failed to create Socket"); + } + + sa.sin_addr.s_addr = 0L; + sa.sin_family = AF_INET; + sa.sin_port = htons (port); + + r = bind (this->srv, (SOCKADDR*)&sa, sizeof(sa)); + if (r == SOCKET_ERROR) + { + throw ServerException (2, "Failed to bind socket"); + } + + this->isRunning = true; + for (int i = 0;i < threads;i++) + { +#ifdef WIN32 + this->threads[i] = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, this, 0, NULL); +#else + pthread_create (&this->threads[i], NULL, &HTTPServer::_thread_start, this); +#endif + } + } + +#ifdef WIN32 + DWORD HTTPServer::_thread_start (LPVOID arg) +#else + void* HTTPServer::_thread_start (void *arg) +#endif + { + HTTPServer *s = (HTTPServer*)arg; +doSrv: + try { + HTTPServer::handleConnections (s); + } catch (ServerException &se) + { + cerr << "SRV ERR #" << se.getErrorCode() << ": " << se.getErrorMsg () << endl; + goto doSrv; + } + return 0; + } + + void HTTPServer::handleConnections (HTTPServer *server) + { + int r; +#ifdef WIN32 + int addrSz; +#else + socklen_t addrSz; +#endif + SOCKADDR_IN addr; + SOCKET cli; + + while (server->isRunning) + { + r = listen (server->srv, 50); + if (r == SOCKET_ERROR) + { +#ifdef WIN32 + Sleep (500); +#else + sleep (1); +#endif + continue; + } + addrSz = sizeof addr; + cli = accept (server->srv, (SOCKADDR*)&addr, &addrSz); + if (cli == INVALID_SOCKET) + continue; + + Response resp (cli); // doesn't throw exceptions. + + try { + Request req (cli, &addr); // may throw exceptions. + reqCallback *cb = getRequestHandler (&server->rootNode, req.getPath()); + if (cb == NULL) + { + // error 404 + resp.setStatus (404, "Not Found"); + resp.addHeader ("Content-Type", "text/html; charset=US-ASCII"); + stringstream stream; + stream << ""; + stream << "Not Found"; + stream << "

Not Found

The server couldn't find the request resource.


© 2013 Naim A. | ContactMe server
"; + stream << ""; + string str = stream.str(); + resp.write (str.c_str(), str.length()); + } + else + { + try { + cb (server, &req, &resp); + } catch (...) + { + // error 500 + } + } + } catch (ServerException &e) + { + // Error 400 Bad Request! + } + + closesocket (cli); + } + } + + void HTTPServer::addApp (list *path, reqCallback *cb) + { + list::iterator it = path->begin(); + appNode *node = &this->rootNode; + while (it != path->end()) + { + map::iterator se; + se = node->nodes.find (*it); + if (se == node->nodes.end()) + { + node->nodes[*it].callback = NULL; + } + node = &node->nodes[*it]; + it++; + } + node->callback = cb; + } + + HTTPServer::reqCallback* HTTPServer::getRequestHandler (appNode *node, list *path) + { + appNode *cn = node; + list::iterator it = path->begin(), + end = path->end(); + map::iterator n; + while (true) + { + if (it == end) + { + return cn->callback; + } + + n = cn->nodes.find (*it); + if (n == cn->nodes.end()) + return NULL; // node not found! + cn = &n->second; + + it++; + } + return NULL; + } + + HTTPServer::~HTTPServer () + { + if (this->srv != INVALID_SOCKET) + closesocket (this->srv); + + if (this->isRunning) + { + for (int i = 0;i < this->thread_count;i++) + { +#ifdef WIN32 + TerminateThread (this->threads[i], 0x00); +#else + pthread_detach (this->threads[i]); + pthread_cancel (this->threads[i]); +#endif + } + } + + delete[] this->threads; + } + + /* HTTPServer::Request */ + HTTPServer::Request::Request (SOCKET cli, const SOCKADDR_IN *addr) + { + this->conn = cli; + this->addr = addr; + + this->parseRequest (); + } + + inline static char* nextReqLine (int &cPos, char *buff, int len) + { + for (int i = cPos;i < len - 1;i++) + { + if (buff[i] == '\r' && buff[i + 1] == '\n') + { + buff[i] = '\0'; + + int r = cPos; + cPos = i + 2; + return (buff + r); + } + } + + return (buff + len); // end + } + + inline void parseURL (string request, list *path, map *params) + { + string::size_type p; + string query, url; + p = request.find ('?'); + if (p == string::npos) + { + p = request.length(); + } + else + { + query = request.substr (p + 1); + } + url = request.substr (0, p); + + path->clear (); + string::size_type s, e; + s = 0; + while (true) + { + e = url.find ('/', s); + if (e == string::npos) + e = url.length(); + + string x = url.substr (s, e - s); + if (!(x.length() == 0 || x == ".")) + { + if (x == "..") + { + if (path->empty()) + throw ServerException (1, "Hack attempt"); + else + path->pop_back (); + } + path->push_back (x); + } + + if (e == url.length()) + break; + s = e + 1; + } + + string::size_type vS, vE, kS, kE; + vS = vE = kS = kE = 0; + while (kS < query.length()) + { + kE = query.find ('=', kS); + if (kE == string::npos) break; + vS = kE + 1; + vE = query.find ('&', vS); + if (vE == string::npos) vE = query.length(); + + params->insert (pair( query.substr (kS, kE - kS), query.substr (vS, vE - vS) )); + + kS = vE + 1; + } + } + + inline void setCookies (string &data, map *cookies) + { + string::size_type kS, kE, vS, vE; + kS = 0; + while (kS < data.length ()) + { + kE = data.find ('=', kS); + if (kE == string::npos) + break; + vS = kE + 1; + vE = data.find ("; ", vS); + if (vE == string::npos) + vE = data.length(); + + (*cookies) [data.substr (kS, kE-kS)] = data.substr (vS, vE-vS); + + kS = vE + 2; + } + } + + void HTTPServer::Request::parseRequest () + { + char buffer [REQUEST_BUFFER_SIZE]; + int r; + r = recv (this->conn, buffer, REQUEST_BUFFER_SIZE, 0); + if (r == REQUEST_BUFFER_SIZE) + throw ServerException (1, "Request Size too big."); + if (r <= 0) + throw ServerException (2, "Socket Error"); + + char *cLine; + int n = 0; + int pos = 0; + string::size_type p; + while ( (cLine = nextReqLine (pos, buffer, r)) < (buffer + r)) + { + string line = string (cLine); + if (line.length() == 0) break; // CRLF CRLF = end of headers. + n++; + + if (n == 1) + { + string::size_type uS, uE; + p = line.find (' '); + if (p == string::npos) + throw ServerException (5, "Malformed request method"); + uS = p + 1; + this->requestMethod.str = line.substr (0, p); + + if (this->requestMethod.str == "GET") + this->requestMethod.rm = RM_GET; + else if (this->requestMethod.str == "POST") + this->requestMethod.rm = RM_POST; + else + this->requestMethod.rm = RM_UNKNOWN; + + uE = uS; + while (p < line.length()) + { + if (p == string::npos) + break; + p = line.find (' ', p + 1); + if (p == string::npos) + break; + uE = p; + } + if (uE + 1 >= line.length()) + throw ServerException (6, "Malformed request"); + string httpVersion = line.substr (uE + 1); + + + parseURL (line.substr (uS, uE - uS), &this->path, &this->params); + } + else + { + p = line.find (": "); + if (p == string::npos) + throw ServerException (4, "Malformed headers"); + string key = line.substr (0, p); + string value = line.substr (p + 2); + if (key != "Cookie") + this->headers.insert(pair( key, value)); + else + setCookies (value, &this->cookies); + } + } + if (n == 0) + throw ServerException (3, "No Request header."); + } + + list* HTTPServer::Request::getPath () + { + return &this->path; + } + + string HTTPServer::Request::getParam (const string key) + { + map::iterator it = this->params.find (key); + if (it == this->params.end()) + return ""; + else + return it->second; + } + + multimap::iterator HTTPServer::Request::getHeader (const string name) + { + multimap::iterator it = this->headers.find (name); + return it; + } + + HTTPServer::Request::RequestMethod HTTPServer::Request::getRequestMethod () + { + return this->requestMethod.rm; + } + + string HTTPServer::Request::getRequestMethodStr () + { + return this->requestMethod.str; + } + + string HTTPServer::Request::getCookie (const string name) + { + map::iterator it = this->cookies.find (name); + if (it == this->cookies.end()) + return ""; + else + return it->second; + } + + const SOCKADDR_IN* HTTPServer::Request::getAddress () + { + return this->addr; + } + + /* HTTPServer::Response */ + HTTPServer::Response::Response (SOCKET cli) + { + this->conn = cli; + this->headerSent = false; + + setStatus (200, "OK"); + } + + void HTTPServer::Response::setStatus (int c, const string m) + { + if (headerSent) + throw ServerException (2, "Can't set status."); + + this->status_code = c; + this->status_msg = m; + } + + void HTTPServer::Response::addHeader (string key, string value) + { + if (headerSent) + throw ServerException (1, "Headers already sent."); + this->headers.insert (pair(key, value)); + } + + void HTTPServer::Response::write (const char *data, int len) + { + if (!this->headerSent) + sendHeaders (); + if (len < 0) + len = strlen (data); + writeRaw (data, len); + } + + void HTTPServer::Response::sendHeaders () + { + if (this->headerSent) + return; + + this->headerSent = true; + + addHeader ("Server", "ContactMe"); + + stringstream stream; + stream << "HTTP/1.1 " << this->status_code << " " << this->status_msg << "\r\n"; + stream << "Connection: Close\r\n"; + + multimap::iterator it; + for (it = this->headers.begin(); it != this->headers.end(); it++) + { + stream << it->first << ": " << it->second << "\r\n"; + } + this->headers.clear(); + stream << "\r\n"; + string str = stream.str(); + writeRaw (str.c_str(), str.length()); + } + + bool HTTPServer::Response::isHeadersSent () const + { + return this->headerSent; + } + + int HTTPServer::Response::writeRaw (const char *data, int len) + { + return send (this->conn, data, len, 0); + } + }; +}; diff --git a/src/http/httpserver.hpp b/src/http/httpserver.hpp index 6e30dca..510d0db 100644 --- a/src/http/httpserver.hpp +++ b/src/http/httpserver.hpp @@ -1,135 +1,157 @@ -/* - * Copyright © 2012,2013 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#ifndef HTTPSERVER_HPP_ -#define HTTPSERVER_HPP_ - -#include -#include -#include -#include -#include -#include "../multiplatform.h" - -using namespace std; - -namespace UDPT -{ - namespace API - { - class APIException - { - public: - inline - APIException (const string msg) - { - this->msg = msg; - } - - inline - const string& getMessage () - { - return this->msg; - } - - private: - string msg; - }; - - class HTTPServer - { - public: - class Request - { - public: - enum RequestMethod { - RM_UNKNOWN = 0, - RM_GET = 1 - }; - - Request (SOCKET sock, const SOCKADDR *sock_addr); - private: - friend class HTTPServer; - - enum RequestMethod requestMethod; - string str_requestMethod; - struct { - unsigned int major; - unsigned int minor; - } httpVersion; - SOCKET sock; - multimap headers; - list path; // /some/path - map query; // a=b&c=d - const SOCKADDR *sock_addr; // IP address+family - - void loadAndParse (); - }; - - class Response - { - public: - Response (SOCKET sock); - - void sendRaw (void*, int); - void setStatus (int code, string msg); - - private: - friend class HTTPServer; - SOCKET sock; - bool isHeaderSent; - string statusMsg; - int statusCode; - }; - - typedef int (srvCallback) (Request *, Response *); - - HTTPServer (uint16_t port, int threads); - - void addApplication (const string path, srvCallback *callback); - - virtual ~HTTPServer (); - - - static list split (const string str, const string del, int limit = -1); - private: - typedef struct _serve_node { - string name; // part of path name - map children; - srvCallback *callback; - } serveNode; - - bool isRunning; - serveNode rootNode; - SOCKET sock; - int thread_count; - HANDLE *threads; - -#ifdef WIN32 - static DWORD doServe (LPVOID arg); -#else - static void* doServe (void* arg); -#endif - - static void handleConnection (HTTPServer *, Request *, Response *); - }; - }; -}; - -#endif /* HTTPSERVER_HPP_ */ +/* + * Copyright © 2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#pragma once + +#include +#include +#include +#include +#include "../multiplatform.h" +using namespace std; + +#define REQUEST_BUFFER_SIZE 2048 + +namespace UDPT +{ + namespace Server + { + class ServerException + { + public: + inline ServerException (int ec) + { + this->ec = ec; + this->em = NULL; + } + + inline ServerException (int ec, const char *em) + { + this->ec = ec; + this->em = em; + } + + inline const char *getErrorMsg () const + { + return this->em; + } + + inline int getErrorCode () const + { + return this->ec; + } + private: + int ec; + const char *em; + }; + + class HTTPServer + { + public: + class Request + { + public: + enum RequestMethod + { + RM_UNKNOWN = 0, + RM_GET = 1, + RM_POST = 2 + }; + + Request (SOCKET, const SOCKADDR_IN *); + list* getPath (); + + string getParam (const string key); + multimap::iterator getHeader (const string name); + RequestMethod getRequestMethod (); + string getRequestMethodStr (); + string getCookie (const string name); + const SOCKADDR_IN* getAddress (); + + private: + const SOCKADDR_IN *addr; + SOCKET conn; + struct { + int major; + int minor; + } httpVer; + struct { + string str; + RequestMethod rm; + } requestMethod; + list path; + map params; + map cookies; + multimap headers; + + void parseRequest (); + }; + + class Response + { + public: + Response (SOCKET conn); + + void setStatus (int, const string); + void addHeader (string key, string value); + void sendHeaders (); + int writeRaw (const char *data, int len); + void write (const char *data, int len = -1); + bool isHeadersSent () const; + private: + SOCKET conn; + int status_code; + string status_msg; + multimap headers; + bool headerSent; + }; + + typedef void (reqCallback)(HTTPServer*,Request*,Response*); + + HTTPServer (uint16_t port, int threads); + + void addApp (list *path, reqCallback *); + + virtual ~HTTPServer (); + + private: + typedef struct appNode + { + reqCallback *callback; + map nodes; + } appNode; + + SOCKET srv; + int thread_count; + HANDLE *threads; + bool isRunning; + appNode rootNode; + + static void handleConnections (HTTPServer *); + +#ifdef WIN32 + static DWORD _thread_start (LPVOID); +#else + static void* _thread_start (void*); +#endif + + static reqCallback* getRequestHandler (appNode *, list *); + }; + }; +}; diff --git a/src/main.cpp b/src/main.cpp index 8f5a5df..48a2148 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -26,6 +26,7 @@ using namespace std; using namespace UDPT; +using namespace UDPT::Server; static void _print_usage () { @@ -79,7 +80,7 @@ int main(int argc, char *argv[]) usi = new UDPTracker (settings); - API::HTTPServer *apiSrv = NULL; + HTTPServer *apiSrv = NULL; r = usi->start(); if (r != UDPTracker::START_OK) @@ -101,10 +102,10 @@ int main(int argc, char *argv[]) } try{ - apiSrv = new API::HTTPServer(6969, 2); - } catch (API::APIException &ex) + apiSrv = new HTTPServer(6969, 8); + } catch (ServerException &ex) { - cerr << "APIException: " << ex.getMessage() << endl; + cerr << "ServerException #" << ex.getErrorCode() << ": " << ex.getErrorMsg() << endl; goto cleanup; } From 5c57728630c25eecf5c3ab505b3650f2ced71bbb Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 21 Mar 2013 02:44:10 +0200 Subject: [PATCH 27/99] A bit API Progress... --- src/http/httpserver.cpp | 81 ++++++++++---------- src/http/httpserver.hpp | 15 +++- src/http/webapp.cpp | 158 ++++++++++++++++++++++++++++++++++++++++ src/http/webapp.hpp | 55 ++++++++++++++ src/main.cpp | 6 ++ src/settings.cpp | 5 ++ src/settings.hpp | 1 + src/udpTracker.hpp | 2 +- 8 files changed, 279 insertions(+), 44 deletions(-) create mode 100644 src/http/webapp.cpp create mode 100644 src/http/webapp.hpp diff --git a/src/http/httpserver.cpp b/src/http/httpserver.cpp index d3fa533..c32a2b9 100644 --- a/src/http/httpserver.cpp +++ b/src/http/httpserver.cpp @@ -128,7 +128,7 @@ doSrv: stringstream stream; stream << ""; stream << "Not Found"; - stream << "

Not Found

The server couldn't find the request resource.


© 2013 Naim A. | ContactMe server
"; + stream << "

Not Found

The server couldn't find the request resource.


© 2013 Naim A. | The UDPT Project
"; stream << ""; string str = stream.str(); resp.write (str.c_str(), str.length()); @@ -139,9 +139,18 @@ doSrv: cb (server, &req, &resp); } catch (...) { - // error 500 + resp.setStatus(500, "Internal Server Error"); + resp.addHeader ("Content-Type", "text/html; charset=US-ASCII"); + stringstream stream; + stream << ""; + stream << "Internal Server Error"; + stream << "

Internal Server Error

An Error Occurred while trying to process your request.


© 2013 Naim A. | The UDPT Project
"; + stream << ""; + string str = stream.str(); + resp.write (str.c_str(), str.length()); } } + resp.finalize(); } catch (ServerException &e) { // Error 400 Bad Request! @@ -192,6 +201,19 @@ doSrv: return NULL; } + void HTTPServer::setData(string k, void *d) + { + this->customData[k] = d; + } + + void* HTTPServer::getData(string k) + { + map::iterator it = this->customData.find(k); + if (it == this->customData.end()) + return NULL; + return it->second; + } + HTTPServer::~HTTPServer () { if (this->srv != INVALID_SOCKET) @@ -435,68 +457,47 @@ doSrv: HTTPServer::Response::Response (SOCKET cli) { this->conn = cli; - this->headerSent = false; setStatus (200, "OK"); } void HTTPServer::Response::setStatus (int c, const string m) { - if (headerSent) - throw ServerException (2, "Can't set status."); - this->status_code = c; this->status_msg = m; } void HTTPServer::Response::addHeader (string key, string value) { - if (headerSent) - throw ServerException (1, "Headers already sent."); this->headers.insert (pair(key, value)); } void HTTPServer::Response::write (const char *data, int len) { - if (!this->headerSent) - sendHeaders (); if (len < 0) len = strlen (data); - writeRaw (data, len); + msg.write(data, len); } - - void HTTPServer::Response::sendHeaders () - { - if (this->headerSent) - return; - - this->headerSent = true; - - addHeader ("Server", "ContactMe"); - stringstream stream; - stream << "HTTP/1.1 " << this->status_code << " " << this->status_msg << "\r\n"; - stream << "Connection: Close\r\n"; - - multimap::iterator it; - for (it = this->headers.begin(); it != this->headers.end(); it++) + void HTTPServer::Response::finalize () + { + stringstream x; + x << "HTTP/1.1 " << this->status_code << " " << this->status_msg << "\r\n"; + multimap::iterator it, end; + end = this->headers.end(); + for (it = this->headers.begin(); it != end;it++) { - stream << it->first << ": " << it->second << "\r\n"; + x << it->first << ": " << it->second << "\r\n"; } - this->headers.clear(); - stream << "\r\n"; - string str = stream.str(); - writeRaw (str.c_str(), str.length()); - } - - bool HTTPServer::Response::isHeadersSent () const - { - return this->headerSent; + x << "Connection: Close\r\n"; + x << "Content-Length: " << this->msg.tellp() << "\r\n"; + x << "Server: udpt\r\n"; + x << "\r\n"; + x << this->msg.str(); + + // write to socket + send (this->conn, x.str().c_str(), x.str().length(), 0); } - int HTTPServer::Response::writeRaw (const char *data, int len) - { - return send (this->conn, data, len, 0); - } }; }; diff --git a/src/http/httpserver.hpp b/src/http/httpserver.hpp index 510d0db..4a32e0a 100644 --- a/src/http/httpserver.hpp +++ b/src/http/httpserver.hpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include "../multiplatform.h" using namespace std; @@ -110,16 +111,20 @@ namespace UDPT void setStatus (int, const string); void addHeader (string key, string value); - void sendHeaders (); + int writeRaw (const char *data, int len); void write (const char *data, int len = -1); - bool isHeadersSent () const; + private: + friend class HTTPServer; + SOCKET conn; int status_code; string status_msg; multimap headers; - bool headerSent; + stringstream msg; + + void finalize (); }; typedef void (reqCallback)(HTTPServer*,Request*,Response*); @@ -128,6 +133,9 @@ namespace UDPT void addApp (list *path, reqCallback *); + void setData (string, void *); + void* getData (string); + virtual ~HTTPServer (); private: @@ -142,6 +150,7 @@ namespace UDPT HANDLE *threads; bool isRunning; appNode rootNode; + map customData; static void handleConnections (HTTPServer *); diff --git a/src/http/webapp.cpp b/src/http/webapp.cpp new file mode 100644 index 0000000..eca9188 --- /dev/null +++ b/src/http/webapp.cpp @@ -0,0 +1,158 @@ +/* + * Copyright © 2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "webapp.hpp" +#include "../tools.h" +#include + +using namespace std; + +namespace UDPT +{ + namespace Server + { + + static uint32_t _getNextIPv4 (string::size_type &i, string &line) + { + string::size_type len = line.length(); + char c; + while (i < len) + { + c = line.at(i); + if (c >= '0' && c <= '9') + break; + i++; + } + + uint32_t ip = 0; + for (int n = 0;n < 4;n++) + { + int cn = 0; + while (i < len) + { + c = line.at (i++); + if (c == '.' || ((c == ' ' || c == ',' || c == ';') && n == 3)) + break; + else if (!(c >= '0' && c <= '9')) + return 0; + cn *= 10; + cn += (c - '0'); + } + ip *= 256; + ip += cn; + } + return ip; + } + + WebApp::WebApp(HTTPServer *srv, DatabaseDriver *db, Settings *settings) + { + this->instance = srv; + this->db = db; + this->sc_api = settings->getClass("api"); + + Settings::SettingClass *apiKeys = settings->getClass("api.keys"); + if (apiKeys != NULL) + { + map* aK = apiKeys->getMap(); + map::iterator it, end; + end = aK->end(); + for (it = aK->begin();it != end;it++) + { + string key = it->first; + list ips; + + string::size_type strp = 0; + uint32_t ip; + while ((ip = _getNextIPv4(strp, it->second)) != 0) + { + ips.push_back( m_hton32(ip) ); + } + +// ips.push_back(0); // end of list +// uint32_t *rList = new uint32_t [ips.size()]; +// list::iterator it; +// int i = 0; +// for (it = ips.begin();it != ips.end();it++) +// { +// rList[i++] = m_hton32((*it)); +// } + this->ip_whitelist.insert(pair >(key, ips)); + } + + } + + srv->setData("webapp", this); + } + + WebApp::~WebApp() + { + } + + void WebApp::deploy() + { + list path; + path.push_back("api"); + this->instance->addApp(&path, &WebApp::handleAPI); // "/api" + } + + bool WebApp::isAllowedIP (WebApp *app, string key, uint32_t ip) + { + std::map >::iterator it, end; + end = app->ip_whitelist.end (); + it = app->ip_whitelist.find (key); + if (it == app->ip_whitelist.end()) + return false; // no such key + + list *lst = &it->second; + list::iterator ipit; + for (ipit = lst->begin();ipit != lst->end();ipit++) + { + if (*ipit == ip) + return true; + } + + return false; + } + + void WebApp::handleAPI(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) + { + if (req->getAddress()->sin_family != AF_INET) + { + throw ServerException (0, "IPv4 supported Only."); + } + + string key = req->getParam("auth"); + if (key.length() <= 0) + throw ServerException (0, "Bad Authentication Key"); + + WebApp *app = (WebApp*)srv->getData("webapp"); + if (app == NULL) + throw ServerException(0, "WebApp object wasn't found"); + + if (!isAllowedIP(app, key, req->getAddress()->sin_addr.s_addr)) + { + resp->setStatus(403, "Forbidden"); + resp->write("IP not whitelisted. Access Denied."); + return; + } + + string action = req->getParam("action"); + } + }; +}; diff --git a/src/http/webapp.hpp b/src/http/webapp.hpp new file mode 100644 index 0000000..9b3b3e5 --- /dev/null +++ b/src/http/webapp.hpp @@ -0,0 +1,55 @@ +/* + * Copyright © 2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#pragma once + +#include "httpserver.hpp" +#include "../db/database.hpp" +#include "../settings.hpp" +#include +#include +#include +using namespace std; + +using namespace UDPT; +using namespace UDPT::Data; + +namespace UDPT +{ + namespace Server + { + class WebApp + { + public: + WebApp (HTTPServer *, DatabaseDriver *, Settings *); + ~WebApp (); + void deploy (); + + + private: + HTTPServer *instance; + UDPT::Data::DatabaseDriver *db; + Settings::SettingClass *sc_api; + std::map > ip_whitelist; + + static void handleAPI (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); + static bool isAllowedIP (WebApp *, string, uint32_t); + }; + }; +}; diff --git a/src/main.cpp b/src/main.cpp index 48a2148..822fee0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -23,6 +23,7 @@ #include "udpTracker.hpp" #include "settings.hpp" #include "http/httpserver.hpp" +#include "http/webapp.hpp" using namespace std; using namespace UDPT; @@ -81,6 +82,7 @@ int main(int argc, char *argv[]) usi = new UDPTracker (settings); HTTPServer *apiSrv = NULL; + WebApp *wa = NULL; r = usi->start(); if (r != UDPTracker::START_OK) @@ -101,8 +103,11 @@ int main(int argc, char *argv[]) goto cleanup; } + try{ apiSrv = new HTTPServer(6969, 8); + wa = new WebApp (apiSrv, usi->conn, settings); + wa->deploy(); } catch (ServerException &ex) { cerr << "ServerException #" << ex.getErrorCode() << ": " << ex.getErrorMsg() << endl; @@ -119,6 +124,7 @@ cleanup: delete usi; delete settings; delete apiSrv; + delete wa; #ifdef WIN32 WSACleanup(); diff --git a/src/settings.cpp b/src/settings.cpp index 4253678..5ef0d05 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -284,6 +284,11 @@ void _settings_clean_string (char **str) return this->entries[name]; } + map* Settings::SettingClass::getMap() + { + return &this->entries; + } + bool Settings::SettingClass::set (const string name, const string value) { pair::iterator, bool> r; diff --git a/src/settings.hpp b/src/settings.hpp index 8e9ec51..bda24d5 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -36,6 +36,7 @@ namespace UDPT SettingClass (const string className); bool set (const string key, const string value); string get (const string key); + map* getMap (); private: friend class Settings; string className; diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index f0bd18e..282020f 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -131,6 +131,7 @@ namespace UDPT */ virtual ~UDPTracker (); + Data::DatabaseDriver *conn; private: SOCKET sock; uint16_t port; @@ -142,7 +143,6 @@ namespace UDPT uint8_t settings; Settings *o_settings; - Data::DatabaseDriver *conn; #ifdef WIN32 static DWORD _thread_start (LPVOID arg); From 5ad5d82e2fb96d1301c71daa7958db954b696c83 Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 22 Mar 2013 01:52:15 +0200 Subject: [PATCH 28/99] Added add/remove api functions; Added promation page for root page. --- src/db/driver_sqlite.cpp | 29 ++++------ src/http/webapp.cpp | 116 ++++++++++++++++++++++++++++++++++++--- src/http/webapp.hpp | 4 ++ 3 files changed, 122 insertions(+), 27 deletions(-) diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp index 5f75429..b3956fa 100644 --- a/src/db/driver_sqlite.cpp +++ b/src/db/driver_sqlite.cpp @@ -239,16 +239,12 @@ namespace UDPT _to_hex_str(info_hash, xHash); - // if non-dynamic, called only when adding to DB. - if (!this->isDynamic()) - { - sqlite3_stmt *stmt; - sqlite3_prepare(this->db, "INSERT INTO torrents (info_hash,created) VALUES (?,?)", -1, &stmt, NULL); - sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); - sqlite3_bind_int(stmt, 1, time(NULL)); - sqlite3_step(stmt); - sqlite3_finalize(stmt); - } + sqlite3_stmt *stmt; + sqlite3_prepare(this->db, "INSERT INTO torrents (info_hash,created) VALUES (?,?)", -1, &stmt, NULL); + sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); + sqlite3_bind_int(stmt, 1, time(NULL)); + sqlite3_step(stmt); + sqlite3_finalize(stmt); string sql = "CREATE TABLE IF NOT EXISTS 't"; sql += xHash; @@ -338,14 +334,11 @@ namespace UDPT bool SQLite3Driver::removeTorrent(uint8_t info_hash[20]) { // if non-dynamic, remove from table - if (!this->isDynamic()) - { - sqlite3_stmt *stmt; - sqlite3_prepare(this->db, "DELETE FROM torrents WHERE info_hash=?", -1, &stmt, NULL); - sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); - sqlite3_step(stmt); - sqlite3_finalize(stmt); - } + sqlite3_stmt *stmt; + sqlite3_prepare(this->db, "DELETE FROM torrents WHERE info_hash=?", -1, &stmt, NULL); + sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); + sqlite3_step(stmt); + sqlite3_finalize(stmt); // remove from stats sqlite3_stmt *rmS; diff --git a/src/http/webapp.cpp b/src/http/webapp.cpp index eca9188..d388cb7 100644 --- a/src/http/webapp.cpp +++ b/src/http/webapp.cpp @@ -20,7 +20,7 @@ #include "webapp.hpp" #include "../tools.h" #include - +#include using namespace std; namespace UDPT @@ -60,6 +60,43 @@ namespace UDPT return ip; } + static bool _hex2bin (uint8_t *data, const string str) + { + int len = str.length(); + + if (len % 2 != 0) + return false; + + char a, b; + uint8_t c; + for (int i = 0;i < len;i+=2) + { + a = str.at (i); + b = str.at (i + 1); + c = 0; + + if (a >= 'a' && a <= 'f') + a = (a - 'a') + 10; + else if (a >= '0' && a <= '9') + a = (a - '0'); + else + return false; + + if (b >= 'a' && b <= 'f') + b = (b - 'a') + 10; + else if (b >= '0' && b <= '9') + b = (b - '0'); + else + return false; + + c = (a * 16) + b; + + data [i / 2] = c; + } + + return true; + } + WebApp::WebApp(HTTPServer *srv, DatabaseDriver *db, Settings *settings) { this->instance = srv; @@ -84,14 +121,6 @@ namespace UDPT ips.push_back( m_hton32(ip) ); } -// ips.push_back(0); // end of list -// uint32_t *rList = new uint32_t [ips.size()]; -// list::iterator it; -// int i = 0; -// for (it = ips.begin();it != ips.end();it++) -// { -// rList[i++] = m_hton32((*it)); -// } this->ip_whitelist.insert(pair >(key, ips)); } @@ -107,10 +136,28 @@ namespace UDPT void WebApp::deploy() { list path; + this->instance->addApp(&path, &WebApp::handleRoot); path.push_back("api"); this->instance->addApp(&path, &WebApp::handleAPI); // "/api" } + void WebApp::handleRoot (HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) + { + // It would be very appreciated to keep this in the code. + resp->write("" + "Powered by UDPT" + "" + "

The UDPT Project

" + "
This tracker is running on UDPT Software.
" + "UDPT is a open-source project, freely available for anyone to use. If you would like to obtain a copy of the software, you can get it here: http://code.googe.com/p/udpt." + "

If you would like to help the project grow, please donate for our hard work, effort & time: " + "\"Donate" + "
" + "

© 2013 Naim A. | Powered by UDPT
" + "" + ""); + } + bool WebApp::isAllowedIP (WebApp *app, string key, uint32_t ip) { std::map >::iterator it, end; @@ -130,6 +177,49 @@ namespace UDPT return false; } + void WebApp::doRemoveTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) + { + string strHash = req->getParam("hash"); + if (strHash.length() != 40) + { + resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); + return; + } + uint8_t hash [20]; + if (!_hex2bin(hash, strHash)) + { + resp->write("{\"error\":\"invalid info_hash.\"}"); + return; + } + + + if (this->db->removeTorrent(hash)) + resp->write("{\"success\":true}"); + else + resp->write("{\"error\":\"failed to remove torrent from DB\"}"); + } + + void WebApp::doAddTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) + { + string strHash = req->getParam("hash"); + if (strHash.length() != 40) + { + resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); + return; + } + uint8_t hash [20]; + if (!_hex2bin(hash, strHash)) + { + resp->write("{\"error\":\"invalid info_hash.\"}"); + return; + } + + if (this->db->addTorrent(hash)) + resp->write("{\"success\":true}"); + else + resp->write("{\"error\":\"failed to add torrent to DB\"}"); + } + void WebApp::handleAPI(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) { if (req->getAddress()->sin_family != AF_INET) @@ -153,6 +243,14 @@ namespace UDPT } string action = req->getParam("action"); + if (action == "add") + app->doAddTorrent(req, resp); + else if (action == "remove") + app->doRemoveTorrent(req, resp); + else + { + resp->write("{\"error\":\"unknown action\"}"); + } } }; }; diff --git a/src/http/webapp.hpp b/src/http/webapp.hpp index 9b3b3e5..11f89bb 100644 --- a/src/http/webapp.hpp +++ b/src/http/webapp.hpp @@ -48,8 +48,12 @@ namespace UDPT Settings::SettingClass *sc_api; std::map > ip_whitelist; + static void handleRoot (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); static void handleAPI (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); static bool isAllowedIP (WebApp *, string, uint32_t); + + void doAddTorrent (HTTPServer::Request*, HTTPServer::Response*); + void doRemoveTorrent (HTTPServer::Request*, HTTPServer::Response*); }; }; }; From 1aa7eceb2f8af9f39f07956ac068d7310fc9cae8 Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 22 Mar 2013 02:20:49 +0200 Subject: [PATCH 29/99] Added settings for API server. --- src/main.cpp | 61 ++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 45 insertions(+), 16 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 822fee0..eef927a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -34,6 +34,39 @@ static void _print_usage () cout << "Usage: udpt []" << endl; } +static void _doAPIStart (Settings *settings, WebApp **wa, HTTPServer **srv, DatabaseDriver *drvr) +{ + if (settings == NULL) + return; + Settings::SettingClass *sc = settings->getClass("apiserver"); + if (sc == NULL) + return; // no settings set! + + if (sc->get("enable") != "1") + { + cerr << "API Server not enabled." << endl; + return; + } + + string s_port = sc->get("port"); + string s_threads = sc->get("threads"); + + uint16_t port = (s_port == "" ? 6969 : atoi (s_port.c_str())); + uint16_t threads = (s_threads == "" ? 1 : atoi (s_threads.c_str())); + + if (threads <= 0) + threads = 1; + + try { + *srv = new HTTPServer (port, threads); + *wa = new WebApp (*srv, drvr, settings); + (*wa)->deploy(); + } catch (ServerException &e) + { + cerr << "ServerException #" << e.getErrorCode() << ": " << e.getErrorMsg() << endl; + } +} + int main(int argc, char *argv[]) { Settings *settings = NULL; @@ -63,20 +96,25 @@ int main(int argc, char *argv[]) { const char strDATABASE[] = "database"; const char strTRACKER[] = "tracker"; + const char strAPISRV [] = "apiserver"; // set default settings: settings->set (strDATABASE, "driver", "sqlite3"); settings->set (strDATABASE, "file", "tracker.db"); - settings->set (strTRACKER, "port", "6969"); + settings->set (strTRACKER, "port", "6969"); // UDP PORT settings->set (strTRACKER, "threads", "5"); settings->set (strTRACKER, "allow_remotes", "yes"); settings->set (strTRACKER, "allow_iana_ips", "yes"); settings->set (strTRACKER, "announce_interval", "1800"); settings->set (strTRACKER, "cleanup_interval", "120"); + settings->set (strAPISRV, "enable", "1"); + settings->set (strAPISRV, "threads", "1"); + settings->set (strAPISRV, "port", "6969"); // TCP PORT + settings->save(); - cout << "Failed to read from '" << config_file.c_str() << "'. Using default settings." << endl; + cerr << "Failed to read from '" << config_file.c_str() << "'. Using default settings." << endl; } usi = new UDPTracker (settings); @@ -87,32 +125,23 @@ int main(int argc, char *argv[]) r = usi->start(); if (r != UDPTracker::START_OK) { - cout << "Error While trying to start server." << endl; + cerr << "Error While trying to start server." << endl; switch (r) { case UDPTracker::START_ESOCKET_FAILED: - cout << "Failed to create socket." << endl; + cerr << "Failed to create socket." << endl; break; case UDPTracker::START_EBIND_FAILED: - cout << "Failed to bind socket." << endl; + cerr << "Failed to bind socket." << endl; break; default: - cout << "Unknown Error" << endl; + cerr << "Unknown Error" << endl; break; } goto cleanup; } - - try{ - apiSrv = new HTTPServer(6969, 8); - wa = new WebApp (apiSrv, usi->conn, settings); - wa->deploy(); - } catch (ServerException &ex) - { - cerr << "ServerException #" << ex.getErrorCode() << ": " << ex.getErrorMsg() << endl; - goto cleanup; - } + _doAPIStart(settings, &wa, &apiSrv, usi->conn); cout << "Press Any key to exit." << endl; From d05820a99209a305d60e9ad9e049143065650565 Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 22 Mar 2013 13:54:50 +0200 Subject: [PATCH 30/99] Modified HTTP Server; Added notice incase a user tries to use tracker as a HTTP tracker. --- src/http/webapp.cpp | 10 ++++++++++ src/http/webapp.hpp | 1 + src/main.cpp | 1 + src/udpTracker.cpp | 4 ++-- 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/http/webapp.cpp b/src/http/webapp.cpp index d388cb7..4f2f870 100644 --- a/src/http/webapp.cpp +++ b/src/http/webapp.cpp @@ -137,8 +137,13 @@ namespace UDPT { list path; this->instance->addApp(&path, &WebApp::handleRoot); + path.push_back("api"); this->instance->addApp(&path, &WebApp::handleAPI); // "/api" + + path.pop_back(); + path.push_back("announce"); + this->instance->addApp(&path, &WebApp::handleAnnounce); } void WebApp::handleRoot (HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) @@ -220,6 +225,11 @@ namespace UDPT resp->write("{\"error\":\"failed to add torrent to DB\"}"); } + void WebApp::handleAnnounce (HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) + { + resp->write("d14:failure reason42:this is a UDP tracker, not a HTTP tracker.e"); + } + void WebApp::handleAPI(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) { if (req->getAddress()->sin_family != AF_INET) diff --git a/src/http/webapp.hpp b/src/http/webapp.hpp index 11f89bb..6a8011f 100644 --- a/src/http/webapp.hpp +++ b/src/http/webapp.hpp @@ -49,6 +49,7 @@ namespace UDPT std::map > ip_whitelist; static void handleRoot (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); + static void handleAnnounce (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); static void handleAPI (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); static bool isAllowedIP (WebApp *, string, uint32_t); diff --git a/src/main.cpp b/src/main.cpp index eef927a..32e83f0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -24,6 +24,7 @@ #include "settings.hpp" #include "http/httpserver.hpp" #include "http/webapp.hpp" +#include // atoi using namespace std; using namespace UDPT; diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index 555fb51..d9e0a34 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -455,7 +455,7 @@ static int _isIANA_IP (uint32_t ip) } } - cout << ":: " << (void*)m_hton32(remote->sin_addr.s_addr) << ": " << m_hton16(remote->sin_port) << " ACTION=" << action << endl; +// cout << ":: " << (void*)m_hton32(remote->sin_addr.s_addr) << ": " << m_hton16(remote->sin_port) << " ACTION=" << action << endl; if (action == 0 && r >= 16) return UDPTracker::handleConnection (usi, remote, data); @@ -465,7 +465,7 @@ static int _isIANA_IP (uint32_t ip) return UDPTracker::handleScrape (usi, remote, data, r); else { - cout << "E: action=" << action << ", r=" << r << endl; +// cout << "E: action=" << action << ", r=" << r << endl; UDPTracker::sendError (usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); return -1; } From b4c0511f8202bc3864cd132c601b9bffe8424993 Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 22 Mar 2013 14:21:00 +0200 Subject: [PATCH 31/99] Updated Makefile for linux --- Makefile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 82c89ed..713bbde 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ # objects = main.o udpTracker.o database.o driver_sqlite.o \ - settings.o tools.o + settings.o tools.o httpserver.o webapp.o target = udpt %.o: src/%.c @@ -27,6 +27,8 @@ target = udpt $(CXX) -c -o $@ $< $(CXXFLAGS) %.o: src/db/%.cpp $(CXX) -c -o $@ $< $(CXXFLAGS) +%.o: src/http/%.cpp + $(CXX) -c -o $@ $< $(CXXFLAGS) all: $(target) $(target): $(objects) From f757db71a4ac636b24145991ab5e8ec3f72440be Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 23 Mar 2013 21:54:25 +0200 Subject: [PATCH 32/99] Small changes; Added "is_dynamic" setting; Changed stuff with Database (I guess i was sleeping when i programmed that part...). --- src/db/driver_sqlite.cpp | 7 ++++--- src/main.cpp | 5 +++-- src/udpTracker.cpp | 12 ++++++++++-- src/udpTracker.hpp | 1 + 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp index b3956fa..47dcba8 100644 --- a/src/db/driver_sqlite.cpp +++ b/src/db/driver_sqlite.cpp @@ -242,7 +242,7 @@ namespace UDPT sqlite3_stmt *stmt; sqlite3_prepare(this->db, "INSERT INTO torrents (info_hash,created) VALUES (?,?)", -1, &stmt, NULL); sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); - sqlite3_bind_int(stmt, 1, time(NULL)); + sqlite3_bind_int(stmt, 2, time(NULL)); sqlite3_step(stmt); sqlite3_finalize(stmt); @@ -266,7 +266,7 @@ namespace UDPT return (r == SQLITE_OK); } - bool SQLite3Driver::isTorrentAllowed(uint8_t info_hash[20]) + bool SQLite3Driver::isTorrentAllowed(uint8_t *info_hash) { if (this->isDynamic()) return true; @@ -275,8 +275,9 @@ namespace UDPT sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); sqlite3_step(stmt); - int n = sqlite3_column_int(stmt, 1); + int n = sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); + return (n == 1); } diff --git a/src/main.cpp b/src/main.cpp index 32e83f0..cb72cb9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -103,10 +103,11 @@ int main(int argc, char *argv[]) settings->set (strDATABASE, "driver", "sqlite3"); settings->set (strDATABASE, "file", "tracker.db"); + settings->set (strTRACKER, "is_dynamic", "0"); settings->set (strTRACKER, "port", "6969"); // UDP PORT settings->set (strTRACKER, "threads", "5"); - settings->set (strTRACKER, "allow_remotes", "yes"); - settings->set (strTRACKER, "allow_iana_ips", "yes"); + settings->set (strTRACKER, "allow_remotes", "1"); + settings->set (strTRACKER, "allow_iana_ips", "1"); settings->set (strTRACKER, "announce_interval", "1800"); settings->set (strTRACKER, "cleanup_interval", "120"); diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index d9e0a34..f288952 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -71,7 +71,8 @@ namespace UDPT s_allow_remotes, // remotes allowed? s_allow_iana_ip, // IANA IPs allowed? s_int_announce, // announce interval - s_int_cleanup; // cleanup interval + s_int_cleanup, // cleanup interval + s_is_dynamic; sc_tracker = settings->getClass("tracker"); @@ -81,6 +82,7 @@ namespace UDPT s_allow_iana_ip = sc_tracker->get ("allow_iana_ips"); s_int_announce = sc_tracker->get ("announce_interval"); s_int_cleanup = sc_tracker-> get ("cleanup_interval"); + s_is_dynamic = sc_tracker->get("is_dynamic"); if (_isTrue(s_allow_remotes) == 1) n_settings |= UDPT_ALLOW_REMOTE_IP; @@ -88,6 +90,11 @@ namespace UDPT if (_isTrue(s_allow_iana_ip) != 0) n_settings |= UDPT_ALLOW_IANA_IP; + if (_isTrue(s_is_dynamic) == 1) + this->isDynamic = true; + else + this->isDynamic = false; + this->announce_interval = (s_int_announce == "" ? 1800 : atoi (s_int_announce.c_str())); this->cleanup_interval = (s_int_cleanup == "" ? 120 : atoi (s_int_cleanup.c_str())); this->port = (s_port == "" ? 6969 : atoi (s_port.c_str())); @@ -169,7 +176,8 @@ namespace UDPT this->sock = sock; - this->conn = new Data::SQLite3Driver (this->o_settings->getClass("database"), true); + this->conn = new Data::SQLite3Driver (this->o_settings->getClass("database"), + this->isDynamic); this->isRunning = true; cout << "Starting maintenance thread (1/" << ((int)this->thread_count) << ")" << endl; diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 282020f..1466e4b 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -137,6 +137,7 @@ namespace UDPT uint16_t port; uint8_t thread_count; bool isRunning; + bool isDynamic; HANDLE *threads; uint32_t announce_interval; uint32_t cleanup_interval; From 2682f81b2084f807b323fb93c0a10430f5dbd4ba Mon Sep 17 00:00:00 2001 From: Naim A Date: Tue, 25 Jun 2013 04:06:52 +0300 Subject: [PATCH 33/99] Modified a bit of code... --- src/multiplatform.h | 6 ++++ src/settings.cpp | 52 ++++++++++++++++++++++++++++++-- src/settings.hpp | 4 ++- src/udpTracker.cpp | 72 ++++++--------------------------------------- src/udpTracker.hpp | 3 +- 5 files changed, 70 insertions(+), 67 deletions(-) diff --git a/src/multiplatform.h b/src/multiplatform.h index 8b9c7a4..5a7bf9a 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -24,6 +24,8 @@ #if defined (_WIN32) && !defined (WIN32) #define WIN32 +#elif defined (__APPLE__) +#define linux #endif #ifdef WIN32 @@ -55,3 +57,7 @@ typedef pthread_t HANDLE; #define VERSION "1.0.0-beta (Linux)" #endif +#ifdef __APPLE__ +#undef VERSION +#define VERSION "1.0.0-beta (Apple)" +#endif diff --git a/src/settings.cpp b/src/settings.cpp index 5ef0d05..89ec2a7 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -21,7 +21,8 @@ #include "settings.hpp" #include // still primitive - need for strlen() #include // need for isspace() - +#include +#include #include #include @@ -277,13 +278,60 @@ void _settings_clean_string (char **str) this->className = cn; } - string Settings::SettingClass::get (const string name) + string Settings::SettingClass::get (const string& name) { if (this->entries.find(name) == this->entries.end()) return ""; return this->entries[name]; } + inline static int _isTrue (string str) + { + int i, // loop index + len; // string's length + + if (str == "") + return -1; + len = str.length(); + for (i = 0;i < len;i++) + { + if (str[i] >= 'A' && str[i] <= 'Z') + { + str[i] = (str[i] - 'A' + 'a'); + } + } + if (str.compare ("yes") == 0) + return 1; + if (str.compare ("no") == 0) + return 0; + if (str.compare("true") == 0) + return 1; + if (str.compare ("false") == 0) + return 0; + if (str.compare("1") == 0) + return 1; + if (str.compare ("0") == 0) + return 0; + return -1; + } + + bool Settings::SettingClass::getBool(const string& name) + { + string v = this->get(name); + int r = _isTrue(v); + if (r == 0 || r == 1) + return (bool)r; + throw exception(); + } + + int Settings::SettingClass::getInt (const string& key, int def) + { + string v = this->get (key); + if (v.length() == 0) + return def; + return std::atoi(v.c_str()); + } + map* Settings::SettingClass::getMap() { return &this->entries; diff --git a/src/settings.hpp b/src/settings.hpp index bda24d5..7eff80b 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -35,7 +35,9 @@ namespace UDPT public: SettingClass (const string className); bool set (const string key, const string value); - string get (const string key); + string get (const string& key); + bool getBool (const string& key); + int getInt (const string& key, int def = -1); map* getMap (); private: friend class Settings; diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index f288952..7e88552 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -32,79 +32,25 @@ using namespace UDPT::Data; namespace UDPT { - inline static int _isTrue (string str) - { - int i, // loop index - len; // string's length - - if (str == "") - return -1; - len = str.length(); - for (i = 0;i < len;i++) - { - if (str[i] >= 'A' && str[i] <= 'Z') - { - str[i] = (str[i] - 'A' + 'a'); - } - } - if (str.compare ("yes") == 0) - return 1; - if (str.compare ("no") == 0) - return 0; - if (str.compare("true") == 0) - return 1; - if (str.compare ("false") == 0) - return 0; - if (str.compare("1") == 0) - return 1; - if (str.compare ("0") == 0) - return 0; - return -1; - } - UDPTracker::UDPTracker (Settings *settings) { Settings::SettingClass *sc_tracker; - uint8_t n_settings = 0; - string s_port, // port - s_threads, // threads - s_allow_remotes, // remotes allowed? - s_allow_iana_ip, // IANA IPs allowed? - s_int_announce, // announce interval - s_int_cleanup, // cleanup interval - s_is_dynamic; sc_tracker = settings->getClass("tracker"); - s_port = sc_tracker->get ("port"); - s_threads = sc_tracker->get ("threads"); - s_allow_remotes = sc_tracker->get ("allow_remotes"); - s_allow_iana_ip = sc_tracker->get ("allow_iana_ips"); - s_int_announce = sc_tracker->get ("announce_interval"); - s_int_cleanup = sc_tracker-> get ("cleanup_interval"); - s_is_dynamic = sc_tracker->get("is_dynamic"); + this->allowRemotes = sc_tracker->getBool("allow_remotes"); + this->allowIANA_IPs = sc_tracker->getBool("allow_iana_ips"); + this->isDynamic = sc_tracker->getBool("is_dynamic"); - if (_isTrue(s_allow_remotes) == 1) - n_settings |= UDPT_ALLOW_REMOTE_IP; - - if (_isTrue(s_allow_iana_ip) != 0) - n_settings |= UDPT_ALLOW_IANA_IP; - - if (_isTrue(s_is_dynamic) == 1) - this->isDynamic = true; - else - this->isDynamic = false; - - this->announce_interval = (s_int_announce == "" ? 1800 : atoi (s_int_announce.c_str())); - this->cleanup_interval = (s_int_cleanup == "" ? 120 : atoi (s_int_cleanup.c_str())); - this->port = (s_port == "" ? 6969 : atoi (s_port.c_str())); - this->thread_count = (s_threads == "" ? 5 : atoi (s_threads.c_str())) + 1; + this->announce_interval = sc_tracker->getInt("announce_interval", 1800); + this->cleanup_interval = sc_tracker->getInt("cleanup_interval", 120); + this->port = sc_tracker->getInt("port", 6969); + this->thread_count = abs (sc_tracker->getInt("threads", 5)) + 1; this->threads = new HANDLE[this->thread_count]; this->isRunning = false; this->conn = NULL; - this->settings = n_settings; this->o_settings = settings; } @@ -278,7 +224,7 @@ namespace UDPT req->num_want = m_hton32 (req->num_want); req->left = m_hton64 (req->left); - if ((usi->settings & UDPT_ALLOW_REMOTE_IP) == 0 && req->ip_address != 0) + if (!usi->allowRemotes && req->ip_address != 0) { UDPTracker::sendError (usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); return 0; @@ -455,7 +401,7 @@ static int _isIANA_IP (uint32_t ip) action = m_hton32(cR->action); - if ((usi->settings & UDPT_ALLOW_IANA_IP) == 0) + if (!usi->allowIANA_IPs) { if (_isIANA_IP (remote->sin_addr.s_addr)) { diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 1466e4b..3f16716 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -138,11 +138,12 @@ namespace UDPT uint8_t thread_count; bool isRunning; bool isDynamic; + bool allowRemotes; + bool allowIANA_IPs; HANDLE *threads; uint32_t announce_interval; uint32_t cleanup_interval; - uint8_t settings; Settings *o_settings; #ifdef WIN32 From 8f4732acbc50f75d5de0e58558759f0096e274cf Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 12 Jul 2013 00:09:47 +0300 Subject: [PATCH 34/99] Security issue fixed. Issue 4 fixed. --- src/udpTracker.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index 7e88552..a067177 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -161,6 +161,10 @@ namespace UDPT msg_sz = 4 + 4 + 1 + msg.length(); + // test against overflow message. resolves issue 4. + if (msg_sz > 1024) + return -1; + memcpy(buff, &error, 8); for (i = 8;i <= msg_sz;i++) { From 74de90badea2b0a09b9ad860e0bce57d7fef8633 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 10 Aug 2013 22:12:08 +0300 Subject: [PATCH 35/99] Added Logger; Partial fix to issue #5 --- src/db/driver_sqlite.cpp | 14 ++++++++++- src/logging.cpp | 34 +++++++++++++++++++++++++++ src/logging.h | 51 ++++++++++++++++++++++++++++++++++++++++ src/main.cpp | 8 +++++++ src/udpTracker.cpp | 17 +++++++++++--- 5 files changed, 120 insertions(+), 4 deletions(-) create mode 100644 src/logging.cpp create mode 100644 src/logging.h diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp index 47dcba8..9601420 100644 --- a/src/db/driver_sqlite.cpp +++ b/src/db/driver_sqlite.cpp @@ -26,6 +26,9 @@ #include #include // memcpy #include "../multiplatform.h" +#include "../logging.h" + +extern UDPT::Logger *logger; using namespace std; @@ -309,7 +312,16 @@ namespace UDPT sqlite3_stmt *collectStats; sqlite3_prepare(this->db, sStr.str().c_str(), sStr.str().length(), &collectStats, NULL); - cout << "[" << sqlite3_errmsg(this->db) << "]" << endl; + + if (sqlite3_errcode(this->db) != SQLITE_OK) + { + string str; + str = "["; + str += sqlite3_errmsg(this->db); + str += "]"; + logger->log(Logger::LL_ERROR, str); + } + int seeders = 0, leechers = 0; while (sqlite3_step(collectStats) == SQLITE_ROW) // expecting two results. { diff --git a/src/logging.cpp b/src/logging.cpp new file mode 100644 index 0000000..bb49555 --- /dev/null +++ b/src/logging.cpp @@ -0,0 +1,34 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "logging.h" + +namespace UDPT { + Logger::Logger(Settings *s, ostream &os) : logfile (os) + { + this->max_time = 120; + this->queue_limit = 50; + } + + void Logger::log(enum LogLevel lvl, string msg) + { + logfile << time (NULL) << ": (" << ((char)lvl) << "): "; + logfile << msg << "\n"; + } +}; diff --git a/src/logging.h b/src/logging.h new file mode 100644 index 0000000..b366592 --- /dev/null +++ b/src/logging.h @@ -0,0 +1,51 @@ +/* + * Copyright © 2012,2013 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#ifndef LOGGING_H_ +#define LOGGING_H_ + +#include "settings.hpp" +#include +#include +#include +#include + +namespace UDPT { + using namespace std; + class Logger { + + public: + enum LogLevel { + LL_ERROR = 'E', + LL_WARNING = 'W', + LL_INFO = 'I', + LL_DEBUG = 'D' + }; + + Logger (Settings *s, ostream &os); + + void log (enum LogLevel, string msg); + private: + ostream &logfile; + unsigned int queue_limit; + int max_time; + }; +}; + +#endif /* LOGGING_H_ */ diff --git a/src/main.cpp b/src/main.cpp index cb72cb9..a814fa1 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -19,6 +19,7 @@ #include +#include "logging.h" #include "multiplatform.h" #include "udpTracker.hpp" #include "settings.hpp" @@ -30,6 +31,8 @@ using namespace std; using namespace UDPT; using namespace UDPT::Server; +Logger *logger; + static void _print_usage () { cout << "Usage: udpt []" << endl; @@ -90,6 +93,10 @@ int main(int argc, char *argv[]) { _print_usage (); } + else if (argc >= 2) + { + config_file = argv[1]; // reported in issue #5. + } settings = new Settings (config_file); @@ -119,6 +126,7 @@ int main(int argc, char *argv[]) cerr << "Failed to read from '" << config_file.c_str() << "'. Using default settings." << endl; } + logger = new Logger (settings, cout); usi = new UDPTracker (settings); HTTPServer *apiSrv = NULL; diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index a067177..2e130a9 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -23,7 +23,11 @@ #include #include #include +#include #include "multiplatform.h" +#include "logging.h" + +extern UDPT::Logger *logger; using namespace std; using namespace UDPT::Data; @@ -126,7 +130,10 @@ namespace UDPT this->isDynamic); this->isRunning = true; - cout << "Starting maintenance thread (1/" << ((int)this->thread_count) << ")" << endl; + + stringstream ss; + ss << "Starting maintenance thread (1/" << ((int)this->thread_count) << ")"; + logger->log(Logger::LL_INFO, ss.str()); // create maintainer thread. #ifdef WIN32 @@ -137,8 +144,12 @@ namespace UDPT for (i = 1;i < this->thread_count; i++) { - cout << "Starting thread (" << (i + 1) << "/" << ((int)this->thread_count) << ")" << endl; - #ifdef WIN32 + stringstream ss; + ss << "Starting thread (" << (i + 1) << "/" << ((int)this->thread_count) << ")"; + logger->log(Logger::LL_INFO, ss.str()); + ss.clear(); + + #ifdef WIN32 this->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)this, 0, NULL); #elif defined (linux) pthread_create (&(this->threads[i]), NULL, _thread_start, (void*)this); From 622ad93872e2fe06404d4343f2bdefdba2cafaa8 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 11 Aug 2013 12:23:27 +0300 Subject: [PATCH 36/99] Makefile updated. --- Makefile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 713bbde..70a3f95 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,8 @@ # objects = main.o udpTracker.o database.o driver_sqlite.o \ - settings.o tools.o httpserver.o webapp.o + settings.o tools.o httpserver.o webapp.o \ + logging.o target = udpt %.o: src/%.c @@ -33,7 +34,7 @@ all: $(target) $(target): $(objects) @echo Linking... - $(CXX) $(LDFLAGS) -O3 -o $(target) $(objects) -lsqlite3 + $(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lsqlite3 @echo Done. clean: @echo Cleaning Up... From db74edbb51df7d0f99a91375a24044af715495b7 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 11 Aug 2013 13:20:15 +0300 Subject: [PATCH 37/99] Fixes for issue #5 --- src/settings.cpp | 17 ++++++++++++++--- src/settings.hpp | 18 ++++++++++++++++++ src/udpTracker.cpp | 6 +++--- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/settings.cpp b/src/settings.cpp index 89ec2a7..3a610ff 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -102,7 +102,7 @@ void _settings_clean_string (char **str) cil = 0; continue; } - if (cil == 0 && c == ';') + if (cil == 0 && (c == ';' || c == '#')) { while (i < len) { @@ -259,7 +259,7 @@ void _settings_clean_string (char **str) { SettingClass *c; - if (classN == "" || name == "") + if (classN == "" || name == "" || value == "") return false; c = this->getClass (classN); @@ -321,9 +321,20 @@ void _settings_clean_string (char **str) int r = _isTrue(v); if (r == 0 || r == 1) return (bool)r; - throw exception(); + throw SettingsException("Invalid boolean value."); } + bool Settings::SettingClass::getBool (const string& key, bool defaultValue) + { + try { + return this->getBool(key); + } catch (SettingsException &e) + { + return defaultValue; + } + } + + int Settings::SettingClass::getInt (const string& key, int def) { string v = this->get (key); diff --git a/src/settings.hpp b/src/settings.hpp index 7eff80b..7193849 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -30,6 +30,23 @@ namespace UDPT class Settings { public: + class SettingsException : public std::exception + { + public: + SettingsException (const char *str) + { + this->str = str; + } + + const char * what () + { + return str; + } + + private: + const char *str; + }; + class SettingClass { public: @@ -37,6 +54,7 @@ namespace UDPT bool set (const string key, const string value); string get (const string& key); bool getBool (const string& key); + bool getBool (const string& key, bool defaultValue); int getInt (const string& key, int def = -1); map* getMap (); private: diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index 2e130a9..3b860bb 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -42,9 +42,9 @@ namespace UDPT sc_tracker = settings->getClass("tracker"); - this->allowRemotes = sc_tracker->getBool("allow_remotes"); - this->allowIANA_IPs = sc_tracker->getBool("allow_iana_ips"); - this->isDynamic = sc_tracker->getBool("is_dynamic"); + this->allowRemotes = sc_tracker->getBool("allow_remotes", true); + this->allowIANA_IPs = sc_tracker->getBool("allow_iana_ips", false); + this->isDynamic = sc_tracker->getBool("is_dynamic", true); this->announce_interval = sc_tracker->getInt("announce_interval", 1800); this->cleanup_interval = sc_tracker->getInt("cleanup_interval", 120); From f7297aa4beec24d71e9b99a93edbfc1d4ab6dde3 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 11 Aug 2013 13:39:17 +0300 Subject: [PATCH 38/99] Logger changes --- src/logging.cpp | 2 -- src/logging.h | 2 -- src/udpTracker.cpp | 10 +++------- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/src/logging.cpp b/src/logging.cpp index bb49555..384154a 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -22,8 +22,6 @@ namespace UDPT { Logger::Logger(Settings *s, ostream &os) : logfile (os) { - this->max_time = 120; - this->queue_limit = 50; } void Logger::log(enum LogLevel lvl, string msg) diff --git a/src/logging.h b/src/logging.h index b366592..fe9362d 100644 --- a/src/logging.h +++ b/src/logging.h @@ -43,8 +43,6 @@ namespace UDPT { void log (enum LogLevel, string msg); private: ostream &logfile; - unsigned int queue_limit; - int max_time; }; }; diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index 3b860bb..c775afb 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -85,7 +85,9 @@ namespace UDPT pthread_detach (this->threads[i]); pthread_cancel (this->threads[i]); #endif - cout << "Thread (" << ( i + 1) << "/" << ((int)this->thread_count) << ") terminated." << endl; + stringstream str; + str << "Thread (" << (i + 1) << "/" << ((int)this->thread_count) << ") terminated."; + logger->log(Logger::LL_INFO, str.str()); } if (this->conn != NULL) delete this->conn; @@ -334,7 +336,6 @@ namespace UDPT i, // loop counter j; // loop counter uint8_t hash [20]; - char xHash [50]; ScrapeResponse *resp; uint8_t buffer [1024]; // up to 74 torrents can be scraped at once (17*74+8) < 1024 @@ -372,10 +373,6 @@ namespace UDPT for (j = 0; j < 20;j++) hash[j] = data[j + (i*20)+16]; - to_hex_str (hash, xHash); - - cout << "\t" << xHash << endl; - seeders = (int32_t*)&buffer[i*12+8]; completed = (int32_t*)&buffer[i*12+12]; leechers = (int32_t*)&buffer[i*12+16]; @@ -392,7 +389,6 @@ namespace UDPT *completed = m_hton32 (tE.completed); *leechers = m_hton32 (tE.leechers); } - cout.flush(); sendto (usi->sock, (const char*)buffer, sizeof(buffer), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); From 9d7c7a055ea44e6990a85be7f5d98ab091a2d16a Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 16 Aug 2013 00:52:36 +0300 Subject: [PATCH 39/99] Change CWD to the program's directory. --- src/main.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index a814fa1..2338548 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -71,6 +71,48 @@ static void _doAPIStart (Settings *settings, WebApp **wa, HTTPServer **srv, Data } } +/** + * Sets current working directory to executables directory. + */ +static void _setCWD (char *argv0) +{ +#ifdef WIN32 + wchar_t strFileName [MAX_PATH]; + DWORD r, i; + r = GetModuleFileNameW(NULL, strFileName, MAX_PATH); + for (i = r;i >= 0;i--) + { + if (strFileName[i] == '\\') + { + strFileName[i] = '\0'; + break; + } + } + SetCurrentDirectoryW(strFileName); + +#elif defined(linux) + int len, i; + char *strFN; + if (argv0 != NULL) + { + len = strlen (argv0); + strFN = new char [len + 1]; + + for (i = len;i >= 0;i--) + { + if (strFN[i] == '/') + { + strFN = '\0'; + break; + } + } + chdir (strFN); + delete [] strFN; + } +#endif + +} + int main(int argc, char *argv[]) { Settings *settings = NULL; @@ -91,6 +133,9 @@ int main(int argc, char *argv[]) if (argc <= 1) { + // set current directory when no filename is present. + _setCWD(argv[0]); + _print_usage (); } else if (argc >= 2) From 65a43c6b8345b6d72f08849d4e692f36eb93b6af Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 16 Aug 2013 01:53:15 +0300 Subject: [PATCH 40/99] Added readed for IP/port lists (settings) --- src/settings.cpp | 94 ++++++++++++++++++++++++++++++++++++++++++++++-- src/settings.hpp | 3 ++ 2 files changed, 94 insertions(+), 3 deletions(-) diff --git a/src/settings.cpp b/src/settings.cpp index 3a610ff..a6efac2 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -25,6 +25,7 @@ #include #include #include +#include "tools.h" using namespace std; @@ -329,11 +330,98 @@ void _settings_clean_string (char **str) try { return this->getBool(key); } catch (SettingsException &e) - { - return defaultValue; - } + { } + + return defaultValue; } + void Settings::SettingClass::getIPs (const string& key, list &ip) + { + string v = this->get(key) + " "; // add padding for last entry. + // expect a.b.c.d[:port], IPv4 only supported with BEP-15. + + string::size_type s, e; + s = e = 0; + char c; + for (string::size_type i = 0;i < v.length();i++) + { + c = v[i]; + if (isspace(c) != 0 || c == ';' || c == ',') + { + if (s == e) + s = e = i; + else + { + string addr = v.substr(s, (e - s) + 1); + SOCKADDR_IN saddr; + saddr.sin_family = AF_INET; + saddr.sin_addr.s_addr = 0L; + saddr.sin_port = (6969); + + { + uint8_t b; // temporary container for IP byte + uint16_t port; + uint32_t ip; + unsigned i, // loop index + stage; // 0,1,2,3=IP[a.b.c.d], 4=port + + ip = 0; + b = 0; + stage = 0; + for (i = 0;i < addr.length();i++) + { + if (addr[i] >= '0' && addr[i] <= '9') + { + if (stage <= 3) + { + b *= 10; + b += (addr[i] - '0'); + } + else if (stage == 4) + { + port *= 10; + port += (addr[i] - '0'); + } + } + else if (addr[i] == '.' && stage < 3) + { + stage ++; + ip *= 256; + ip += b; + b = 0; + } + else if (addr[i] == ':') + { + stage++; + port = 0; + + ip *= 256; + ip += b; + } + } + + if (stage == 3) // port not provided. + { + port = 6969; + // add last byte. + ip *= 256; + ip += b; + } + saddr.sin_addr.s_addr = m_hton32(ip); + saddr.sin_port = m_hton16(port); + } + + ip.push_back(saddr); + + s = e = i + 1; + } + } + else + { + e = i; + } + } + } int Settings::SettingClass::getInt (const string& key, int def) { diff --git a/src/settings.hpp b/src/settings.hpp index 7193849..6c308e2 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -23,6 +23,8 @@ #include #include #include +#include +#include "multiplatform.h" using namespace std; namespace UDPT @@ -57,6 +59,7 @@ namespace UDPT bool getBool (const string& key, bool defaultValue); int getInt (const string& key, int def = -1); map* getMap (); + void getIPs (const string& key, list &ip); private: friend class Settings; string className; From 145751c953ed280a31bd7e129ff9025135a67c2b Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 16 Aug 2013 02:09:29 +0300 Subject: [PATCH 41/99] Can specify an interface other than 0.0.0.0 --- src/udpTracker.cpp | 21 +++++++++++++++------ src/udpTracker.hpp | 1 + 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index c775afb..f137074 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -51,6 +51,20 @@ namespace UDPT this->port = sc_tracker->getInt("port", 6969); this->thread_count = abs (sc_tracker->getInt("threads", 5)) + 1; + list addrs; + sc_tracker->getIPs("bind", addrs); + + if (addrs.empty()) + { + SOCKADDR_IN sa; + sa.sin_port = m_hton16(port); + sa.sin_addr.s_addr = 0L; + addrs.push_back(sa); + } + + this->localEndpoint = addrs.front(); + + this->threads = new HANDLE[this->thread_count]; this->isRunning = false; @@ -97,7 +111,6 @@ namespace UDPT enum UDPTracker::StartStatus UDPTracker::start () { SOCKET sock; - SOCKADDR_IN recvAddr; int r, // saves results i, // loop index yup; // just to set TRUE @@ -107,14 +120,10 @@ namespace UDPT if (sock == INVALID_SOCKET) return START_ESOCKET_FAILED; - recvAddr.sin_addr.s_addr = 0L; - recvAddr.sin_family = AF_INET; - recvAddr.sin_port = m_hton16 (this->port); - yup = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); - r = bind (sock, (SOCKADDR*)&recvAddr, sizeof(SOCKADDR_IN)); + r = bind (sock, (SOCKADDR*)&this->localEndpoint, sizeof(SOCKADDR_IN)); if (r == SOCKET_ERROR) { diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 3f16716..31ab872 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -134,6 +134,7 @@ namespace UDPT Data::DatabaseDriver *conn; private: SOCKET sock; + SOCKADDR_IN localEndpoint; uint16_t port; uint8_t thread_count; bool isRunning; From 7e9ecdb09927010e5b94c8feabc94581f29b5d8b Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 16 Aug 2013 17:06:09 +0300 Subject: [PATCH 42/99] Improved logging, fixed minor bug. --- src/logging.cpp | 76 ++++++++++++++++++++++++++++++++++++++++++++-- src/logging.h | 18 ++++++++--- src/main.cpp | 3 +- src/settings.cpp | 1 + src/udpTracker.cpp | 7 +++-- 5 files changed, 93 insertions(+), 12 deletions(-) diff --git a/src/logging.cpp b/src/logging.cpp index 384154a..80ef946 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -18,15 +18,85 @@ */ #include "logging.h" +#include +#include +#include + +using namespace std; namespace UDPT { - Logger::Logger(Settings *s, ostream &os) : logfile (os) + + Logger::Logger(Settings *s) + : logfile (&std::cout) { + Settings::SettingClass *sc; + string filename = "stdout"; + string level = "error"; + + closeStreamOnDestroy = false; + + sc = s->getClass("logging"); + if (sc != NULL) + { + string::size_type i; + + filename = sc->get("filename"); + level = sc->get("level"); + + for (i = 0;i < level.length(); i++) + { + if (level[i] >= 'A' && level[i] <= 'Z') + level[i] = 'a' + (level[i] - 'A'); + } + } + + if (level == "debug" || level == "d") + this->loglevel = LL_DEBUG; + else if (level == "warning" || level == "w") + this->loglevel = LL_WARNING; + else if (level == "info" || level == "i") + this->loglevel = LL_INFO; + else + this->loglevel = LL_ERROR; + + if (filename.compare("stdout") != 0 && filename.length() > 0) + { + fstream fs; + fs.open(filename.c_str(), ios::binary | ios::out | ios::app); + if (!fs.is_open()) + { + this->log(LL_ERROR, "Failed to open log file."); + return; + } + this->logfile = &fs; + closeStreamOnDestroy = true; + } + } + + Logger::Logger(Settings *s, ostream &os) + : logfile (&os), loglevel (LL_ERROR) + { + closeStreamOnDestroy = false; + } + + Logger::~Logger() + { + fstream *f = (fstream*)this->logfile; + f->flush(); + if (closeStreamOnDestroy) + { + f->close(); + } } void Logger::log(enum LogLevel lvl, string msg) { - logfile << time (NULL) << ": (" << ((char)lvl) << "): "; - logfile << msg << "\n"; + const char letters[] = "EWID"; + if (lvl <= this->loglevel) + { + (*logfile) << time (NULL) << ": (" + << ((char)letters[lvl]) << "): " + << msg << "\n"; + } } }; diff --git a/src/logging.h b/src/logging.h index fe9362d..7d382ee 100644 --- a/src/logging.h +++ b/src/logging.h @@ -32,17 +32,25 @@ namespace UDPT { public: enum LogLevel { - LL_ERROR = 'E', - LL_WARNING = 'W', - LL_INFO = 'I', - LL_DEBUG = 'D' + LL_ERROR = 0, + LL_WARNING = 1, + LL_INFO = 2, + LL_DEBUG = 3 }; + Logger (Settings *s); + Logger (Settings *s, ostream &os); + virtual ~Logger (); + void log (enum LogLevel, string msg); private: - ostream &logfile; + ostream *logfile; + enum LogLevel loglevel; + bool closeStreamOnDestroy; + + static void setStream (Logger *logger, ostream &s); }; }; diff --git a/src/main.cpp b/src/main.cpp index 2338548..b2fb64d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -26,6 +26,7 @@ #include "http/httpserver.hpp" #include "http/webapp.hpp" #include // atoi +#include // signal using namespace std; using namespace UDPT; @@ -171,7 +172,7 @@ int main(int argc, char *argv[]) cerr << "Failed to read from '" << config_file.c_str() << "'. Using default settings." << endl; } - logger = new Logger (settings, cout); + logger = new Logger (settings); usi = new UDPTracker (settings); HTTPServer *apiSrv = NULL; diff --git a/src/settings.cpp b/src/settings.cpp index a6efac2..ab7120f 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -354,6 +354,7 @@ void _settings_clean_string (char **str) { string addr = v.substr(s, (e - s) + 1); SOCKADDR_IN saddr; + memset(&saddr, 0, sizeof (SOCKADDR_IN)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = 0L; saddr.sin_port = (6969); diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index f137074..df4e62f 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -110,6 +110,7 @@ namespace UDPT enum UDPTracker::StartStatus UDPTracker::start () { + stringstream ss; SOCKET sock; int r, // saves results i, // loop index @@ -123,6 +124,7 @@ namespace UDPT yup = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); + this->localEndpoint.sin_family = AF_INET; r = bind (sock, (SOCKADDR*)&this->localEndpoint, sizeof(SOCKADDR_IN)); if (r == SOCKET_ERROR) @@ -142,7 +144,7 @@ namespace UDPT this->isRunning = true; - stringstream ss; + ss.clear(); ss << "Starting maintenance thread (1/" << ((int)this->thread_count) << ")"; logger->log(Logger::LL_INFO, ss.str()); @@ -155,10 +157,9 @@ namespace UDPT for (i = 1;i < this->thread_count; i++) { - stringstream ss; + ss.clear(); ss << "Starting thread (" << (i + 1) << "/" << ((int)this->thread_count) << ")"; logger->log(Logger::LL_INFO, ss.str()); - ss.clear(); #ifdef WIN32 this->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)this, 0, NULL); From 0a222ab3ba6ccbb959563462740306beaff0e781 Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 16 Aug 2013 18:56:27 +0300 Subject: [PATCH 43/99] End process with signals. stdin ignored. --- src/main.cpp | 64 ++++++++++++++++++++++++++++++++++++--------- src/multiplatform.h | 2 +- src/udpTracker.cpp | 17 ++++++++++-- src/udpTracker.hpp | 5 ++++ 4 files changed, 72 insertions(+), 16 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index b2fb64d..7f11f37 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -33,6 +33,12 @@ using namespace UDPT; using namespace UDPT::Server; Logger *logger; +static struct { + Settings *settings; + UDPTracker *usi; + WebApp *wa; + HTTPServer *httpserver; +} Instance; static void _print_usage () { @@ -63,8 +69,8 @@ static void _doAPIStart (Settings *settings, WebApp **wa, HTTPServer **srv, Data threads = 1; try { - *srv = new HTTPServer (port, threads); - *wa = new WebApp (*srv, drvr, settings); + *srv = Instance.httpserver = new HTTPServer (port, threads); + *wa = Instance.wa = new WebApp (*srv, drvr, settings); (*wa)->deploy(); } catch (ServerException &e) { @@ -114,10 +120,33 @@ static void _setCWD (char *argv0) } +/** + * Releases resources before exit. + */ +static void _doCleanup () +{ + delete Instance.wa; + delete Instance.httpserver; + delete Instance.usi; + delete Instance.settings; + delete logger; + + memset (&Instance, 0, sizeof(Instance)); + logger = NULL; +} + +static void _signal_handler (int sig) +{ + stringstream ss; + ss << "Signal " << sig << " raised. Terminating..."; + logger->log(Logger::LL_INFO, ss.str()); + _doCleanup(); +} + int main(int argc, char *argv[]) { - Settings *settings = NULL; - UDPTracker *usi = NULL; + Settings *settings; + UDPTracker *usi; string config_file; int r; @@ -131,6 +160,20 @@ int main(int argc, char *argv[]) cout << "Build Date: " << __DATE__ << endl << endl; config_file = "udpt.conf"; + memset(&Instance, 0, sizeof(Instance)); + +#ifdef SIGBREAK + signal(SIGBREAK, &_signal_handler); +#endif +#ifdef SIGTERM + signal(SIGTERM, &_signal_handler); +#endif +#ifdef SIGABRT + signal(SIGABRT, &_signal_handler); +#endif +#ifdef SIGINT + signal(SIGINT, &_signal_handler); +#endif if (argc <= 1) { @@ -144,7 +187,7 @@ int main(int argc, char *argv[]) config_file = argv[1]; // reported in issue #5. } - settings = new Settings (config_file); + settings = Instance.settings = new Settings (config_file); if (!settings->load()) { @@ -173,7 +216,7 @@ int main(int argc, char *argv[]) } logger = new Logger (settings); - usi = new UDPTracker (settings); + usi = Instance.usi = new UDPTracker (settings); HTTPServer *apiSrv = NULL; WebApp *wa = NULL; @@ -199,18 +242,13 @@ int main(int argc, char *argv[]) _doAPIStart(settings, &wa, &apiSrv, usi->conn); - cout << "Press Any key to exit." << endl; + cout << "Hit Control-C to exit." << endl; - cin.get(); + usi->wait(); cleanup: cout << endl << "Goodbye." << endl; - delete usi; - delete settings; - delete apiSrv; - delete wa; - #ifdef WIN32 WSACleanup(); #endif diff --git a/src/multiplatform.h b/src/multiplatform.h index 5a7bf9a..bc2b18d 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -24,7 +24,7 @@ #if defined (_WIN32) && !defined (WIN32) #define WIN32 -#elif defined (__APPLE__) +#elif defined (__APPLE__) || defined (__CYGWIN__) #define linux #endif diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index df4e62f..2514868 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -108,6 +108,19 @@ namespace UDPT delete[] this->threads; } + void UDPTracker::wait() + { +#ifdef WIN32 + WaitForMultipleObjects(this->thread_count, this->threads, TRUE, INFINITE); +#else + int i; + for (i = 0;i < this->thread_count; i++) + { + pthread_join (this->threads[i], NULL); + } +#endif + } + enum UDPTracker::StartStatus UDPTracker::start () { stringstream ss; @@ -144,7 +157,7 @@ namespace UDPT this->isRunning = true; - ss.clear(); + ss.str(""); ss << "Starting maintenance thread (1/" << ((int)this->thread_count) << ")"; logger->log(Logger::LL_INFO, ss.str()); @@ -157,7 +170,7 @@ namespace UDPT for (i = 1;i < this->thread_count; i++) { - ss.clear(); + ss.str(""); ss << "Starting thread (" << (i + 1) << "/" << ((int)this->thread_count) << ")"; logger->log(Logger::LL_INFO, ss.str()); diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 31ab872..7a89417 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -125,6 +125,11 @@ namespace UDPT */ enum StartStatus start (); + /** + * Joins all threads, and waits for all of them to terminate. + */ + void wait (); + /** * Destroys resources that were created by constructor * @param usi Instance to destroy. From 3f76e9af9fee440081036b37f9efaac90e3317ad Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 17 Aug 2013 20:24:24 +0300 Subject: [PATCH 44/99] Linux fails to compile. Include missing. --- src/main.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.cpp b/src/main.cpp index 7f11f37..357be40 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -27,6 +27,7 @@ #include "http/webapp.hpp" #include // atoi #include // signal +#include // strlen using namespace std; using namespace UDPT; From ddba5b21b3ef163bd14369dfa8a9bd345d0a5601 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 18 Aug 2013 02:49:49 +0300 Subject: [PATCH 45/99] Ability to customize bind for HTTP --- src/http/httpserver.cpp | 51 ++++++++++++++++++++++++++++++++++++----- src/http/httpserver.hpp | 4 ++++ src/main.cpp | 13 ++--------- 3 files changed, 51 insertions(+), 17 deletions(-) diff --git a/src/http/httpserver.cpp b/src/http/httpserver.cpp index c32a2b9..c8d774f 100644 --- a/src/http/httpserver.cpp +++ b/src/http/httpserver.cpp @@ -33,9 +33,52 @@ namespace UDPT /* HTTPServer */ HTTPServer::HTTPServer (uint16_t port, int threads) { - int r; SOCKADDR_IN sa; + memset((void*)&sa, 0, sizeof(sa)); + sa.sin_addr.s_addr = 0L; + sa.sin_family = AF_INET; + sa.sin_port = htons (port); + + this->init(sa, threads); + } + + HTTPServer::HTTPServer(Settings *s) + { + Settings::SettingClass *sc = s->getClass("apiserver"); + list localEndpoints; + uint16_t port; + int threads; + + port = 6969; + threads = 1; + + if (sc != NULL) + { + port = sc->getInt("port", 6969); + threads = sc->getInt("threads", 1); + sc->getIPs("bind", localEndpoints); + } + + if (threads <= 0) + threads = 1; + + if (localEndpoints.empty()) + { + SOCKADDR_IN sa; + memset((void*)&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons (port); + sa.sin_addr.s_addr = 0L; + localEndpoints.push_front(sa); + } + + this->init(localEndpoints.front(), threads); + } + + void HTTPServer::init (SOCKADDR_IN &localEndpoint, int threads) + { + int r; this->thread_count = threads; this->threads = new HANDLE[threads]; this->isRunning = false; @@ -48,11 +91,7 @@ namespace UDPT throw ServerException (1, "Failed to create Socket"); } - sa.sin_addr.s_addr = 0L; - sa.sin_family = AF_INET; - sa.sin_port = htons (port); - - r = bind (this->srv, (SOCKADDR*)&sa, sizeof(sa)); + r = bind (this->srv, (SOCKADDR*)&localEndpoint, sizeof(localEndpoint)); if (r == SOCKET_ERROR) { throw ServerException (2, "Failed to bind socket"); diff --git a/src/http/httpserver.hpp b/src/http/httpserver.hpp index 4a32e0a..e4b1d16 100644 --- a/src/http/httpserver.hpp +++ b/src/http/httpserver.hpp @@ -25,6 +25,7 @@ #include #include #include "../multiplatform.h" +#include "../settings.hpp" using namespace std; #define REQUEST_BUFFER_SIZE 2048 @@ -130,6 +131,7 @@ namespace UDPT typedef void (reqCallback)(HTTPServer*,Request*,Response*); HTTPServer (uint16_t port, int threads); + HTTPServer (Settings *s); void addApp (list *path, reqCallback *); @@ -152,6 +154,8 @@ namespace UDPT appNode rootNode; map customData; + void init (SOCKADDR_IN &localEndpoint, int threads); + static void handleConnections (HTTPServer *); #ifdef WIN32 diff --git a/src/main.cpp b/src/main.cpp index 357be40..67ba4fc 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -54,23 +54,14 @@ static void _doAPIStart (Settings *settings, WebApp **wa, HTTPServer **srv, Data if (sc == NULL) return; // no settings set! - if (sc->get("enable") != "1") + if (!sc->getBool("enable", false)) { cerr << "API Server not enabled." << endl; return; } - string s_port = sc->get("port"); - string s_threads = sc->get("threads"); - - uint16_t port = (s_port == "" ? 6969 : atoi (s_port.c_str())); - uint16_t threads = (s_threads == "" ? 1 : atoi (s_threads.c_str())); - - if (threads <= 0) - threads = 1; - try { - *srv = Instance.httpserver = new HTTPServer (port, threads); + *srv = Instance.httpserver = new HTTPServer (settings); *wa = Instance.wa = new WebApp (*srv, drvr, settings); (*wa)->deploy(); } catch (ServerException &e) From 1702177307141a7b5c7ac7b90fc9093cc96495dd Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 18 Aug 2013 03:22:30 +0300 Subject: [PATCH 46/99] Minor changes, README upddated (finally...) --- README | 39 ++++++++++++++++++++++----------------- src/main.cpp | 2 +- src/multiplatform.h | 15 ++++++++++----- 3 files changed, 33 insertions(+), 23 deletions(-) diff --git a/README b/README index 5110a8f..90e2646 100644 --- a/README +++ b/README @@ -1,23 +1,28 @@ -README for the UDPT project. +What is UDPT? +The UDPT project is a BitTorrent Tracking software. +It uses the UDP protocol (instead of the HTTP protocol) to track +peers downloading the same software. UDPT was written according +to BEP 15 of the BitTorrent standard. -Licensed under GNU GPLv3. -The license file is attached under the name gpl.txt. +Who Wrote UDPT, and when? +UDPT is an ongoing project (at the meantime), it's development +started on Nevember 20th, 2012. +It was written by Naim A. . Naim wrote this +program for fun in his free time. -Compiling under linux or linux environment (MinGW): +Required Software: +UDPT depends on SQLite3 (public-domain, compatible with GPL). +UDPT's source is designed to be platform portable. It is +supported with Windows and with Linux based systems, It should +work with Apple's systems but it might not (no officially supported). -For Windows (with Linux environment): -$ make win32 +I need help using this software, what should I do? +You may want to visit the documentation at the projects's site. +Address: http://code.google.com/p/udpt -For Linux: -$ make linux +Can I suggest a feature or report a bug? +Yes, you can. Please submit a feature request at: +http://code.google.com/p/udpt/issues -Running: -$ ./udpt - -Cleaning: -$ make clean - -This software currently uses the Sqlite3 Library (public domain). - -Developed by Naim A. . +Please visit http://code.google.com/p/udpt for updates. diff --git a/src/main.cpp b/src/main.cpp index 67ba4fc..86c923a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -147,7 +147,7 @@ int main(int argc, char *argv[]) WSAStartup(MAKEWORD(2, 2), &wsadata); #endif - cout << "UDP Tracker (UDPT) " << VERSION << endl; + cout << "UDP Tracker (UDPT) " << VERSION << " (" << PLATFORM << ")" << endl; cout << "Copyright 2012,2013 Naim Abda \n\tReleased under the GPLv3 License." << endl; cout << "Build Date: " << __DATE__ << endl << endl; diff --git a/src/multiplatform.h b/src/multiplatform.h index bc2b18d..e03f9be 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -28,10 +28,11 @@ #define linux #endif +#define VERSION "1.0.0-beta" + #ifdef WIN32 #include #include -#define VERSION "1.0.0-beta (Windows)" #elif defined (linux) #include #include @@ -54,10 +55,14 @@ typedef void* LPVOID; typedef void (LPTHREAD_START_ROUTINE)(LPVOID); typedef pthread_t HANDLE; -#define VERSION "1.0.0-beta (Linux)" #endif -#ifdef __APPLE__ -#undef VERSION -#define VERSION "1.0.0-beta (Apple)" +#ifdef WIN32 +#define PLATFORM "Windows" +#elif defined (__APPLE__) +#define PLATFORM "Apple" +#elif defined (__CYGWIN__) +#define PLATFORM "Cygwin" +#else +#define PLATFORM "Linux" #endif From bf94f4e0bea45277754d6c0a23319eb7c5e67f0b Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 28 Nov 2015 15:37:38 -0800 Subject: [PATCH 47/99] minor fixes --- .gitignore | 1 + Makefile | 4 +--- 2 files changed, 2 insertions(+), 3 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5761abc --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.o diff --git a/Makefile b/Makefile index 70a3f95..0de727a 100644 --- a/Makefile +++ b/Makefile @@ -34,12 +34,10 @@ all: $(target) $(target): $(objects) @echo Linking... - $(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lsqlite3 + $(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lsqlite3 -lpthread @echo Done. clean: @echo Cleaning Up... $(RM) $(objects) $(target) @echo Done. -install: $(target) - @echo Installing $(target) to '$(exec_prefix)/bin'... From 1de524cb9942471ff1675ace1f1f0e4e6ee0c7c2 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 28 Nov 2015 15:44:27 -0800 Subject: [PATCH 48/99] Update to readme --- README | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/README b/README index 90e2646..a941a6a 100644 --- a/README +++ b/README @@ -6,8 +6,7 @@ peers downloading the same software. UDPT was written according to BEP 15 of the BitTorrent standard. Who Wrote UDPT, and when? -UDPT is an ongoing project (at the meantime), it's development -started on Nevember 20th, 2012. +UDPT's development started on Nevember 20th, 2012. It was written by Naim A. . Naim wrote this program for fun in his free time. @@ -17,12 +16,5 @@ UDPT's source is designed to be platform portable. It is supported with Windows and with Linux based systems, It should work with Apple's systems but it might not (no officially supported). -I need help using this software, what should I do? -You may want to visit the documentation at the projects's site. -Address: http://code.google.com/p/udpt +Project page: http://www.github.com/naim94a/udpt -Can I suggest a feature or report a bug? -Yes, you can. Please submit a feature request at: -http://code.google.com/p/udpt/issues - -Please visit http://code.google.com/p/udpt for updates. From 5842706d29bf444a935dc25d7d2e2a0f979adf4c Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 21 Jan 2016 15:40:48 -0800 Subject: [PATCH 49/99] New README --- .gitignore | 1 + README | 20 -------------------- README.md | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 20 deletions(-) delete mode 100644 README create mode 100644 README.md diff --git a/.gitignore b/.gitignore index 5761abc..8c483d3 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ *.o +*.sublime-* diff --git a/README b/README deleted file mode 100644 index a941a6a..0000000 --- a/README +++ /dev/null @@ -1,20 +0,0 @@ - -What is UDPT? -The UDPT project is a BitTorrent Tracking software. -It uses the UDP protocol (instead of the HTTP protocol) to track -peers downloading the same software. UDPT was written according -to BEP 15 of the BitTorrent standard. - -Who Wrote UDPT, and when? -UDPT's development started on Nevember 20th, 2012. -It was written by Naim A. . Naim wrote this -program for fun in his free time. - -Required Software: -UDPT depends on SQLite3 (public-domain, compatible with GPL). -UDPT's source is designed to be platform portable. It is -supported with Windows and with Linux based systems, It should -work with Apple's systems but it might not (no officially supported). - -Project page: http://www.github.com/naim94a/udpt - diff --git a/README.md b/README.md new file mode 100644 index 0000000..82b0d2a --- /dev/null +++ b/README.md @@ -0,0 +1,39 @@ + +# UDPT +The UDPT project is a BitTorrent Tracking software. +It uses the UDP protocol (instead of the HTTP protocol) to track +peers downloading the same software. UDPT was written according +to [BEP 15](http://www.bittorrent.org/beps/bep_0015.html) of the BitTorrent standard. + +UDPT is designed to run on both Windows and Linux-based platform (It may run on Apple systems too). + +### License +UDPT is released under the [GPL](http://www.gnu.org/licenses/gpl-3.0.en.html) license, a copy is included in this repository. +We use [SQLite3](http://www.sqlite.org/) which is public-domain. + +### Building +We didn't really work on creating any installer, at the moment you can just run udpt from anywhere on your filesystem. +Building udpt is pretty straightforward, just download the project or clone the repo: + +UDPT requires the SQLite3 develpment package to be installed. + +
+    $ git clone https://github.com/naim94a/udpt.git
+    $ cd udpt
+    $ make
+
+ +And finally: + +
+    $ ./udpt
+
+ +### Links +* Documentation can be found at our wiki: https://github.com/naim94a/udpt/wiki +* If you have any suggestions or find any bugs, please report them here: https://github.com/naim94a/udpt/issues +* Project Page: http://www.github.com/naim94a/udpt + +### Author(s) +UDPT was developed by [Naim A.](http://www.github.com/naim94a) at for fun at his free time. +The development started on November 20th, 2012. From bc97b747ad3727b4e41a2a62ece19c44d9035443 Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 21 Jan 2016 16:06:05 -0800 Subject: [PATCH 50/99] Remove useless comments or prints --- src/db/database.cpp | 2 +- src/db/database.hpp | 2 +- src/db/driver_sqlite.cpp | 9 ++------ src/db/driver_sqlite.hpp | 4 ++-- src/http/httpserver.cpp | 6 ++--- src/http/httpserver.hpp | 2 +- src/http/webapp.cpp | 13 ++++------- src/http/webapp.hpp | 2 +- src/logging.cpp | 2 +- src/logging.h | 2 +- src/main.cpp | 2 +- src/multiplatform.h | 2 +- src/settings.cpp | 4 +--- src/settings.hpp | 50 +--------------------------------------- src/tools.c | 2 +- src/tools.h | 2 +- src/udpTracker.cpp | 5 +--- src/udpTracker.hpp | 2 +- 18 files changed, 25 insertions(+), 88 deletions(-) diff --git a/src/db/database.cpp b/src/db/database.cpp index a521a9f..c0e0a2d 100644 --- a/src/db/database.cpp +++ b/src/db/database.cpp @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/db/database.hpp b/src/db/database.hpp index ac4f9e5..6af4353 100644 --- a/src/db/database.hpp +++ b/src/db/database.hpp @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp index 9601420..e859055 100644 --- a/src/db/driver_sqlite.cpp +++ b/src/db/driver_sqlite.cpp @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * @@ -99,7 +99,6 @@ namespace UDPT void SQLite3Driver::doSetup() { -// cout << "Creating DB..." << endl; char *eMsg = NULL; // for quicker stats. sqlite3_exec(this->db, "CREATE TABLE stats (" @@ -109,13 +108,11 @@ namespace UDPT "seeders INTEGER DEFAULT 0," "last_mod INTEGER DEFAULT 0" ")", NULL, NULL, &eMsg); -// cout << "stats: " << (eMsg == NULL ? "OK" : eMsg) << endl; - // for non-Dynamic trackers + sqlite3_exec(this->db, "CREATE TABLE torrents (" "info_hash blob(20) UNIQUE," "created INTEGER" ")", NULL, NULL, &eMsg); -// cout << "torrents: " << (eMsg == NULL ? "OK" : eMsg) << endl; } bool SQLite3Driver::getTorrentInfo(TorrentEntry *e) @@ -209,8 +206,6 @@ namespace UDPT sql += hash; sql += "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)"; - // printf("IP->%x::%u\n", pE->ip, pE->port); - sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL); sqlite3_bind_blob(stmt, 1, (void*)peer_id, 20, NULL); diff --git a/src/db/driver_sqlite.hpp b/src/db/driver_sqlite.hpp index 34b28d9..2c6b392 100644 --- a/src/db/driver_sqlite.hpp +++ b/src/db/driver_sqlite.hpp @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * @@ -43,7 +43,7 @@ namespace UDPT bool getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe); void cleanup (); - ~SQLite3Driver (); + virtual ~SQLite3Driver (); private: sqlite3 *db; diff --git a/src/http/httpserver.cpp b/src/http/httpserver.cpp index c8d774f..053c128 100644 --- a/src/http/httpserver.cpp +++ b/src/http/httpserver.cpp @@ -1,5 +1,5 @@ /* - * Copyright © 2013 Naim A. + * Copyright © 2013-2016 Naim A. * * This file is part of UDPT. * @@ -167,7 +167,7 @@ doSrv: stringstream stream; stream << ""; stream << "Not Found"; - stream << "

Not Found

The server couldn't find the request resource.


© 2013 Naim A. | The UDPT Project
"; + stream << "

Not Found

The server couldn't find the request resource.


"; stream << ""; string str = stream.str(); resp.write (str.c_str(), str.length()); @@ -183,7 +183,7 @@ doSrv: stringstream stream; stream << ""; stream << "Internal Server Error"; - stream << "

Internal Server Error

An Error Occurred while trying to process your request.


© 2013 Naim A. | The UDPT Project
"; + stream << "

Internal Server Error

An Error Occurred while trying to process your request.


"; stream << ""; string str = stream.str(); resp.write (str.c_str(), str.length()); diff --git a/src/http/httpserver.hpp b/src/http/httpserver.hpp index e4b1d16..39e2602 100644 --- a/src/http/httpserver.hpp +++ b/src/http/httpserver.hpp @@ -1,5 +1,5 @@ /* - * Copyright © 2013 Naim A. + * Copyright © 2013-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/http/webapp.cpp b/src/http/webapp.cpp index 4f2f870..4450d57 100644 --- a/src/http/webapp.cpp +++ b/src/http/webapp.cpp @@ -1,5 +1,5 @@ /* - * Copyright © 2013 Naim A. + * Copyright © 2013-2016 Naim A. * * This file is part of UDPT. * @@ -150,15 +150,10 @@ namespace UDPT { // It would be very appreciated to keep this in the code. resp->write("" - "Powered by UDPT" + "UDPT Torrent Tracker" "" - "

The UDPT Project

" - "
This tracker is running on UDPT Software.
" - "UDPT is a open-source project, freely available for anyone to use. If you would like to obtain a copy of the software, you can get it here: http://code.googe.com/p/udpt." - "

If you would like to help the project grow, please donate for our hard work, effort & time: " - "\"Donate" - "
" - "

© 2013 Naim A. | Powered by UDPT
" + "
This tracker is running on UDPT Software.
" + "

" "" ""); } diff --git a/src/http/webapp.hpp b/src/http/webapp.hpp index 6a8011f..7b807fa 100644 --- a/src/http/webapp.hpp +++ b/src/http/webapp.hpp @@ -1,5 +1,5 @@ /* - * Copyright © 2013 Naim A. + * Copyright © 2013-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/logging.cpp b/src/logging.cpp index 80ef946..e7110f9 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/logging.h b/src/logging.h index 7d382ee..e7f300b 100644 --- a/src/logging.h +++ b/src/logging.h @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/main.cpp b/src/main.cpp index 86c923a..7414ea9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/multiplatform.h b/src/multiplatform.h index e03f9be..5ff6d1c 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/settings.cpp b/src/settings.cpp index ab7120f..4da755e 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1,6 +1,6 @@ /* * - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * @@ -156,8 +156,6 @@ void _settings_clean_string (char **str) _settings_clean_string(&key); _settings_clean_string(&value); - // printf("KEY: '%s'\tVALUE: '%s'\n", key, value); - // add to settings... this->set (className, key, value); diff --git a/src/settings.hpp b/src/settings.hpp index 6c308e2..dcec64a 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -1,6 +1,6 @@ /* * - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * @@ -119,51 +119,3 @@ namespace UDPT void parseSettings (char *data, int len); }; }; - -//#ifdef __cplusplus -//extern "C" { -//#endif -// -//typedef struct { -// char *key; -// char *values; -//} KeyValue; -// -//typedef struct { -// char *classname; -// KeyValue *entries; -// uint32_t entry_count, entry_size; -//} SettingClass; -// -//typedef struct { -// char *filename; -// -// SettingClass *classes; -// uint32_t class_count, class_size; -// -// char *buffer; -//} Settings; -// -// -//void settings_init (Settings *s, const char *filename); -// -//int settings_load (Settings *s); -// -//int settings_save (Settings *s); -// -//void settings_destroy (Settings *s); -// -//SettingClass* settings_get_class (Settings *s, const char *classname); -// -//char* settingclass_get (SettingClass *s, const char *name); -// -//int settingclass_set (SettingClass *s, const char *name, const char *value); -// -//char* settings_get (Settings *s, const char *classn, const char *name); -// -// -//int settings_set (Settings *s, const char *classn, const char *name, const char *value); -// -//#ifdef __cplusplus -//} -//#endif diff --git a/src/tools.c b/src/tools.c index e47098d..60faa2b 100644 --- a/src/tools.c +++ b/src/tools.c @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/tools.h b/src/tools.h index be0afc5..39b1840 100644 --- a/src/tools.h +++ b/src/tools.h @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index 2514868..00f4f70 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * @@ -443,8 +443,6 @@ static int _isIANA_IP (uint32_t ip) } } -// cout << ":: " << (void*)m_hton32(remote->sin_addr.s_addr) << ": " << m_hton16(remote->sin_port) << " ACTION=" << action << endl; - if (action == 0 && r >= 16) return UDPTracker::handleConnection (usi, remote, data); else if (action == 1 && r >= 98) @@ -453,7 +451,6 @@ static int _isIANA_IP (uint32_t ip) return UDPTracker::handleScrape (usi, remote, data, r); else { -// cout << "E: action=" << action << ", r=" << r << endl; UDPTracker::sendError (usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); return -1; } diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 7a89417..6344740 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -1,5 +1,5 @@ /* - * Copyright © 2012,2013 Naim A. + * Copyright © 2012-2016 Naim A. * * This file is part of UDPT. * From edaa44bfc7bf1ed1ce5a7d939a0a54921349aa90 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 23 Jan 2016 18:11:51 +0200 Subject: [PATCH 51/99] Resolved Issues #10 and #11 --- src/db/database.cpp | 3 +- src/db/database.hpp | 37 +++++----- src/db/driver_sqlite.cpp | 4 +- src/db/driver_sqlite.hpp | 26 +++---- src/http/httpserver.cpp | 31 +++----- src/http/httpserver.hpp | 4 +- src/http/webapp.cpp | 6 +- src/http/webapp.hpp | 7 +- src/logging.cpp | 24 +----- src/logging.h | 14 ++-- src/main.cpp | 155 ++++++++++++++++++++++++--------------- src/udpTracker.cpp | 30 +++----- src/udpTracker.hpp | 5 +- 13 files changed, 178 insertions(+), 168 deletions(-) diff --git a/src/db/database.cpp b/src/db/database.cpp index c0e0a2d..1df5798 100644 --- a/src/db/database.cpp +++ b/src/db/database.cpp @@ -23,9 +23,8 @@ namespace UDPT { namespace Data { - DatabaseDriver::DatabaseDriver(Settings::SettingClass *sc, bool isDynamic) + DatabaseDriver::DatabaseDriver(const boost::program_options::variables_map& conf, bool isDynamic) : m_conf(conf) { - this->dClass = sc; this->is_dynamic = isDynamic; } diff --git a/src/db/database.hpp b/src/db/database.hpp index 6af4353..535ef17 100644 --- a/src/db/database.hpp +++ b/src/db/database.hpp @@ -21,6 +21,7 @@ #define DATABASE_HPP_ #include "../settings.hpp" +#include namespace UDPT { @@ -35,10 +36,10 @@ namespace UDPT E_CONNECTION_FAILURE = 2 }; - DatabaseException (); - DatabaseException (EType); - EType getErrorType (); - const char* getErrorMessage (); + DatabaseException(); + DatabaseException(EType); + EType getErrorType(); + const char* getErrorMessage(); private: EType errorNum; }; @@ -68,34 +69,34 @@ namespace UDPT * Opens the DB's connection * @param dClass Settings class ('database' class). */ - DatabaseDriver (Settings::SettingClass *dClass, bool isDynamic = false); + DatabaseDriver(const boost::program_options::variables_map& conf, bool isDynamic = false); /** * Adds a torrent to the Database. automatically done if in dynamic mode. * @param hash The info_hash of the torrent. * @return true on success. false on failure. */ - virtual bool addTorrent (uint8_t hash[20]); + virtual bool addTorrent(uint8_t hash[20]); /** * Removes a torrent from the database. should be used only for non-dynamic trackers or by cleanup. * @param hash The info_hash to drop. * @return true if torrent's database was dropped or no longer exists. otherwise false (shouldn't happen - critical) */ - virtual bool removeTorrent (uint8_t hash[20]); + virtual bool removeTorrent(uint8_t hash[20]); /** * Checks if the Database is acting as a dynamic tracker DB. * @return true if dynamic. otherwise false. */ - bool isDynamic (); + bool isDynamic(); /** * Checks if the torrent can be used in the tracker. * @param info_hash The torrent's info_hash. * @return true if allowed. otherwise false. */ - virtual bool isTorrentAllowed (uint8_t info_hash [20]); + virtual bool isTorrentAllowed(uint8_t info_hash [20]); /** * Generate a Connection ID for the peer. @@ -104,9 +105,9 @@ namespace UDPT * @param port The peer's IP (remote port if tracker accepts) * @return */ - virtual bool genConnectionId (uint64_t *connectionId, uint32_t ip, uint16_t port); + virtual bool genConnectionId(uint64_t *connectionId, uint32_t ip, uint16_t port); - virtual bool verifyConnectionId (uint64_t connectionId, uint32_t ip, uint16_t port); + virtual bool verifyConnectionId(uint64_t connectionId, uint32_t ip, uint16_t port); /** * Updates/Adds a peer to/in the database. @@ -119,7 +120,7 @@ namespace UDPT * @param uploaded total bytes uploaded * @return true on success, false on failure. */ - virtual bool updatePeer (uint8_t peer_id [20], uint8_t info_hash [20], + virtual bool updatePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port, int64_t downloaded, int64_t left, int64_t uploaded, enum TrackerEvents event); @@ -132,14 +133,14 @@ namespace UDPT * @param port The TCP port (remote port if tracker accepts) * @return true on success. false on failure (shouldn't happen - critical) */ - virtual bool removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port); + virtual bool removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port); /** * Gets stats on a torrent * @param e TorrentEntry, only this info_hash has to be set * @return true on success, false on failure. */ - virtual bool getTorrentInfo (TorrentEntry *e); + virtual bool getTorrentInfo(TorrentEntry *e); /** * Gets a list of peers from the database. @@ -148,21 +149,21 @@ namespace UDPT * @param pe The list of peers. Must be pre-allocated to the size of max_count. * @return true on success, otherwise false (shouldn't happen). */ - virtual bool getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe); + virtual bool getPeers(uint8_t info_hash [20], int *max_count, PeerEntry *pe); /** * Cleanup the database. * Other actions may be locked when using this depending on the driver. */ - virtual void cleanup (); + virtual void cleanup(); /** * Closes the connections, and releases all other resources. */ - virtual ~DatabaseDriver (); + virtual ~DatabaseDriver(); protected: - Settings::SettingClass *dClass; + const boost::program_options::variables_map& m_conf; private: bool is_dynamic; }; diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp index e859055..cf8bc65 100644 --- a/src/db/driver_sqlite.cpp +++ b/src/db/driver_sqlite.cpp @@ -69,13 +69,13 @@ namespace UDPT return data; } - SQLite3Driver::SQLite3Driver (Settings::SettingClass *sc, bool isDyn) : DatabaseDriver(sc, isDyn) + SQLite3Driver::SQLite3Driver(const boost::program_options::variables_map& conf, bool isDyn) : DatabaseDriver(conf, isDyn) { int r; bool doSetup; fstream fCheck; - string filename = sc->get("file"); + string filename = m_conf["db.param"].as(); fCheck.open(filename.c_str(), ios::binary | ios::in); if (fCheck.is_open()) diff --git a/src/db/driver_sqlite.hpp b/src/db/driver_sqlite.hpp index 2c6b392..048abbc 100644 --- a/src/db/driver_sqlite.hpp +++ b/src/db/driver_sqlite.hpp @@ -31,23 +31,23 @@ namespace UDPT class SQLite3Driver : public DatabaseDriver { public: - SQLite3Driver (Settings::SettingClass *sc, bool isDyn = false); - bool addTorrent (uint8_t info_hash[20]); - bool removeTorrent (uint8_t info_hash[20]); - bool genConnectionId (uint64_t *connId, uint32_t ip, uint16_t port); - bool verifyConnectionId (uint64_t connId, uint32_t ip, uint16_t port); - bool updatePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port, int64_t downloaded, int64_t left, int64_t uploaded, enum TrackerEvents event); - bool removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port); - bool getTorrentInfo (TorrentEntry *e); - bool isTorrentAllowed (uint8_t info_hash[20]); - bool getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe); - void cleanup (); + SQLite3Driver(const boost::program_options::variables_map& conf, bool isDyn = false); + bool addTorrent(uint8_t info_hash[20]); + bool removeTorrent(uint8_t info_hash[20]); + bool genConnectionId(uint64_t *connId, uint32_t ip, uint16_t port); + bool verifyConnectionId(uint64_t connId, uint32_t ip, uint16_t port); + bool updatePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port, int64_t downloaded, int64_t left, int64_t uploaded, enum TrackerEvents event); + bool removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port); + bool getTorrentInfo(TorrentEntry *e); + bool isTorrentAllowed(uint8_t info_hash[20]); + bool getPeers(uint8_t info_hash [20], int *max_count, PeerEntry *pe); + void cleanup(); - virtual ~SQLite3Driver (); + virtual ~SQLite3Driver(); private: sqlite3 *db; - void doSetup (); + void doSetup(); }; }; }; diff --git a/src/http/httpserver.cpp b/src/http/httpserver.cpp index 053c128..27ac298 100644 --- a/src/http/httpserver.cpp +++ b/src/http/httpserver.cpp @@ -23,6 +23,7 @@ #include #include #include "httpserver.hpp" +#include using namespace std; @@ -43,26 +44,18 @@ namespace UDPT this->init(sa, threads); } - HTTPServer::HTTPServer(Settings *s) + HTTPServer::HTTPServer(const boost::program_options::variables_map& conf) { - Settings::SettingClass *sc = s->getClass("apiserver"); list localEndpoints; uint16_t port; int threads; - port = 6969; - threads = 1; - - if (sc != NULL) - { - port = sc->getInt("port", 6969); - threads = sc->getInt("threads", 1); - sc->getIPs("bind", localEndpoints); - } + port = conf["apiserver.port"].as(); + threads = conf["apiserver.threads"].as(); if (threads <= 0) threads = 1; - + if (localEndpoints.empty()) { SOCKADDR_IN sa; @@ -85,16 +78,16 @@ namespace UDPT this->rootNode.callback = NULL; - this->srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); + this->srv = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (this->srv == INVALID_SOCKET) { throw ServerException (1, "Failed to create Socket"); } - r = bind (this->srv, (SOCKADDR*)&localEndpoint, sizeof(localEndpoint)); + r = ::bind(this->srv, (SOCKADDR*)&localEndpoint, sizeof(localEndpoint)); if (r == SOCKET_ERROR) { - throw ServerException (2, "Failed to bind socket"); + throw ServerException(2, "Failed to bind socket"); } this->isRunning = true; @@ -118,7 +111,7 @@ namespace UDPT doSrv: try { HTTPServer::handleConnections (s); - } catch (ServerException &se) + } catch (const ServerException &se) { cerr << "SRV ERR #" << se.getErrorCode() << ": " << se.getErrorMsg () << endl; goto doSrv; @@ -139,13 +132,13 @@ doSrv: while (server->isRunning) { - r = listen (server->srv, 50); + r = ::listen(server->srv, 50); if (r == SOCKET_ERROR) { #ifdef WIN32 - Sleep (500); + ::Sleep(500); #else - sleep (1); + ::sleep(1); #endif continue; } diff --git a/src/http/httpserver.hpp b/src/http/httpserver.hpp index 39e2602..45d48a9 100644 --- a/src/http/httpserver.hpp +++ b/src/http/httpserver.hpp @@ -24,8 +24,8 @@ #include #include #include +#include #include "../multiplatform.h" -#include "../settings.hpp" using namespace std; #define REQUEST_BUFFER_SIZE 2048 @@ -131,7 +131,7 @@ namespace UDPT typedef void (reqCallback)(HTTPServer*,Request*,Response*); HTTPServer (uint16_t port, int threads); - HTTPServer (Settings *s); + HTTPServer(const boost::program_options::variables_map& conf); void addApp (list *path, reqCallback *); diff --git a/src/http/webapp.cpp b/src/http/webapp.cpp index 4450d57..297fce0 100644 --- a/src/http/webapp.cpp +++ b/src/http/webapp.cpp @@ -97,11 +97,11 @@ namespace UDPT return true; } - WebApp::WebApp(HTTPServer *srv, DatabaseDriver *db, Settings *settings) + WebApp::WebApp(HTTPServer *srv, DatabaseDriver *db, const boost::program_options::variables_map& conf) : m_conf(conf) { this->instance = srv; this->db = db; - this->sc_api = settings->getClass("api"); + /* this->sc_api = settings->getClass("api"); Settings::SettingClass *apiKeys = settings->getClass("api.keys"); if (apiKeys != NULL) @@ -124,7 +124,7 @@ namespace UDPT this->ip_whitelist.insert(pair >(key, ips)); } - } + } */ srv->setData("webapp", this); } diff --git a/src/http/webapp.hpp b/src/http/webapp.hpp index 7b807fa..fdb37c4 100644 --- a/src/http/webapp.hpp +++ b/src/http/webapp.hpp @@ -25,6 +25,7 @@ #include #include #include +#include using namespace std; using namespace UDPT; @@ -37,15 +38,15 @@ namespace UDPT class WebApp { public: - WebApp (HTTPServer *, DatabaseDriver *, Settings *); - ~WebApp (); + WebApp(HTTPServer *, DatabaseDriver *, const boost::program_options::variables_map& conf); + ~WebApp(); void deploy (); private: HTTPServer *instance; UDPT::Data::DatabaseDriver *db; - Settings::SettingClass *sc_api; + const boost::program_options::variables_map& m_conf; std::map > ip_whitelist; static void handleRoot (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); diff --git a/src/logging.cpp b/src/logging.cpp index e7110f9..5fcf3dc 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -26,30 +26,14 @@ using namespace std; namespace UDPT { - Logger::Logger(Settings *s) + Logger::Logger(const boost::program_options::variables_map& s) : logfile (&std::cout) { - Settings::SettingClass *sc; - string filename = "stdout"; - string level = "error"; + const string& filename = s["logging.filename"].as(); + const string& level = s["logging.level"].as(); closeStreamOnDestroy = false; - sc = s->getClass("logging"); - if (sc != NULL) - { - string::size_type i; - - filename = sc->get("filename"); - level = sc->get("level"); - - for (i = 0;i < level.length(); i++) - { - if (level[i] >= 'A' && level[i] <= 'Z') - level[i] = 'a' + (level[i] - 'A'); - } - } - if (level == "debug" || level == "d") this->loglevel = LL_DEBUG; else if (level == "warning" || level == "w") @@ -73,7 +57,7 @@ namespace UDPT { } } - Logger::Logger(Settings *s, ostream &os) + Logger::Logger(const boost::program_options::variables_map& s, ostream &os) : logfile (&os), loglevel (LL_ERROR) { closeStreamOnDestroy = false; diff --git a/src/logging.h b/src/logging.h index e7f300b..a9c4af6 100644 --- a/src/logging.h +++ b/src/logging.h @@ -25,10 +25,12 @@ #include #include #include +#include namespace UDPT { using namespace std; - class Logger { + class Logger + { public: enum LogLevel { @@ -38,19 +40,19 @@ namespace UDPT { LL_DEBUG = 3 }; - Logger (Settings *s); + Logger(const boost::program_options::variables_map& s); - Logger (Settings *s, ostream &os); + Logger(const boost::program_options::variables_map& s, ostream &os); - virtual ~Logger (); + virtual ~Logger(); - void log (enum LogLevel, string msg); + void log(enum LogLevel, string msg); private: ostream *logfile; enum LogLevel loglevel; bool closeStreamOnDestroy; - static void setStream (Logger *logger, ostream &s); + static void setStream(Logger *logger, ostream &s); }; }; diff --git a/src/main.cpp b/src/main.cpp index 7414ea9..4e466f7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -28,6 +28,8 @@ #include // atoi #include // signal #include // strlen +#include +#include using namespace std; using namespace UDPT; @@ -41,32 +43,28 @@ static struct { HTTPServer *httpserver; } Instance; + static void _print_usage () { cout << "Usage: udpt []" << endl; } -static void _doAPIStart (Settings *settings, WebApp **wa, HTTPServer **srv, DatabaseDriver *drvr) +static void _doAPIStart (const boost::program_options::variables_map& settings, WebApp **wa, HTTPServer **srv, DatabaseDriver *drvr) { - if (settings == NULL) - return; - Settings::SettingClass *sc = settings->getClass("apiserver"); - if (sc == NULL) - return; // no settings set! - - if (!sc->getBool("enable", false)) + if (!settings["apiserver.enable"].as()) { - cerr << "API Server not enabled." << endl; return; } - try { - *srv = Instance.httpserver = new HTTPServer (settings); - *wa = Instance.wa = new WebApp (*srv, drvr, settings); - (*wa)->deploy(); - } catch (ServerException &e) + try { - cerr << "ServerException #" << e.getErrorCode() << ": " << e.getErrorMsg() << endl; + *srv = Instance.httpserver = new HTTPServer(settings); + *wa = Instance.wa = new WebApp(*srv, drvr, settings); + (*wa)->deploy(); + } + catch (const ServerException &e) + { + std::cerr << "ServerException #" << e.getErrorCode() << ": " << e.getErrorMsg() << endl; } } @@ -137,9 +135,7 @@ static void _signal_handler (int sig) int main(int argc, char *argv[]) { - Settings *settings; UDPTracker *usi; - string config_file; int r; #ifdef WIN32 @@ -147,11 +143,81 @@ int main(int argc, char *argv[]) WSAStartup(MAKEWORD(2, 2), &wsadata); #endif - cout << "UDP Tracker (UDPT) " << VERSION << " (" << PLATFORM << ")" << endl; - cout << "Copyright 2012,2013 Naim Abda \n\tReleased under the GPLv3 License." << endl; - cout << "Build Date: " << __DATE__ << endl << endl; + boost::program_options::options_description commandLine("Command line options"); + commandLine.add_options() + ("help,h", "produce help message") + ("all-help", "displays all help") + ("test,t", "test configuration file") + ("config,c", boost::program_options::value()->default_value("/etc/udpt.conf"), "configuration file to use") + ; + + boost::program_options::options_description configOptions("Configuration options"); + configOptions.add_options() + ("db.driver", boost::program_options::value()->default_value("sqlite3"), "database driver to use") + ("db.param", boost::program_options::value()->default_value("/var/lib/udpt.db"), "database connection parameters") + + ("tracker.is_dynamic", boost::program_options::value()->default_value(true), "Sets if the tracker is dynamic") + ("tracker.port", boost::program_options::value()->default_value(6969), "UDP port to listen on") + ("tracker.threads", boost::program_options::value()->default_value(5), "threads to run (UDP only)") + ("tracker.allow_remotes", boost::program_options::value()->default_value(true), "allows clients to report remote IPs") + ("tracker.allow_iana_ips", boost::program_options::value()->default_value(false), "allows IANA reserved IPs to connect (useful for debugging)") + ("tracker.announce_interval", boost::program_options::value()->default_value(1800), "announce interval") + ("tracker.cleanup_interval", boost::program_options::value()->default_value(120), "sets database cleanup interval") + + ("apiserver.enable", boost::program_options::value()->default_value(0), "Enable API server?") + ("apiserver.threads", boost::program_options::value()->default_value(1), "threads for API server") + ("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on") + + ("logging.filename", boost::program_options::value()->default_value("stdout"), "file to write logs to") + ("logging.level", boost::program_options::value()->default_value("warning"), "log level (error/warning/info/debug)") + ; + + boost::program_options::variables_map var_map; + boost::program_options::store(boost::program_options::parse_command_line(argc, argv, commandLine), var_map); + boost::program_options::notify(var_map); + + if (var_map.count("help")) + { + std::cout << "UDP Tracker (UDPT) " << VERSION << " (" << PLATFORM << ")" << std::endl + << "Copyright 2012-2016 Naim A. " << std::endl + << "Build Date: " << __DATE__ << std::endl << std::endl; + + std::cout << commandLine << std::endl; + return 0; + } + + if (var_map.count("all-help")) + { + std::cout << commandLine << std::endl; + std::cout << configOptions << std::endl; + return 0; + } + + std::string config_filename(var_map["config"].as()); + bool isTest = var_map.count("test"); + + if (var_map.count("config")) + { + try + { + boost::program_options::basic_parsed_options parsed_options = boost::program_options::parse_config_file(config_filename.c_str(), configOptions); + boost::program_options::store( + parsed_options, + var_map); + } + catch (const boost::program_options::error& ex) + { + std::cerr << "ERROR: " << ex.what() << std::endl; + return -1; + } + + if (isTest) + { + std::cout << "Config OK" << std::endl; + return 0; + } + } - config_file = "udpt.conf"; memset(&Instance, 0, sizeof(Instance)); #ifdef SIGBREAK @@ -166,49 +232,18 @@ int main(int argc, char *argv[]) #ifdef SIGINT signal(SIGINT, &_signal_handler); #endif - - if (argc <= 1) + + try { - // set current directory when no filename is present. - _setCWD(argv[0]); - - _print_usage (); + logger = new Logger(var_map); } - else if (argc >= 2) + catch (const std::exception& ex) { - config_file = argv[1]; // reported in issue #5. + std::cerr << "Failed to initialize logger: " << ex.what() << std::endl; + return -1; } - settings = Instance.settings = new Settings (config_file); - - if (!settings->load()) - { - const char strDATABASE[] = "database"; - const char strTRACKER[] = "tracker"; - const char strAPISRV [] = "apiserver"; - // set default settings: - - settings->set (strDATABASE, "driver", "sqlite3"); - settings->set (strDATABASE, "file", "tracker.db"); - - settings->set (strTRACKER, "is_dynamic", "0"); - settings->set (strTRACKER, "port", "6969"); // UDP PORT - settings->set (strTRACKER, "threads", "5"); - settings->set (strTRACKER, "allow_remotes", "1"); - settings->set (strTRACKER, "allow_iana_ips", "1"); - settings->set (strTRACKER, "announce_interval", "1800"); - settings->set (strTRACKER, "cleanup_interval", "120"); - - settings->set (strAPISRV, "enable", "1"); - settings->set (strAPISRV, "threads", "1"); - settings->set (strAPISRV, "port", "6969"); // TCP PORT - - settings->save(); - cerr << "Failed to read from '" << config_file.c_str() << "'. Using default settings." << endl; - } - - logger = new Logger (settings); - usi = Instance.usi = new UDPTracker (settings); + usi = Instance.usi = new UDPTracker(var_map); HTTPServer *apiSrv = NULL; WebApp *wa = NULL; @@ -232,7 +267,7 @@ int main(int argc, char *argv[]) goto cleanup; } - _doAPIStart(settings, &wa, &apiSrv, usi->conn); + _doAPIStart(var_map, &wa, &apiSrv, usi->conn); cout << "Hit Control-C to exit." << endl; diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index 00f4f70..aa31e29 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -36,23 +36,19 @@ using namespace UDPT::Data; namespace UDPT { - UDPTracker::UDPTracker (Settings *settings) + UDPTracker::UDPTracker(const boost::program_options::variables_map& conf) : m_conf(conf) { - Settings::SettingClass *sc_tracker; - sc_tracker = settings->getClass("tracker"); + this->allowRemotes = conf["tracker.allow_remotes"].as(); + this->allowIANA_IPs = conf["tracker.allow_iana_ips"].as(); + this->isDynamic = conf["tracker.is_dynamic"].as(); - this->allowRemotes = sc_tracker->getBool("allow_remotes", true); - this->allowIANA_IPs = sc_tracker->getBool("allow_iana_ips", false); - this->isDynamic = sc_tracker->getBool("is_dynamic", true); - - this->announce_interval = sc_tracker->getInt("announce_interval", 1800); - this->cleanup_interval = sc_tracker->getInt("cleanup_interval", 120); - this->port = sc_tracker->getInt("port", 6969); - this->thread_count = abs (sc_tracker->getInt("threads", 5)) + 1; + this->announce_interval = conf["tracker.announce_interval"].as(); + this->cleanup_interval = conf["tracker.cleanup_interval"].as(); + this->port = conf["tracker.port"].as(); + this->thread_count = conf["tracker.threads"].as() + 1; list addrs; - sc_tracker->getIPs("bind", addrs); if (addrs.empty()) { @@ -69,7 +65,6 @@ namespace UDPT this->isRunning = false; this->conn = NULL; - this->o_settings = settings; } UDPTracker::~UDPTracker () @@ -130,15 +125,15 @@ namespace UDPT yup; // just to set TRUE string dbname;// saves the Database name. - sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); + sock = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == INVALID_SOCKET) return START_ESOCKET_FAILED; yup = 1; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); + ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); this->localEndpoint.sin_family = AF_INET; - r = bind (sock, (SOCKADDR*)&this->localEndpoint, sizeof(SOCKADDR_IN)); + r = ::bind(sock, (SOCKADDR*)&this->localEndpoint, sizeof(SOCKADDR_IN)); if (r == SOCKET_ERROR) { @@ -152,8 +147,7 @@ namespace UDPT this->sock = sock; - this->conn = new Data::SQLite3Driver (this->o_settings->getClass("database"), - this->isDynamic); + this->conn = new Data::SQLite3Driver(m_conf, this->isDynamic); this->isRunning = true; diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 6344740..175fcfa 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -25,6 +25,7 @@ #include "multiplatform.h" #include "db/driver_sqlite.hpp" #include "settings.hpp" +#include #include using namespace std; @@ -117,7 +118,7 @@ namespace UDPT * Initializes the UDP Tracker. * @param settings Settings to start server with */ - UDPTracker (Settings *); + UDPTracker(const boost::program_options::variables_map& conf); /** * Starts the Initialized instance. @@ -150,7 +151,7 @@ namespace UDPT uint32_t announce_interval; uint32_t cleanup_interval; - Settings *o_settings; + const boost::program_options::variables_map& m_conf; #ifdef WIN32 static DWORD _thread_start (LPVOID arg); From 1db33eb0b6a47d3d7b2f02587abda40ea57bc6cf Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 23 Jan 2016 20:39:03 +0200 Subject: [PATCH 52/99] Code cleanup (WIP) --- src/db/database.hpp | 1 - src/exceptions.h | 33 ++++ src/http/webapp.cpp | 44 +---- src/http/webapp.hpp | 8 +- src/logging.cpp | 33 +--- src/logging.h | 10 +- src/main.cpp | 170 ++++------------- src/multiplatform.h | 2 +- src/settings.cpp | 449 -------------------------------------------- src/settings.hpp | 121 ------------ src/udpTracker.cpp | 190 +++++++++---------- src/udpTracker.hpp | 63 +++---- 12 files changed, 213 insertions(+), 911 deletions(-) create mode 100644 src/exceptions.h delete mode 100644 src/settings.cpp delete mode 100644 src/settings.hpp diff --git a/src/db/database.hpp b/src/db/database.hpp index 535ef17..878da73 100644 --- a/src/db/database.hpp +++ b/src/db/database.hpp @@ -20,7 +20,6 @@ #ifndef DATABASE_HPP_ #define DATABASE_HPP_ -#include "../settings.hpp" #include namespace UDPT diff --git a/src/exceptions.h b/src/exceptions.h new file mode 100644 index 0000000..43e14b4 --- /dev/null +++ b/src/exceptions.h @@ -0,0 +1,33 @@ +#pragma once + + +namespace UDPT +{ + class UDPTException + { + public: + UDPTException(const char* errorMsg = "", int errorCode = 0) : m_error(errorMsg), m_errorCode(errorCode) + { + + } + + virtual const char* what() const + { + return m_error; + } + + virtual int getErrorCode() const + { + return m_errorCode; + } + + virtual ~UDPTException() + { + + } + + protected: + const char* m_error; + const int m_errorCode; + }; +} diff --git a/src/http/webapp.cpp b/src/http/webapp.cpp index 297fce0..3ab1c03 100644 --- a/src/http/webapp.cpp +++ b/src/http/webapp.cpp @@ -97,36 +97,12 @@ namespace UDPT return true; } - WebApp::WebApp(HTTPServer *srv, DatabaseDriver *db, const boost::program_options::variables_map& conf) : m_conf(conf) + WebApp::WebApp(std::shared_ptr srv, DatabaseDriver *db, const boost::program_options::variables_map& conf) : m_conf(conf), m_server(srv) { - this->instance = srv; this->db = db; - /* this->sc_api = settings->getClass("api"); + // TODO: Implement authentication by keys - Settings::SettingClass *apiKeys = settings->getClass("api.keys"); - if (apiKeys != NULL) - { - map* aK = apiKeys->getMap(); - map::iterator it, end; - end = aK->end(); - for (it = aK->begin();it != end;it++) - { - string key = it->first; - list ips; - - string::size_type strp = 0; - uint32_t ip; - while ((ip = _getNextIPv4(strp, it->second)) != 0) - { - ips.push_back( m_hton32(ip) ); - } - - this->ip_whitelist.insert(pair >(key, ips)); - } - - } */ - - srv->setData("webapp", this); + m_server->setData("webapp", this); } WebApp::~WebApp() @@ -136,17 +112,17 @@ namespace UDPT void WebApp::deploy() { list path; - this->instance->addApp(&path, &WebApp::handleRoot); + m_server->addApp(&path, &WebApp::handleRoot); path.push_back("api"); - this->instance->addApp(&path, &WebApp::handleAPI); // "/api" + m_server->addApp(&path, &WebApp::handleAPI); // "/api" path.pop_back(); path.push_back("announce"); - this->instance->addApp(&path, &WebApp::handleAnnounce); + m_server->addApp(&path, &WebApp::handleAnnounce); } - void WebApp::handleRoot (HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) + void WebApp::handleRoot(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) { // It would be very appreciated to keep this in the code. resp->write("" @@ -201,7 +177,7 @@ namespace UDPT void WebApp::doAddTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) { - string strHash = req->getParam("hash"); + std::string strHash = req->getParam("hash"); if (strHash.length() != 40) { resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); @@ -232,7 +208,7 @@ namespace UDPT throw ServerException (0, "IPv4 supported Only."); } - string key = req->getParam("auth"); + std::string key = req->getParam("auth"); if (key.length() <= 0) throw ServerException (0, "Bad Authentication Key"); @@ -247,7 +223,7 @@ namespace UDPT return; } - string action = req->getParam("action"); + std::string action = req->getParam("action"); if (action == "add") app->doAddTorrent(req, resp); else if (action == "remove") diff --git a/src/http/webapp.hpp b/src/http/webapp.hpp index fdb37c4..dc4bafb 100644 --- a/src/http/webapp.hpp +++ b/src/http/webapp.hpp @@ -21,10 +21,10 @@ #include "httpserver.hpp" #include "../db/database.hpp" -#include "../settings.hpp" #include #include #include +#include #include using namespace std; @@ -38,13 +38,13 @@ namespace UDPT class WebApp { public: - WebApp(HTTPServer *, DatabaseDriver *, const boost::program_options::variables_map& conf); - ~WebApp(); + WebApp(std::shared_ptr , DatabaseDriver *, const boost::program_options::variables_map& conf); + virtual ~WebApp(); void deploy (); private: - HTTPServer *instance; + std::shared_ptr m_server; UDPT::Data::DatabaseDriver *db; const boost::program_options::variables_map& m_conf; std::map > ip_whitelist; diff --git a/src/logging.cpp b/src/logging.cpp index 5fcf3dc..4266c73 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -27,10 +27,10 @@ using namespace std; namespace UDPT { Logger::Logger(const boost::program_options::variables_map& s) - : logfile (&std::cout) + : m_logfile (std::cout) { - const string& filename = s["logging.filename"].as(); - const string& level = s["logging.level"].as(); + const std::string& filename = s["logging.filename"].as(); + const std::string& level = s["logging.level"].as(); closeStreamOnDestroy = false; @@ -42,35 +42,10 @@ namespace UDPT { this->loglevel = LL_INFO; else this->loglevel = LL_ERROR; - - if (filename.compare("stdout") != 0 && filename.length() > 0) - { - fstream fs; - fs.open(filename.c_str(), ios::binary | ios::out | ios::app); - if (!fs.is_open()) - { - this->log(LL_ERROR, "Failed to open log file."); - return; - } - this->logfile = &fs; - closeStreamOnDestroy = true; - } - } - - Logger::Logger(const boost::program_options::variables_map& s, ostream &os) - : logfile (&os), loglevel (LL_ERROR) - { - closeStreamOnDestroy = false; } Logger::~Logger() { - fstream *f = (fstream*)this->logfile; - f->flush(); - if (closeStreamOnDestroy) - { - f->close(); - } } void Logger::log(enum LogLevel lvl, string msg) @@ -78,7 +53,7 @@ namespace UDPT { const char letters[] = "EWID"; if (lvl <= this->loglevel) { - (*logfile) << time (NULL) << ": (" + m_logfile << time (NULL) << ": (" << ((char)letters[lvl]) << "): " << msg << "\n"; } diff --git a/src/logging.h b/src/logging.h index a9c4af6..4ca37a9 100644 --- a/src/logging.h +++ b/src/logging.h @@ -20,7 +20,6 @@ #ifndef LOGGING_H_ #define LOGGING_H_ -#include "settings.hpp" #include #include #include @@ -28,7 +27,6 @@ #include namespace UDPT { - using namespace std; class Logger { @@ -42,17 +40,15 @@ namespace UDPT { Logger(const boost::program_options::variables_map& s); - Logger(const boost::program_options::variables_map& s, ostream &os); - virtual ~Logger(); - void log(enum LogLevel, string msg); + void log(enum LogLevel, std::string msg); private: - ostream *logfile; + std::ostream& m_logfile; enum LogLevel loglevel; bool closeStreamOnDestroy; - static void setStream(Logger *logger, ostream &s); + static void setStream(Logger *logger, std::ostream &s); }; }; diff --git a/src/main.cpp b/src/main.cpp index 4e466f7..a78fe2c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -19,128 +19,35 @@ #include -#include "logging.h" -#include "multiplatform.h" -#include "udpTracker.hpp" -#include "settings.hpp" -#include "http/httpserver.hpp" -#include "http/webapp.hpp" #include // atoi #include // signal #include // strlen -#include +#include #include -using namespace std; -using namespace UDPT; -using namespace UDPT::Server; +#include "logging.h" +#include "multiplatform.h" +#include "udpTracker.hpp" +#include "http/httpserver.hpp" +#include "http/webapp.hpp" -Logger *logger; -static struct { - Settings *settings; - UDPTracker *usi; - WebApp *wa; - HTTPServer *httpserver; -} Instance; +UDPT::Logger *logger; -static void _print_usage () -{ - cout << "Usage: udpt []" << endl; -} - -static void _doAPIStart (const boost::program_options::variables_map& settings, WebApp **wa, HTTPServer **srv, DatabaseDriver *drvr) -{ - if (!settings["apiserver.enable"].as()) - { - return; - } - - try - { - *srv = Instance.httpserver = new HTTPServer(settings); - *wa = Instance.wa = new WebApp(*srv, drvr, settings); - (*wa)->deploy(); - } - catch (const ServerException &e) - { - std::cerr << "ServerException #" << e.getErrorCode() << ": " << e.getErrorMsg() << endl; - } -} - -/** - * Sets current working directory to executables directory. - */ -static void _setCWD (char *argv0) -{ -#ifdef WIN32 - wchar_t strFileName [MAX_PATH]; - DWORD r, i; - r = GetModuleFileNameW(NULL, strFileName, MAX_PATH); - for (i = r;i >= 0;i--) - { - if (strFileName[i] == '\\') - { - strFileName[i] = '\0'; - break; - } - } - SetCurrentDirectoryW(strFileName); - -#elif defined(linux) - int len, i; - char *strFN; - if (argv0 != NULL) - { - len = strlen (argv0); - strFN = new char [len + 1]; - - for (i = len;i >= 0;i--) - { - if (strFN[i] == '/') - { - strFN = '\0'; - break; - } - } - chdir (strFN); - delete [] strFN; - } -#endif - -} - -/** - * Releases resources before exit. - */ -static void _doCleanup () -{ - delete Instance.wa; - delete Instance.httpserver; - delete Instance.usi; - delete Instance.settings; - delete logger; - - memset (&Instance, 0, sizeof(Instance)); - logger = NULL; -} - static void _signal_handler (int sig) { - stringstream ss; - ss << "Signal " << sig << " raised. Terminating..."; + std::stringstream ss; + ss << "Signal " << sig << " raised. "; logger->log(Logger::LL_INFO, ss.str()); - _doCleanup(); } int main(int argc, char *argv[]) { - UDPTracker *usi; int r; #ifdef WIN32 WSADATA wsadata; - WSAStartup(MAKEWORD(2, 2), &wsadata); + ::WSAStartup(MAKEWORD(2, 2), &wsadata); #endif boost::program_options::options_description commandLine("Command line options"); @@ -194,7 +101,7 @@ int main(int argc, char *argv[]) } std::string config_filename(var_map["config"].as()); - bool isTest = var_map.count("test"); + bool isTest = (0 != var_map.count("test")); if (var_map.count("config")) { @@ -218,8 +125,6 @@ int main(int argc, char *argv[]) } } - memset(&Instance, 0, sizeof(Instance)); - #ifdef SIGBREAK signal(SIGBREAK, &_signal_handler); #endif @@ -235,7 +140,7 @@ int main(int argc, char *argv[]) try { - logger = new Logger(var_map); + logger = new UDPT::Logger(var_map); } catch (const std::exception& ex) { @@ -243,41 +148,42 @@ int main(int argc, char *argv[]) return -1; } - usi = Instance.usi = new UDPTracker(var_map); + std::shared_ptr tracker; + std::shared_ptr apiSrv; + std::shared_ptr webApp; - HTTPServer *apiSrv = NULL; - WebApp *wa = NULL; - - r = usi->start(); - if (r != UDPTracker::START_OK) + try { - cerr << "Error While trying to start server." << endl; - switch (r) + tracker = std::shared_ptr(new UDPTracker(var_map)); + tracker->start(); + + if (var_map["apiserver.enable"].as()) { - case UDPTracker::START_ESOCKET_FAILED: - cerr << "Failed to create socket." << endl; - break; - case UDPTracker::START_EBIND_FAILED: - cerr << "Failed to bind socket." << endl; - break; - default: - cerr << "Unknown Error" << endl; - break; + try + { + apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(var_map)); + webApp = std::shared_ptr(new UDPT::Server::WebApp(apiSrv, tracker->conn, var_map)); + webApp->deploy(); + } + catch (const UDPT::Server::ServerException &e) + { + std::cerr << "ServerException #" << e.getErrorCode() << ": " << e.getErrorMsg() << endl; + } } - goto cleanup; + } + catch (const UDPT::UDPTException& ex) + { + std::cerr << "UDPTException: " << ex.what() << std::endl; } - _doAPIStart(var_map, &wa, &apiSrv, usi->conn); + std::cout << "Hit Control-C to exit." << endl; - cout << "Hit Control-C to exit." << endl; + tracker->wait(); - usi->wait(); - -cleanup: - cout << endl << "Goodbye." << endl; + std::cout << endl << "Goodbye." << endl; #ifdef WIN32 - WSACleanup(); + ::WSACleanup(); #endif return 0; diff --git a/src/multiplatform.h b/src/multiplatform.h index 5ff6d1c..6dc3a33 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -28,7 +28,7 @@ #define linux #endif -#define VERSION "1.0.0-beta" +#define VERSION "1.0.2-dev" #ifdef WIN32 #include diff --git a/src/settings.cpp b/src/settings.cpp deleted file mode 100644 index 4da755e..0000000 --- a/src/settings.cpp +++ /dev/null @@ -1,449 +0,0 @@ -/* - * - * Copyright © 2012-2016 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include "settings.hpp" -#include // still primitive - need for strlen() -#include // need for isspace() -#include -#include -#include -#include -#include "tools.h" - -using namespace std; - -namespace UDPT -{ - Settings::SettingClass* Settings::getClass(const string classname) - { - if (classname == "") - return NULL; - - map::iterator it; - it = this->classes.find(classname); - - if (it == this->classes.end()) - return NULL; - else - return it->second; - - return NULL; - } - - Settings::Settings (const string filename) - { - this->filename = filename; - this->classes.clear(); - } - -static -void _settings_clean_string (char **str) -{ - int len, - i, - offset; - - len = strlen(*str); - - //strip leading whitespaces. - offset = 0; - for (i = 0;i < len;i++) - { - if (isspace(*str[i]) == 0) - break; - offset++; - } - - (*str) += offset; - len -= offset; - - for (i = len - 1;i >= 0;i--) - { - if (isspace( (*str)[i] ) != 0) - { - (*str)[i] = '\0'; - } - else - break; - } -} - - void Settings::parseSettings (char *data, int len) - { - char *className, *key, *value; - int i, - cil; // cil = Chars in line. - char c; - - className = key = value = NULL; - cil = 0; - - for (i = 0;i < len;i++) - { - c = data[i]; - if (c == '\n') - { - cil = 0; - continue; - } - if (cil == 0 && (c == ';' || c == '#')) - { - while (i < len) - { - if (data[i] == '\n') - break; - i++; - } - continue; - } - if (isspace(c) != 0 && cil == 0) - { - continue; - } - if (cil == 0 && c == '[') - { - className = (char*)(i + data + 1); - while (i < len) - { - if (data[i] != ']') - { - i++; - continue; - } - data[i] = '\0'; - break; - } - continue; - } - - if (isgraph(c) != 0 && cil == 0) // must be a key. - { - key = (char*)(i + data); - while (i < len) - { - if (data[i] == '\n') - { - key = NULL; - break; - } - if (data[i] == '=') - { - data[i] = '\0'; - value = (char*)(data + i + 1); - while (i < len) - { - if (data[i] == '\n') - { - data[i] = '\0'; - - _settings_clean_string(&key); - _settings_clean_string(&value); - - // add to settings... - this->set (className, key, value); - - cil = 0; - break; - } - i++; - } - break; - } - i++; - } - continue; - } - - if (isgraph(c) != 0) - { - cil++; - } - } - } - - bool Settings::load() - { - int len; - char *buffer; - - fstream cfg; - cfg.open(this->filename.c_str(), ios::in | ios::binary); - - if (!cfg.is_open()) - return false; - - cfg.seekg(0, ios::end); - len = cfg.tellg(); - cfg.seekg(0, ios::beg); - - buffer = new char [len]; - cfg.read(buffer, len); - cfg.close(); - - this->parseSettings(buffer, len); - - delete[] buffer; - - return true; - } - - bool Settings::save () - { - SettingClass *sclass; - - fstream cfg (this->filename.c_str(), ios::binary | ios::out); - if (!cfg.is_open()) - return false; - - cfg << "; udpt Settings File - Created Automatically.\n"; - - map::iterator it; - for (it = this->classes.begin();it != this->classes.end();it++) - { - sclass = it->second; - cfg << "[" << it->first.c_str() << "]\n"; - - map::iterator rec; - for (rec = sclass->entries.begin();rec != sclass->entries.end();rec++) - { - cfg << rec->first.c_str() << "=" << rec->second.c_str() << "\n"; - } - - cfg << "\n"; - } - cfg.close(); - - return 0; - } - - Settings::~Settings() - { - map::iterator it; - for (it = this->classes.begin();it != this->classes.end();it++) - { - SettingClass *sc = it->second; - delete sc; - } - this->classes.clear(); - } - - string Settings::get (const string classN, const string name) - { - SettingClass *c; - - c = this->getClass(classN); - if (c == NULL) - return ""; - return c->get(name); - } - - bool Settings::set (const string classN, const string name, const string value) - { - SettingClass *c; - - if (classN == "" || name == "" || value == "") - return false; - - c = this->getClass (classN); - - if (c == NULL) - { - c = new SettingClass(classN); - this->classes.insert(pair(classN, c)); - } - - return c->set (name, value); - } - - Settings::SettingClass::SettingClass(const string cn) - { - this->className = cn; - } - - string Settings::SettingClass::get (const string& name) - { - if (this->entries.find(name) == this->entries.end()) - return ""; - return this->entries[name]; - } - - inline static int _isTrue (string str) - { - int i, // loop index - len; // string's length - - if (str == "") - return -1; - len = str.length(); - for (i = 0;i < len;i++) - { - if (str[i] >= 'A' && str[i] <= 'Z') - { - str[i] = (str[i] - 'A' + 'a'); - } - } - if (str.compare ("yes") == 0) - return 1; - if (str.compare ("no") == 0) - return 0; - if (str.compare("true") == 0) - return 1; - if (str.compare ("false") == 0) - return 0; - if (str.compare("1") == 0) - return 1; - if (str.compare ("0") == 0) - return 0; - return -1; - } - - bool Settings::SettingClass::getBool(const string& name) - { - string v = this->get(name); - int r = _isTrue(v); - if (r == 0 || r == 1) - return (bool)r; - throw SettingsException("Invalid boolean value."); - } - - bool Settings::SettingClass::getBool (const string& key, bool defaultValue) - { - try { - return this->getBool(key); - } catch (SettingsException &e) - { } - - return defaultValue; - } - - void Settings::SettingClass::getIPs (const string& key, list &ip) - { - string v = this->get(key) + " "; // add padding for last entry. - // expect a.b.c.d[:port], IPv4 only supported with BEP-15. - - string::size_type s, e; - s = e = 0; - char c; - for (string::size_type i = 0;i < v.length();i++) - { - c = v[i]; - if (isspace(c) != 0 || c == ';' || c == ',') - { - if (s == e) - s = e = i; - else - { - string addr = v.substr(s, (e - s) + 1); - SOCKADDR_IN saddr; - memset(&saddr, 0, sizeof (SOCKADDR_IN)); - saddr.sin_family = AF_INET; - saddr.sin_addr.s_addr = 0L; - saddr.sin_port = (6969); - - { - uint8_t b; // temporary container for IP byte - uint16_t port; - uint32_t ip; - unsigned i, // loop index - stage; // 0,1,2,3=IP[a.b.c.d], 4=port - - ip = 0; - b = 0; - stage = 0; - for (i = 0;i < addr.length();i++) - { - if (addr[i] >= '0' && addr[i] <= '9') - { - if (stage <= 3) - { - b *= 10; - b += (addr[i] - '0'); - } - else if (stage == 4) - { - port *= 10; - port += (addr[i] - '0'); - } - } - else if (addr[i] == '.' && stage < 3) - { - stage ++; - ip *= 256; - ip += b; - b = 0; - } - else if (addr[i] == ':') - { - stage++; - port = 0; - - ip *= 256; - ip += b; - } - } - - if (stage == 3) // port not provided. - { - port = 6969; - // add last byte. - ip *= 256; - ip += b; - } - saddr.sin_addr.s_addr = m_hton32(ip); - saddr.sin_port = m_hton16(port); - } - - ip.push_back(saddr); - - s = e = i + 1; - } - } - else - { - e = i; - } - } - } - - int Settings::SettingClass::getInt (const string& key, int def) - { - string v = this->get (key); - if (v.length() == 0) - return def; - return std::atoi(v.c_str()); - } - - map* Settings::SettingClass::getMap() - { - return &this->entries; - } - - bool Settings::SettingClass::set (const string name, const string value) - { - pair::iterator, bool> r; - r = this->entries.insert(pair(name, value)); - if (!r.second) - { - r.first->second = value; - } - - return true; - } -}; diff --git a/src/settings.hpp b/src/settings.hpp deleted file mode 100644 index dcec64a..0000000 --- a/src/settings.hpp +++ /dev/null @@ -1,121 +0,0 @@ -/* - * - * Copyright © 2012-2016 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#pragma once - -#include -#include -#include -#include -#include "multiplatform.h" -using namespace std; - -namespace UDPT -{ - class Settings - { - public: - class SettingsException : public std::exception - { - public: - SettingsException (const char *str) - { - this->str = str; - } - - const char * what () - { - return str; - } - - private: - const char *str; - }; - - class SettingClass - { - public: - SettingClass (const string className); - bool set (const string key, const string value); - string get (const string& key); - bool getBool (const string& key); - bool getBool (const string& key, bool defaultValue); - int getInt (const string& key, int def = -1); - map* getMap (); - void getIPs (const string& key, list &ip); - private: - friend class Settings; - string className; - map entries; - }; - - /** - * Initializes the settings type. - * @param filename the settings filename. - */ - Settings (const string filename); - - /** - * Gets a setting from a Settings type. - * @param class The class of the requested setting. - * @param name The name of the requested setting. - * @return The value for the requested setting, NULL if not available. - */ - SettingClass* getClass (const string name); - - /** - * Loads settings from file - * @return true on success, otherwise false. - */ - bool load (); - - /** - * Saves settings to file. - * @return true on success; otherwise false. - */ - bool save (); - - /** - * Sets a setting in a settings type. - * @param className The class of the setting. - * @param key The name of the setting. - * @param value The value to set for the setting. - * @return true on success, otherwise false. - */ - bool set (const string className, const string key, const string value); - - /** - * Gets the requested SettingClass. - * @param classname The name of the class to find (case sensitive). - * @return a pointer to the found class, or NULL if not found. - */ - string get (const string className, const string key); - - /** - * Destroys the settings "object" - */ - virtual ~Settings (); - private: - string filename; - map classes; - - void parseSettings (char *data, int len); - }; -}; diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index aa31e29..26632e3 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -17,19 +17,19 @@ * along with UDPT. If not, see . */ -#include "udpTracker.hpp" -#include "tools.h" #include // atoi #include #include #include #include +#include +#include "udpTracker.hpp" +#include "tools.h" #include "multiplatform.h" #include "logging.h" extern UDPT::Logger *logger; -using namespace std; using namespace UDPT::Data; #define UDP_BUFFER_SIZE 2048 @@ -39,146 +39,146 @@ namespace UDPT UDPTracker::UDPTracker(const boost::program_options::variables_map& conf) : m_conf(conf) { - this->allowRemotes = conf["tracker.allow_remotes"].as(); - this->allowIANA_IPs = conf["tracker.allow_iana_ips"].as(); - this->isDynamic = conf["tracker.is_dynamic"].as(); + this->m_allowRemotes = conf["tracker.allow_remotes"].as(); + this->m_allowIANA_IPs = conf["tracker.allow_iana_ips"].as(); + this->m_isDynamic = conf["tracker.is_dynamic"].as(); - this->announce_interval = conf["tracker.announce_interval"].as(); - this->cleanup_interval = conf["tracker.cleanup_interval"].as(); - this->port = conf["tracker.port"].as(); - this->thread_count = conf["tracker.threads"].as() + 1; + this->m_announceInterval = conf["tracker.announce_interval"].as(); + this->m_cleanupInterval = conf["tracker.cleanup_interval"].as(); + this->m_port = conf["tracker.port"].as(); + this->m_threadCount = conf["tracker.threads"].as() + 1; - list addrs; + std::list addrs; if (addrs.empty()) { SOCKADDR_IN sa; - sa.sin_port = m_hton16(port); + sa.sin_port = m_hton16(m_port); sa.sin_addr.s_addr = 0L; addrs.push_back(sa); } - this->localEndpoint = addrs.front(); + this->m_localEndpoint = addrs.front(); - this->threads = new HANDLE[this->thread_count]; + this->m_threads = new HANDLE[this->m_threadCount]; - this->isRunning = false; - this->conn = NULL; + this->m_isRunning = false; + this->conn = nullptr; } - UDPTracker::~UDPTracker () + UDPTracker::~UDPTracker() { int i; // loop index - this->isRunning = false; + this->m_isRunning = false; // drop listener connection to continue thread loops. // wait for request to finish (1 second max; allot of time for a computer!). #ifdef linux - close (this->sock); + ::close(this->m_sock); - sleep (1); + ::sleep(1); #elif defined (WIN32) - closesocket (this->sock); + ::closesocket(this->m_sock); - Sleep (1000); + ::Sleep(1000); #endif - for (i = 0;i < this->thread_count;i++) + for (i = 0;i < this->m_threadCount;i++) { #ifdef WIN32 - TerminateThread (this->threads[i], 0x00); + ::TerminateThread(this->m_threads[i], 0x00); #elif defined (linux) - pthread_detach (this->threads[i]); - pthread_cancel (this->threads[i]); + ::pthread_detach(this->m_threads[i]); + ::pthread_cancel(this->m_threads[i]); #endif - stringstream str; - str << "Thread (" << (i + 1) << "/" << ((int)this->thread_count) << ") terminated."; + std::stringstream str; + str << "Thread (" << (i + 1) << "/" << ((int)this->m_threadCount) << ") terminated."; logger->log(Logger::LL_INFO, str.str()); } if (this->conn != NULL) delete this->conn; - delete[] this->threads; + delete[] this->m_threads; } void UDPTracker::wait() { #ifdef WIN32 - WaitForMultipleObjects(this->thread_count, this->threads, TRUE, INFINITE); + WaitForMultipleObjects(this->m_threadCount, this->m_threads, TRUE, INFINITE); #else int i; - for (i = 0;i < this->thread_count; i++) + for (i = 0;i < this->m_threadCount; i++) { - pthread_join (this->threads[i], NULL); + pthread_join (this->m_threads[i], NULL); } #endif } - enum UDPTracker::StartStatus UDPTracker::start () + void UDPTracker::start() { - stringstream ss; + std::stringstream ss; SOCKET sock; int r, // saves results i, // loop index yup; // just to set TRUE - string dbname;// saves the Database name. + std::string dbname;// saves the Database name. sock = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == INVALID_SOCKET) - return START_ESOCKET_FAILED; + { + throw UDPT::UDPTException("Failed to create socket"); + } yup = 1; ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); - this->localEndpoint.sin_family = AF_INET; - r = ::bind(sock, (SOCKADDR*)&this->localEndpoint, sizeof(SOCKADDR_IN)); + this->m_localEndpoint.sin_family = AF_INET; + r = ::bind(sock, reinterpret_cast(&this->m_localEndpoint), sizeof(SOCKADDR_IN)); if (r == SOCKET_ERROR) { #ifdef WIN32 - closesocket (sock); + ::closesocket(sock); #elif defined (linux) - close (sock); + ::close(sock); #endif - return START_EBIND_FAILED; + throw UDPT::UDPTException("Failed to bind socket."); } - this->sock = sock; + this->m_sock = sock; - this->conn = new Data::SQLite3Driver(m_conf, this->isDynamic); + this->conn = new Data::SQLite3Driver(m_conf, this->m_isDynamic); - this->isRunning = true; + this->m_isRunning = true; ss.str(""); - ss << "Starting maintenance thread (1/" << ((int)this->thread_count) << ")"; + ss << "Starting maintenance thread (1/" << ((int)this->m_threadCount) << ")"; logger->log(Logger::LL_INFO, ss.str()); // create maintainer thread. #ifdef WIN32 - this->threads[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_maintainance_start, (LPVOID)this, 0, NULL); + this->m_threads[0] = ::CreateThread(NULL, 0, reinterpret_cast(_maintainance_start), (LPVOID)this, 0, NULL); #elif defined (linux) - pthread_create (&this->threads[0], NULL, _maintainance_start, (void*)this); + ::pthread_create (&this->m_threads[0], NULL, _maintainance_start, (void*)this); #endif - for (i = 1;i < this->thread_count; i++) + for (i = 1;i < this->m_threadCount; i++) { ss.str(""); - ss << "Starting thread (" << (i + 1) << "/" << ((int)this->thread_count) << ")"; + ss << "Starting thread (" << (i + 1) << "/" << ((int)this->m_threadCount) << ")"; logger->log(Logger::LL_INFO, ss.str()); #ifdef WIN32 - this->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)this, 0, NULL); + this->m_threads[i] = ::CreateThread(NULL, 0, reinterpret_cast(_thread_start), (LPVOID)this, 0, NULL); #elif defined (linux) - pthread_create (&(this->threads[i]), NULL, _thread_start, (void*)this); + ::pthread_create (&(this->m_threads[i]), NULL, _thread_start, (void*)this); #endif } - - return START_OK; } - int UDPTracker::sendError (UDPTracker *usi, SOCKADDR_IN *remote, uint32_t transactionID, const string &msg) + int UDPTracker::sendError(UDPTracker* usi, SOCKADDR_IN* remote, uint32_t transactionID, const std::string &msg) { struct udp_error_response error; int msg_sz, // message size to send. @@ -195,24 +195,22 @@ namespace UDPT if (msg_sz > 1024) return -1; - memcpy(buff, &error, 8); + ::memcpy(buff, &error, 8); for (i = 8;i <= msg_sz;i++) { buff[i] = msg[i - 8]; } - sendto(usi->sock, buff, msg_sz, 0, (SOCKADDR*)remote, sizeof(*remote)); + ::sendto(usi->m_sock, buff, msg_sz, 0, reinterpret_cast(remote), sizeof(*remote)); return 0; } - int UDPTracker::handleConnection (UDPTracker *usi, SOCKADDR_IN *remote, char *data) + int UDPTracker::handleConnection(UDPTracker *usi, SOCKADDR_IN *remote, char *data) { - ConnectionRequest *req; + ConnectionRequest *req = reinterpret_cast(data); ConnectionResponse resp; - req = (ConnectionRequest*)data; - resp.action = m_hton32(0); resp.transaction_id = req->transaction_id; @@ -223,7 +221,7 @@ namespace UDPT return 1; } - sendto(usi->sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + ::sendto(usi->m_sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); return 0; } @@ -258,7 +256,7 @@ namespace UDPT req->num_want = m_hton32 (req->num_want); req->left = m_hton64 (req->left); - if (!usi->allowRemotes && req->ip_address != 0) + if (!usi->m_allowRemotes && req->ip_address != 0) { UDPTracker::sendError (usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); return 0; @@ -309,7 +307,7 @@ namespace UDPT resp = (AnnounceResponse*)buff; resp->action = m_hton32(1); - resp->interval = m_hton32 ( usi->announce_interval ); + resp->interval = m_hton32 ( usi->m_announceInterval ); resp->leechers = m_hton32(tE.leechers); resp->seeders = m_hton32 (tE.seeders); resp->transaction_id = req->transaction_id; @@ -331,7 +329,7 @@ namespace UDPT } delete[] peers; - sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + ::sendto(usi->m_sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); // update DB. uint32_t ip; @@ -345,9 +343,9 @@ namespace UDPT return 0; } - int UDPTracker::handleScrape (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len) + int UDPTracker::handleScrape(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len) { - ScrapeRequest *sR; + ScrapeRequest *sR = reinterpret_cast(data); int v, // validation helper c, // torrent counter i, // loop counter @@ -356,14 +354,11 @@ namespace UDPT ScrapeResponse *resp; uint8_t buffer [1024]; // up to 74 torrents can be scraped at once (17*74+8) < 1024 - - sR = (ScrapeRequest*)data; - // validate request length: v = len - 16; if (v < 0 || v % 20 != 0) { - UDPTracker::sendError (usi, remote, sR->transaction_id, "Bad scrape request."); + UDPTracker::sendError(usi, remote, sR->transaction_id, "Bad scrape request."); return 0; } @@ -377,8 +372,8 @@ namespace UDPT // get torrent count. c = v / 20; - resp = (ScrapeResponse*)buffer; - resp->action = m_hton32 (2); + resp = reinterpret_cast(buffer); + resp->action = m_hton32(2); resp->transaction_id = sR->transaction_id; for (i = 0;i < c;i++) @@ -402,12 +397,12 @@ namespace UDPT return 0; } - *seeders = m_hton32 (tE.seeders); - *completed = m_hton32 (tE.completed); - *leechers = m_hton32 (tE.leechers); + *seeders = m_hton32(tE.seeders); + *completed = m_hton32(tE.completed); + *leechers = m_hton32(tE.leechers); } - sendto (usi->sock, (const char*)buffer, sizeof(buffer), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + ::sendto(usi->m_sock, reinterpret_cast(buffer), sizeof(buffer), 0, reinterpret_cast(remote), sizeof(SOCKADDR_IN)); return 0; } @@ -422,14 +417,12 @@ static int _isIANA_IP (uint32_t ip) int UDPTracker::resolveRequest (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r) { - ConnectionRequest *cR; + ConnectionRequest* cR = reinterpret_cast(data); uint32_t action; - cR = (ConnectionRequest*)data; - action = m_hton32(cR->action); - if (!usi->allowIANA_IPs) + if (!usi->m_allowIANA_IPs) { if (_isIANA_IP (remote->sin_addr.s_addr)) { @@ -438,14 +431,14 @@ static int _isIANA_IP (uint32_t ip) } if (action == 0 && r >= 16) - return UDPTracker::handleConnection (usi, remote, data); + return UDPTracker::handleConnection(usi, remote, data); else if (action == 1 && r >= 98) - return UDPTracker::handleAnnounce (usi, remote, data); + return UDPTracker::handleAnnounce(usi, remote, data); else if (action == 2) - return UDPTracker::handleScrape (usi, remote, data, r); + return UDPTracker::handleScrape(usi, remote, data, r); else { - UDPTracker::sendError (usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); + UDPTracker::sendError(usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); return -1; } @@ -468,47 +461,44 @@ static int _isIANA_IP (uint32_t ip) #endif int r; - char tmpBuff [UDP_BUFFER_SIZE]; + char tmpBuff[UDP_BUFFER_SIZE]; - usi = (UDPTracker*)arg; + usi = reinterpret_cast(arg); - addrSz = sizeof (SOCKADDR_IN); + addrSz = sizeof(SOCKADDR_IN); - while (usi->isRunning) + while (usi->m_isRunning) { - cout.flush(); // peek into the first 12 bytes of data; determine if connection request or announce request. - r = recvfrom(usi->sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); + r = ::recvfrom(usi->m_sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); if (r <= 0) continue; // bad request... - r = UDPTracker::resolveRequest (usi, &remoteAddr, tmpBuff, r); + r = UDPTracker::resolveRequest(usi, &remoteAddr, tmpBuff, r); } #ifdef linux - pthread_exit (NULL); + ::pthread_exit (NULL); #endif return 0; } #ifdef WIN32 - DWORD UDPTracker::_maintainance_start (LPVOID arg) + DWORD UDPTracker::_maintainance_start(LPVOID arg) #elif defined (linux) - void* UDPTracker::_maintainance_start (void *arg) + void* UDPTracker::_maintainance_start(void *arg) #endif { - UDPTracker *usi; + UDPTracker* usi = reinterpret_cast(arg); - usi = (UDPTracker *)arg; - - while (usi->isRunning) + while (usi->m_isRunning) { usi->conn->cleanup(); #ifdef WIN32 - Sleep (usi->cleanup_interval * 1000); + ::Sleep(usi->m_cleanupInterval * 1000); #elif defined (linux) - sleep (usi->cleanup_interval); + ::sleep(usi->m_cleanupInterval); #else #error Unsupported OS. #endif diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 175fcfa..084a52b 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -22,18 +22,16 @@ #include +#include +#include +#include "exceptions.h" #include "multiplatform.h" #include "db/driver_sqlite.hpp" -#include "settings.hpp" -#include -#include -using namespace std; - -#define UDPT_DYNAMIC 0x01 // Track Any info_hash? -#define UDPT_ALLOW_REMOTE_IP 0x02 // Allow client's to send other IPs? -#define UDPT_ALLOW_IANA_IP 0x04 // allow IP's like 127.0.0.1 or other IANA reserved IPs? -#define UDPT_VALIDATE_CLIENT 0x08 // validate client before adding to Database? (check if connection is open?) +#define UDPT_DYNAMIC (0x01) // Track Any info_hash? +#define UDPT_ALLOW_REMOTE_IP (0x02) // Allow client's to send other IPs? +#define UDPT_ALLOW_IANA_IP (0x04) // allow IP's like 127.0.0.1 or other IANA reserved IPs? +#define UDPT_VALIDATE_CLIENT (0x08) // validate client before adding to Database? (check if connection is open?) namespace UDPT @@ -122,52 +120,51 @@ namespace UDPT /** * Starts the Initialized instance. - * @return 0 on success, otherwise non-zero. */ - enum StartStatus start (); + void start(); /** * Joins all threads, and waits for all of them to terminate. */ - void wait (); + void wait(); /** * Destroys resources that were created by constructor * @param usi Instance to destroy. */ - virtual ~UDPTracker (); + virtual ~UDPTracker(); Data::DatabaseDriver *conn; private: - SOCKET sock; - SOCKADDR_IN localEndpoint; - uint16_t port; - uint8_t thread_count; - bool isRunning; - bool isDynamic; - bool allowRemotes; - bool allowIANA_IPs; - HANDLE *threads; - uint32_t announce_interval; - uint32_t cleanup_interval; + SOCKET m_sock; + SOCKADDR_IN m_localEndpoint; + uint16_t m_port; + uint8_t m_threadCount; + bool m_isRunning; + bool m_isDynamic; + bool m_allowRemotes; + bool m_allowIANA_IPs; + HANDLE *m_threads; + uint32_t m_announceInterval; + uint32_t m_cleanupInterval; const boost::program_options::variables_map& m_conf; #ifdef WIN32 - static DWORD _thread_start (LPVOID arg); - static DWORD _maintainance_start (LPVOID arg); + static DWORD _thread_start(LPVOID arg); + static DWORD _maintainance_start(LPVOID arg); #elif defined (linux) - static void* _thread_start (void *arg); - static void* _maintainance_start (void *arg); + static void* _thread_start(void *arg); + static void* _maintainance_start(void *arg); #endif - static int resolveRequest (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r); + static int resolveRequest(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r); - static int handleConnection (UDPTracker *usi, SOCKADDR_IN *remote, char *data); - static int handleAnnounce (UDPTracker *usi, SOCKADDR_IN *remote, char *data); - static int handleScrape (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len); + static int handleConnection(UDPTracker *usi, SOCKADDR_IN *remote, char *data); + static int handleAnnounce(UDPTracker *usi, SOCKADDR_IN *remote, char *data); + static int handleScrape(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len); - static int sendError (UDPTracker *, SOCKADDR_IN *remote, uint32_t transId, const string &); + static int sendError(UDPTracker *, SOCKADDR_IN *remote, uint32_t transId, const std::string &); }; }; From 81d4ad1ae8a8ddd3b177f9ede52043e368d7c77b Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 23 Jan 2016 15:08:30 -0800 Subject: [PATCH 53/99] Some Linux ajustments --- Makefile | 11 +++++------ README.md | 2 +- src/udpTracker.cpp | 12 ++++++------ 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/Makefile b/Makefile index 0de727a..25762d5 100644 --- a/Makefile +++ b/Makefile @@ -18,23 +18,22 @@ # objects = main.o udpTracker.o database.o driver_sqlite.o \ - settings.o tools.o httpserver.o webapp.o \ - logging.o + tools.o httpserver.o webapp.o logging.o target = udpt %.o: src/%.c $(CC) -c -o $@ $< $(CFLAGS) %.o: src/%.cpp - $(CXX) -c -o $@ $< $(CXXFLAGS) + $(CXX) -g -std=gnu++11 -c -o $@ $< $(CXXFLAGS) %.o: src/db/%.cpp - $(CXX) -c -o $@ $< $(CXXFLAGS) + $(CXX) -g -std=gnu++11 -c -o $@ $< $(CXXFLAGS) %.o: src/http/%.cpp - $(CXX) -c -o $@ $< $(CXXFLAGS) + $(CXX) -g -std=gnu++11 -c -o $@ $< $(CXXFLAGS) all: $(target) $(target): $(objects) @echo Linking... - $(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lsqlite3 -lpthread + $(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lboost_program_options -lsqlite3 -lpthread @echo Done. clean: @echo Cleaning Up... diff --git a/README.md b/README.md index 82b0d2a..a350e12 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ UDPT is designed to run on both Windows and Linux-based platform (It may run on ### License UDPT is released under the [GPL](http://www.gnu.org/licenses/gpl-3.0.en.html) license, a copy is included in this repository. -We use [SQLite3](http://www.sqlite.org/) which is public-domain. +We use [SQLite3](http://www.sqlite.org/) which is public-domain, and [Boost](http://www.boost.org/) which is released under the [boost license](http://www.boost.org/LICENSE_1_0.txt). ### Building We didn't really work on creating any installer, at the moment you can just run udpt from anywhere on your filesystem. diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index 26632e3..e16950d 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -106,12 +106,12 @@ namespace UDPT void UDPTracker::wait() { #ifdef WIN32 - WaitForMultipleObjects(this->m_threadCount, this->m_threads, TRUE, INFINITE); + ::WaitForMultipleObjects(this->m_threadCount, this->m_threads, TRUE, INFINITE); #else int i; for (i = 0;i < this->m_threadCount; i++) { - pthread_join (this->m_threads[i], NULL); + ::pthread_join(this->m_threads[i], NULL); } #endif } @@ -161,7 +161,7 @@ namespace UDPT #ifdef WIN32 this->m_threads[0] = ::CreateThread(NULL, 0, reinterpret_cast(_maintainance_start), (LPVOID)this, 0, NULL); #elif defined (linux) - ::pthread_create (&this->m_threads[0], NULL, _maintainance_start, (void*)this); + ::pthread_create(&this->m_threads[0], NULL, _maintainance_start, (void*)this); #endif for (i = 1;i < this->m_threadCount; i++) @@ -173,7 +173,7 @@ namespace UDPT #ifdef WIN32 this->m_threads[i] = ::CreateThread(NULL, 0, reinterpret_cast(_thread_start), (LPVOID)this, 0, NULL); #elif defined (linux) - ::pthread_create (&(this->m_threads[i]), NULL, _thread_start, (void*)this); + ::pthread_create(&(this->m_threads[i]), NULL, _thread_start, (void*)this); #endif } } @@ -258,7 +258,7 @@ namespace UDPT if (!usi->m_allowRemotes && req->ip_address != 0) { - UDPTracker::sendError (usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); + UDPTracker::sendError(usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); return 0; } @@ -424,7 +424,7 @@ static int _isIANA_IP (uint32_t ip) if (!usi->m_allowIANA_IPs) { - if (_isIANA_IP (remote->sin_addr.s_addr)) + if (_isIANA_IP(remote->sin_addr.s_addr)) { return 0; // Access Denied: IANA reserved IP. } From 9d319aa946805127c3e62c8129cd6e5ab52a06d3 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 23 Jan 2016 18:25:39 -0800 Subject: [PATCH 54/99] minor fix --- src/udpTracker.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index e16950d..fceb498 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -271,7 +271,7 @@ namespace UDPT // load peers q = 30; if (req->num_want >= 1) - q = min (q, req->num_want); + q = std::min(q, req->num_want); peers = new DatabaseDriver::PeerEntry [q]; From 2b594fd418f50715b86413bd24314c9f77f67736 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 23 Jan 2016 18:31:43 -0800 Subject: [PATCH 55/99] WIP: writing daemon + reloadable --- src/main.cpp | 102 +++++++++++++++++++++++--------------------- src/multiplatform.h | 2 + src/tracker.cpp | 50 ++++++++++++++++++++++ src/tracker.hpp | 35 +++++++++++++++ 4 files changed, 141 insertions(+), 48 deletions(-) create mode 100644 src/tracker.cpp create mode 100644 src/tracker.hpp diff --git a/src/main.cpp b/src/main.cpp index a78fe2c..8e0781b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -30,20 +30,50 @@ #include "udpTracker.hpp" #include "http/httpserver.hpp" #include "http/webapp.hpp" +#include "tracker.hpp" -UDPT::Logger *logger; +UDPT::Logger *logger = NULL; +UDPT::Tracker *instance = NULL; static void _signal_handler (int sig) { - std::stringstream ss; - ss << "Signal " << sig << " raised. "; - logger->log(Logger::LL_INFO, ss.str()); + switch (sig) + { + case SIGTERM: + instance->stop(); + break; + case SIGHUP: + break; + } } +#ifdef linux +static void daemonize(const boost::program_options::variables_map& conf) +{ + if (1 == ::getppid()) return; // already a daemon + int r = ::fork(); + if (0 > r) ::exit(-1); // failed to daemonize. + if (0 < r) ::exit(0); // parent exists. + + ::umask(0); + ::setsid(); + + // close all fds. + for (int i = ::getdtablesize(); i >=0; --i) + { + ::close(i); + } + + ::chdir(conf["daemon.chdir"].as().c_str()); + +} +#endif + int main(int argc, char *argv[]) { - int r; + Tracker& tracker = UDPT::Tracker::getInstance(); + instance = &tracker; #ifdef WIN32 WSADATA wsadata; @@ -56,6 +86,9 @@ int main(int argc, char *argv[]) ("all-help", "displays all help") ("test,t", "test configuration file") ("config,c", boost::program_options::value()->default_value("/etc/udpt.conf"), "configuration file to use") +#ifdef linux + ("interactive,i", "doesn't start as daemon") +#endif ; boost::program_options::options_description configOptions("Configuration options"); @@ -77,6 +110,10 @@ int main(int argc, char *argv[]) ("logging.filename", boost::program_options::value()->default_value("stdout"), "file to write logs to") ("logging.level", boost::program_options::value()->default_value("warning"), "log level (error/warning/info/debug)") + +#ifdef linux + ("daemon.chdir", boost::program_options::value()->default_value("/"), "home directory for daemon") +#endif ; boost::program_options::variables_map var_map; @@ -125,22 +162,11 @@ int main(int argc, char *argv[]) } } -#ifdef SIGBREAK - signal(SIGBREAK, &_signal_handler); -#endif -#ifdef SIGTERM - signal(SIGTERM, &_signal_handler); -#endif -#ifdef SIGABRT - signal(SIGABRT, &_signal_handler); -#endif -#ifdef SIGINT - signal(SIGINT, &_signal_handler); -#endif - + std::shared_ptr spLogger; try { - logger = new UDPT::Logger(var_map); + spLogger = std::shared_ptr(new UDPT::Logger(var_map)); + logger = spLogger.get(); } catch (const std::exception& ex) { @@ -148,39 +174,19 @@ int main(int argc, char *argv[]) return -1; } - std::shared_ptr tracker; - std::shared_ptr apiSrv; - std::shared_ptr webApp; - - try +#ifdef linux + if (!var_map.count("interactive")) { - tracker = std::shared_ptr(new UDPTracker(var_map)); - tracker->start(); - - if (var_map["apiserver.enable"].as()) - { - try - { - apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(var_map)); - webApp = std::shared_ptr(new UDPT::Server::WebApp(apiSrv, tracker->conn, var_map)); - webApp->deploy(); - } - catch (const UDPT::Server::ServerException &e) - { - std::cerr << "ServerException #" << e.getErrorCode() << ": " << e.getErrorMsg() << endl; - } - } - } - catch (const UDPT::UDPTException& ex) - { - std::cerr << "UDPTException: " << ex.what() << std::endl; + daemonize(var_map); } + ::signal(SIGHUP, _signal_handler); + ::signal(SIGTERM, _signal_handler); +#endif - std::cout << "Hit Control-C to exit." << endl; + tracker.start(var_map); + tracker.wait(); - tracker->wait(); - - std::cout << endl << "Goodbye." << endl; + std::cerr << "Bye." << std::endl; #ifdef WIN32 ::WSACleanup(); diff --git a/src/multiplatform.h b/src/multiplatform.h index 6dc3a33..d837c9f 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -36,11 +36,13 @@ #elif defined (linux) #include #include +#include #include #include #include #include #include +#include #define SOCKET int #define INVALID_SOCKET 0 diff --git a/src/tracker.cpp b/src/tracker.cpp new file mode 100644 index 0000000..df2093a --- /dev/null +++ b/src/tracker.cpp @@ -0,0 +1,50 @@ +#include "tracker.hpp" + +namespace UDPT +{ + Tracker::Tracker() + { + + } + + Tracker::~Tracker() + { + + } + + void Tracker::stop() + { + m_udpTracker->stop(); + wait(); + + m_apiSrv = nullptr; + m_webApp = nullptr; + m_udpTracker = nullptr; + } + + void Tracker::wait() + { + m_udpTracker->wait(); + } + + void Tracker::start(const boost::program_options::variables_map& conf) + { + m_udpTracker = std::shared_ptr(new UDPTracker(conf)); + + if (conf["apiserver.enable"].as()) + { + m_apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(conf)); + m_webApp = std::shared_ptr(new UDPT::Server::WebApp(m_apiSrv, m_udpTracker->conn, conf)); + m_webApp->deploy(); + } + + m_udpTracker->start(); + } + + Tracker& Tracker::getInstance() + { + static Tracker s_tracker; + + return s_tracker; + } +} diff --git a/src/tracker.hpp b/src/tracker.hpp new file mode 100644 index 0000000..0a0ea73 --- /dev/null +++ b/src/tracker.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +#include "logging.h" +#include "multiplatform.h" +#include "udpTracker.hpp" +#include "http/httpserver.hpp" +#include "http/webapp.hpp" + +namespace UDPT +{ + class Tracker + { + public: + + virtual ~Tracker(); + + void stop(); + + void start(const boost::program_options::variables_map& conf); + + void wait(); + + static Tracker& getInstance(); + + private: + std::shared_ptr m_udpTracker; + std::shared_ptr m_apiSrv; + std::shared_ptr m_webApp; + + Tracker(); + }; +} From cac3f5d209fc42f627a3281ccab79eed7a3e1dc0 Mon Sep 17 00:00:00 2001 From: Naim A Date: Fri, 29 Jan 2016 04:32:47 +0200 Subject: [PATCH 56/99] Better threading and IO --- src/main.cpp | 6 +- src/udpTracker.cpp | 200 ++++++++++++++++++--------------------------- src/udpTracker.hpp | 25 +++--- 3 files changed, 94 insertions(+), 137 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index a78fe2c..71ae48c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -162,7 +162,7 @@ int main(int argc, char *argv[]) try { apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(var_map)); - webApp = std::shared_ptr(new UDPT::Server::WebApp(apiSrv, tracker->conn, var_map)); + webApp = std::shared_ptr(new UDPT::Server::WebApp(apiSrv, tracker->m_conn.get(), var_map)); webApp->deploy(); } catch (const UDPT::Server::ServerException &e) @@ -177,11 +177,11 @@ int main(int argc, char *argv[]) } std::cout << "Hit Control-C to exit." << endl; + std::cin.get(); - tracker->wait(); + tracker->stop(); std::cout << endl << "Goodbye." << endl; - #ifdef WIN32 ::WSACleanup(); #endif diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index fceb498..ad24e26 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -38,7 +38,6 @@ namespace UDPT { UDPTracker::UDPTracker(const boost::program_options::variables_map& conf) : m_conf(conf) { - this->m_allowRemotes = conf["tracker.allow_remotes"].as(); this->m_allowIANA_IPs = conf["tracker.allow_iana_ips"].as(); this->m_isDynamic = conf["tracker.is_dynamic"].as(); @@ -59,61 +58,11 @@ namespace UDPT } this->m_localEndpoint = addrs.front(); - - - this->m_threads = new HANDLE[this->m_threadCount]; - - this->m_isRunning = false; - this->conn = nullptr; } UDPTracker::~UDPTracker() { - int i; // loop index - - this->m_isRunning = false; - - // drop listener connection to continue thread loops. - // wait for request to finish (1 second max; allot of time for a computer!). - - #ifdef linux - ::close(this->m_sock); - - ::sleep(1); - #elif defined (WIN32) - ::closesocket(this->m_sock); - - ::Sleep(1000); - #endif - - for (i = 0;i < this->m_threadCount;i++) - { - #ifdef WIN32 - ::TerminateThread(this->m_threads[i], 0x00); - #elif defined (linux) - ::pthread_detach(this->m_threads[i]); - ::pthread_cancel(this->m_threads[i]); - #endif - std::stringstream str; - str << "Thread (" << (i + 1) << "/" << ((int)this->m_threadCount) << ") terminated."; - logger->log(Logger::LL_INFO, str.str()); - } - if (this->conn != NULL) - delete this->conn; - delete[] this->m_threads; - } - - void UDPTracker::wait() - { -#ifdef WIN32 - ::WaitForMultipleObjects(this->m_threadCount, this->m_threads, TRUE, INFINITE); -#else - int i; - for (i = 0;i < this->m_threadCount; i++) - { - ::pthread_join(this->m_threads[i], NULL); - } -#endif + // left empty. } void UDPTracker::start() @@ -134,6 +83,19 @@ namespace UDPT yup = 1; ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); + { + // don't block recvfrom for too long. +#if defined(linux) + timeval timeout = { 0 }; + timeout.tv_sec = 5; +#elif defined(WIN32) + DWORD timeout = 5000; +#else +#error Unsupported OS. +#endif + ::setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); + } + this->m_localEndpoint.sin_family = AF_INET; r = ::bind(sock, reinterpret_cast(&this->m_localEndpoint), sizeof(SOCKADDR_IN)); @@ -149,20 +111,15 @@ namespace UDPT this->m_sock = sock; - this->conn = new Data::SQLite3Driver(m_conf, this->m_isDynamic); - - this->m_isRunning = true; + this->m_conn = std::shared_ptr(new Data::SQLite3Driver(m_conf, this->m_isDynamic)); ss.str(""); ss << "Starting maintenance thread (1/" << ((int)this->m_threadCount) << ")"; logger->log(Logger::LL_INFO, ss.str()); // create maintainer thread. - #ifdef WIN32 - this->m_threads[0] = ::CreateThread(NULL, 0, reinterpret_cast(_maintainance_start), (LPVOID)this, 0, NULL); - #elif defined (linux) - ::pthread_create(&this->m_threads[0], NULL, _maintainance_start, (void*)this); - #endif + + m_threads.push_back(boost::thread(UDPTracker::_maintainance_start, this)); for (i = 1;i < this->m_threadCount; i++) { @@ -170,14 +127,33 @@ namespace UDPT ss << "Starting thread (" << (i + 1) << "/" << ((int)this->m_threadCount) << ")"; logger->log(Logger::LL_INFO, ss.str()); - #ifdef WIN32 - this->m_threads[i] = ::CreateThread(NULL, 0, reinterpret_cast(_thread_start), (LPVOID)this, 0, NULL); - #elif defined (linux) - ::pthread_create(&(this->m_threads[i]), NULL, _thread_start, (void*)this); - #endif + m_threads.push_back(boost::thread(UDPTracker::_thread_start, this)); } } + void UDPTracker::stop() + { +#ifdef linux + ::close(m_sock); +#elif defined (WIN32) + ::closesocket(m_sock); +#endif + + for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it) + { + std::cout << "Interrupted thread " << it->get_id() << std::endl; + it->interrupt(); + } + + for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it) + { + std::cout << "waiting for " << it->get_id() << std::endl; + it->join(); + } + + std::cout << "All threads terminated." << std::endl; + } + int UDPTracker::sendError(UDPTracker* usi, SOCKADDR_IN* remote, uint32_t transactionID, const std::string &msg) { struct udp_error_response error; @@ -214,7 +190,7 @@ namespace UDPT resp.action = m_hton32(0); resp.transaction_id = req->transaction_id; - if (!usi->conn->genConnectionId(&resp.connection_id, + if (!usi->m_conn->genConnectionId(&resp.connection_id, m_hton32(remote->sin_addr.s_addr), m_hton16(remote->sin_port))) { @@ -240,7 +216,7 @@ namespace UDPT req = (AnnounceRequest*)data; - if (!usi->conn->verifyConnectionId(req->connection_id, + if (!usi->m_conn->verifyConnectionId(req->connection_id, m_hton32(remote->sin_addr.s_addr), m_hton16(remote->sin_port))) { @@ -262,7 +238,7 @@ namespace UDPT return 0; } - if (!usi->conn->isTorrentAllowed(req->info_hash)) + if (!usi->m_conn->isTorrentAllowed(req->info_hash)) { UDPTracker::sendError(usi, remote, req->transaction_id, "info_hash not registered."); return 0; @@ -271,7 +247,7 @@ namespace UDPT // load peers q = 30; if (req->num_want >= 1) - q = std::min(q, req->num_want); + q = std::min(q, req->num_want); peers = new DatabaseDriver::PeerEntry [q]; @@ -297,13 +273,13 @@ namespace UDPT q = 0; // no need for peers when stopping. if (q > 0) - usi->conn->getPeers(req->info_hash, &q, peers); + usi->m_conn->getPeers(req->info_hash, &q, peers); bSize = 20; // header is 20 bytes bSize += (6 * q); // + 6 bytes per peer. tE.info_hash = req->info_hash; - usi->conn->getTorrentInfo(&tE); + usi->m_conn->getTorrentInfo(&tE); resp = (AnnounceResponse*)buff; resp->action = m_hton32(1); @@ -337,7 +313,7 @@ namespace UDPT ip = m_hton32 (remote->sin_addr.s_addr); else ip = req->ip_address; - usi->conn->updatePeer(req->peer_id, req->info_hash, ip, req->port, + usi->m_conn->updatePeer(req->peer_id, req->info_hash, ip, req->port, req->downloaded, req->left, req->uploaded, event); return 0; @@ -362,7 +338,7 @@ namespace UDPT return 0; } - if (!usi->conn->verifyConnectionId(sR->connection_id, + if (!usi->m_conn->verifyConnectionId(sR->connection_id, m_hton32(remote->sin_addr.s_addr), m_hton16(remote->sin_port))) { @@ -391,7 +367,7 @@ namespace UDPT DatabaseDriver::TorrentEntry tE; tE.info_hash = hash; - if (!usi->conn->getTorrentInfo(&tE)) + if (!usi->m_conn->getTorrentInfo(&tE)) { sendError(usi, remote, sR->transaction_id, "Scrape Failed: couldn't retrieve torrent data"); return 0; @@ -407,15 +383,15 @@ namespace UDPT return 0; } -static int _isIANA_IP (uint32_t ip) -{ - uint8_t x = (ip % 256); - if (x == 0 || x == 10 || x == 127 || x >= 224) - return 1; - return 0; -} + int UDPTracker::isIANAIP(uint32_t ip) + { + uint8_t x = (ip % 256); + if (x == 0 || x == 10 || x == 127 || x >= 224) + return 1; + return 0; + } - int UDPTracker::resolveRequest (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r) + int UDPTracker::resolveRequest(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r) { ConnectionRequest* cR = reinterpret_cast(data); uint32_t action; @@ -424,7 +400,7 @@ static int _isIANA_IP (uint32_t ip) if (!usi->m_allowIANA_IPs) { - if (_isIANA_IP(remote->sin_addr.s_addr)) + if (isIANAIP(remote->sin_addr.s_addr)) { return 0; // Access Denied: IANA reserved IP. } @@ -445,14 +421,10 @@ static int _isIANA_IP (uint32_t ip) return 0; } -#ifdef WIN32 - DWORD UDPTracker::_thread_start (LPVOID arg) -#elif defined (linux) - void* UDPTracker::_thread_start (void *arg) -#endif + void UDPTracker::_thread_start(UDPTracker *usi) { - UDPTracker *usi; SOCKADDR_IN remoteAddr; + char tmpBuff[UDP_BUFFER_SIZE]; #ifdef linux socklen_t addrSz; @@ -460,51 +432,37 @@ static int _isIANA_IP (uint32_t ip) int addrSz; #endif - int r; - char tmpBuff[UDP_BUFFER_SIZE]; - - usi = reinterpret_cast(arg); - addrSz = sizeof(SOCKADDR_IN); - while (usi->m_isRunning) + while (true) { // peek into the first 12 bytes of data; determine if connection request or announce request. - r = ::recvfrom(usi->m_sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); + int r = ::recvfrom(usi->m_sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); if (r <= 0) - continue; // bad request... - r = UDPTracker::resolveRequest(usi, &remoteAddr, tmpBuff, r); - } + { + boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); + continue; + } - #ifdef linux - ::pthread_exit (NULL); - #endif - return 0; + { + boost::this_thread::disable_interruption di; + r = UDPTracker::resolveRequest(usi, &remoteAddr, tmpBuff, r); + } + } } -#ifdef WIN32 - DWORD UDPTracker::_maintainance_start(LPVOID arg) -#elif defined (linux) - void* UDPTracker::_maintainance_start(void *arg) -#endif + void UDPTracker::_maintainance_start(UDPTracker* usi) { - UDPTracker* usi = reinterpret_cast(arg); - - while (usi->m_isRunning) + while (true) { - usi->conn->cleanup(); + { + boost::this_thread::disable_interruption di; + usi->m_conn->cleanup(); + } -#ifdef WIN32 - ::Sleep(usi->m_cleanupInterval * 1000); -#elif defined (linux) - ::sleep(usi->m_cleanupInterval); -#else -#error Unsupported OS. -#endif + boost::this_thread::sleep_for(boost::chrono::seconds(usi->m_cleanupInterval)); } - - return 0; } }; diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 084a52b..b57ab64 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -22,6 +22,9 @@ #include +#include +#include +#include #include #include #include "exceptions.h" @@ -123,10 +126,10 @@ namespace UDPT */ void start(); - /** - * Joins all threads, and waits for all of them to terminate. + /** + * Terminates tracker. */ - void wait(); + void stop(); /** * Destroys resources that were created by constructor @@ -134,29 +137,24 @@ namespace UDPT */ virtual ~UDPTracker(); - Data::DatabaseDriver *conn; + std::shared_ptr m_conn; + private: SOCKET m_sock; SOCKADDR_IN m_localEndpoint; uint16_t m_port; uint8_t m_threadCount; - bool m_isRunning; bool m_isDynamic; bool m_allowRemotes; bool m_allowIANA_IPs; - HANDLE *m_threads; + std::vector m_threads; uint32_t m_announceInterval; uint32_t m_cleanupInterval; const boost::program_options::variables_map& m_conf; -#ifdef WIN32 - static DWORD _thread_start(LPVOID arg); - static DWORD _maintainance_start(LPVOID arg); -#elif defined (linux) - static void* _thread_start(void *arg); - static void* _maintainance_start(void *arg); -#endif + static void _thread_start(UDPTracker *usi); + static void _maintainance_start(UDPTracker* usi); static int resolveRequest(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r); @@ -166,6 +164,7 @@ namespace UDPT static int sendError(UDPTracker *, SOCKADDR_IN *remote, uint32_t transId, const std::string &); + static int isIANAIP(uint32_t ip); }; }; From d27b7b29c3a1f5a7db0fbaf718728d04748ab021 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sat, 23 Jan 2016 18:31:43 -0800 Subject: [PATCH 57/99] WIP: writing daemon + reloadable --- src/main.cpp | 102 +++++++++++++++++++++++--------------------- src/multiplatform.h | 2 + src/tracker.cpp | 50 ++++++++++++++++++++++ src/tracker.hpp | 35 +++++++++++++++ 4 files changed, 141 insertions(+), 48 deletions(-) create mode 100644 src/tracker.cpp create mode 100644 src/tracker.hpp diff --git a/src/main.cpp b/src/main.cpp index 71ae48c..8e0781b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -30,20 +30,50 @@ #include "udpTracker.hpp" #include "http/httpserver.hpp" #include "http/webapp.hpp" +#include "tracker.hpp" -UDPT::Logger *logger; +UDPT::Logger *logger = NULL; +UDPT::Tracker *instance = NULL; static void _signal_handler (int sig) { - std::stringstream ss; - ss << "Signal " << sig << " raised. "; - logger->log(Logger::LL_INFO, ss.str()); + switch (sig) + { + case SIGTERM: + instance->stop(); + break; + case SIGHUP: + break; + } } +#ifdef linux +static void daemonize(const boost::program_options::variables_map& conf) +{ + if (1 == ::getppid()) return; // already a daemon + int r = ::fork(); + if (0 > r) ::exit(-1); // failed to daemonize. + if (0 < r) ::exit(0); // parent exists. + + ::umask(0); + ::setsid(); + + // close all fds. + for (int i = ::getdtablesize(); i >=0; --i) + { + ::close(i); + } + + ::chdir(conf["daemon.chdir"].as().c_str()); + +} +#endif + int main(int argc, char *argv[]) { - int r; + Tracker& tracker = UDPT::Tracker::getInstance(); + instance = &tracker; #ifdef WIN32 WSADATA wsadata; @@ -56,6 +86,9 @@ int main(int argc, char *argv[]) ("all-help", "displays all help") ("test,t", "test configuration file") ("config,c", boost::program_options::value()->default_value("/etc/udpt.conf"), "configuration file to use") +#ifdef linux + ("interactive,i", "doesn't start as daemon") +#endif ; boost::program_options::options_description configOptions("Configuration options"); @@ -77,6 +110,10 @@ int main(int argc, char *argv[]) ("logging.filename", boost::program_options::value()->default_value("stdout"), "file to write logs to") ("logging.level", boost::program_options::value()->default_value("warning"), "log level (error/warning/info/debug)") + +#ifdef linux + ("daemon.chdir", boost::program_options::value()->default_value("/"), "home directory for daemon") +#endif ; boost::program_options::variables_map var_map; @@ -125,22 +162,11 @@ int main(int argc, char *argv[]) } } -#ifdef SIGBREAK - signal(SIGBREAK, &_signal_handler); -#endif -#ifdef SIGTERM - signal(SIGTERM, &_signal_handler); -#endif -#ifdef SIGABRT - signal(SIGABRT, &_signal_handler); -#endif -#ifdef SIGINT - signal(SIGINT, &_signal_handler); -#endif - + std::shared_ptr spLogger; try { - logger = new UDPT::Logger(var_map); + spLogger = std::shared_ptr(new UDPT::Logger(var_map)); + logger = spLogger.get(); } catch (const std::exception& ex) { @@ -148,40 +174,20 @@ int main(int argc, char *argv[]) return -1; } - std::shared_ptr tracker; - std::shared_ptr apiSrv; - std::shared_ptr webApp; - - try +#ifdef linux + if (!var_map.count("interactive")) { - tracker = std::shared_ptr(new UDPTracker(var_map)); - tracker->start(); - - if (var_map["apiserver.enable"].as()) - { - try - { - apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(var_map)); - webApp = std::shared_ptr(new UDPT::Server::WebApp(apiSrv, tracker->m_conn.get(), var_map)); - webApp->deploy(); - } - catch (const UDPT::Server::ServerException &e) - { - std::cerr << "ServerException #" << e.getErrorCode() << ": " << e.getErrorMsg() << endl; - } - } - } - catch (const UDPT::UDPTException& ex) - { - std::cerr << "UDPTException: " << ex.what() << std::endl; + daemonize(var_map); } + ::signal(SIGHUP, _signal_handler); + ::signal(SIGTERM, _signal_handler); +#endif - std::cout << "Hit Control-C to exit." << endl; - std::cin.get(); + tracker.start(var_map); + tracker.wait(); - tracker->stop(); + std::cerr << "Bye." << std::endl; - std::cout << endl << "Goodbye." << endl; #ifdef WIN32 ::WSACleanup(); #endif diff --git a/src/multiplatform.h b/src/multiplatform.h index 6dc3a33..d837c9f 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -36,11 +36,13 @@ #elif defined (linux) #include #include +#include #include #include #include #include #include +#include #define SOCKET int #define INVALID_SOCKET 0 diff --git a/src/tracker.cpp b/src/tracker.cpp new file mode 100644 index 0000000..df2093a --- /dev/null +++ b/src/tracker.cpp @@ -0,0 +1,50 @@ +#include "tracker.hpp" + +namespace UDPT +{ + Tracker::Tracker() + { + + } + + Tracker::~Tracker() + { + + } + + void Tracker::stop() + { + m_udpTracker->stop(); + wait(); + + m_apiSrv = nullptr; + m_webApp = nullptr; + m_udpTracker = nullptr; + } + + void Tracker::wait() + { + m_udpTracker->wait(); + } + + void Tracker::start(const boost::program_options::variables_map& conf) + { + m_udpTracker = std::shared_ptr(new UDPTracker(conf)); + + if (conf["apiserver.enable"].as()) + { + m_apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(conf)); + m_webApp = std::shared_ptr(new UDPT::Server::WebApp(m_apiSrv, m_udpTracker->conn, conf)); + m_webApp->deploy(); + } + + m_udpTracker->start(); + } + + Tracker& Tracker::getInstance() + { + static Tracker s_tracker; + + return s_tracker; + } +} diff --git a/src/tracker.hpp b/src/tracker.hpp new file mode 100644 index 0000000..0a0ea73 --- /dev/null +++ b/src/tracker.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +#include "logging.h" +#include "multiplatform.h" +#include "udpTracker.hpp" +#include "http/httpserver.hpp" +#include "http/webapp.hpp" + +namespace UDPT +{ + class Tracker + { + public: + + virtual ~Tracker(); + + void stop(); + + void start(const boost::program_options::variables_map& conf); + + void wait(); + + static Tracker& getInstance(); + + private: + std::shared_ptr m_udpTracker; + std::shared_ptr m_apiSrv; + std::shared_ptr m_webApp; + + Tracker(); + }; +} From 37c965019bc1f3585b7ec3d53070fa7071bef0db Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 28 Jan 2016 19:08:43 -0800 Subject: [PATCH 58/99] Basic daemon support --- Makefile | 4 ++-- README.md | 2 +- src/main.cpp | 10 +++------- src/tracker.cpp | 2 +- src/udpTracker.cpp | 11 ++++++----- src/udpTracker.hpp | 5 +++++ 6 files changed, 18 insertions(+), 16 deletions(-) diff --git a/Makefile b/Makefile index 25762d5..9b37e76 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ # objects = main.o udpTracker.o database.o driver_sqlite.o \ - tools.o httpserver.o webapp.o logging.o + tools.o httpserver.o webapp.o logging.o tracker.o target = udpt %.o: src/%.c @@ -33,7 +33,7 @@ all: $(target) $(target): $(objects) @echo Linking... - $(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lboost_program_options -lsqlite3 -lpthread + $(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lboost_program_options -lsqlite3 -lpthread -lboost_thread -lboost_system @echo Done. clean: @echo Cleaning Up... diff --git a/README.md b/README.md index a350e12..f5f8604 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ We use [SQLite3](http://www.sqlite.org/) which is public-domain, and [Boost](htt We didn't really work on creating any installer, at the moment you can just run udpt from anywhere on your filesystem. Building udpt is pretty straightforward, just download the project or clone the repo: -UDPT requires the SQLite3 develpment package to be installed. +UDPT requires the SQLite3, boost_program_options and boost_thread develpment packages to be installed.
     $ git clone https://github.com/naim94a/udpt.git
diff --git a/src/main.cpp b/src/main.cpp
index 8e0781b..c8bd11f 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -33,17 +33,16 @@
 #include "tracker.hpp"
 
 UDPT::Logger *logger = NULL;
-UDPT::Tracker *instance = NULL;
 
-
-static void _signal_handler (int sig)
+static void _signal_handler(int sig)
 {
 	switch (sig)
 	{
 		case SIGTERM:
-			instance->stop();
+			UDPT::Tracker::getInstance().stop();
 			break;
 		case SIGHUP:
+			// TODO: Reload config.
 			break;
 	}
 }
@@ -73,7 +72,6 @@ static void daemonize(const boost::program_options::variables_map& conf)
 int main(int argc, char *argv[])
 {
 	Tracker& tracker = UDPT::Tracker::getInstance();
-	instance = &tracker;
 
 #ifdef WIN32
 	WSADATA wsadata;
@@ -186,8 +184,6 @@ int main(int argc, char *argv[])
 	tracker.start(var_map);
 	tracker.wait();
 
-	std::cerr << "Bye." << std::endl;
-
 #ifdef WIN32
 	::WSACleanup();
 #endif
diff --git a/src/tracker.cpp b/src/tracker.cpp
index df2093a..9cb7d68 100644
--- a/src/tracker.cpp
+++ b/src/tracker.cpp
@@ -34,7 +34,7 @@ namespace UDPT
         if (conf["apiserver.enable"].as())
         {
             m_apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(conf));
-            m_webApp = std::shared_ptr(new UDPT::Server::WebApp(m_apiSrv, m_udpTracker->conn, conf));
+            m_webApp = std::shared_ptr(new UDPT::Server::WebApp(m_apiSrv, m_udpTracker->m_conn.get(), conf));
             m_webApp->deploy();
         }
 
diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp
index ad24e26..dd6b5cd 100644
--- a/src/udpTracker.cpp
+++ b/src/udpTracker.cpp
@@ -62,7 +62,7 @@ namespace UDPT
 
 	UDPTracker::~UDPTracker()
 	{
-		// left empty.
+		stop();
 	}
 
 	void UDPTracker::start()
@@ -141,17 +141,18 @@ namespace UDPT
 
 		for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
 		{
-			std::cout << "Interrupted thread " << it->get_id() << std::endl;
 			it->interrupt();
 		}
 
+		wait();
+	}
+
+	void UDPTracker::wait()
+	{
 		for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
 		{
-			std::cout << "waiting for " << it->get_id() << std::endl;
 			it->join();
 		}
-
-		std::cout << "All threads terminated." << std::endl;
 	}
 
 	int UDPTracker::sendError(UDPTracker* usi, SOCKADDR_IN* remote, uint32_t transactionID, const std::string &msg)
diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp
index b57ab64..5e7cf4d 100644
--- a/src/udpTracker.hpp
+++ b/src/udpTracker.hpp
@@ -131,6 +131,11 @@ namespace UDPT
 		 */
 		void stop();
 
+		/** 
+		 * Joins worker threads
+		 */
+		void wait();
+
 		/**
 		 * Destroys resources that were created by constructor
 		 * @param usi Instance to destroy.

From 20ce6f44026aa06f09917fb9e5fe56ebd8e83746 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sat, 30 Jan 2016 23:10:07 +0200
Subject: [PATCH 59/99] Removed unused signal

---
 src/main.cpp | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/src/main.cpp b/src/main.cpp
index c8bd11f..99834b8 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -41,9 +41,6 @@ static void _signal_handler(int sig)
 		case SIGTERM:
 			UDPT::Tracker::getInstance().stop();
 			break;
-		case SIGHUP:
-			// TODO: Reload config.
-			break;
 	}
 }
 
@@ -177,7 +174,6 @@ int main(int argc, char *argv[])
 	{
 		daemonize(var_map);
 	}
-	::signal(SIGHUP, _signal_handler);
 	::signal(SIGTERM, _signal_handler);
 #endif
 

From 07eb3a56037c41c5019d8c65c6d2405c799b6e9b Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sat, 30 Jan 2016 23:12:23 +0200
Subject: [PATCH 60/99] Added files for Visual Studio

---
 .gitignore                   |   6 ++
 vs/UDPT.sln                  |  22 +++++++
 vs/UDPT/UDPT.vcxproj         | 108 +++++++++++++++++++++++++++++++++++
 vs/UDPT/UDPT.vcxproj.filters |  90 +++++++++++++++++++++++++++++
 4 files changed, 226 insertions(+)
 create mode 100644 vs/UDPT.sln
 create mode 100644 vs/UDPT/UDPT.vcxproj
 create mode 100644 vs/UDPT/UDPT.vcxproj.filters

diff --git a/.gitignore b/.gitignore
index 8c483d3..4d233f0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,8 @@
 *.o
 *.sublime-*
+*.sqlite3
+*.vcxproj.user
+*.sdf
+*.suo
+*.opensdf
+**/Debug/*
diff --git a/vs/UDPT.sln b/vs/UDPT.sln
new file mode 100644
index 0000000..5c1e620
--- /dev/null
+++ b/vs/UDPT.sln
@@ -0,0 +1,22 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2013
+VisualStudioVersion = 12.0.31101.0
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UDPT", "UDPT\UDPT.vcxproj", "{9F399AF8-861E-4E50-A94C-1388089E3FA0}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Release|Win32 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{9F399AF8-861E-4E50-A94C-1388089E3FA0}.Debug|Win32.ActiveCfg = Debug|Win32
+		{9F399AF8-861E-4E50-A94C-1388089E3FA0}.Debug|Win32.Build.0 = Debug|Win32
+		{9F399AF8-861E-4E50-A94C-1388089E3FA0}.Release|Win32.ActiveCfg = Release|Win32
+		{9F399AF8-861E-4E50-A94C-1388089E3FA0}.Release|Win32.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/vs/UDPT/UDPT.vcxproj b/vs/UDPT/UDPT.vcxproj
new file mode 100644
index 0000000..d7bcb9a
--- /dev/null
+++ b/vs/UDPT/UDPT.vcxproj
@@ -0,0 +1,108 @@
+
+
+  
+    
+      Debug
+      Win32
+    
+    
+      Release
+      Win32
+    
+  
+  
+    {9F399AF8-861E-4E50-A94C-1388089E3FA0}
+    UDPT
+  
+  
+  
+    Application
+    true
+    v120
+    MultiByte
+    true
+  
+  
+    Application
+    false
+    v120
+    true
+    MultiByte
+  
+  
+  
+  
+  
+    
+  
+  
+    
+  
+  
+  
+    $(VC_IncludePath);$(WindowsSDK_IncludePath);D:\libs\sqlite3;D:\libs\boost\boost_1_59_0
+    D:\libs\boost\boost_1_59_0\stage\lib;D:\libs\sqlite3\Release;$(LibraryPath)
+    false
+  
+  
+    $(VC_IncludePath);$(WindowsSDK_IncludePath);D:\libs\sqlite3;D:\libs\boost\boost_1_59_0
+    D:\libs\boost\boost_1_59_0\stage\lib;D:\libs\sqlite3\Release;$(LibraryPath)
+  
+  
+    
+      Level3
+      Disabled
+      true
+      MultiThreadedDebugDLL
+      Async
+      ProgramDatabase
+    
+    
+      true
+      ws2_32.lib;sqlite3.lib;
+    
+  
+  
+    
+      Level3
+      MaxSpeed
+      true
+      true
+      true
+      MultiThreadedDLL
+      Async
+    
+    
+      true
+      true
+      true
+      ws2_32.lib;sqlite3.lib;%(AdditionalDependencies)
+    
+  
+  
+    
+    
+    
+    
+    
+    
+    
+    
+    
+  
+  
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+  
+  
+  
+  
+
\ No newline at end of file
diff --git a/vs/UDPT/UDPT.vcxproj.filters b/vs/UDPT/UDPT.vcxproj.filters
new file mode 100644
index 0000000..db3e909
--- /dev/null
+++ b/vs/UDPT/UDPT.vcxproj.filters
@@ -0,0 +1,90 @@
+
+
+  
+    
+      {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
+      cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
+    
+    
+      {93995380-89BD-4b04-88EB-625FBE52EBFB}
+      h;hh;hpp;hxx;hm;inl;inc;xsd
+    
+    
+      {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
+      rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
+    
+    
+      {f5a85f67-2777-4fa5-828e-9c79af9f4b13}
+    
+    
+      {643f664e-8751-4440-8b90-fe95b15e0aac}
+    
+    
+      {bcb1fa9f-c9ec-4398-97f9-544baf69f2a9}
+    
+    
+      {f65a2e69-6a71-4cd0-ad64-36a73c6c94c4}
+    
+  
+  
+    
+      Source Files
+    
+    
+      Source Files
+    
+    
+      Source Files
+    
+    
+      Source Files
+    
+    
+      Source Files\db
+    
+    
+      Source Files\db
+    
+    
+      Source Files\http
+    
+    
+      Source Files\http
+    
+    
+      Source Files
+    
+  
+  
+    
+      Header Files
+    
+    
+      Header Files
+    
+    
+      Header Files
+    
+    
+      Header Files
+    
+    
+      Header Files\db
+    
+    
+      Header Files\db
+    
+    
+      Header Files\http
+    
+    
+      Header Files\http
+    
+    
+      Header Files
+    
+    
+      Header Files
+    
+  
+
\ No newline at end of file

From 4f473fe8402d85f529b57e287bb691ae05c58e58 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sun, 31 Jan 2016 04:46:26 +0200
Subject: [PATCH 61/99] Added copyright notice for tracker.*

---
 src/tracker.cpp | 18 ++++++++++++++++++
 src/tracker.hpp | 18 ++++++++++++++++++
 2 files changed, 36 insertions(+)

diff --git a/src/tracker.cpp b/src/tracker.cpp
index 9cb7d68..0aa7014 100644
--- a/src/tracker.cpp
+++ b/src/tracker.cpp
@@ -1,3 +1,21 @@
+/*
+*	Copyright © 2012-2016 Naim A.
+*
+*	This file is part of UDPT.
+*
+*		UDPT is free software: you can redistribute it and/or modify
+*		it under the terms of the GNU General Public License as published by
+*		the Free Software Foundation, either version 3 of the License, or
+*		(at your option) any later version.
+*
+*		UDPT 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 UDPT.  If not, see .
+*/
 #include "tracker.hpp"
 
 namespace UDPT
diff --git a/src/tracker.hpp b/src/tracker.hpp
index 0a0ea73..b5fae24 100644
--- a/src/tracker.hpp
+++ b/src/tracker.hpp
@@ -1,3 +1,21 @@
+/*
+*	Copyright © 2012-2016 Naim A.
+*
+*	This file is part of UDPT.
+*
+*		UDPT is free software: you can redistribute it and/or modify
+*		it under the terms of the GNU General Public License as published by
+*		the Free Software Foundation, either version 3 of the License, or
+*		(at your option) any later version.
+*
+*		UDPT 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 UDPT.  If not, see .
+*/
 #pragma once
 
 #include 

From 32fc6203d91689a4f67ce058e21b9319bad908c8 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sun, 31 Jan 2016 22:41:59 +0200
Subject: [PATCH 62/99] Bugfix for issue #17

---
 src/main.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/main.cpp b/src/main.cpp
index 99834b8..c4efe15 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -100,7 +100,7 @@ int main(int argc, char *argv[])
 		("tracker.cleanup_interval", boost::program_options::value()->default_value(120), "sets database cleanup interval")
 		
 		("apiserver.enable", boost::program_options::value()->default_value(0), "Enable API server?")
-		("apiserver.threads", boost::program_options::value()->default_value(1), "threads for API server")
+		("apiserver.threads", boost::program_options::value()->default_value(1), "threads for API server")
 		("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on")
 
 		("logging.filename", boost::program_options::value()->default_value("stdout"), "file to write logs to")

From f0f0f0f2faa75ad113317762f1df7df3aff3c776 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Mon, 1 Feb 2016 00:10:49 +0200
Subject: [PATCH 63/99] Added only localhost to whitelist

---
 src/http/webapp.cpp | 27 ++-------------------------
 src/http/webapp.hpp |  2 --
 src/main.cpp        |  1 +
 src/udpTracker.cpp  |  4 ++--
 4 files changed, 5 insertions(+), 29 deletions(-)

diff --git a/src/http/webapp.cpp b/src/http/webapp.cpp
index 3ab1c03..d3e7c4f 100644
--- a/src/http/webapp.cpp
+++ b/src/http/webapp.cpp
@@ -134,25 +134,6 @@ namespace UDPT
 					"");
 		}
 
-		bool WebApp::isAllowedIP (WebApp *app, string key, uint32_t ip)
-		{
-			std::map >::iterator it, end;
-			end = app->ip_whitelist.end ();
-			it = app->ip_whitelist.find (key);
-			if (it == app->ip_whitelist.end())
-				return false;	// no such key
-
-			list *lst = &it->second;
-			list::iterator ipit;
-			for (ipit = lst->begin();ipit != lst->end();ipit++)
-			{
-				if (*ipit == ip)
-					return true;
-			}
-
-			return false;
-		}
-
 		void WebApp::doRemoveTorrent (HTTPServer::Request *req, HTTPServer::Response *resp)
 		{
 			string strHash = req->getParam("hash");
@@ -208,18 +189,14 @@ namespace UDPT
 				throw ServerException (0, "IPv4 supported Only.");
 			}
 
-			std::string key = req->getParam("auth");
-			if (key.length() <= 0)
-				throw ServerException (0, "Bad Authentication Key");
-
 			WebApp *app = (WebApp*)srv->getData("webapp");
 			if (app == NULL)
 				throw ServerException(0, "WebApp object wasn't found");
 
-			if (!isAllowedIP(app, key, req->getAddress()->sin_addr.s_addr))
+			if (req->getAddress()->sin_addr.s_addr != 0x0100007f)
 			{
 				resp->setStatus(403, "Forbidden");
-				resp->write("IP not whitelisted. Access Denied.");
+				resp->write("Access Denied. Only 127.0.0.1 can access this method.");
 				return;
 			}
 
diff --git a/src/http/webapp.hpp b/src/http/webapp.hpp
index dc4bafb..b764e2e 100644
--- a/src/http/webapp.hpp
+++ b/src/http/webapp.hpp
@@ -47,12 +47,10 @@ namespace UDPT
 			std::shared_ptr m_server;
 			UDPT::Data::DatabaseDriver *db;
 			const boost::program_options::variables_map& m_conf;
-			std::map > ip_whitelist;
 
 			static void handleRoot (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*);
 			static void handleAnnounce (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*);
 			static void handleAPI (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*);
-			static bool isAllowedIP (WebApp *, string, uint32_t);
 
 			void doAddTorrent (HTTPServer::Request*, HTTPServer::Response*);
 			void doRemoveTorrent (HTTPServer::Request*, HTTPServer::Response*);
diff --git a/src/main.cpp b/src/main.cpp
index c4efe15..08b56f5 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -86,6 +86,7 @@ int main(int argc, char *argv[])
 #endif
 		;
 
+
 	boost::program_options::options_description configOptions("Configuration options");
 	configOptions.add_options()
 		("db.driver", boost::program_options::value()->default_value("sqlite3"), "database driver to use")
diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp
index dd6b5cd..15d3a49 100644
--- a/src/udpTracker.cpp
+++ b/src/udpTracker.cpp
@@ -58,6 +58,8 @@ namespace UDPT
 		}
 
 		this->m_localEndpoint = addrs.front();
+
+		this->m_conn = std::shared_ptr(new Data::SQLite3Driver(m_conf, this->m_isDynamic));
 	}
 
 	UDPTracker::~UDPTracker()
@@ -111,8 +113,6 @@ namespace UDPT
 
 		this->m_sock = sock;
 
-		this->m_conn = std::shared_ptr(new Data::SQLite3Driver(m_conf, this->m_isDynamic));
-
 		ss.str("");
 		ss << "Starting maintenance thread (1/" << ((int)this->m_threadCount) << ")";
 		logger->log(Logger::LL_INFO, ss.str());

From 465f942baf9c72e4593cba6e1b88ee295d0c19d3 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sun, 31 Jan 2016 04:44:04 +0200
Subject: [PATCH 64/99] Added OSError exception class

---
 src/exceptions.h | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/src/exceptions.h b/src/exceptions.h
index 43e14b4..589bbdc 100644
--- a/src/exceptions.h
+++ b/src/exceptions.h
@@ -1,5 +1,6 @@
 #pragma once
 
+#include "multiplatform.h"
 
 namespace UDPT
 {
@@ -30,4 +31,17 @@ namespace UDPT
 		const char* m_error;
 		const int m_errorCode;
 	};
+
+	class OSError : public UDPTException
+	{
+	public:
+		OSError(int errorCode
+#ifdef WIN32 
+			= ::GetLastError()
+#endif
+			) : UDPTException("OSError", errorCode)
+		{
+		}
+
+	};
 }

From 7271aa2cb0ac9130f194682a51d24f681fee49f4 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sun, 31 Jan 2016 04:45:03 +0200
Subject: [PATCH 65/99] WIP: adding windows service

---
 src/main.cpp                 |  56 +++++++++++++++
 src/service.cpp              | 135 +++++++++++++++++++++++++++++++++++
 src/service.hpp              |  60 ++++++++++++++++
 vs/UDPT/UDPT.vcxproj         |  13 ++--
 vs/UDPT/UDPT.vcxproj.filters |   6 ++
 5 files changed, 265 insertions(+), 5 deletions(-)
 create mode 100644 src/service.cpp
 create mode 100644 src/service.hpp

diff --git a/src/main.cpp b/src/main.cpp
index 08b56f5..cfae957 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -31,6 +31,7 @@
 #include "http/httpserver.hpp"
 #include "http/webapp.hpp"
 #include "tracker.hpp"
+#include "service.hpp"
 
 UDPT::Logger *logger = NULL;
 
@@ -83,6 +84,9 @@ int main(int argc, char *argv[])
 		("config,c", boost::program_options::value()->default_value("/etc/udpt.conf"), "configuration file to use")
 #ifdef linux
 		("interactive,i", "doesn't start as daemon")
+#endif
+#ifdef WIN32
+		("service,s", boost::program_options::value(), "start/stop/install/uninstall service")
 #endif
 		;
 
@@ -109,6 +113,9 @@ int main(int argc, char *argv[])
 
 #ifdef linux
 		("daemon.chdir", boost::program_options::value()->default_value("/"), "home directory for daemon")
+#endif
+#ifdef WIN32 
+		("service.name", boost::program_options::value()->default_value("udpt"), "service name to use")
 #endif
 		;
 
@@ -177,6 +184,55 @@ int main(int argc, char *argv[])
 	}
 	::signal(SIGTERM, _signal_handler);
 #endif
+#ifdef WIN32 
+	UDPT::Service svc(var_map);
+	if (var_map.count("service"))
+	{
+		const std::string& action = var_map["service"].as();
+		try
+		{
+			if ("install" == action)
+			{
+				std::cout << "Installing service..." << std::endl;
+				svc.install();
+				std::cout << "Installed." << std::endl;
+			}
+			else if ("uninstall" == action)
+			{
+				std::cout << "Removing service..." << std::endl;
+				svc.uninstall();
+				std::cout << "Removed." << std::endl;
+			}
+			else if ("start" == action)
+			{
+				svc.start();
+			}
+			else if ("stop" == action)
+			{
+				svc.stop();
+			}
+		}
+		catch (const UDPT::OSError& ex)
+		{
+			std::cout << "An operating system error occurred: " << ex.getErrorCode() << std::endl;
+			return -1;
+		}
+
+		return 0;
+	}
+
+	try 
+	{
+		svc.setup();
+	}
+	catch (const OSError& err)
+	{
+		if (ERROR_FAILED_SERVICE_CONTROLLER_CONNECT != err.getErrorCode())
+		{
+			logger->log(UDPT::Logger::LL_ERROR, "failed to start as service");
+		}
+	}
+#endif
 
 	tracker.start(var_map);
 	tracker.wait();
diff --git a/src/service.cpp b/src/service.cpp
new file mode 100644
index 0000000..1d2169b
--- /dev/null
+++ b/src/service.cpp
@@ -0,0 +1,135 @@
+/*
+*	Copyright © 2012-2016 Naim A.
+*
+*	This file is part of UDPT.
+*
+*		UDPT is free software: you can redistribute it and/or modify
+*		it under the terms of the GNU General Public License as published by
+*		the Free Software Foundation, either version 3 of the License, or
+*		(at your option) any later version.
+*
+*		UDPT 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 UDPT.  If not, see .
+*/
+#include "service.hpp"
+
+#ifdef WIN32 
+
+namespace UDPT
+{
+	Service::Service(const boost::program_options::variables_map& conf) : m_conf(conf)
+	{
+
+	}
+
+	Service::~Service()
+	{
+
+	}
+
+	void Service::install()
+	{
+		std::string& binaryPath = getFilename();
+		binaryPath = "\"" + binaryPath + "\"";
+		std::shared_ptr svcMgr = getServiceManager(SC_MANAGER_CREATE_SERVICE);
+		{
+			SC_HANDLE installedService = ::CreateService(reinterpret_cast(svcMgr.get()),
+				m_conf["service.name"].as().c_str(),
+				"UDPT Tracker",
+				SC_MANAGER_CREATE_SERVICE,
+				SERVICE_WIN32_OWN_PROCESS,
+				SERVICE_AUTO_START,
+				SERVICE_ERROR_NORMAL,
+				binaryPath.c_str(),
+				NULL,
+				NULL,
+				NULL,
+				NULL,
+				NULL
+				);
+			if (nullptr == installedService)
+			{
+				throw OSError();
+			}
+
+			::CloseServiceHandle(installedService);
+		}
+	}
+
+	void Service::uninstall()
+	{
+		std::shared_ptr service = getService(DELETE);
+		BOOL bRes = ::DeleteService(reinterpret_cast(service.get()));
+		if (FALSE == bRes)
+		{
+			throw OSError();
+		}
+	}
+
+	void Service::start()
+	{
+
+	}
+
+	void Service::stop()
+	{
+
+	}
+
+	void Service::setup()
+	{
+		SERVICE_TABLE_ENTRY service = { 0 };
+		service.lpServiceName = const_cast(m_conf["service.name"].as().c_str());
+		service.lpServiceProc = reinterpret_cast(&Service::serviceMain);
+		if (FALSE == ::StartServiceCtrlDispatcher(&service))
+		{
+			throw OSError();
+		}
+	}
+
+	VOID Service::serviceMain(DWORD argc, LPCSTR argv[])
+	{
+
+	}
+
+	std::shared_ptr Service::getService(DWORD access)
+	{
+		std::shared_ptr serviceManager = getServiceManager(access);
+		{
+			SC_HANDLE service = ::OpenService(reinterpret_cast(serviceManager.get()), m_conf["service.name"].as().c_str(), access);
+			if (nullptr == service)
+			{
+				throw OSError();
+			}
+			return std::shared_ptr(service, ::CloseServiceHandle);
+		}
+	}
+
+	std::shared_ptr Service::getServiceManager(DWORD access)
+	{
+		SC_HANDLE svcMgr = ::OpenSCManager(NULL, NULL, access);
+		if (nullptr == svcMgr)
+		{
+			throw OSError();
+		}
+		return std::shared_ptr(svcMgr, ::CloseServiceHandle);
+	}
+
+	std::string Service::getFilename()
+	{
+		char filename[MAX_PATH];
+		DWORD dwRet = ::GetModuleFileName(NULL, filename, sizeof(filename) / sizeof(char));
+		if (0 == dwRet)
+		{
+			throw OSError();
+		}
+		return std::string(filename);
+	}
+}
+
+#endif
diff --git a/src/service.hpp b/src/service.hpp
new file mode 100644
index 0000000..4255756
--- /dev/null
+++ b/src/service.hpp
@@ -0,0 +1,60 @@
+/*
+*	Copyright © 2012-2016 Naim A.
+*
+*	This file is part of UDPT.
+*
+*		UDPT is free software: you can redistribute it and/or modify
+*		it under the terms of the GNU General Public License as published by
+*		the Free Software Foundation, either version 3 of the License, or
+*		(at your option) any later version.
+*
+*		UDPT 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 UDPT.  If not, see .
+*/
+#pragma once
+
+#include 
+#include "multiplatform.h"
+#include "exceptions.h"
+
+#ifdef WIN32 
+namespace UDPT
+{
+	class Service
+	{
+	public:
+		Service(const boost::program_options::variables_map& conf);
+
+		virtual ~Service();
+
+
+		void install();
+
+		void uninstall();
+
+		void start();
+
+		void stop();
+
+		void setup();
+	private:
+		const boost::program_options::variables_map& m_conf;
+
+		std::shared_ptr getService(DWORD access);
+
+		static VOID WINAPI handler(DWORD controlCode);
+
+		static VOID WINAPI serviceMain(DWORD argc, LPCSTR argv[]);
+
+		static std::shared_ptr getServiceManager(DWORD access);
+
+		static std::string getFilename();
+	};
+}
+
+#endif
\ No newline at end of file
diff --git a/vs/UDPT/UDPT.vcxproj b/vs/UDPT/UDPT.vcxproj
index d7bcb9a..a32e40f 100644
--- a/vs/UDPT/UDPT.vcxproj
+++ b/vs/UDPT/UDPT.vcxproj
@@ -59,7 +59,7 @@
     
     
       true
-      ws2_32.lib;sqlite3.lib;
+      ws2_32.lib;sqlite3.lib;advapi32.lib
     
   
   
@@ -73,10 +73,11 @@
       Async
     
     
-      true
-      true
-      true
-      ws2_32.lib;sqlite3.lib;%(AdditionalDependencies)
+      
+      
+      
+      
+      ws2_32.lib;sqlite3.lib;advapi32.lib
     
   
   
@@ -86,6 +87,7 @@
     
     
     
+    
     
     
     
@@ -98,6 +100,7 @@
     
     
     
+    
     
     
     
diff --git a/vs/UDPT/UDPT.vcxproj.filters b/vs/UDPT/UDPT.vcxproj.filters
index db3e909..431084e 100644
--- a/vs/UDPT/UDPT.vcxproj.filters
+++ b/vs/UDPT/UDPT.vcxproj.filters
@@ -54,6 +54,9 @@
     
       Source Files
     
+    
+      Source Files
+    
   
   
     
@@ -86,5 +89,8 @@
     
       Header Files
     
+    
+      Header Files
+    
   
 
\ No newline at end of file

From db4b8e8c81b1e3be024630ceb5c05bde44affa53 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Fri, 5 Feb 2016 02:13:55 +0200
Subject: [PATCH 66/99] Completely removed logging

---
 Makefile                     |  2 +-
 src/db/driver_sqlite.cpp     | 12 +------
 src/logging.cpp              | 61 ------------------------------------
 src/logging.h                | 55 --------------------------------
 src/main.cpp                 | 17 +---------
 src/tracker.hpp              |  1 -
 src/udpTracker.cpp           |  7 -----
 vs/UDPT/UDPT.vcxproj         |  2 --
 vs/UDPT/UDPT.vcxproj.filters |  6 ----
 9 files changed, 3 insertions(+), 160 deletions(-)
 delete mode 100644 src/logging.cpp
 delete mode 100644 src/logging.h

diff --git a/Makefile b/Makefile
index 9b37e76..7ea19b5 100644
--- a/Makefile
+++ b/Makefile
@@ -18,7 +18,7 @@
 #
 
 objects = main.o udpTracker.o database.o driver_sqlite.o \
-	tools.o httpserver.o webapp.o logging.o tracker.o
+	tools.o httpserver.o webapp.o tracker.o
 target = udpt
 
 %.o: src/%.c
diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp
index cf8bc65..3cf383d 100644
--- a/src/db/driver_sqlite.cpp
+++ b/src/db/driver_sqlite.cpp
@@ -26,9 +26,6 @@
 #include 
 #include  // memcpy
 #include "../multiplatform.h"
-#include "../logging.h"
-
-extern UDPT::Logger *logger;
 
 using namespace std;
 
@@ -180,8 +177,6 @@ namespace UDPT
 				}
 			}
 
-			printf("%d Clients Dumped.\n", i);
-
 			sqlite3_finalize(stmt);
 
 			*max_count = i;
@@ -259,7 +254,6 @@ namespace UDPT
 
 			// create table.
 			r = sqlite3_exec(this->db, sql.c_str(), NULL, NULL, &err_msg);
-			printf("E:%s\n", err_msg);
 
 			return (r == SQLITE_OK);
 		}
@@ -310,11 +304,7 @@ namespace UDPT
 
 				if (sqlite3_errcode(this->db) != SQLITE_OK)
 				{
-					string str;
-					str = "[";
-					str += sqlite3_errmsg(this->db);
-					str += "]";
-					logger->log(Logger::LL_ERROR, str);
+					// TODO: Log this error
 				}
 
 				int seeders = 0, leechers = 0;
diff --git a/src/logging.cpp b/src/logging.cpp
deleted file mode 100644
index 4266c73..0000000
--- a/src/logging.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- *	Copyright © 2012-2016 Naim A.
- *
- *	This file is part of UDPT.
- *
- *		UDPT is free software: you can redistribute it and/or modify
- *		it under the terms of the GNU General Public License as published by
- *		the Free Software Foundation, either version 3 of the License, or
- *		(at your option) any later version.
- *
- *		UDPT 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 UDPT.  If not, see .
- */
-
-#include "logging.h"
-#include 
-#include 
-#include 
-
-using namespace std;
-
-namespace UDPT {
-
-	Logger::Logger(const boost::program_options::variables_map& s)
-		: m_logfile (std::cout)
-	{
-		const std::string& filename = s["logging.filename"].as();
-		const std::string& level = s["logging.level"].as();
-
-		closeStreamOnDestroy = false;
-
-		if (level == "debug" || level == "d")
-			this->loglevel = LL_DEBUG;
-		else if (level == "warning" || level == "w")
-			this->loglevel = LL_WARNING;
-		else if (level == "info" || level == "i")
-			this->loglevel = LL_INFO;
-		else
-			this->loglevel = LL_ERROR;
-	}
-
-	Logger::~Logger()
-	{
-	}
-
-	void Logger::log(enum LogLevel lvl, string msg)
-	{
-		const char letters[] = "EWID";
-		if (lvl <= this->loglevel)
-		{
-			m_logfile << time (NULL) << ": ("
-					<< ((char)letters[lvl]) << "): "
-					<< msg << "\n";
-		}
-	}
-};
diff --git a/src/logging.h b/src/logging.h
deleted file mode 100644
index 4ca37a9..0000000
--- a/src/logging.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *	Copyright © 2012-2016 Naim A.
- *
- *	This file is part of UDPT.
- *
- *		UDPT is free software: you can redistribute it and/or modify
- *		it under the terms of the GNU General Public License as published by
- *		the Free Software Foundation, either version 3 of the License, or
- *		(at your option) any later version.
- *
- *		UDPT 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 UDPT.  If not, see .
- */
-
-#ifndef LOGGING_H_
-#define LOGGING_H_
-
-#include 
-#include 
-#include 
-#include 
-#include 
-
-namespace UDPT {
-	class Logger 
-	{
-
-	public:
-		enum LogLevel {
-			LL_ERROR 	= 0,
-			LL_WARNING 	= 1,
-			LL_INFO		= 2,
-			LL_DEBUG	= 3
-		};
-
-		Logger(const boost::program_options::variables_map& s);
-
-		virtual ~Logger();
-
-		void log(enum LogLevel, std::string msg);
-	private:
-		std::ostream& m_logfile;
-		enum LogLevel loglevel;
-		bool closeStreamOnDestroy;
-
-		static void setStream(Logger *logger, std::ostream &s);
-	};
-};
-
-#endif /* LOGGING_H_ */
diff --git a/src/main.cpp b/src/main.cpp
index cfae957..7abf65c 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -25,7 +25,6 @@
 #include 
 #include 
 
-#include "logging.h"
 #include "multiplatform.h"
 #include "udpTracker.hpp"
 #include "http/httpserver.hpp"
@@ -33,8 +32,6 @@
 #include "tracker.hpp"
 #include "service.hpp"
 
-UDPT::Logger *logger = NULL;
-
 static void _signal_handler(int sig)
 {
 	switch (sig)
@@ -165,18 +162,6 @@ int main(int argc, char *argv[])
 		}
 	}
 
-	std::shared_ptr spLogger;
-	try
-	{
-		spLogger = std::shared_ptr(new UDPT::Logger(var_map));
-		logger = spLogger.get();
-	}
-	catch (const std::exception& ex)
-	{
-		std::cerr << "Failed to initialize logger: " << ex.what() << std::endl;
-		return -1;
-	}
-
 #ifdef linux
 	if (!var_map.count("interactive"))
 	{
@@ -229,7 +214,7 @@ int main(int argc, char *argv[])
 	{
 		if (ERROR_FAILED_SERVICE_CONTROLLER_CONNECT != err.getErrorCode())
 		{
-			logger->log(UDPT::Logger::LL_ERROR, "failed to start as service");
+			// TODO: log this error and exit
 		}
 	}
 #endif
diff --git a/src/tracker.hpp b/src/tracker.hpp
index b5fae24..4178477 100644
--- a/src/tracker.hpp
+++ b/src/tracker.hpp
@@ -21,7 +21,6 @@
 #include 
 #include 
 
-#include "logging.h"
 #include "multiplatform.h"
 #include "udpTracker.hpp"
 #include "http/httpserver.hpp"
diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp
index 15d3a49..650e456 100644
--- a/src/udpTracker.cpp
+++ b/src/udpTracker.cpp
@@ -26,9 +26,7 @@
 #include "udpTracker.hpp"
 #include "tools.h"
 #include "multiplatform.h"
-#include "logging.h"
 
-extern UDPT::Logger *logger;
 
 using namespace UDPT::Data;
 
@@ -115,7 +113,6 @@ namespace UDPT
 
 		ss.str("");
 		ss << "Starting maintenance thread (1/" << ((int)this->m_threadCount) << ")";
-		logger->log(Logger::LL_INFO, ss.str());
 
 		// create maintainer thread.
 
@@ -123,10 +120,6 @@ namespace UDPT
 
 		for (i = 1;i < this->m_threadCount; i++)
 		{
-			ss.str("");
-			ss << "Starting thread (" << (i + 1) << "/" << ((int)this->m_threadCount) << ")";
-			logger->log(Logger::LL_INFO, ss.str());
-
 			m_threads.push_back(boost::thread(UDPTracker::_thread_start, this));
 		}
 	}
diff --git a/vs/UDPT/UDPT.vcxproj b/vs/UDPT/UDPT.vcxproj
index a32e40f..ff5d787 100644
--- a/vs/UDPT/UDPT.vcxproj
+++ b/vs/UDPT/UDPT.vcxproj
@@ -85,7 +85,6 @@
     
     
     
-    
     
     
     
@@ -98,7 +97,6 @@
     
     
     
-    
     
     
     
diff --git a/vs/UDPT/UDPT.vcxproj.filters b/vs/UDPT/UDPT.vcxproj.filters
index 431084e..638b4ae 100644
--- a/vs/UDPT/UDPT.vcxproj.filters
+++ b/vs/UDPT/UDPT.vcxproj.filters
@@ -27,9 +27,6 @@
     
   
   
-    
-      Source Files
-    
     
       Source Files
     
@@ -59,9 +56,6 @@
     
   
   
-    
-      Header Files
-    
     
       Header Files
     

From d1d879c27c96cdca3a6433734327e60c09d52423 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Fri, 5 Feb 2016 03:56:49 +0200
Subject: [PATCH 67/99] WIP: Added some logging to tracker

---
 src/multiplatform.h |   1 +
 src/tracker.cpp     |  25 ++++---
 src/tracker.hpp     |   6 +-
 src/udpTracker.cpp  | 170 +++++++++++++++++++++++---------------------
 src/udpTracker.hpp  |  13 +++-
 5 files changed, 122 insertions(+), 93 deletions(-)

diff --git a/src/multiplatform.h b/src/multiplatform.h
index d837c9f..ab254b2 100644
--- a/src/multiplatform.h
+++ b/src/multiplatform.h
@@ -32,6 +32,7 @@
 
 #ifdef WIN32
 #include 
+#include 
 #include 
 #elif defined (linux)
 #include 
diff --git a/src/tracker.cpp b/src/tracker.cpp
index 0aa7014..f0d9abe 100644
--- a/src/tracker.cpp
+++ b/src/tracker.cpp
@@ -20,18 +20,19 @@
 
 namespace UDPT
 {
-    Tracker::Tracker()
+	Tracker::Tracker() : m_logger(boost::log::keywords::channel = "TRACKER")
     {
-
+		BOOST_LOG_SEV(m_logger, boost::log::trivial::debug) << "Initialized Tracker";
     }
 
     Tracker::~Tracker()
     {
-
+		BOOST_LOG_SEV(m_logger, boost::log::trivial::debug) << "Destroying Tracker...";
     }
 
     void Tracker::stop()
-    {
+	{
+		BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Requesting Tracker to terminate.";
         m_udpTracker->stop();
         wait();
 
@@ -41,22 +42,26 @@ namespace UDPT
     }
 
     void Tracker::wait()
-    {
-        m_udpTracker->wait();
+	{
+		m_udpTracker->wait();
+		BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Tracker terminated.";
     }
 
     void Tracker::start(const boost::program_options::variables_map& conf)
-    {
-        m_udpTracker = std::shared_ptr(new UDPTracker(conf));
+	{
+		BOOST_LOG_SEV(m_logger, boost::log::trivial::debug) << "Starting Tracker...";
+		m_udpTracker = std::shared_ptr(new UDPTracker(conf));
 
         if (conf["apiserver.enable"].as())
-        {
+		{
+			BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Initializing and deploying WebAPI...";
             m_apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(conf));
             m_webApp = std::shared_ptr(new UDPT::Server::WebApp(m_apiSrv, m_udpTracker->m_conn.get(), conf));
             m_webApp->deploy();
         }
 
-        m_udpTracker->start();
+		m_udpTracker->start();
+		BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Tracker started.";
     }
     
     Tracker& Tracker::getInstance()
diff --git a/src/tracker.hpp b/src/tracker.hpp
index 4178477..2ff169f 100644
--- a/src/tracker.hpp
+++ b/src/tracker.hpp
@@ -21,6 +21,9 @@
 #include 
 #include 
 
+#include 
+#include 
+
 #include "multiplatform.h"
 #include "udpTracker.hpp"
 #include "http/httpserver.hpp"
@@ -46,7 +49,8 @@ namespace UDPT
         std::shared_ptr m_udpTracker;
         std::shared_ptr m_apiSrv;
         std::shared_ptr m_webApp;
-        
+		boost::log::sources::severity_channel_logger_mt<> m_logger;
+
         Tracker();
     };
 }
diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp
index 650e456..2d6c976 100644
--- a/src/udpTracker.cpp
+++ b/src/udpTracker.cpp
@@ -17,15 +17,7 @@
  *		along with UDPT.  If not, see .
  */
 
-#include  // atoi
-#include 
-#include 
-#include 
-#include 
-#include 
 #include "udpTracker.hpp"
-#include "tools.h"
-#include "multiplatform.h"
 
 
 using namespace UDPT::Data;
@@ -34,7 +26,7 @@ using namespace UDPT::Data;
 
 namespace UDPT
 {
-	UDPTracker::UDPTracker(const boost::program_options::variables_map& conf) : m_conf(conf)
+	UDPTracker::UDPTracker(const boost::program_options::variables_map& conf) : m_conf(conf), m_logger(boost::log::keywords::channel = "UDPTracker")
 	{
 		this->m_allowRemotes = conf["tracker.allow_remotes"].as();
 		this->m_allowIANA_IPs = conf["tracker.allow_iana_ips"].as();
@@ -67,7 +59,6 @@ namespace UDPT
 
 	void UDPTracker::start()
 	{
-		std::stringstream ss;
 		SOCKET sock;
 		int r,		// saves results
 			i,		// loop index
@@ -105,15 +96,12 @@ namespace UDPT
 			::closesocket(sock);
 	#elif defined (linux)
 			::close(sock);
-	#endif
+#endif
 			throw UDPT::UDPTException("Failed to bind socket.");
 		}
 
 		this->m_sock = sock;
 
-		ss.str("");
-		ss << "Starting maintenance thread (1/" << ((int)this->m_threadCount) << ")";
-
 		// create maintainer thread.
 
 		m_threads.push_back(boost::thread(UDPTracker::_maintainance_start, this));
@@ -132,6 +120,7 @@ namespace UDPT
 		::closesocket(m_sock);
 #endif
 
+		BOOST_LOG_SEV(m_logger, boost::log::trivial::warning) << "Interrupting workers...";
 		for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
 		{
 			it->interrupt();
@@ -142,6 +131,8 @@ namespace UDPT
 
 	void UDPTracker::wait()
 	{
+		BOOST_LOG_SEV(m_logger, boost::log::trivial::warning) << "Waiting for threads to terminate...";
+
 		for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
 		{
 			it->join();
@@ -193,38 +184,43 @@ namespace UDPT
 
 		::sendto(usi->m_sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN));
 
+		{
+			char buffer[INET_ADDRSTRLEN];
+			BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::debug) << "Connection Request from " << ::inet_ntop(AF_INET, &remote->sin_addr, buffer, sizeof(buffer)) << "; cId=" << resp.connection_id << "; tId=" << resp.transaction_id;
+		}
+		
+
 		return 0;
 	}
 
-	int UDPTracker::handleAnnounce (UDPTracker *usi, SOCKADDR_IN *remote, char *data)
+	int UDPTracker::handleAnnounce(UDPTracker *usi, SOCKADDR_IN *remote, char *data)
 	{
 		AnnounceRequest *req;
 		AnnounceResponse *resp;
 		int q,		// peer counts
 			bSize,	// message size
 			i;		// loop index
-		DatabaseDriver::PeerEntry *peers;
 		DatabaseDriver::TorrentEntry tE;
 
-		uint8_t buff [1028];	// Reasonable buffer size. (header+168 peers)
+		uint8_t buff[1028];	// Reasonable buffer size. (header+168 peers)
 
 		req = (AnnounceRequest*)data;
 
 		if (!usi->m_conn->verifyConnectionId(req->connection_id,
-				m_hton32(remote->sin_addr.s_addr),
-				m_hton16(remote->sin_port)))
+			m_hton32(remote->sin_addr.s_addr),
+			m_hton16(remote->sin_port)))
 		{
 			return 1;
 		}
 
 		// change byte order:
-		req->port = m_hton16 (req->port);
-		req->ip_address = m_hton32 (req->ip_address);
-		req->downloaded = m_hton64 (req->downloaded);
-		req->event = m_hton32 (req->event);	// doesn't really matter for this tracker
-		req->uploaded = m_hton64 (req->uploaded);
-		req->num_want = m_hton32 (req->num_want);
-		req->left = m_hton64 (req->left);
+		req->port = m_hton16(req->port);
+		req->ip_address = m_hton32(req->ip_address);
+		req->downloaded = m_hton64(req->downloaded);
+		req->event = m_hton32(req->event);	// doesn't really matter for this tracker
+		req->uploaded = m_hton64(req->uploaded);
+		req->num_want = m_hton32(req->num_want);
+		req->left = m_hton64(req->left);
 
 		if (!usi->m_allowRemotes && req->ip_address != 0)
 		{
@@ -243,62 +239,64 @@ namespace UDPT
 		if (req->num_want >= 1)
 			q = std::min(q, req->num_want);
 
-		peers = new DatabaseDriver::PeerEntry [q];
-
-
 		DatabaseDriver::TrackerEvents event;
-		switch (req->event)
+
 		{
-		case 1:
-			event = DatabaseDriver::EVENT_COMPLETE;
-			break;
-		case 2:
-			event = DatabaseDriver::EVENT_START;
-			break;
-		case 3:
-			event = DatabaseDriver::EVENT_STOP;
-			break;
-		default:
-			event = DatabaseDriver::EVENT_UNSPEC;
-			break;
+			std::shared_ptr peersSptr = std::shared_ptr(new DatabaseDriver::PeerEntry[q]);
+			DatabaseDriver::PeerEntry *peers = peersSptr.get();
+
+			switch (req->event)
+			{
+			case 1:
+				event = DatabaseDriver::EVENT_COMPLETE;
+				break;
+			case 2:
+				event = DatabaseDriver::EVENT_START;
+				break;
+			case 3:
+				event = DatabaseDriver::EVENT_STOP;
+				break;
+			default:
+				event = DatabaseDriver::EVENT_UNSPEC;
+				break;
+			}
+
+			if (event == DatabaseDriver::EVENT_STOP)
+				q = 0;	// no need for peers when stopping.
+
+			if (q > 0)
+				usi->m_conn->getPeers(req->info_hash, &q, peers);
+
+			bSize = 20; // header is 20 bytes
+			bSize += (6 * q); // + 6 bytes per peer.
+
+			tE.info_hash = req->info_hash;
+			usi->m_conn->getTorrentInfo(&tE);
+
+			resp = (AnnounceResponse*)buff;
+			resp->action = m_hton32(1);
+			resp->interval = m_hton32(usi->m_announceInterval);
+			resp->leechers = m_hton32(tE.leechers);
+			resp->seeders = m_hton32(tE.seeders);
+			resp->transaction_id = req->transaction_id;
+
+			for (i = 0; i < q; i++)
+			{
+				int x = i * 6;
+				// network byte order!!!
+
+				// IP
+				buff[20 + x] = ((peers[i].ip & (0xff << 24)) >> 24);
+				buff[21 + x] = ((peers[i].ip & (0xff << 16)) >> 16);
+				buff[22 + x] = ((peers[i].ip & (0xff << 8)) >> 8);
+				buff[23 + x] = (peers[i].ip & 0xff);
+
+				// port
+				buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8);
+				buff[25 + x] = (peers[i].port & 0xff);
+
+			}
 		}
-
-		if (event == DatabaseDriver::EVENT_STOP)
-			q = 0;	// no need for peers when stopping.
-
-		if (q > 0)
-			usi->m_conn->getPeers(req->info_hash, &q, peers);
-
-		bSize = 20; // header is 20 bytes
-		bSize += (6 * q); // + 6 bytes per peer.
-
-		tE.info_hash = req->info_hash;
-		usi->m_conn->getTorrentInfo(&tE);
-
-		resp = (AnnounceResponse*)buff;
-		resp->action = m_hton32(1);
-		resp->interval = m_hton32 ( usi->m_announceInterval );
-		resp->leechers = m_hton32(tE.leechers);
-		resp->seeders = m_hton32 (tE.seeders);
-		resp->transaction_id = req->transaction_id;
-
-		for (i = 0;i < q;i++)
-		{
-			int x = i * 6;
-			// network byte order!!!
-
-			// IP
-			buff[20 + x] = ((peers[i].ip & (0xff << 24)) >> 24);
-			buff[21 + x] = ((peers[i].ip & (0xff << 16)) >> 16);
-			buff[22 + x] = ((peers[i].ip & (0xff << 8)) >> 8);
-			buff[23 + x] = (peers[i].ip & 0xff);
-
-			// port
-			buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8);
-			buff[25 + x] = (peers[i].port & 0xff);
-
-		}
-		delete[] peers;
 		::sendto(usi->m_sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN));
 
 		// update DB.
@@ -396,10 +394,18 @@ namespace UDPT
 		{
 			if (isIANAIP(remote->sin_addr.s_addr))
 			{
+				char buffer[INET_ADDRSTRLEN];
+				BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::warning) << "Client ignored (IANA IP): " << ::inet_ntop(AF_INET, &remote->sin_addr, buffer, sizeof(buffer));
 				return 0;	// Access Denied: IANA reserved IP.
 			}
 		}
 
+		{
+
+			char buffer[INET_ADDRSTRLEN];
+			BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::debug) << "Client request from " << ::inet_ntop(AF_INET, &remote->sin_addr, buffer, sizeof(buffer));
+		}
+
 		if (action == 0 && r >= 16)
 			return UDPTracker::handleConnection(usi, remote, data);
 		else if (action == 1 && r >= 98)
@@ -417,6 +423,7 @@ namespace UDPT
 
 	void UDPTracker::_thread_start(UDPTracker *usi)
 	{
+		BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::info) << "Worker thread started with PID=" << boost::this_thread::get_id() << ".";
 		SOCKADDR_IN remoteAddr;
 		char tmpBuff[UDP_BUFFER_SIZE];
 
@@ -441,17 +448,20 @@ namespace UDPT
 
 			{
 				boost::this_thread::disable_interruption di;
-				r = UDPTracker::resolveRequest(usi, &remoteAddr, tmpBuff, r);
+
+				UDPTracker::resolveRequest(usi, &remoteAddr, tmpBuff, r);
 			}
 		}
 	}
 
 	void UDPTracker::_maintainance_start(UDPTracker* usi)
 	{
+		BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::info) << "Maintenance thread started with PID=" << boost::this_thread::get_id() << ".";
 		while (true)
 		{
 			{
 				boost::this_thread::disable_interruption di;
+				BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::info) << "Running cleanup...";
 				usi->m_conn->cleanup();
 			}
 
diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp
index 5e7cf4d..c0441c8 100644
--- a/src/udpTracker.hpp
+++ b/src/udpTracker.hpp
@@ -22,11 +22,19 @@
 
 
 #include 
-#include 
 #include 
 #include 
-#include 
 #include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+#include "tools.h"
 #include "exceptions.h"
 #include "multiplatform.h"
 #include "db/driver_sqlite.hpp"
@@ -155,6 +163,7 @@ namespace UDPT
 		std::vector m_threads;
 		uint32_t m_announceInterval;
 		uint32_t m_cleanupInterval;
+		boost::log::sources::severity_channel_logger_mt<> m_logger;
 
 		const boost::program_options::variables_map& m_conf;
 

From c0d93e63407919206aca0242804f9cc0de25aa27 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Fri, 5 Feb 2016 16:36:44 +0200
Subject: [PATCH 68/99] basic logging + windows service fix

---
 src/db/database.hpp      |  2 ++
 src/db/driver_sqlite.cpp | 18 ++++++++++++++--
 src/db/driver_sqlite.hpp |  1 +
 src/exceptions.h         | 33 ++++++++++++++++++++++++++++--
 src/main.cpp             | 44 +++++++++++++++++++++++++++-------------
 src/service.cpp          |  9 ++++----
 src/udpTracker.cpp       |  5 +++++
 7 files changed, 90 insertions(+), 22 deletions(-)

diff --git a/src/db/database.hpp b/src/db/database.hpp
index 878da73..31513c8 100644
--- a/src/db/database.hpp
+++ b/src/db/database.hpp
@@ -21,6 +21,8 @@
 #define DATABASE_HPP_
 
 #include 
+#include 
+#include 
 
 namespace UDPT
 {
diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp
index 3cf383d..78f3706 100644
--- a/src/db/driver_sqlite.cpp
+++ b/src/db/driver_sqlite.cpp
@@ -66,7 +66,7 @@ namespace UDPT
 			return data;
 		}
 
-		SQLite3Driver::SQLite3Driver(const boost::program_options::variables_map& conf, bool isDyn) : DatabaseDriver(conf, isDyn)
+		SQLite3Driver::SQLite3Driver(const boost::program_options::variables_map& conf, bool isDyn) : DatabaseDriver(conf, isDyn), m_logger(boost::log::keywords::channel="SQLite3")
 		{
 			int r;
 			bool doSetup;
@@ -177,6 +177,8 @@ namespace UDPT
 				}
 			}
 
+			BOOST_LOG_SEV(m_logger, boost::log::trivial::debug) << "Retrieved " << i << " peers";
+
 			sqlite3_finalize(stmt);
 
 			*max_count = i;
@@ -255,7 +257,16 @@ namespace UDPT
 			// create table.
 			r = sqlite3_exec(this->db, sql.c_str(), NULL, NULL, &err_msg);
 
-			return (r == SQLITE_OK);
+			if (SQLITE_OK == r)
+			{
+				BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Added torrent";
+				return true;
+			}
+			else
+			{
+				BOOST_LOG_SEV(m_logger, boost::log::trivial::error) << "Failed to add torrent: SQLite3 error code = " << r;
+				return false;
+			}
 		}
 
 		bool SQLite3Driver::isTorrentAllowed(uint8_t *info_hash)
@@ -357,6 +368,8 @@ namespace UDPT
 
 			sqlite3_exec(this->db, str.c_str(), NULL, NULL, NULL);
 
+			BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Torrent removed.";
+
 			return true;
 		}
 
@@ -411,6 +424,7 @@ namespace UDPT
 
 		SQLite3Driver::~SQLite3Driver()
 		{
+			BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Closing SQLite";
 			sqlite3_close(this->db);
 		}
 	};
diff --git a/src/db/driver_sqlite.hpp b/src/db/driver_sqlite.hpp
index 048abbc..55f7014 100644
--- a/src/db/driver_sqlite.hpp
+++ b/src/db/driver_sqlite.hpp
@@ -46,6 +46,7 @@ namespace UDPT
 			virtual ~SQLite3Driver();
 		private:
 			sqlite3 *db;
+			boost::log::sources::severity_channel_logger_mt<> m_logger;
 
 			void doSetup();
 		};
diff --git a/src/exceptions.h b/src/exceptions.h
index 589bbdc..33c5213 100644
--- a/src/exceptions.h
+++ b/src/exceptions.h
@@ -7,11 +7,15 @@ namespace UDPT
 	class UDPTException
 	{
 	public:
-		UDPTException(const char* errorMsg = "", int errorCode = 0) : m_error(errorMsg), m_errorCode(errorCode)
+		UDPTException(const char* errorMsg, int errorCode = 0) : m_error(errorMsg), m_errorCode(errorCode)
 		{
 
 		}
 
+		UDPTException(int errorCode = 0) : m_errorCode(errorCode), m_error("")
+		{
+		}
+
 		virtual const char* what() const
 		{
 			return m_error;
@@ -39,9 +43,34 @@ namespace UDPT
 #ifdef WIN32 
 			= ::GetLastError()
 #endif
-			) : UDPTException("OSError", errorCode)
+			) : UDPTException(errorCode)
 		{
 		}
 
+		virtual ~OSError() {}
+
+		const char* what() const
+		{
+			if (m_errorMessage.length() > 0)
+			{
+				return m_errorMessage.c_str();
+			}
+
+#ifdef WIN32 
+			char *buffer = nullptr;
+			DWORD msgLen = ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, m_errorCode, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), reinterpret_cast(&buffer), 1, NULL);
+			std::shared_ptr formatStr = std::shared_ptr(
+				buffer,
+				::LocalFree);
+			m_errorMessage = std::string(reinterpret_cast(formatStr.get()));
+
+			return m_errorMessage.c_str();
+#else 
+			return "OSError";
+#endif
+		}
+	private:
+		// allow to generate a message only when needed.
+		mutable std::string m_errorMessage;
 	};
 }
diff --git a/src/main.cpp b/src/main.cpp
index 7abf65c..9f469fd 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -64,13 +64,19 @@ static void daemonize(const boost::program_options::variables_map& conf)
 }
 #endif
 
+#ifdef WIN32 
+void _close_wsa()
+{
+	::WSACleanup();
+}
+#endif
+
 int main(int argc, char *argv[])
 {
-	Tracker& tracker = UDPT::Tracker::getInstance();
-
 #ifdef WIN32
 	WSADATA wsadata;
 	::WSAStartup(MAKEWORD(2, 2), &wsadata);
+	::atexit(_close_wsa);
 #endif
 
 	boost::program_options::options_description commandLine("Command line options");
@@ -162,6 +168,10 @@ int main(int argc, char *argv[])
 		}
 	}
 
+	// setup logging...
+
+	boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "main");
+
 #ifdef linux
 	if (!var_map.count("interactive"))
 	{
@@ -178,15 +188,15 @@ int main(int argc, char *argv[])
 		{
 			if ("install" == action)
 			{
-				std::cout << "Installing service..." << std::endl;
+				std::cerr << "Installing service..." << std::endl;
 				svc.install();
-				std::cout << "Installed." << std::endl;
+				std::cerr << "Installed." << std::endl;
 			}
 			else if ("uninstall" == action)
 			{
-				std::cout << "Removing service..." << std::endl;
+				std::cerr << "Removing service..." << std::endl;
 				svc.uninstall();
-				std::cout << "Removed." << std::endl;
+				std::cerr << "Removed." << std::endl;
 			}
 			else if ("start" == action)
 			{
@@ -199,7 +209,7 @@ int main(int argc, char *argv[])
 		}
 		catch (const UDPT::OSError& ex)
 		{
-			std::cout << "An operating system error occurred: " << ex.getErrorCode() << std::endl;
+			std::cerr << "An operating system error occurred: " << ex.getErrorCode() << std::endl;
 			return -1;
 		}
 
@@ -214,17 +224,23 @@ int main(int argc, char *argv[])
 	{
 		if (ERROR_FAILED_SERVICE_CONTROLLER_CONNECT != err.getErrorCode())
 		{
-			// TODO: log this error and exit
+			BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed to start as a Windows service: (" << err.getErrorCode() << "): " << err.what();
+			return -1;
 		}
 	}
 #endif
 
-	tracker.start(var_map);
-	tracker.wait();
-
-#ifdef WIN32
-	::WSACleanup();
-#endif
+	try
+	{
+		Tracker& tracker = UDPT::Tracker::getInstance();
+		tracker.start(var_map);
+		tracker.wait();
+	}
+	catch (const UDPT::UDPTException& ex)
+	{
+		BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "UDPT exception: (" << ex.getErrorCode() << "): " << ex.what();
+		return -1;
+	}
 
 	return 0;
 }
diff --git a/src/service.cpp b/src/service.cpp
index 1d2169b..879639e 100644
--- a/src/service.cpp
+++ b/src/service.cpp
@@ -83,10 +83,11 @@ namespace UDPT
 
 	void Service::setup()
 	{
-		SERVICE_TABLE_ENTRY service = { 0 };
-		service.lpServiceName = const_cast(m_conf["service.name"].as().c_str());
-		service.lpServiceProc = reinterpret_cast(&Service::serviceMain);
-		if (FALSE == ::StartServiceCtrlDispatcher(&service))
+		SERVICE_TABLE_ENTRY service[] = { 
+			{ const_cast(m_conf["service.name"].as().c_str()), reinterpret_cast(&Service::serviceMain) },
+			{0, 0}
+		};
+		if (FALSE == ::StartServiceCtrlDispatcher(service))
 		{
 			throw OSError();
 		}
diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp
index 2d6c976..a8a04c2 100644
--- a/src/udpTracker.cpp
+++ b/src/udpTracker.cpp
@@ -100,6 +100,11 @@ namespace UDPT
 			throw UDPT::UDPTException("Failed to bind socket.");
 		}
 
+		{
+			char buff[INET_ADDRSTRLEN];
+			BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "UDP tracker bound on " << ::inet_ntop(AF_INET, reinterpret_cast(&m_localEndpoint.sin_addr), buff, sizeof(buff)) << ":" << ::htons(m_localEndpoint.sin_port);
+		}
+
 		this->m_sock = sock;
 
 		// create maintainer thread.

From 99c87f657877aeb06902e12fb506987de5124173 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sat, 6 Feb 2016 23:26:01 +0200
Subject: [PATCH 69/99] Logging to file. WIP

---
 src/main.cpp | 27 ++++++++++++++++++++++++++-
 1 file changed, 26 insertions(+), 1 deletion(-)

diff --git a/src/main.cpp b/src/main.cpp
index 9f469fd..418283c 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -24,6 +24,15 @@
 #include 	// strlen
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
 
 #include "multiplatform.h"
 #include "udpTracker.hpp"
@@ -111,7 +120,7 @@ int main(int argc, char *argv[])
 		("apiserver.threads", boost::program_options::value()->default_value(1), "threads for API server")
 		("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on")
 
-		("logging.filename", boost::program_options::value()->default_value("stdout"), "file to write logs to")
+		("logging.filename", boost::program_options::value()->default_value("/var/log/udpt.log"), "file to write logs to")
 		("logging.level", boost::program_options::value()->default_value("warning"), "log level (error/warning/info/debug)")
 
 #ifdef linux
@@ -169,6 +178,22 @@ int main(int argc, char *argv[])
 	}
 
 	// setup logging...
+	boost::log::add_common_attributes();
+	boost::shared_ptr logBackend = boost::make_shared(
+		boost::log::keywords::file_name = var_map["logging.filename"].as(),
+		boost::log::keywords::auto_flush = true,
+		boost::log::keywords::open_mode = std::ios::out | std::ios::app
+	);
+	typedef boost::log::sinks::asynchronous_sink udptSink_t;
+	boost::shared_ptr async_sink (new udptSink_t(logBackend));
+	async_sink->set_formatter(
+		boost::log::expressions::stream
+		<< boost::log::expressions::format_date_time("TimeStamp", "%Y-%m-%d %H:%M:%S") << " "
+		<< boost::log::expressions::attr("Severity")
+		<< " [" << boost::log::expressions::attr("Channel") << "] \t"
+		<< boost::log::expressions::smessage
+	);
+	boost::log::core::get()->add_sink(async_sink);
 
 	boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "main");
 

From 221d374ff2b0fdce353b8d6de7177fa411e85876 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sun, 7 Feb 2016 00:48:44 +0200
Subject: [PATCH 70/99] Adjustable logging level

---
 src/main.cpp | 24 ++++++++++++++++++++++--
 1 file changed, 22 insertions(+), 2 deletions(-)

diff --git a/src/main.cpp b/src/main.cpp
index 418283c..ca7aea5 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -23,6 +23,7 @@
 #include 	// signal
 #include 	// strlen
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -121,7 +122,7 @@ int main(int argc, char *argv[])
 		("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on")
 
 		("logging.filename", boost::program_options::value()->default_value("/var/log/udpt.log"), "file to write logs to")
-		("logging.level", boost::program_options::value()->default_value("warning"), "log level (error/warning/info/debug)")
+		("logging.level", boost::program_options::value()->default_value("warning"), "log level (fatal/error/warning/info/debug/trace)")
 
 #ifdef linux
 		("daemon.chdir", boost::program_options::value()->default_value("/"), "home directory for daemon")
@@ -193,10 +194,29 @@ int main(int argc, char *argv[])
 		<< " [" << boost::log::expressions::attr("Channel") << "] \t"
 		<< boost::log::expressions::smessage
 	);
-	boost::log::core::get()->add_sink(async_sink);
+	auto loggingCore = boost::log::core::get();	
+	loggingCore->add_sink(async_sink);
 
 	boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "main");
 
+	std::string severity = var_map["logging.level"].as();
+	std::transform(severity.begin(), severity.end(), severity.begin(), std::tolower);
+	int severityVal = boost::log::trivial::warning;
+	if ("fatal" == severity) severityVal = boost::log::trivial::fatal;
+	else if ("error" == severity) severityVal = boost::log::trivial::error;
+	else if ("warning" == severity) severityVal = boost::log::trivial::warning;
+	else if ("info" == severity) severityVal = boost::log::trivial::info;
+	else if ("debug" == severity) severityVal = boost::log::trivial::debug;
+	else if ("trace" == severity) severityVal = boost::log::trivial::trace;
+	else
+	{
+		BOOST_LOG_SEV(logger, boost::log::trivial::warning) << "Unknown debug level \"" << severity << "\" defaulting to warning";
+	}
+
+	loggingCore->set_filter(
+		boost::log::trivial::severity >= severityVal
+	);
+
 #ifdef linux
 	if (!var_map.count("interactive"))
 	{

From c54a48c40b00509b81662ffb65d25b0bc6c95eee Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Mon, 8 Feb 2016 12:42:58 -0800
Subject: [PATCH 71/99] Fix issue #22

---
 Makefile            | 3 ++-
 src/main.cpp        | 2 +-
 src/multiplatform.h | 1 +
 3 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/Makefile b/Makefile
index 7ea19b5..989d693 100644
--- a/Makefile
+++ b/Makefile
@@ -20,6 +20,7 @@
 objects = main.o udpTracker.o database.o driver_sqlite.o \
 	tools.o httpserver.o webapp.o tracker.o
 target = udpt
+CXXFLAGS = -DBOOST_LOG_DYN_LINK
 
 %.o: src/%.c
 	$(CC) -c -o $@ $< $(CFLAGS)
@@ -33,7 +34,7 @@ all: $(target)
 	
 $(target): $(objects)
 	@echo Linking...
-	$(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lboost_program_options -lsqlite3 -lpthread -lboost_thread -lboost_system
+	$(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lboost_program_options -lsqlite3 -lpthread -lboost_thread -lboost_system -lboost_log
 	@echo Done.
 clean:
 	@echo Cleaning Up...
diff --git a/src/main.cpp b/src/main.cpp
index ca7aea5..b00ce97 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -200,7 +200,7 @@ int main(int argc, char *argv[])
 	boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "main");
 
 	std::string severity = var_map["logging.level"].as();
-	std::transform(severity.begin(), severity.end(), severity.begin(), std::tolower);
+	std::transform(severity.begin(), severity.end(), severity.begin(), ::tolower);
 	int severityVal = boost::log::trivial::warning;
 	if ("fatal" == severity) severityVal = boost::log::trivial::fatal;
 	else if ("error" == severity) severityVal = boost::log::trivial::error;
diff --git a/src/multiplatform.h b/src/multiplatform.h
index ab254b2..2471888 100644
--- a/src/multiplatform.h
+++ b/src/multiplatform.h
@@ -44,6 +44,7 @@
 #include 
 #include 
 #include 
+#include 
 
 #define SOCKET int
 #define INVALID_SOCKET 0

From c9cf00da5fbd13e30484e09bff7ad730e5b22822 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sat, 13 Feb 2016 18:40:48 +0200
Subject: [PATCH 72/99] Updated project to VS2015

---
 .gitignore           | 1 +
 vs/UDPT/UDPT.vcxproj | 6 +++---
 2 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/.gitignore b/.gitignore
index 4d233f0..4c6ac2c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@
 *.suo
 *.opensdf
 **/Debug/*
+*.opendb
diff --git a/vs/UDPT/UDPT.vcxproj b/vs/UDPT/UDPT.vcxproj
index ff5d787..67474c6 100644
--- a/vs/UDPT/UDPT.vcxproj
+++ b/vs/UDPT/UDPT.vcxproj
@@ -1,5 +1,5 @@
 
-
+
   
     
       Debug
@@ -18,14 +18,14 @@
   
     Application
     true
-    v120
+    v140_xp
     MultiByte
     true
   
   
     Application
     false
-    v120
+    v140
     true
     MultiByte
   

From 35e9a27ad2f859967d2aedd9c4065c2824a4d8ad Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Wed, 17 Feb 2016 01:51:31 +0200
Subject: [PATCH 73/99] Seperating config

---
 src/main.cpp    | 78 ++++---------------------------------------------
 src/tracker.cpp | 72 +++++++++++++++++++++++++++++++++++++++++++++
 src/tracker.hpp | 14 ++++++++-
 3 files changed, 90 insertions(+), 74 deletions(-)

diff --git a/src/main.cpp b/src/main.cpp
index b00ce97..9ad57c3 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -25,15 +25,8 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
 
 #include "multiplatform.h"
 #include "udpTracker.hpp"
@@ -104,33 +97,7 @@ int main(int argc, char *argv[])
 		;
 
 
-	boost::program_options::options_description configOptions("Configuration options");
-	configOptions.add_options()
-		("db.driver", boost::program_options::value()->default_value("sqlite3"), "database driver to use")
-		("db.param", boost::program_options::value()->default_value("/var/lib/udpt.db"), "database connection parameters")
-		
-		("tracker.is_dynamic", boost::program_options::value()->default_value(true), "Sets if the tracker is dynamic")
-		("tracker.port", boost::program_options::value()->default_value(6969), "UDP port to listen on")
-		("tracker.threads", boost::program_options::value()->default_value(5), "threads to run (UDP only)")
-		("tracker.allow_remotes", boost::program_options::value()->default_value(true), "allows clients to report remote IPs")
-		("tracker.allow_iana_ips", boost::program_options::value()->default_value(false), "allows IANA reserved IPs to connect (useful for debugging)")
-		("tracker.announce_interval", boost::program_options::value()->default_value(1800), "announce interval")
-		("tracker.cleanup_interval", boost::program_options::value()->default_value(120), "sets database cleanup interval")
-		
-		("apiserver.enable", boost::program_options::value()->default_value(0), "Enable API server?")
-		("apiserver.threads", boost::program_options::value()->default_value(1), "threads for API server")
-		("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on")
-
-		("logging.filename", boost::program_options::value()->default_value("/var/log/udpt.log"), "file to write logs to")
-		("logging.level", boost::program_options::value()->default_value("warning"), "log level (fatal/error/warning/info/debug/trace)")
-
-#ifdef linux
-		("daemon.chdir", boost::program_options::value()->default_value("/"), "home directory for daemon")
-#endif
-#ifdef WIN32 
-		("service.name", boost::program_options::value()->default_value("udpt"), "service name to use")
-#endif
-		;
+	boost::program_options::options_description& configOptions = Tracker::getConfigOptions();
 
 	boost::program_options::variables_map var_map;
 	boost::program_options::store(boost::program_options::parse_command_line(argc, argv, commandLine), var_map);
@@ -178,44 +145,8 @@ int main(int argc, char *argv[])
 		}
 	}
 
-	// setup logging...
-	boost::log::add_common_attributes();
-	boost::shared_ptr logBackend = boost::make_shared(
-		boost::log::keywords::file_name = var_map["logging.filename"].as(),
-		boost::log::keywords::auto_flush = true,
-		boost::log::keywords::open_mode = std::ios::out | std::ios::app
-	);
-	typedef boost::log::sinks::asynchronous_sink udptSink_t;
-	boost::shared_ptr async_sink (new udptSink_t(logBackend));
-	async_sink->set_formatter(
-		boost::log::expressions::stream
-		<< boost::log::expressions::format_date_time("TimeStamp", "%Y-%m-%d %H:%M:%S") << " "
-		<< boost::log::expressions::attr("Severity")
-		<< " [" << boost::log::expressions::attr("Channel") << "] \t"
-		<< boost::log::expressions::smessage
-	);
-	auto loggingCore = boost::log::core::get();	
-	loggingCore->add_sink(async_sink);
-
 	boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "main");
-
-	std::string severity = var_map["logging.level"].as();
-	std::transform(severity.begin(), severity.end(), severity.begin(), ::tolower);
-	int severityVal = boost::log::trivial::warning;
-	if ("fatal" == severity) severityVal = boost::log::trivial::fatal;
-	else if ("error" == severity) severityVal = boost::log::trivial::error;
-	else if ("warning" == severity) severityVal = boost::log::trivial::warning;
-	else if ("info" == severity) severityVal = boost::log::trivial::info;
-	else if ("debug" == severity) severityVal = boost::log::trivial::debug;
-	else if ("trace" == severity) severityVal = boost::log::trivial::trace;
-	else
-	{
-		BOOST_LOG_SEV(logger, boost::log::trivial::warning) << "Unknown debug level \"" << severity << "\" defaulting to warning";
-	}
-
-	loggingCore->set_filter(
-		boost::log::trivial::severity >= severityVal
-	);
+	Tracker::setupLogging(var_map, logger);
 
 #ifdef linux
 	if (!var_map.count("interactive"))
@@ -234,7 +165,7 @@ int main(int argc, char *argv[])
 			if ("install" == action)
 			{
 				std::cerr << "Installing service..." << std::endl;
-				svc.install();
+				svc.install(var_map["config"].as());
 				std::cerr << "Installed." << std::endl;
 			}
 			else if ("uninstall" == action)
@@ -254,7 +185,7 @@ int main(int argc, char *argv[])
 		}
 		catch (const UDPT::OSError& ex)
 		{
-			std::cerr << "An operating system error occurred: " << ex.getErrorCode() << std::endl;
+			std::cerr << "An operating system error occurred: " << ex.what() << std::endl;
 			return -1;
 		}
 
@@ -264,6 +195,7 @@ int main(int argc, char *argv[])
 	try 
 	{
 		svc.setup();
+		return 0;
 	}
 	catch (const OSError& err)
 	{
diff --git a/src/tracker.cpp b/src/tracker.cpp
index f0d9abe..0c75a8a 100644
--- a/src/tracker.cpp
+++ b/src/tracker.cpp
@@ -70,4 +70,76 @@ namespace UDPT
 
         return s_tracker;
     }
+
+	boost::program_options::options_description Tracker::getConfigOptions()
+	{
+		boost::program_options::options_description configOptions("Configuration options");
+		configOptions.add_options()
+			("db.driver", boost::program_options::value()->default_value("sqlite3"), "database driver to use")
+			("db.param", boost::program_options::value()->default_value("/var/lib/udpt.db"), "database connection parameters")
+
+			("tracker.is_dynamic", boost::program_options::value()->default_value(true), "Sets if the tracker is dynamic")
+			("tracker.port", boost::program_options::value()->default_value(6969), "UDP port to listen on")
+			("tracker.threads", boost::program_options::value()->default_value(5), "threads to run (UDP only)")
+			("tracker.allow_remotes", boost::program_options::value()->default_value(true), "allows clients to report remote IPs")
+			("tracker.allow_iana_ips", boost::program_options::value()->default_value(false), "allows IANA reserved IPs to connect (useful for debugging)")
+			("tracker.announce_interval", boost::program_options::value()->default_value(1800), "announce interval")
+			("tracker.cleanup_interval", boost::program_options::value()->default_value(120), "sets database cleanup interval")
+
+			("apiserver.enable", boost::program_options::value()->default_value(0), "Enable API server?")
+			("apiserver.threads", boost::program_options::value()->default_value(1), "threads for API server")
+			("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on")
+
+			("logging.filename", boost::program_options::value()->default_value("/var/log/udpt.log"), "file to write logs to")
+			("logging.level", boost::program_options::value()->default_value("warning"), "log level (fatal/error/warning/info/debug/trace)")
+
+#ifdef linux
+			("daemon.chdir", boost::program_options::value()->default_value("/"), "home directory for daemon")
+#endif
+#ifdef WIN32 
+			("service.name", boost::program_options::value()->default_value("udpt"), "service name to use")
+#endif
+			;
+
+		return configOptions;
+	}
+
+	void Tracker::setupLogging(const boost::program_options::variables_map& config, boost::log::sources::severity_channel_logger_mt<>& logger)
+	{
+		boost::log::add_common_attributes();
+		boost::shared_ptr logBackend = boost::make_shared(
+			boost::log::keywords::file_name = config["logging.filename"].as(),
+			boost::log::keywords::auto_flush = true,
+			boost::log::keywords::open_mode = std::ios::out | std::ios::app
+			);
+		typedef boost::log::sinks::asynchronous_sink udptSink_t;
+		boost::shared_ptr async_sink(new udptSink_t(logBackend));
+		async_sink->set_formatter(
+			boost::log::expressions::stream
+			<< boost::log::expressions::format_date_time("TimeStamp", "%Y-%m-%d %H:%M:%S") << " "
+			<< boost::log::expressions::attr("Severity")
+			<< " [" << boost::log::expressions::attr("Channel") << "] \t"
+			<< boost::log::expressions::smessage
+			);
+		auto loggingCore = boost::log::core::get();
+		loggingCore->add_sink(async_sink);
+
+		std::string severity = config["logging.level"].as();
+		std::transform(severity.begin(), severity.end(), severity.begin(), ::tolower);
+		int severityVal = boost::log::trivial::warning;
+		if ("fatal" == severity) severityVal = boost::log::trivial::fatal;
+		else if ("error" == severity) severityVal = boost::log::trivial::error;
+		else if ("warning" == severity) severityVal = boost::log::trivial::warning;
+		else if ("info" == severity) severityVal = boost::log::trivial::info;
+		else if ("debug" == severity) severityVal = boost::log::trivial::debug;
+		else if ("trace" == severity) severityVal = boost::log::trivial::trace;
+		else
+		{
+			BOOST_LOG_SEV(logger, boost::log::trivial::warning) << "Unknown debug level \"" << severity << "\" defaulting to warning";
+		}
+
+		loggingCore->set_filter(
+			boost::log::trivial::severity >= severityVal
+		);
+	}
 }
diff --git a/src/tracker.hpp b/src/tracker.hpp
index 2ff169f..fc4bc25 100644
--- a/src/tracker.hpp
+++ b/src/tracker.hpp
@@ -23,6 +23,14 @@
 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
 
 #include "multiplatform.h"
 #include "udpTracker.hpp"
@@ -43,7 +51,11 @@ namespace UDPT
 
         void wait();
 
-        static Tracker& getInstance();
+		static Tracker& getInstance();
+
+		static boost::program_options::options_description getConfigOptions();
+
+		static void setupLogging(const boost::program_options::variables_map& config, boost::log::sources::severity_channel_logger_mt<>& logger);
 
     private:
         std::shared_ptr m_udpTracker;

From 14dd7e004b7ee01e3a8e8bd5922afd68a8fe5a20 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Wed, 17 Feb 2016 01:52:10 +0200
Subject: [PATCH 74/99] Added SubSystem to VS project

---
 vs/UDPT/UDPT.vcxproj | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/vs/UDPT/UDPT.vcxproj b/vs/UDPT/UDPT.vcxproj
index 67474c6..99855c3 100644
--- a/vs/UDPT/UDPT.vcxproj
+++ b/vs/UDPT/UDPT.vcxproj
@@ -60,6 +60,7 @@
     
       true
       ws2_32.lib;sqlite3.lib;advapi32.lib
+      Console
     
   
   
@@ -78,6 +79,7 @@
       
       
       ws2_32.lib;sqlite3.lib;advapi32.lib
+      Console
     
   
   

From b8db8f5d5157924d96be5a0932354e51cadbbc7e Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Fri, 19 Feb 2016 13:33:02 +0200
Subject: [PATCH 75/99] Basic working windows service

---
 src/service.cpp      | 112 ++++++++++++++++++++++++++++++++++++++++++-
 src/service.hpp      |  13 ++++-
 vs/UDPT/UDPT.vcxproj |   4 +-
 3 files changed, 123 insertions(+), 6 deletions(-)

diff --git a/src/service.cpp b/src/service.cpp
index 879639e..9c146c2 100644
--- a/src/service.cpp
+++ b/src/service.cpp
@@ -17,11 +17,15 @@
 *		along with UDPT.  If not, see .
 */
 #include "service.hpp"
+#include 
 
 #ifdef WIN32 
 
 namespace UDPT
 {
+	SERVICE_STATUS_HANDLE Service::s_hServiceStatus = nullptr;
+	SERVICE_STATUS Service::s_serviceStatus = { 0 };
+
 	Service::Service(const boost::program_options::variables_map& conf) : m_conf(conf)
 	{
 
@@ -32,10 +36,10 @@ namespace UDPT
 
 	}
 
-	void Service::install()
+	void Service::install(const std::string& config_path)
 	{
 		std::string& binaryPath = getFilename();
-		binaryPath = "\"" + binaryPath + "\"";
+		binaryPath = "\"" + binaryPath + "\" -c \"" + config_path + "\"";
 		std::shared_ptr svcMgr = getServiceManager(SC_MANAGER_CREATE_SERVICE);
 		{
 			SC_HANDLE installedService = ::CreateService(reinterpret_cast(svcMgr.get()),
@@ -87,15 +91,119 @@ namespace UDPT
 			{ const_cast(m_conf["service.name"].as().c_str()), reinterpret_cast(&Service::serviceMain) },
 			{0, 0}
 		};
+
 		if (FALSE == ::StartServiceCtrlDispatcher(service))
 		{
 			throw OSError();
 		}
 	}
 
+	DWORD Service::handler(DWORD controlCode, DWORD dwEventType, LPVOID eventData, LPVOID context)
+	{
+		switch (controlCode)
+		{
+		case SERVICE_CONTROL_INTERROGATE:
+			return NO_ERROR;
+
+		case SERVICE_CONTROL_STOP:
+		{
+			reportServiceStatus(SERVICE_STOP_PENDING, 0, 3000);
+			Tracker::getInstance().stop();
+
+			return NO_ERROR;
+		}
+
+		default:
+			return ERROR_CALL_NOT_IMPLEMENTED;
+		}
+	}
+
+	void Service::reportServiceStatus(DWORD currentState, DWORD dwExitCode, DWORD dwWaitHint)
+	{
+		static DWORD checkpoint = 1;
+
+		if (currentState == SERVICE_STOPPED || currentState == SERVICE_RUNNING)
+		{
+			checkpoint = 0;
+		}
+		else
+		{
+			++checkpoint;
+		}
+
+		switch (currentState)
+		{
+		case SERVICE_RUNNING:
+			s_serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
+			break;
+
+		default:
+			s_serviceStatus.dwControlsAccepted = 0;
+		}
+
+		s_serviceStatus.dwCheckPoint = checkpoint;
+		s_serviceStatus.dwCurrentState = currentState;
+		s_serviceStatus.dwWin32ExitCode = dwExitCode;
+		s_serviceStatus.dwWaitHint = dwWaitHint;
+
+		::SetServiceStatus(s_hServiceStatus, &s_serviceStatus);
+	}
+
 	VOID Service::serviceMain(DWORD argc, LPCSTR argv[])
 	{
+		boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "service");
+		
+		wchar_t *commandLine = ::GetCommandLineW();
+		int argCount = 0;
+		std::shared_ptr args(::CommandLineToArgvW(commandLine, &argCount), ::LocalFree);
+		if (nullptr == args)
+		{
+			BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed parse command-line.";
+			::exit(-1);
+		}
 
+		if (3 != argCount)
+		{
+			BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Bad command-line length (must have exactly 2 arguments).";
+			::exit(-1);
+		}
+
+		if (std::wstring(args.get()[1]) != L"-c")
+		{
+			BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Argument 1 must be \"-c\".";
+			::exit(-1);
+		}
+
+		std::wstring wFilename(args.get()[2]);
+		std::string cFilename(wFilename.begin(), wFilename.end());
+
+		boost::program_options::options_description& configOptions = UDPT::Tracker::getConfigOptions();
+		boost::program_options::variables_map config;
+		boost::program_options::basic_parsed_options parsed_options = boost::program_options::parse_config_file(cFilename.c_str(), configOptions);
+		boost::program_options::store(parsed_options, config);
+
+		s_hServiceStatus = ::RegisterServiceCtrlHandlerEx(config["service.name"].as().c_str(), Service::handler, NULL);
+		if (nullptr == s_hServiceStatus)
+		{
+			BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed to register service control handler.";
+			::exit(-1);
+		}
+
+		s_serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
+		s_serviceStatus.dwServiceSpecificExitCode = 0;
+
+		reportServiceStatus(SERVICE_START_PENDING, 0, 0);
+
+		{
+			UDPT::Tracker& tracker = UDPT::Tracker::getInstance();
+			tracker.start(config);
+
+			reportServiceStatus(SERVICE_RUNNING, 0, 0);
+
+			tracker.wait();
+
+			reportServiceStatus(SERVICE_STOPPED, 0, 0);
+		}
 	}
 
 	std::shared_ptr Service::getService(DWORD access)
diff --git a/src/service.hpp b/src/service.hpp
index 4255756..2cefeb8 100644
--- a/src/service.hpp
+++ b/src/service.hpp
@@ -18,9 +18,12 @@
 */
 #pragma once
 
+#include 
+#include 
 #include 
 #include "multiplatform.h"
 #include "exceptions.h"
+#include "tracker.hpp"
 
 #ifdef WIN32 
 namespace UDPT
@@ -33,7 +36,7 @@ namespace UDPT
 		virtual ~Service();
 
 
-		void install();
+		void install(const std::string& config_path);
 
 		void uninstall();
 
@@ -45,9 +48,15 @@ namespace UDPT
 	private:
 		const boost::program_options::variables_map& m_conf;
 
+		static SERVICE_STATUS_HANDLE s_hServiceStatus;
+
+		static SERVICE_STATUS s_serviceStatus;
+
 		std::shared_ptr getService(DWORD access);
 
-		static VOID WINAPI handler(DWORD controlCode);
+		static DWORD WINAPI handler(DWORD controlCode, DWORD dwEventType, LPVOID eventData, LPVOID context);
+
+		static void reportServiceStatus(DWORD currentState, DWORD dwExitCode, DWORD dwWaitHint);
 
 		static VOID WINAPI serviceMain(DWORD argc, LPCSTR argv[]);
 
diff --git a/vs/UDPT/UDPT.vcxproj b/vs/UDPT/UDPT.vcxproj
index 99855c3..22afae6 100644
--- a/vs/UDPT/UDPT.vcxproj
+++ b/vs/UDPT/UDPT.vcxproj
@@ -59,7 +59,7 @@
     
     
       true
-      ws2_32.lib;sqlite3.lib;advapi32.lib
+      ws2_32.lib;sqlite3.lib;advapi32.lib;shell32.lib
       Console
     
   
@@ -78,7 +78,7 @@
       
       
       
-      ws2_32.lib;sqlite3.lib;advapi32.lib
+      ws2_32.lib;sqlite3.lib;advapi32.lib;shell32.lib
       Console
     
   

From c91efa300bbccfcffd702efe5bd890603f30997d Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Fri, 19 Feb 2016 13:41:15 +0200
Subject: [PATCH 76/99] Fix for gcc

---
 src/main.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/main.cpp b/src/main.cpp
index 9ad57c3..cdebc42 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -97,7 +97,7 @@ int main(int argc, char *argv[])
 		;
 
 
-	boost::program_options::options_description& configOptions = Tracker::getConfigOptions();
+	const boost::program_options::options_description& configOptions = Tracker::getConfigOptions();
 
 	boost::program_options::variables_map var_map;
 	boost::program_options::store(boost::program_options::parse_command_line(argc, argv, commandLine), var_map);

From 4b26c859173428d9f6dc7b34ec5796b14c1ad03a Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sat, 20 Feb 2016 21:13:09 +0200
Subject: [PATCH 77/99] Start + Stop service

---
 src/main.cpp    |  5 +++++
 src/service.cpp | 14 +++++++++++++-
 2 files changed, 18 insertions(+), 1 deletion(-)

diff --git a/src/main.cpp b/src/main.cpp
index cdebc42..2aa342e 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -182,6 +182,11 @@ int main(int argc, char *argv[])
 			{
 				svc.stop();
 			}
+			else
+			{
+				std::cerr << "No such service command." << std::endl;
+				return -1;
+			}
 		}
 		catch (const UDPT::OSError& ex)
 		{
diff --git a/src/service.cpp b/src/service.cpp
index 9c146c2..d61aacf 100644
--- a/src/service.cpp
+++ b/src/service.cpp
@@ -77,12 +77,24 @@ namespace UDPT
 
 	void Service::start()
 	{
-
+		std::shared_ptr hSvc = getService(SERVICE_START);
+		BOOL bRes = ::StartService(reinterpret_cast(hSvc.get()), 0, NULL);
+		if (FALSE == bRes)
+		{
+			throw OSError();
+		}
 	}
 
 	void Service::stop()
 	{
+		SERVICE_STATUS status = { 0 };
 
+		std::shared_ptr hSvc = getService(SERVICE_STOP);
+		BOOL bRes = ::ControlService(reinterpret_cast(hSvc.get()), SERVICE_CONTROL_STOP, &status);
+		if (FALSE == bRes)
+		{
+			throw OSError();
+		}
 	}
 
 	void Service::setup()

From 0790558de8b5bb841bb10a9115bbf72c3b4711b5 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Sat, 20 Feb 2016 21:42:48 +0200
Subject: [PATCH 78/99] Added samploe configuration

---
 udpt.conf | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
 create mode 100644 udpt.conf

diff --git a/udpt.conf b/udpt.conf
new file mode 100644
index 0000000..0dec3d3
--- /dev/null
+++ b/udpt.conf
@@ -0,0 +1,22 @@
+# This is a sample configuration file that can
+# be used for production use on a dynamic tracker.
+
+[db]
+driver=sqlite3
+param=:memory:
+
+[tracker]
+is_dynamic=yes
+port=6969
+threads=5
+allow_remotes=yes
+allow_iana_ips=no
+announce_interval=1800
+cleanup_interval=120
+
+[apiserver]
+enable=no
+
+[logging]
+filename=udpt-log.log
+level=warning

From e826b58ea0ae3eebc771d4aa38d7d0998cd8a4e3 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Wed, 5 Oct 2016 00:20:08 +0300
Subject: [PATCH 79/99] Fix for issue #25

---
 src/udpTracker.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp
index a8a04c2..d5f265b 100644
--- a/src/udpTracker.cpp
+++ b/src/udpTracker.cpp
@@ -102,7 +102,7 @@ namespace UDPT
 
 		{
 			char buff[INET_ADDRSTRLEN];
-			BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "UDP tracker bound on " << ::inet_ntop(AF_INET, reinterpret_cast(&m_localEndpoint.sin_addr), buff, sizeof(buff)) << ":" << ::htons(m_localEndpoint.sin_port);
+			BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "UDP tracker bound on " << ::inet_ntop(AF_INET, reinterpret_cast(&m_localEndpoint.sin_addr), buff, sizeof(buff)) << ":" << htons(m_localEndpoint.sin_port);
 		}
 
 		this->m_sock = sock;

From d7e8df7e713d1deb883ffd93d1322fb79f5a0e36 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Tue, 6 Dec 2016 23:14:08 +0200
Subject: [PATCH 80/99] Renamed license filename

---
 gpl.txt => LICENSE | 0
 1 file changed, 0 insertions(+), 0 deletions(-)
 rename gpl.txt => LICENSE (100%)

diff --git a/gpl.txt b/LICENSE
similarity index 100%
rename from gpl.txt
rename to LICENSE

From 82a40bfdbc5f6e27cfa1f422327feebd249ad3a0 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Thu, 8 Dec 2016 20:38:14 +0200
Subject: [PATCH 81/99] Converted bad character

---
 CMakeLists.txt  | 0
 src/service.hpp | 2 +-
 src/tracker.cpp | 2 +-
 src/tracker.hpp | 2 +-
 4 files changed, 3 insertions(+), 3 deletions(-)
 create mode 100644 CMakeLists.txt

diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..e69de29
diff --git a/src/service.hpp b/src/service.hpp
index 2cefeb8..9c845e8 100644
--- a/src/service.hpp
+++ b/src/service.hpp
@@ -1,5 +1,5 @@
 /*
-*	Copyright © 2012-2016 Naim A.
+*	Copyright © 2012-2016 Naim A.
 *
 *	This file is part of UDPT.
 *
diff --git a/src/tracker.cpp b/src/tracker.cpp
index 0c75a8a..f05e5e3 100644
--- a/src/tracker.cpp
+++ b/src/tracker.cpp
@@ -1,5 +1,5 @@
 /*
-*	Copyright © 2012-2016 Naim A.
+*	Copyright © 2012-2016 Naim A.
 *
 *	This file is part of UDPT.
 *
diff --git a/src/tracker.hpp b/src/tracker.hpp
index fc4bc25..43d19ff 100644
--- a/src/tracker.hpp
+++ b/src/tracker.hpp
@@ -1,5 +1,5 @@
 /*
-*	Copyright © 2012-2016 Naim A.
+*	Copyright © 2012-2016 Naim A.
 *
 *	This file is part of UDPT.
 *

From 6bf8a7ca6c15a309235e140d446cd2342b310215 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Thu, 8 Dec 2016 20:38:43 +0200
Subject: [PATCH 82/99] Moving to CMake...

---
 CMakeLists.txt | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index e69de29..3bfa1b1 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -0,0 +1,15 @@
+project(udpt)
+cmake_minimum_required(VERSION 3.6)
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+add_definitions(-DBOOST_LOG_DYN_LINK)
+
+file(GLOB src_files "src/*.c"
+        "src/*.cpp"
+        "src/db/*.cpp"
+        "src/http/*.cpp")
+
+
+add_executable(udpt ${src_files})
+target_link_libraries(udpt pthread sqlite3 boost_log boost_program_options boost_thread boost_system)

From bffded45faf576ee0692c0d6f936f5e68c0f205a Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Thu, 8 Dec 2016 20:39:09 +0200
Subject: [PATCH 83/99] added gitignores for Clion

---
 .gitignore | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/.gitignore b/.gitignore
index 4c6ac2c..7d77394 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,5 @@
 *.opensdf
 **/Debug/*
 *.opendb
+cmake-build-debug/
+

From 382f775130cef60d6f2715ded6f7866d112c1015 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Thu, 14 Sep 2017 02:34:23 +0300
Subject: [PATCH 84/99] Removed Makefile, using CMake now...

---
 Makefile | 43 -------------------------------------------
 1 file changed, 43 deletions(-)
 delete mode 100644 Makefile

diff --git a/Makefile b/Makefile
deleted file mode 100644
index 989d693..0000000
--- a/Makefile
+++ /dev/null
@@ -1,43 +0,0 @@
-#
-#	Copyright © 2012,2013 Naim A.
-#
-#	This file is part of UDPT.
-#
-#		UDPT is free software: you can redistribute it and/or modify
-#		it under the terms of the GNU General Public License as published by
-#		the Free Software Foundation, either version 3 of the License, or
-#		(at your option) any later version.
-#
-#		UDPT 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 UDPT.  If not, see .
-#
-
-objects = main.o udpTracker.o database.o driver_sqlite.o \
-	tools.o httpserver.o webapp.o tracker.o
-target = udpt
-CXXFLAGS = -DBOOST_LOG_DYN_LINK
-
-%.o: src/%.c
-	$(CC) -c -o $@ $< $(CFLAGS)
-%.o: src/%.cpp
-	$(CXX) -g -std=gnu++11 -c -o $@ $< $(CXXFLAGS)
-%.o: src/db/%.cpp
-	$(CXX) -g -std=gnu++11 -c -o $@ $< $(CXXFLAGS)
-%.o: src/http/%.cpp
-	$(CXX) -g -std=gnu++11 -c -o $@ $< $(CXXFLAGS)
-all: $(target)
-	
-$(target): $(objects)
-	@echo Linking...
-	$(CXX) -O3 -o $(target) $(objects) $(LDFLAGS) -lboost_program_options -lsqlite3 -lpthread -lboost_thread -lboost_system -lboost_log
-	@echo Done.
-clean:
-	@echo Cleaning Up...
-	$(RM) $(objects) $(target)
-	@echo Done.
-

From f6318e9debfad45cb0b071f3df640f96593bc02f Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Thu, 14 Sep 2017 02:35:01 +0300
Subject: [PATCH 85/99] Changed C++11's filesystem include header

---
 src/service.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/service.cpp b/src/service.cpp
index d61aacf..bdd8d33 100644
--- a/src/service.cpp
+++ b/src/service.cpp
@@ -17,7 +17,7 @@
 *		along with UDPT.  If not, see .
 */
 #include "service.hpp"
-#include 
+#include 
 
 #ifdef WIN32 
 

From 7193f945a9047d132c1e0495019d9ccdb2b312f8 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Thu, 14 Sep 2017 03:56:29 +0300
Subject: [PATCH 86/99] Update README.md

---
 README.md | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/README.md b/README.md
index f5f8604..b0dce52 100644
--- a/README.md
+++ b/README.md
@@ -37,3 +37,5 @@ And finally:
 ### Author(s)
 UDPT was developed by [Naim A.](http://www.github.com/naim94a) at for fun at his free time. 
 The development started on November 20th, 2012.
+
+If you find the project useful, please consider a donation to the following bitcoin address: 1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3.

From f34fcdbd041ae97f8c98aefa05e71a65f6de53c5 Mon Sep 17 00:00:00 2001
From: Naim A 
Date: Wed, 27 Sep 2017 04:33:21 +0300
Subject: [PATCH 87/99] Refactored (#31)

* Build system changed to CMake
* Converted tabs to spaces
* Removed all usages of boost::log
* Replaced boost::thread with std::thread
* Update copyright year
* Added a tiny bit of unit tests
* Added a simple message queue
* Added basic independent logging
* Added CONTRIBUTING
---
 .github/CONTRIBUTING.md      |   44 ++
 .github/bitcoin-qr.png       |  Bin 0 -> 5762 bytes
 CMakeLists.txt               |   15 +-
 src/MessageQueue.hpp         |   64 ++
 src/db/database.cpp          |  160 ++---
 src/db/database.hpp          |  256 ++++----
 src/db/driver_sqlite.cpp     |  866 +++++++++++++--------------
 src/db/driver_sqlite.hpp     |  111 ++--
 src/exceptions.h             |  104 ++--
 src/http/httpserver.cpp      | 1070 +++++++++++++++++-----------------
 src/http/httpserver.hpp      |  340 +++++------
 src/http/webapp.cpp          |  320 +++++-----
 src/http/webapp.hpp          |   42 +-
 src/logging.cpp              |  140 +++++
 src/logging.hpp              |   83 +++
 src/main.cpp                 |  300 +++++-----
 src/multiplatform.h          |    2 +-
 src/service.cpp              |  384 ++++++------
 src/service.hpp              |   44 +-
 src/tools.c                  |  130 ++---
 src/tools.h                  |  100 ++--
 src/tracker.cpp              |  160 ++---
 src/tracker.hpp              |   21 +-
 src/udpTracker.cpp           |  927 ++++++++++++++---------------
 src/udpTracker.hpp           |  373 ++++++------
 tests/main.cpp               |   55 ++
 vs/UDPT.sln                  |   22 -
 vs/UDPT/UDPT.vcxproj         |  111 ----
 vs/UDPT/UDPT.vcxproj.filters |   90 ---
 29 files changed, 3243 insertions(+), 3091 deletions(-)
 create mode 100644 .github/CONTRIBUTING.md
 create mode 100644 .github/bitcoin-qr.png
 create mode 100644 src/MessageQueue.hpp
 create mode 100644 src/logging.cpp
 create mode 100644 src/logging.hpp
 create mode 100644 tests/main.cpp
 delete mode 100644 vs/UDPT.sln
 delete mode 100644 vs/UDPT/UDPT.vcxproj
 delete mode 100644 vs/UDPT/UDPT.vcxproj.filters

diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
new file mode 100644
index 0000000..3ead340
--- /dev/null
+++ b/.github/CONTRIBUTING.md
@@ -0,0 +1,44 @@
+# Contributing
+Thank you for looking into [UDPT](https://github.com/naim94a/udpt)!
+
+This document lists various ways to contribute to UDPT. If you can, please do.
+
+## Bug Reports
+Bug reports are always welcome, they help us maintain a quality product.
+
+Before submitting a bug report, please first check that the issue does not already exist and that the effected version
+is the most recent one.
+
+* If a similar (or same) issue already exists, please upvote, comment, elaborate on the existing issue.
+* If you found a new issue, please attach the used configuration and how to cause the bug to appear.
+* Core dumps are always welcome
+
+Bugs should be reported at [UDPT's issue tracker](https://github.com/naim94a/udpt) on GitHub.
+
+## Suggesting new features
+New features are welcome, it doesn't mean they will enter immediately.
+
+Suggestions should be filed as issues along with bug reports, just add the "enhancement" label to the created issue.
+
+## Donations
+Please show us your appreciation by donating BitCoin at bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3. 
+
+![bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3](bitcoin-qr.png)
+
+## Pull requests
+Before submitting a pull request, please check that the changes don't effect other platforms or have any unwanted
+side-effects.
+
+Pull Requests should address open issue(s), where the project owner and contributors can discuss how the issue should be
+addressed.
+
+Pull requests that add new features should be first mentioned in issues in order to verify that the project owner will
+allow such changes to the project.
+
+Code in pull requests should meet the following requirements:
+
+* Class names should be CamelCase, and the first letter should be capital.
+* Functions should be camelCase, and the first letter should be lower-case.
+* Class members should be prefixed with `m_`, for example: `bool m_isRunning`
+* All variables, classes, functions and class members should have an indicative name.
+* Adding external libraries is allowed, but frowned upon
diff --git a/.github/bitcoin-qr.png b/.github/bitcoin-qr.png
new file mode 100644
index 0000000000000000000000000000000000000000..1f8f80f41e015558746d16ce0d01404fec2ef9a7
GIT binary patch
literal 5762
zcma)Adpwi<-?uT<+~^L|&5e$ZMF*!=V-7h)2(z$JR1W2I+t9R`m86pHq(#`A57XR*
zVvJHz3S*Yi4@oi;i{>=Ub4~a2{P#Ss=a21ry{_+deXr~Kd_M2P=ac5)=BNnOfXc|o
zC^|dYdjdzX^tVwS_`mku4Ue7Z2HuFL!BE%wVQ93QdK;r2}FOP+DcdzKd-
zBrkd}%Y$d;Xni>L?pP{Vj8MzwuRi`yNsqiJPWxcb;Y>0tL6?y9xVQ7NK!+nMegNjB
zz<}ddf=R?kZ$Z_x@1Wj|#~-(a1v4URv-#15+^n!CrySy#@n@;D6HQBN=hf&Ji|6Zl
z;;ogAz3_$iJ>Y}bEV(a94j`y;9W8Cd!aPsWF31P2%1O#>%_Uv|t75_fiK*lvj}KY;
zRGPr{+FCQ%G^4NCZ;h&+rWm
ziccFxk-f*?$4<2Sq62&oRDlV94-uWIWS}z|2Rgc0d+eULY+nEVtw)m$46^?mrm}@z
z1B6DO&czK)g#}fxwLdOoGRK+VNM3A(gwnO8rni9X#{Gj6qV`rm@-h_i(~|-Nu-h7&
z2=BmVk5zO#3*MqK@w`|^mSklOl2ew{)g58X|(@|p5YX5?Su8O0-Y`lqd{)g2u%kmm5#
zhA)9*>aNn4oiWX^4(P|3puR1nkd&3H6d3qM3PB*p&BGSU^tpQVctM3iL1f()Q
zuuT`TL&$&OutWO&h!^da;tr(3J?2YO?SAO7RgNXYLQ_MTU2R12Q(j8>qkcbUlZ`?$
zEXPP&Lys7V4=$2~t(cnds&|33&RvN+iB9IU7N?~gFzpO`-h0(%w0LRY=u-jVwSBj}
z@G*=NW+Z4)Y1B}QI0d}P23-1CMr1aBvwhCNfzvgtVbxOjo;_b*+@a5KS%nWcw!~s(
zes4ki@5*bLuDneJ!n@3b(Cr-C*ufjHZ4tRRNC~_iR|*s|TfJ^L4qv8TGS5q^oY&#h
z#gBy#VlKC$y49_Fqwgu5Ega_hU^mu2KT~*K@v^}6dC7b>U-4C?3Tmo_aG)pa6K@{|
z;-+cXsa{vMP&f~~TD�K?c7Rqn3bN^Y$EQEwS?*tYNLm-KX#ePGLv~dOq!4`oTCn
z^_e#>V*K@8=jSb#=YD4cu{26jn59c9K?S?9N#yiQu|81Y=6k!anDDOM=Su8A#3ojC
z4zl)k@Nm=>jTArTi!UjKX5dSpCb7^L}5cmNp!4U((A*#h;COBc>Y
zK7ECbuN*Tr(r2UJ=9fMak53w}Vi)ie-)Ccc9M?f242xCMUDf|)m`k4aoZU|Xvz*6K
zpXEi8{wS(d?W63Dj&Hj32gSefiQ6Z>IX(Ytg2r2I1p5vqd0%00_;Q8wrOiH)4F+JA
zkrz!fLt6Dh{zXUH-eIy8qc3;x38V468g3~&Gx0Y#Rtx(;E}a&+#W=dcN)+JjE@%OQ
zkP6b0^d-YC;Df?W_fiT^^(0iz6>MXDi3e~t+~XyUW*09HwkHp1oXk+jhUxOs1<28g
z_wA5e#`9`clrBLRes-iY-`oufjd1F-hIEb5tf=M#t~f3&Gj8{PP_J>6-tk`BqM0hg
zOJWRqXad0CdSxS#LX&+=hok+wa?}SBw3}IhPpx)Pq6_R6`jn@dc#QAHGxc9~nf0DO
z#cZnAkeM3|mjP+{+%-DUJ&*uq#RqTXD*{Mbrw*a($V0xq=ww@k)B&$;p_kFu7x}JpY?!&<
zdg@!KK6slG9-&A2tmwml4*avbQSNd^L=LyLY@SEwB$N~JD~wqu;aH`=&3f4#=sDPv
zL>UpcZRRX%+70y_SF=65r>-n>C!_J+2SHQQJNp(=>JA;7P*(Zvz7~aTf-()9V0fS!?q(`VzFU(kr(Bg^|p5Z}mGh|XI@Jpt1c4z{$<0Gzg#tWg-%nB)7@FF|`
zt3nOwffbY_&Mvwgr0WT^_l>>6nXDvqZpd4-&w>zo2ETUVcP0f7y2~S0cW&xBxKh^i
znB|qCIS*o+>>@(w51_|KKWZ4J(*zeaI1?TADyY4?_PT0V&$$a-G}Y?LX6nCJbTQ$$
zu^Vl}VKUMe6Abzt)B&$NS;9=aCG}bDW=way@aH@it%3RH+>*3;S~SY7I^wNZ%mj
zM-`1s@)8tYUf*kj$QOx?3nH%lTtrpxGnH^J-E5TmYtiT*k!`EsuY{L%TezruLsXbw
zos}sGYTT*7qcJ-Go(d?B%u93zk-`1(TZl1h}#VLSNQh^
z4S!1&4wE)WgedZXlAZH-SZ3rFJoro4>&uuqNM@_faCBE8!IL%ZuN8ufI&&TB{yfKs
z+nB|uL93U(wdS?gb$D7cmwO3CG4diZsRLzBPYm3@E+#72l*kKA#i{{icK;LLK}KG4
zhN!$BX?|At={ur2ce1z(*qmx#_q0XCPM|rY1e?@oOiCHMMqDco?!;%-*H$M
zV=Ffgq|SL&&hB*S9th5aeM1UUxLCxNKLOoYzUBiod@!SkFoD1wcmy
zleG#PsYw9|TpL7gmnF!h~k;Qv4Z~ziF)6XAh
zfS&ntCO2g=0JK{A^hfwM;57&)X)jtPrwv{EuN09&SB%%X#Ta!Cj>5{H48IT?A&TUs
z1^%M>O`G_uTjD_KoG9p#6~;1tavS#8$rIO>zd^r(|Ay^>HU~E?$A+yi;V}pc6$CvA
zcT%03N(z0>qQoGmV&LZZ1y@m9#>9ahGm!zE8TFe~_l(}7?lUR8AL0e?Id-McWmK83
zC(E9T#fjZ&-a5jd#)G@`H}lAzYsN$jotse3Hgel8?A?Hy;Gpi3hfLDR%!yI(wRKp^
z;}*;A@O5pb!nVr+l!*fQMdgYAUWXa+CQ&ME#CMw{83ru4F7^%ILS8)GSb3Ubspl!~
zyz=dB$-#7Pi7Y!x7rwGzgSY|8C#nJ}A_?318{Z@OeY@qrMT2X4-~aJw2#!T3dm$!b
zu}k=+3i&+2L}m9atKP{cxblTt&4$Ufr_veT$QFI%90sLl>I>4kb5tQYE_|z!v8zS~
zgI<|TXEl6@S@O+N7h{ULez^s&o9*)eSEOfJ^+U?vDnlZ3(}b{W{y(;ulnKIy%3JLy
z4<7QFsd@F$xvFM$9__ta#6E|AJzacO&!F;NIVh~I%mTMmM$(TK1(;a(m{5Er2>5aD
zx*xS1Oy--h)He6I_~Xr}i^X)WM1o1da~FUrM5HD1Pz4x@LADqmHI*SZfH;O70X*S8
zwZ{ao)Q}V?UZtQO>ZP}%lvVlRTJX7TiXjsoy5jmh`q3bS3K4_STUene-B|Mg
zN686PsB%Lb|H>U-G|xQ3()}|%1n{|C6t-z@iCzC^Fv0pLGtF3)GPV(N!`!J-8BoQf
zZYLz|CB-es?{((sBkyif)Hpg+jWK5s(X);$j2!7Yn?7
zJ-6S8o>9lF-N^qj&TqSQbyh%NzEuY5-&KKgb{Lx0TO4|eHUmv#A
zFBXRPZXXN&vr|@W(RT`+Tz9Nnu-u#2gUU5eC;&PA>W@~L86LK+%IBj|+qvURmPz_S
z`U@Ul3`%7pe&eZhp!CpV~CpR4Hu}}Pb&8wZNts`of
zVe@i{F#y2{ds^}=L$UM5qnVntpW3y!*A1*jXfo`8+ECU>KeDL7cw6WQdUArLo?gSU
zs_3E;Zr{&Rf{0=Wm~_W?lh&Z#gf@$nNE?tJ-b5n=X|dYsT6Y^q$={ogLduDN9?zsr
ze&?@(-zp2YsaUn7G^Duz%?gLv=1iLm|G`|8CD=LpkyTXy(dLA_
zwV-z!nnmdSN)7SJ9$9gfCpYeYmJj@|%i4U?N8J8Ii{e0Ee+i>S;HAZ9hpsTb6zCX*
zsvYO>fZozZMzGBP++s(n^hb@
zY~|ZV87dWv=R8;cL*1|n0&{Y82E35ibo&If-3%8DI7)c^ivRWE(JSwjc}qdk)_wa~
zeA!F`l%{)6w*y6HE_+%VFNbSkBw+}TL_cc~duCxI>_xfTU51Q7vpqoC~
z+?VmT*>3|i$xpdYGNCITvu$5X4y}B*V;Pm6+Tk!-l`m4YBm|-laiX>W)wE_yDv@@G
z41EyRUn^`xAtm}`4MW$0Z32lzjc(#IUDcKgWKMYS&y+x1#tLSD?@e(R9>o_eRL;9k
z{t)}x_Ba9cPon1NUWaMSxoh48+HIYZYZ+bM?W40MU(xGekQKYvV^VZDsnB(NOPl6)
z{*hC`nLzEb^)BA1o)!(_KDg^CR?;SCg@&%^BTTe1RfkX=zMR@p6sWzGbC|=u;y$0@
zevrCGCS~4jCR9CE<|}$)kX7Iwv+Q!(JvQSRdct{fa`~C`vO+
zrr^z&fzgI60U2d@YE9r~J?;AST*sB>!)}LGgY1(YCA)z&GR~`&b(g>!zlY`W#NPdO
zWhANb5$@0?;g$IVjh{b48^po?nNHtFHxWBV;QsRXr&7gbv?Bi`h)w%j+M!4BbvVlp
zt}y=g$ivPv7qOZl$Zq>2#+yMjS4vXKkl9;96)9wrik=E~`CQGEzzwY>R`SDoG*(^m
zwqR{RPr8mCdcbD5!8Nl)AS}H267b;FO^%=v0t>p2zTkhuWt^}NC2luIDy(_e
zfDg3(x>FS}>D)I0aEg@$-D^xISg5fvo1e`e%)r#1=FD~jvx9DX8okXd4NKCsm7LoG
zv}ImoH#CuofG`J!AhqYSO41+t=>Ra#Ro7ad8H7j#(_kvaRwW?9eY9-el=P^1BDi!)
z7Jex;-)Fw45xK^A_R#oJCD75$cqO8b0Ci_Yx7%Ftqmk^7UG%mHm)^xpDA%D%jY?FV
zH+GRpiC6+kC{ZKHXW>E6MaQU1MIX+}(o+H>+<|$5sRYOm)y>0?Tsu=sK3Nan;ecH@
zs;qXiBHvVK>(qJHWoGVi;Go*0TV0$hjZhlw+w=ndl`uTlRM@sCb(lh%qNGy6ma7y`
zMLD*5`Y>R_Z2j?p=oMo`h0?D}K&$!YIX}pfC1zOF>TqMBZ1T6&h2Kg4k|^2AznJsWxUJrx#fyrUz~wjKx_sn?yhd@O`X
zmrc9E6LU-|FYhP)Qt+~Lm>b}{{laX1s&Qx{A&a}CC`E-+(HfALQw;=Z*zh)R!2-pF
z-E)b3gzx=1Jh2}=Ttoa`1Q@aEc{|O3w?k^Ll`g}rZZm1_|r21a!w{2zqx03;*<$6dkt7RR(k^JxsC4fc+5lfgG(~G8Qr`kLiIM#pWnG~NEI><
ztO>KK?KL60AYj%me_%g0u$DMx)Z_5~-D**1BE>fO)go8}m@UgVA9b^5+Mc5P7a%h~
AQ2+n{

literal 0
HcmV?d00001

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3bfa1b1..9da8e20 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,15 +1,24 @@
 project(udpt)
-cmake_minimum_required(VERSION 3.6)
+cmake_minimum_required(VERSION 3.2)
+enable_testing()
 
 set(CMAKE_CXX_STANDARD 11)
 set(CMAKE_CXX_STANDARD_REQUIRED ON)
-add_definitions(-DBOOST_LOG_DYN_LINK)
 
 file(GLOB src_files "src/*.c"
         "src/*.cpp"
         "src/db/*.cpp"
         "src/http/*.cpp")
 
+LIST(APPEND LIBS "pthread" "sqlite3" "boost_program_options" "boost_system")
+
 
 add_executable(udpt ${src_files})
-target_link_libraries(udpt pthread sqlite3 boost_log boost_program_options boost_thread boost_system)
+target_link_libraries(udpt ${LIBS})
+
+add_executable(udpt_tests tests/main.cpp ${src_files})
+target_compile_definitions(udpt_tests PRIVATE TEST=1)
+
+target_link_libraries(udpt_tests gtest ${LIBS})
+
+add_test(NAME udpt_tests COMMAND udpt_tests)
\ No newline at end of file
diff --git a/src/MessageQueue.hpp b/src/MessageQueue.hpp
new file mode 100644
index 0000000..dc61390
--- /dev/null
+++ b/src/MessageQueue.hpp
@@ -0,0 +1,64 @@
+/*
+*	Copyright © 2012-2017 Naim A.
+*
+*	This file is part of UDPT.
+*
+*		UDPT is free software: you can redistribute it and/or modify
+*		it under the terms of the GNU General Public License as published by
+*		the Free Software Foundation, either version 3 of the License, or
+*		(at your option) any later version.
+*
+*		UDPT 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 UDPT.  If not, see .
+*/
+#pragma once
+
+#include 
+#include 
+
+namespace UDPT
+{
+    namespace Utils {
+
+        template
+        class MessageQueue {
+        public:
+            MessageQueue() {}
+
+            virtual ~MessageQueue() {}
+
+            bool IsEmpty() const {
+                return m_queue.empty();
+            }
+
+            T Pop() {
+                m_queueMutex.lock();
+                T val = m_queue.front();
+                m_queue.pop();
+                m_queueMutex.unlock();
+
+                return val;
+            }
+
+            void Push(T obj) {
+                m_queueMutex.lock();
+                m_queue.push(obj);
+                m_queueMutex.unlock();
+            }
+
+            size_t Count() const {
+                return m_queue.size();
+            }
+
+        private:
+            std::queue m_queue;
+            std::mutex m_queueMutex;
+        };
+
+    }
+}
diff --git a/src/db/database.cpp b/src/db/database.cpp
index 1df5798..455bede 100644
--- a/src/db/database.cpp
+++ b/src/db/database.cpp
@@ -1,5 +1,5 @@
 /*
- *	Copyright © 2012-2016 Naim A.
+ *	Copyright © 2012-2017 Naim A.
  *
  *	This file is part of UDPT.
  *
@@ -21,100 +21,100 @@
 
 namespace UDPT
 {
-	namespace Data
-	{
-		DatabaseDriver::DatabaseDriver(const boost::program_options::variables_map& conf, bool isDynamic) : m_conf(conf)
-		{
-			this->is_dynamic = isDynamic;
-		}
+    namespace Data
+    {
+        DatabaseDriver::DatabaseDriver(const boost::program_options::variables_map& conf, bool isDynamic) : m_conf(conf)
+        {
+            this->is_dynamic = isDynamic;
+        }
 
-		bool DatabaseDriver::addTorrent(uint8_t hash [20])
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        bool DatabaseDriver::addTorrent(uint8_t hash [20])
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		bool DatabaseDriver::removeTorrent(uint8_t hash[20])
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        bool DatabaseDriver::removeTorrent(uint8_t hash[20])
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		bool DatabaseDriver::isDynamic()
-		{
-			return this->is_dynamic;
-		}
+        bool DatabaseDriver::isDynamic()
+        {
+            return this->is_dynamic;
+        }
 
-		bool DatabaseDriver::genConnectionId(uint64_t *cid, uint32_t ip, uint16_t port)
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        bool DatabaseDriver::genConnectionId(uint64_t *cid, uint32_t ip, uint16_t port)
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		bool DatabaseDriver::verifyConnectionId(uint64_t cid, uint32_t ip, uint16_t port)
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        bool DatabaseDriver::verifyConnectionId(uint64_t cid, uint32_t ip, uint16_t port)
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		bool DatabaseDriver::updatePeer(uint8_t peer_id [20], uint8_t info_hash [20],
-					uint32_t ip, uint16_t port,
-					int64_t downloaded, int64_t left, int64_t uploaded,
-					enum TrackerEvents event)
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        bool DatabaseDriver::updatePeer(uint8_t peer_id [20], uint8_t info_hash [20],
+                    uint32_t ip, uint16_t port,
+                    int64_t downloaded, int64_t left, int64_t uploaded,
+                    enum TrackerEvents event)
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		bool DatabaseDriver::removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port)
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        bool DatabaseDriver::removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port)
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		bool DatabaseDriver::getTorrentInfo (TorrentEntry *e)
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        bool DatabaseDriver::getTorrentInfo (TorrentEntry *e)
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		bool DatabaseDriver::getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe)
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        bool DatabaseDriver::getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe)
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		void DatabaseDriver::cleanup()
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        void DatabaseDriver::cleanup()
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		bool DatabaseDriver::isTorrentAllowed(uint8_t info_hash[20])
-		{
-			throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
-		}
+        bool DatabaseDriver::isTorrentAllowed(uint8_t info_hash[20])
+        {
+            throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED);
+        }
 
-		DatabaseDriver::~DatabaseDriver()
-		{
-		}
+        DatabaseDriver::~DatabaseDriver()
+        {
+        }
 
-		/*-- Exceptions --*/
-		static const char *EMessages[] = {
-				"Unknown Error",
-				"Not Implemented",
-				"Failed to connect to database"
-		};
+        /*-- Exceptions --*/
+        static const char *EMessages[] = {
+                "Unknown Error",
+                "Not Implemented",
+                "Failed to connect to database"
+        };
 
-		DatabaseException::DatabaseException()
-		{
-			this->errorNum = E_UNKNOWN;
-		}
+        DatabaseException::DatabaseException()
+        {
+            this->errorNum = E_UNKNOWN;
+        }
 
-		DatabaseException::DatabaseException(enum EType e)
-		{
-			this->errorNum = e;
-		}
+        DatabaseException::DatabaseException(enum EType e)
+        {
+            this->errorNum = e;
+        }
 
-		enum DatabaseException::EType DatabaseException::getErrorType()
-		{
-			return this->errorNum;
-		}
+        enum DatabaseException::EType DatabaseException::getErrorType()
+        {
+            return this->errorNum;
+        }
 
-		const char* DatabaseException::getErrorMessage()
-		{
-			return EMessages[this->errorNum];
-		}
-	};
+        const char* DatabaseException::getErrorMessage()
+        {
+            return EMessages[this->errorNum];
+        }
+    };
 };
diff --git a/src/db/database.hpp b/src/db/database.hpp
index 31513c8..8a5ba21 100644
--- a/src/db/database.hpp
+++ b/src/db/database.hpp
@@ -1,5 +1,5 @@
 /*
- *	Copyright © 2012-2016 Naim A.
+ *	Copyright © 2012-2017 Naim A.
  *
  *	This file is part of UDPT.
  *
@@ -21,154 +21,152 @@
 #define DATABASE_HPP_
 
 #include 
-#include 
-#include 
 
 namespace UDPT
 {
-	namespace Data
-	{
-		class DatabaseException
-		{
-		public:
-			enum EType {
-				E_UNKNOWN = 0,			// Unknown error
-				E_NOT_IMPLEMENTED = 1,	// not implemented
-				E_CONNECTION_FAILURE = 2
-			};
+    namespace Data
+    {
+        class DatabaseException
+        {
+        public:
+            enum EType {
+                E_UNKNOWN = 0,			// Unknown error
+                E_NOT_IMPLEMENTED = 1,	// not implemented
+                E_CONNECTION_FAILURE = 2
+            };
 
-			DatabaseException();
-			DatabaseException(EType);
-			EType getErrorType();
-			const char* getErrorMessage();
-		private:
-			EType errorNum;
-		};
+            DatabaseException();
+            DatabaseException(EType);
+            EType getErrorType();
+            const char* getErrorMessage();
+        private:
+            EType errorNum;
+        };
 
-		class DatabaseDriver
-		{
-		public:
-			typedef struct {
-				uint8_t *info_hash;
-				int32_t seeders;
-				int32_t leechers;
-				int32_t completed;
-			} TorrentEntry;
-			typedef struct {
-				uint32_t ip;
-				uint16_t port;
-			} PeerEntry;
+        class DatabaseDriver
+        {
+        public:
+            typedef struct {
+                uint8_t *info_hash;
+                int32_t seeders;
+                int32_t leechers;
+                int32_t completed;
+            } TorrentEntry;
+            typedef struct {
+                uint32_t ip;
+                uint16_t port;
+            } PeerEntry;
 
-			enum TrackerEvents {
-				EVENT_UNSPEC = 0,
-				EVENT_COMPLETE = 1,
-				EVENT_START = 2,
-				EVENT_STOP = 3
-			};
+            enum TrackerEvents {
+                EVENT_UNSPEC = 0,
+                EVENT_COMPLETE = 1,
+                EVENT_START = 2,
+                EVENT_STOP = 3
+            };
 
-			/**
-			 * Opens the DB's connection
-			 * @param dClass Settings class ('database' class).
-			 */
-			DatabaseDriver(const boost::program_options::variables_map& conf, bool isDynamic = false);
+            /**
+             * Opens the DB's connection
+             * @param dClass Settings class ('database' class).
+             */
+            DatabaseDriver(const boost::program_options::variables_map& conf, bool isDynamic = false);
 
-			/**
-			 * Adds a torrent to the Database. automatically done if in dynamic mode.
-			 * @param hash The info_hash of the torrent.
-			 * @return true on success. false on failure.
-			 */
-			virtual bool addTorrent(uint8_t hash[20]);
+            /**
+             * Adds a torrent to the Database. automatically done if in dynamic mode.
+             * @param hash The info_hash of the torrent.
+             * @return true on success. false on failure.
+             */
+            virtual bool addTorrent(uint8_t hash[20]);
 
-			/**
-			 * Removes a torrent from the database. should be used only for non-dynamic trackers or by cleanup.
-			 * @param hash The info_hash to drop.
-			 * @return true if torrent's database was dropped or no longer exists. otherwise false (shouldn't happen - critical)
-			 */
-			virtual bool removeTorrent(uint8_t hash[20]);
+            /**
+             * Removes a torrent from the database. should be used only for non-dynamic trackers or by cleanup.
+             * @param hash The info_hash to drop.
+             * @return true if torrent's database was dropped or no longer exists. otherwise false (shouldn't happen - critical)
+             */
+            virtual bool removeTorrent(uint8_t hash[20]);
 
-			/**
-			 * Checks if the Database is acting as a dynamic tracker DB.
-			 * @return true if dynamic. otherwise false.
-			 */
-			bool isDynamic();
+            /**
+             * Checks if the Database is acting as a dynamic tracker DB.
+             * @return true if dynamic. otherwise false.
+             */
+            bool isDynamic();
 
-			/**
-			 * Checks if the torrent can be used in the tracker.
-			 * @param info_hash The torrent's info_hash.
-			 * @return true if allowed. otherwise false.
-			 */
-			virtual bool isTorrentAllowed(uint8_t info_hash [20]);
+            /**
+             * Checks if the torrent can be used in the tracker.
+             * @param info_hash The torrent's info_hash.
+             * @return true if allowed. otherwise false.
+             */
+            virtual bool isTorrentAllowed(uint8_t info_hash [20]);
 
-			/**
-			 * Generate a Connection ID for the peer.
-			 * @param connectionId (Output) the generated connection ID.
-			 * @param ip The peer's IP (requesting peer. not remote)
-			 * @param port The peer's IP (remote port if tracker accepts)
-			 * @return
-			 */
-			virtual bool genConnectionId(uint64_t *connectionId, uint32_t ip, uint16_t port);
+            /**
+             * Generate a Connection ID for the peer.
+             * @param connectionId (Output) the generated connection ID.
+             * @param ip The peer's IP (requesting peer. not remote)
+             * @param port The peer's IP (remote port if tracker accepts)
+             * @return
+             */
+            virtual bool genConnectionId(uint64_t *connectionId, uint32_t ip, uint16_t port);
 
-			virtual bool verifyConnectionId(uint64_t connectionId, uint32_t ip, uint16_t port);
+            virtual bool verifyConnectionId(uint64_t connectionId, uint32_t ip, uint16_t port);
 
-			/**
-			 * Updates/Adds a peer to/in the database.
-			 * @param peer_id the peer's peer_id
-			 * @param info_hash the torrent info_hash
-			 * @param ip IP of peer (remote ip if tracker accepts)
-			 * @param port TCP port of peer (remote port if tracker accepts)
-			 * @param downloaded total Bytes downloaded
-			 * @param left total bytes left
-			 * @param uploaded total bytes uploaded
-			 * @return true on success, false on failure.
-			 */
-			virtual bool updatePeer(uint8_t peer_id [20], uint8_t info_hash [20],
-					uint32_t ip, uint16_t port,
-					int64_t downloaded, int64_t left, int64_t uploaded,
-					enum TrackerEvents event);
+            /**
+             * Updates/Adds a peer to/in the database.
+             * @param peer_id the peer's peer_id
+             * @param info_hash the torrent info_hash
+             * @param ip IP of peer (remote ip if tracker accepts)
+             * @param port TCP port of peer (remote port if tracker accepts)
+             * @param downloaded total Bytes downloaded
+             * @param left total bytes left
+             * @param uploaded total bytes uploaded
+             * @return true on success, false on failure.
+             */
+            virtual bool updatePeer(uint8_t peer_id [20], uint8_t info_hash [20],
+                    uint32_t ip, uint16_t port,
+                    int64_t downloaded, int64_t left, int64_t uploaded,
+                    enum TrackerEvents event);
 
-			/**
-			 * Remove a peer from a torrent (if stop action occurred, or if peer is inactive in cleanup)
-			 * @param peer_id The peer's peer_id
-			 * @param info_hash Torrent's info_hash
-			 * @param ip The IP of the peer (remote IP if tracker accepts)
-			 * @param port The TCP port (remote port if tracker accepts)
-			 * @return true on success. false on failure (shouldn't happen - critical)
-			 */
-			virtual bool removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port);
+            /**
+             * Remove a peer from a torrent (if stop action occurred, or if peer is inactive in cleanup)
+             * @param peer_id The peer's peer_id
+             * @param info_hash Torrent's info_hash
+             * @param ip The IP of the peer (remote IP if tracker accepts)
+             * @param port The TCP port (remote port if tracker accepts)
+             * @return true on success. false on failure (shouldn't happen - critical)
+             */
+            virtual bool removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port);
 
-			/**
-			 * Gets stats on a torrent
-			 * @param e TorrentEntry, only this info_hash has to be set
-			 * @return true on success, false on failure.
-			 */
-			virtual bool getTorrentInfo(TorrentEntry *e);
+            /**
+             * Gets stats on a torrent
+             * @param e TorrentEntry, only this info_hash has to be set
+             * @return true on success, false on failure.
+             */
+            virtual bool getTorrentInfo(TorrentEntry *e);
 
-			/**
-			 * Gets a list of peers from the database.
-			 * @param info_hash The torrent's info_hash
-			 * @param max_count The maximum amount of peers to load from the database. The amount of loaded peers is returned through this variable.
-			 * @param pe The list of peers. Must be pre-allocated to the size of max_count.
-			 * @return true on success, otherwise false (shouldn't happen).
-			 */
-			virtual bool getPeers(uint8_t info_hash [20], int *max_count, PeerEntry *pe);
+            /**
+             * Gets a list of peers from the database.
+             * @param info_hash The torrent's info_hash
+             * @param max_count The maximum amount of peers to load from the database. The amount of loaded peers is returned through this variable.
+             * @param pe The list of peers. Must be pre-allocated to the size of max_count.
+             * @return true on success, otherwise false (shouldn't happen).
+             */
+            virtual bool getPeers(uint8_t info_hash [20], int *max_count, PeerEntry *pe);
 
-			/**
-			 * Cleanup the database.
-			 * Other actions may be locked when using this depending on the driver.
-			 */
-			virtual void cleanup();
+            /**
+             * Cleanup the database.
+             * Other actions may be locked when using this depending on the driver.
+             */
+            virtual void cleanup();
 
-			/**
-			 * Closes the connections, and releases all other resources.
-			 */
-			virtual ~DatabaseDriver();
+            /**
+             * Closes the connections, and releases all other resources.
+             */
+            virtual ~DatabaseDriver();
 
-		protected:
-			const boost::program_options::variables_map& m_conf;
-		private:
-			bool is_dynamic;
-		};
-	};
+        protected:
+            const boost::program_options::variables_map& m_conf;
+        private:
+            bool is_dynamic;
+        };
+    };
 };
 
 
diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp
index 78f3706..36374fd 100644
--- a/src/db/driver_sqlite.cpp
+++ b/src/db/driver_sqlite.cpp
@@ -1,431 +1,435 @@
-/*
- *	Copyright © 2012-2016 Naim A.
- *
- *	This file is part of UDPT.
- *
- *		UDPT is free software: you can redistribute it and/or modify
- *		it under the terms of the GNU General Public License as published by
- *		the Free Software Foundation, either version 3 of the License, or
- *		(at your option) any later version.
- *
- *		UDPT 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 UDPT.  If not, see .
- */
-
-#include "driver_sqlite.hpp"
-#include "../tools.h"
-#include 
-#include 
-#include 
-#include 
-#include 
-#include  // memcpy
-#include "../multiplatform.h"
-
-using namespace std;
-
-namespace UDPT
-{
-	namespace Data
-	{
-		static const char hexadecimal[] = "0123456789abcdef";
-
-		static char* _to_hex_str (const uint8_t *hash, char *data)
-		{
-			int i;
-			for (i = 0;i < 20;i++)
-			{
-				data[i * 2] = hexadecimal[hash[i] / 16];
-				data[i * 2 + 1] = hexadecimal[hash[i] % 16];
-			}
-			data[40] = '\0';
-			return data;
-		}
-
-		static uint8_t* _hash_to_bin (const char *hash, uint8_t *data)
-		{
-			for (int i = 0;i < 20;i++)
-			{
-				data [i] = 0;
-				char a = hash[i * 2];
-				char b = hash[i * 2 + 1];
-
-				assert ( (a >= 'a' && a <= 'f') || (a >= '0' && a <= '9') );
-				assert ( (b >= 'a' && b <= 'f') || (b >= '0' && b <= '9') );
-
-				data[i] = ( (a >= '0' && a <= 'f') ? (a - '0') : (a - 'f' + 10) );
-				data[i] <<= 4;
-				data[i] = ( (b >= '0' && b <= 'f') ? (b - '0') : (b - 'f' + 10) );
-			}
-
-			return data;
-		}
-
-		SQLite3Driver::SQLite3Driver(const boost::program_options::variables_map& conf, bool isDyn) : DatabaseDriver(conf, isDyn), m_logger(boost::log::keywords::channel="SQLite3")
-		{
-			int r;
-			bool doSetup;
-
-			fstream fCheck;
-			string filename = m_conf["db.param"].as();
-
-			fCheck.open(filename.c_str(), ios::binary | ios::in);
-			if (fCheck.is_open())
-			{
-				doSetup = false;
-				fCheck.close();
-			}
-			else
-				doSetup = true;
-
-			r = sqlite3_open(filename.c_str(), &this->db);
-			if (r != SQLITE_OK)
-			{
-				sqlite3_close(this->db);
-				throw DatabaseException (DatabaseException::E_CONNECTION_FAILURE);
-			}
-
-			if (doSetup)
-				this->doSetup();
-		}
-
-		void SQLite3Driver::doSetup()
-		{
-			char *eMsg = NULL;
-			// for quicker stats.
-			sqlite3_exec(this->db, "CREATE TABLE stats ("
-					"info_hash blob(20) UNIQUE,"
-					"completed INTEGER DEFAULT 0,"
-					"leechers INTEGER DEFAULT 0,"
-					"seeders INTEGER DEFAULT 0,"
-					"last_mod INTEGER DEFAULT 0"
-					")", NULL, NULL, &eMsg);
-
-			sqlite3_exec(this->db, "CREATE TABLE torrents ("
-					"info_hash blob(20) UNIQUE,"
-					"created INTEGER"
-					")", NULL, NULL, &eMsg);
-		}
-
-		bool SQLite3Driver::getTorrentInfo(TorrentEntry *e)
-		{
-			bool gotInfo = false;
-
-			const char sql[] = "SELECT seeders,leechers,completed FROM 'stats' WHERE info_hash=?";
-			sqlite3_stmt *stmt;
-
-			e->seeders = 0;
-			e->leechers = 0;
-			e->completed = 0;
-
-
-			sqlite3_prepare (this->db, sql, -1, &stmt, NULL);
-			sqlite3_bind_blob (stmt, 1, (void*)e->info_hash, 20, NULL);
-
-			if (sqlite3_step(stmt) == SQLITE_ROW)
-			{
-				e->seeders = sqlite3_column_int (stmt, 0);
-				e->leechers = sqlite3_column_int (stmt, 1);
-				e->completed = sqlite3_column_int (stmt, 2);
-
-				gotInfo = true;
-			}
-
-			sqlite3_finalize (stmt);
-
-			return gotInfo;
-		}
-
-		bool SQLite3Driver::getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe)
-		{
-			string sql;
-			char hash [50];
-			sqlite3_stmt *stmt;
-			int r, i;
-
-			to_hex_str(info_hash, hash);
-
-			sql = "SELECT ip,port FROM 't";
-			sql += hash;
-			sql += "' LIMIT ?";
-
-			sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL);
-			sqlite3_bind_int(stmt, 1, *max_count);
-
-			i = 0;
-			while (*max_count > i)
-			{
-				r = sqlite3_step(stmt);
-				if (r == SQLITE_ROW)
-				{
-					const char *ip = (const char*)sqlite3_column_blob (stmt, 0);
-					const char *port = (const char*)sqlite3_column_blob (stmt, 1);
-
-					memcpy(&pe[i].ip, ip, 4);
-					memcpy(&pe[i].port, port, 2);
-
-					i++;
-				}
-				else
-				{
-					break;
-				}
-			}
-
-			BOOST_LOG_SEV(m_logger, boost::log::trivial::debug) << "Retrieved " << i << " peers";
-
-			sqlite3_finalize(stmt);
-
-			*max_count = i;
-
-			return true;
-		}
-
-		bool SQLite3Driver::updatePeer(uint8_t peer_id[20], uint8_t info_hash[20], uint32_t ip, uint16_t port, int64_t downloaded, int64_t left, int64_t uploaded, enum TrackerEvents event)
-		{
-			char xHash [50]; // we just need 40 + \0 = 41.
-			sqlite3_stmt *stmt;
-			string sql;
-			int r;
-
-			char *hash = xHash;
-			to_hex_str(info_hash, hash);
-
-			addTorrent (info_hash);
-
-
-			sql = "REPLACE INTO 't";
-			sql += hash;
-			sql += "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)";
-
-			sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL);
-
-			sqlite3_bind_blob(stmt, 1, (void*)peer_id, 20, NULL);
-			sqlite3_bind_blob(stmt, 2, (void*)&ip, 4, NULL);
-			sqlite3_bind_blob(stmt, 3, (void*)&port, 2, NULL);
-			sqlite3_bind_blob(stmt, 4, (void*)&uploaded, 8, NULL);
-			sqlite3_bind_blob(stmt, 5, (void*)&downloaded, 8, NULL);
-			sqlite3_bind_blob(stmt, 6, (void*)&left, 8, NULL);
-			sqlite3_bind_int(stmt, 7, time(NULL));
-
-			r = sqlite3_step(stmt);
-			sqlite3_finalize(stmt);
-
-			sql = "REPLACE INTO stats (info_hash,last_mod) VALUES (?,?)";
-			sqlite3_prepare (this->db, sql.c_str(), sql.length(), &stmt, NULL);
-			sqlite3_bind_blob (stmt, 1, hash, 20, NULL);
-			sqlite3_bind_int (stmt, 2, time(NULL));
-			sqlite3_step (stmt);
-			sqlite3_finalize (stmt);
-
-			return r;
-		}
-
-		bool SQLite3Driver::addTorrent (uint8_t info_hash[20])
-		{
-			char xHash [41];
-			char *err_msg;
-			int r;
-
-			_to_hex_str(info_hash, xHash);
-
-			sqlite3_stmt *stmt;
-			sqlite3_prepare(this->db, "INSERT INTO torrents (info_hash,created) VALUES (?,?)", -1, &stmt, NULL);
-			sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL);
-			sqlite3_bind_int(stmt, 2, time(NULL));
-			sqlite3_step(stmt);
-			sqlite3_finalize(stmt);
-
-			string sql = "CREATE TABLE IF NOT EXISTS 't";
-			sql += xHash;
-			sql += "' (";
-			sql += "peer_id blob(20),"
-					"ip blob(4),"
-					"port blob(2),"
-					"uploaded blob(8)," // uint64
-					"downloaded blob(8),"
-					"left blob(8),"
-					"last_seen INT DEFAULT 0";
-
-			sql += ", CONSTRAINT c1 UNIQUE (ip,port) ON CONFLICT REPLACE)";
-
-			// create table.
-			r = sqlite3_exec(this->db, sql.c_str(), NULL, NULL, &err_msg);
-
-			if (SQLITE_OK == r)
-			{
-				BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Added torrent";
-				return true;
-			}
-			else
-			{
-				BOOST_LOG_SEV(m_logger, boost::log::trivial::error) << "Failed to add torrent: SQLite3 error code = " << r;
-				return false;
-			}
-		}
-
-		bool SQLite3Driver::isTorrentAllowed(uint8_t *info_hash)
-		{
-			if (this->isDynamic())
-				return true;
-			sqlite3_stmt *stmt;
-			sqlite3_prepare(this->db, "SELECT COUNT(*) FROM torrents WHERE info_hash=?", -1, &stmt, NULL);
-			sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL);
-			sqlite3_step(stmt);
-
-			int n = sqlite3_column_int(stmt, 0);
-			sqlite3_finalize(stmt);
-
-			return (n == 1);
-		}
-
-		void SQLite3Driver::cleanup()
-		{
-			int exp = time (NULL) - 7200;	// 2 hours,  expired.
-
-			// drop all peers with no activity for 2 hours.
-			sqlite3_stmt *getTables;
-			// torrent table names: t
-			sqlite3_prepare(this->db, "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 't________________________________________'", -1, &getTables, NULL);
-
-			uint8_t buff [20];
-			sqlite3_stmt *updateStats;
-			assert (sqlite3_prepare(this->db, "REPLACE INTO stats (info_hash,seeders,leechers,last_mod) VALUES (?,?,?,?)", -1, &updateStats, NULL) == SQLITE_OK);
-
-
-			while (sqlite3_step(getTables) == SQLITE_ROW)
-			{
-				char* tblN = (char*)sqlite3_column_text(getTables, 0);
-				stringstream sStr;
-				sStr << "DELETE FROM " << tblN << " WHERE last_seen<" << exp;
-
-				assert (sqlite3_exec(this->db, sStr.str().c_str(), NULL, NULL, NULL) == SQLITE_OK);
-
-				sStr.str (string());
-				sStr << "SELECT left,COUNT(*) FROM " << tblN << " GROUP BY left==0";
-
-				sqlite3_stmt *collectStats;
-
-				sqlite3_prepare(this->db, sStr.str().c_str(), sStr.str().length(), &collectStats, NULL);
-
-				if (sqlite3_errcode(this->db) != SQLITE_OK)
-				{
-					// TODO: Log this error
-				}
-
-				int seeders = 0, leechers = 0;
-				while (sqlite3_step(collectStats) == SQLITE_ROW) // expecting two results.
-				{
-					if (sqlite3_column_int(collectStats, 0) == 0)
-						seeders = sqlite3_column_int (collectStats, 1);
-					else
-						leechers = sqlite3_column_int (collectStats, 1);
-				}
-				sqlite3_finalize(collectStats);
-
-				sqlite3_bind_blob(updateStats, 1, _hash_to_bin((const char*)(tblN + 1), buff), 20, NULL);
-				sqlite3_bind_int(updateStats, 2, seeders);
-				sqlite3_bind_int(updateStats, 3, leechers);
-				sqlite3_bind_int(updateStats, 4, time (NULL));
-
-				sqlite3_step(updateStats);
-				sqlite3_reset (updateStats);
-			}
-			sqlite3_finalize(updateStats);
-			sqlite3_finalize(getTables);
-		}
-
-		bool SQLite3Driver::removeTorrent(uint8_t info_hash[20])
-		{
-			// if non-dynamic, remove from table
-			sqlite3_stmt *stmt;
-			sqlite3_prepare(this->db, "DELETE FROM torrents WHERE info_hash=?", -1, &stmt, NULL);
-			sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL);
-			sqlite3_step(stmt);
-			sqlite3_finalize(stmt);
-
-			// remove from stats
-			sqlite3_stmt *rmS;
-			if (sqlite3_prepare(this->db, "DELETE FROM stats WHERE info_hash=?", -1, &rmS, NULL) != SQLITE_OK)
-			{
-				sqlite3_finalize(rmS);
-				return false;
-			}
-			sqlite3_bind_blob(rmS, 1, (const void*)info_hash, 20, NULL);
-			sqlite3_step(rmS);
-			sqlite3_finalize(rmS);
-
-			// remove table
-			string str = "DROP TABLE IF EXISTS 't";
-			char buff [41];
-			str += _to_hex_str(info_hash, buff);
-			str += "'";
-
-			sqlite3_exec(this->db, str.c_str(), NULL, NULL, NULL);
-
-			BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Torrent removed.";
-
-			return true;
-		}
-
-		bool SQLite3Driver::removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port)
-		{
-			string sql;
-			char xHash [50];
-			sqlite3_stmt *stmt;
-
-			_to_hex_str (info_hash, xHash);
-
-			sql += "DELETE FROM 't";
-			sql += xHash;
-			sql += "' WHERE ip=? AND port=? AND peer_id=?";
-
-			sqlite3_prepare (this->db, sql.c_str(), sql.length(), &stmt, NULL);
-
-			sqlite3_bind_blob(stmt, 0, (const void*)&ip, 4, NULL);
-			sqlite3_bind_blob(stmt, 1, (const void*)&port, 2, NULL);
-			sqlite3_bind_blob(stmt, 2, (const void*)peer_id, 20, NULL);
-
-			sqlite3_step(stmt);
-
-			sqlite3_finalize(stmt);
-
-			return true;
-		}
-
-	static uint64_t _genCiD (uint32_t ip, uint16_t port)
-	{
-		uint64_t x;
-		x = (time(NULL) / 3600) * port;	// x will probably overload.
-		x = (ip ^ port);
-		x <<= 16;
-		x |= (~port);
-		return x;
-	}
-
-		bool SQLite3Driver::genConnectionId (uint64_t *connectionId, uint32_t ip, uint16_t port)
-		{
-			*connectionId = _genCiD(ip, port);
-			return true;
-		}
-
-		bool SQLite3Driver::verifyConnectionId(uint64_t cId, uint32_t ip, uint16_t port)
-		{
-			if (cId == _genCiD(ip, port))
-				return true;
-			else
-				return false;
-		}
-
-		SQLite3Driver::~SQLite3Driver()
-		{
-			BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Closing SQLite";
-			sqlite3_close(this->db);
-		}
-	};
-};
+/*
+ *	Copyright © 2012-2017 Naim A.
+ *
+ *	This file is part of UDPT.
+ *
+ *		UDPT is free software: you can redistribute it and/or modify
+ *		it under the terms of the GNU General Public License as published by
+ *		the Free Software Foundation, either version 3 of the License, or
+ *		(at your option) any later version.
+ *
+ *		UDPT 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 UDPT.  If not, see .
+ */
+
+#include "driver_sqlite.hpp"
+#include "../tools.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include  // memcpy
+#include "../multiplatform.h"
+#include "../logging.hpp"
+
+using namespace std;
+
+namespace UDPT
+{
+    namespace Data
+    {
+        static const char hexadecimal[] = "0123456789abcdef";
+
+        static char* _to_hex_str (const uint8_t *hash, char *data)
+        {
+            int i;
+            for (i = 0;i < 20;i++)
+            {
+                data[i * 2] = hexadecimal[hash[i] / 16];
+                data[i * 2 + 1] = hexadecimal[hash[i] % 16];
+            }
+            data[40] = '\0';
+            return data;
+        }
+
+        static uint8_t* _hash_to_bin (const char *hash, uint8_t *data)
+        {
+            for (int i = 0;i < 20;i++)
+            {
+                data [i] = 0;
+                char a = hash[i * 2];
+                char b = hash[i * 2 + 1];
+
+                assert ( (a >= 'a' && a <= 'f') || (a >= '0' && a <= '9') );
+                assert ( (b >= 'a' && b <= 'f') || (b >= '0' && b <= '9') );
+
+                data[i] = ( (a >= '0' && a <= 'f') ? (a - '0') : (a - 'f' + 10) );
+                data[i] <<= 4;
+                data[i] = ( (b >= '0' && b <= 'f') ? (b - '0') : (b - 'f' + 10) );
+            }
+
+            return data;
+        }
+
+        SQLite3Driver::SQLite3Driver(const boost::program_options::variables_map& conf, bool isDyn) : DatabaseDriver(conf, isDyn)
+        {
+            int r;
+            bool doSetup;
+
+            fstream fCheck;
+            string filename = m_conf["db.param"].as();
+
+            fCheck.open(filename.c_str(), ios::binary | ios::in);
+            if (fCheck.is_open())
+            {
+                doSetup = false;
+                fCheck.close();
+            }
+            else
+                doSetup = true;
+
+            r = sqlite3_open(filename.c_str(), &this->db);
+            if (r != SQLITE_OK)
+            {
+                LOG_FATAL("db-sqlite", "Failed to connect DB. sqlite returned " << r);
+                sqlite3_close(this->db);
+                throw DatabaseException (DatabaseException::E_CONNECTION_FAILURE);
+            }
+
+            if (doSetup)
+                this->doSetup();
+        }
+
+        void SQLite3Driver::doSetup()
+        {
+            char *eMsg = NULL;
+            LOG_INFO("db-sqlite", "Setting up database...");
+            // for quicker stats.
+            sqlite3_exec(this->db, "CREATE TABLE stats ("
+                    "info_hash blob(20) UNIQUE,"
+                    "completed INTEGER DEFAULT 0,"
+                    "leechers INTEGER DEFAULT 0,"
+                    "seeders INTEGER DEFAULT 0,"
+                    "last_mod INTEGER DEFAULT 0"
+                    ")", NULL, NULL, &eMsg);
+
+            sqlite3_exec(this->db, "CREATE TABLE torrents ("
+                    "info_hash blob(20) UNIQUE,"
+                    "created INTEGER"
+                    ")", NULL, NULL, &eMsg);
+        }
+
+        bool SQLite3Driver::getTorrentInfo(TorrentEntry *e)
+        {
+            bool gotInfo = false;
+
+            const char sql[] = "SELECT seeders,leechers,completed FROM 'stats' WHERE info_hash=?";
+            sqlite3_stmt *stmt;
+
+            e->seeders = 0;
+            e->leechers = 0;
+            e->completed = 0;
+
+
+            sqlite3_prepare (this->db, sql, -1, &stmt, NULL);
+            sqlite3_bind_blob (stmt, 1, (void*)e->info_hash, 20, NULL);
+
+            if (sqlite3_step(stmt) == SQLITE_ROW)
+            {
+                e->seeders = sqlite3_column_int (stmt, 0);
+                e->leechers = sqlite3_column_int (stmt, 1);
+                e->completed = sqlite3_column_int (stmt, 2);
+
+                gotInfo = true;
+            }
+
+            sqlite3_finalize (stmt);
+
+            return gotInfo;
+        }
+
+        bool SQLite3Driver::getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe)
+        {
+            string sql;
+            char hash [50];
+            sqlite3_stmt *stmt;
+            int r, i;
+
+            to_hex_str(info_hash, hash);
+
+            sql = "SELECT ip,port FROM 't";
+            sql += hash;
+            sql += "' LIMIT ?";
+
+            sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL);
+            sqlite3_bind_int(stmt, 1, *max_count);
+
+            i = 0;
+            while (*max_count > i)
+            {
+                r = sqlite3_step(stmt);
+                if (r == SQLITE_ROW)
+                {
+                    const char *ip = (const char*)sqlite3_column_blob (stmt, 0);
+                    const char *port = (const char*)sqlite3_column_blob (stmt, 1);
+
+                    memcpy(&pe[i].ip, ip, 4);
+                    memcpy(&pe[i].port, port, 2);
+
+                    i++;
+                }
+                else
+                {
+                    break;
+                }
+            }
+
+            sqlite3_finalize(stmt);
+
+            *max_count = i;
+
+            return true;
+        }
+
+        bool SQLite3Driver::updatePeer(uint8_t peer_id[20], uint8_t info_hash[20], uint32_t ip, uint16_t port, int64_t downloaded, int64_t left, int64_t uploaded, enum TrackerEvents event)
+        {
+            char xHash [50]; // we just need 40 + \0 = 41.
+            sqlite3_stmt *stmt;
+            string sql;
+            int r;
+
+            char *hash = xHash;
+            to_hex_str(info_hash, hash);
+
+            addTorrent (info_hash);
+
+
+            sql = "REPLACE INTO 't";
+            sql += hash;
+            sql += "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)";
+
+            sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL);
+
+            sqlite3_bind_blob(stmt, 1, (void*)peer_id, 20, NULL);
+            sqlite3_bind_blob(stmt, 2, (void*)&ip, 4, NULL);
+            sqlite3_bind_blob(stmt, 3, (void*)&port, 2, NULL);
+            sqlite3_bind_blob(stmt, 4, (void*)&uploaded, 8, NULL);
+            sqlite3_bind_blob(stmt, 5, (void*)&downloaded, 8, NULL);
+            sqlite3_bind_blob(stmt, 6, (void*)&left, 8, NULL);
+            sqlite3_bind_int(stmt, 7, time(NULL));
+
+            r = sqlite3_step(stmt);
+            sqlite3_finalize(stmt);
+
+            sql = "REPLACE INTO stats (info_hash,last_mod) VALUES (?,?)";
+            sqlite3_prepare (this->db, sql.c_str(), sql.length(), &stmt, NULL);
+            sqlite3_bind_blob (stmt, 1, hash, 20, NULL);
+            sqlite3_bind_int (stmt, 2, time(NULL));
+            sqlite3_step (stmt);
+            sqlite3_finalize (stmt);
+
+            return r;
+        }
+
+        bool SQLite3Driver::addTorrent (uint8_t info_hash[20])
+        {
+            char xHash [41];
+            char *err_msg;
+            int r;
+
+            _to_hex_str(info_hash, xHash);
+
+            sqlite3_stmt *stmt;
+            sqlite3_prepare(this->db, "INSERT INTO torrents (info_hash,created) VALUES (?,?)", -1, &stmt, NULL);
+            sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL);
+            sqlite3_bind_int(stmt, 2, time(NULL));
+            sqlite3_step(stmt);
+            sqlite3_finalize(stmt);
+
+            string sql = "CREATE TABLE IF NOT EXISTS 't";
+            sql += xHash;
+            sql += "' (";
+            sql += "peer_id blob(20),"
+                    "ip blob(4),"
+                    "port blob(2),"
+                    "uploaded blob(8)," // uint64
+                    "downloaded blob(8),"
+                    "left blob(8),"
+                    "last_seen INT DEFAULT 0";
+
+            sql += ", CONSTRAINT c1 UNIQUE (ip,port) ON CONFLICT REPLACE)";
+
+            // create table.
+            r = sqlite3_exec(this->db, sql.c_str(), NULL, NULL, &err_msg);
+
+            if (SQLITE_OK == r)
+            {
+                return true;
+            }
+            else
+            {
+                return false;
+            }
+        }
+
+        bool SQLite3Driver::isTorrentAllowed(uint8_t *info_hash)
+        {
+            if (this->isDynamic())
+                return true;
+            sqlite3_stmt *stmt;
+            sqlite3_prepare(this->db, "SELECT COUNT(*) FROM torrents WHERE info_hash=?", -1, &stmt, NULL);
+            sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL);
+            sqlite3_step(stmt);
+
+            int n = sqlite3_column_int(stmt, 0);
+            sqlite3_finalize(stmt);
+
+            return (n == 1);
+        }
+
+        void SQLite3Driver::cleanup()
+        {
+            LOG_INFO("db-sqlite", "Cleaning up...");
+            int exp = time (NULL) - 7200;	// 2 hours,  expired.
+            int r = 0;
+
+            // drop all peers with no activity for 2 hours.
+            sqlite3_stmt *getTables;
+            // torrent table names: t
+            r = sqlite3_prepare(this->db, "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 't________________________________________'", -1, &getTables, NULL);
+            if (r != SQLITE_OK) {
+                LOG_ERR("db-sqlite", "Failed fetch tables from DB for cleanup.");
+                return;
+            }
+
+            uint8_t buff [20];
+            sqlite3_stmt *updateStats;
+            r = sqlite3_prepare(this->db, "REPLACE INTO stats (info_hash,seeders,leechers,last_mod) VALUES (?,?,?,?)", -1, &updateStats, NULL);
+            if (r != SQLITE_OK) {
+                LOG_ERR("db-sqlite", "Failed to prepare update stats query.");
+                return;
+            }
+
+            while (sqlite3_step(getTables) == SQLITE_ROW)
+            {
+                char* tblN = (char*)sqlite3_column_text(getTables, 0);
+                stringstream sStr;
+                sStr << "DELETE FROM " << tblN << " WHERE last_seen<" << exp;
+
+                r = sqlite3_exec(this->db, sStr.str().c_str(), NULL, NULL, NULL);
+                if (r != SQLITE_OK) {
+                    LOG_ERR("db-sqlite", "Failed to execute cleanup for table '" << tblN << "'.");
+                    continue;
+                }
+
+                sStr.str (string());
+                sStr << "SELECT left,COUNT(*) FROM " << tblN << " GROUP BY left==0";
+
+                sqlite3_stmt *collectStats;
+
+                r = sqlite3_prepare(this->db, sStr.str().c_str(), sStr.str().length(), &collectStats, NULL);
+
+                if (r != SQLITE_OK)
+                {
+                    LOG_ERR("db-sqlite", "Failed while trying to prepare stats query for '" << tblN << "', sqlite returned " << r);
+                    continue;
+                }
+
+                int seeders = 0, leechers = 0;
+                while (sqlite3_step(collectStats) == SQLITE_ROW) // expecting two results.
+                {
+                    if (sqlite3_column_int(collectStats, 0) == 0)
+                        seeders = sqlite3_column_int (collectStats, 1);
+                    else
+                        leechers = sqlite3_column_int (collectStats, 1);
+                }
+                sqlite3_finalize(collectStats);
+
+                sqlite3_bind_blob(updateStats, 1, _hash_to_bin((const char*)(tblN + 1), buff), 20, NULL);
+                sqlite3_bind_int(updateStats, 2, seeders);
+                sqlite3_bind_int(updateStats, 3, leechers);
+                sqlite3_bind_int(updateStats, 4, time (NULL));
+
+                sqlite3_step(updateStats);
+                sqlite3_reset (updateStats);
+            }
+            sqlite3_finalize(updateStats);
+            sqlite3_finalize(getTables);
+        }
+
+        bool SQLite3Driver::removeTorrent(uint8_t info_hash[20]) {
+            // if non-dynamic, remove from table
+            sqlite3_stmt *stmt;
+            sqlite3_prepare(this->db, "DELETE FROM torrents WHERE info_hash=?", -1, &stmt, NULL);
+            sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL);
+            sqlite3_step(stmt);
+            sqlite3_finalize(stmt);
+
+            // remove from stats
+            sqlite3_stmt *rmS;
+            if (sqlite3_prepare(this->db, "DELETE FROM stats WHERE info_hash=?", -1, &rmS, NULL) != SQLITE_OK)
+            {
+                sqlite3_finalize(rmS);
+                return false;
+            }
+            sqlite3_bind_blob(rmS, 1, (const void*)info_hash, 20, NULL);
+            sqlite3_step(rmS);
+            sqlite3_finalize(rmS);
+
+            // remove table
+            string str = "DROP TABLE IF EXISTS 't";
+            char buff [41];
+            str += _to_hex_str(info_hash, buff);
+            str += "'";
+
+            sqlite3_exec(this->db, str.c_str(), NULL, NULL, NULL);
+
+            return true;
+        }
+
+        bool SQLite3Driver::removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port) {
+            string sql;
+            char xHash [50];
+            sqlite3_stmt *stmt;
+
+            _to_hex_str (info_hash, xHash);
+
+            sql += "DELETE FROM 't";
+            sql += xHash;
+            sql += "' WHERE ip=? AND port=? AND peer_id=?";
+
+            sqlite3_prepare (this->db, sql.c_str(), sql.length(), &stmt, NULL);
+
+            sqlite3_bind_blob(stmt, 0, (const void*)&ip, 4, NULL);
+            sqlite3_bind_blob(stmt, 1, (const void*)&port, 2, NULL);
+            sqlite3_bind_blob(stmt, 2, (const void*)peer_id, 20, NULL);
+
+            sqlite3_step(stmt);
+
+            sqlite3_finalize(stmt);
+
+            return true;
+        }
+
+        static uint64_t _genCiD (uint32_t ip, uint16_t port) {
+            uint64_t x;
+            x = (time(NULL) / 3600) * port;	// x will probably overload.
+            x = (ip ^ port);
+            x <<= 16;
+            x |= (~port);
+            return x;
+        }
+
+        bool SQLite3Driver::genConnectionId (uint64_t *connectionId, uint32_t ip, uint16_t port) {
+            *connectionId = _genCiD(ip, port);
+            return true;
+        }
+
+        bool SQLite3Driver::verifyConnectionId(uint64_t cId, uint32_t ip, uint16_t port) {
+            if (cId == _genCiD(ip, port))
+                return true;
+            else
+                return false;
+        }
+
+        SQLite3Driver::~SQLite3Driver() {
+            sqlite3_close(this->db);
+        }
+    };
+};
diff --git a/src/db/driver_sqlite.hpp b/src/db/driver_sqlite.hpp
index 55f7014..07421dc 100644
--- a/src/db/driver_sqlite.hpp
+++ b/src/db/driver_sqlite.hpp
@@ -1,56 +1,55 @@
-/*
- *	Copyright © 2012-2016 Naim A.
- *
- *	This file is part of UDPT.
- *
- *		UDPT is free software: you can redistribute it and/or modify
- *		it under the terms of the GNU General Public License as published by
- *		the Free Software Foundation, either version 3 of the License, or
- *		(at your option) any later version.
- *
- *		UDPT 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 UDPT.  If not, see .
- */
-
-#ifndef DATABASE_H_
-#define DATABASE_H_
-
-#include 
-#include "database.hpp"
-#include 
-
-namespace UDPT
-{
-	namespace Data
-	{
-		class SQLite3Driver : public DatabaseDriver
-		{
-		public:
-			SQLite3Driver(const boost::program_options::variables_map& conf, bool isDyn = false);
-			bool addTorrent(uint8_t info_hash[20]);
-			bool removeTorrent(uint8_t info_hash[20]);
-			bool genConnectionId(uint64_t *connId, uint32_t ip, uint16_t port);
-			bool verifyConnectionId(uint64_t connId, uint32_t ip, uint16_t port);
-			bool updatePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port, int64_t downloaded, int64_t left, int64_t uploaded, enum TrackerEvents event);
-			bool removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port);
-			bool getTorrentInfo(TorrentEntry *e);
-			bool isTorrentAllowed(uint8_t info_hash[20]);
-			bool getPeers(uint8_t info_hash [20], int *max_count, PeerEntry *pe);
-			void cleanup();
-
-			virtual ~SQLite3Driver();
-		private:
-			sqlite3 *db;
-			boost::log::sources::severity_channel_logger_mt<> m_logger;
-
-			void doSetup();
-		};
-	};
-};
-
-#endif /* DATABASE_H_ */
+/*
+ *	Copyright © 2012-2017 Naim A.
+ *
+ *	This file is part of UDPT.
+ *
+ *		UDPT is free software: you can redistribute it and/or modify
+ *		it under the terms of the GNU General Public License as published by
+ *		the Free Software Foundation, either version 3 of the License, or
+ *		(at your option) any later version.
+ *
+ *		UDPT 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 UDPT.  If not, see .
+ */
+
+#ifndef DATABASE_H_
+#define DATABASE_H_
+
+#include 
+#include "database.hpp"
+#include 
+
+namespace UDPT
+{
+    namespace Data
+    {
+        class SQLite3Driver : public DatabaseDriver
+        {
+        public:
+            SQLite3Driver(const boost::program_options::variables_map& conf, bool isDyn = false);
+            bool addTorrent(uint8_t info_hash[20]);
+            bool removeTorrent(uint8_t info_hash[20]);
+            bool genConnectionId(uint64_t *connId, uint32_t ip, uint16_t port);
+            bool verifyConnectionId(uint64_t connId, uint32_t ip, uint16_t port);
+            bool updatePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port, int64_t downloaded, int64_t left, int64_t uploaded, enum TrackerEvents event);
+            bool removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port);
+            bool getTorrentInfo(TorrentEntry *e);
+            bool isTorrentAllowed(uint8_t info_hash[20]);
+            bool getPeers(uint8_t info_hash [20], int *max_count, PeerEntry *pe);
+            void cleanup();
+
+            virtual ~SQLite3Driver();
+        private:
+            sqlite3 *db;
+
+            void doSetup();
+        };
+    };
+};
+
+#endif /* DATABASE_H_ */
diff --git a/src/exceptions.h b/src/exceptions.h
index 33c5213..2f52cd2 100644
--- a/src/exceptions.h
+++ b/src/exceptions.h
@@ -4,73 +4,73 @@
 
 namespace UDPT
 {
-	class UDPTException
-	{
-	public:
-		UDPTException(const char* errorMsg, int errorCode = 0) : m_error(errorMsg), m_errorCode(errorCode)
-		{
+    class UDPTException
+    {
+    public:
+        UDPTException(const char* errorMsg, int errorCode = 0) : m_error(errorMsg), m_errorCode(errorCode)
+        {
 
-		}
+        }
 
-		UDPTException(int errorCode = 0) : m_errorCode(errorCode), m_error("")
-		{
-		}
+        UDPTException(int errorCode = 0) : m_errorCode(errorCode), m_error("")
+        {
+        }
 
-		virtual const char* what() const
-		{
-			return m_error;
-		}
+        virtual const char* what() const
+        {
+            return m_error;
+        }
 
-		virtual int getErrorCode() const
-		{
-			return m_errorCode;
-		}
+        virtual int getErrorCode() const
+        {
+            return m_errorCode;
+        }
 
-		virtual ~UDPTException()
-		{
+        virtual ~UDPTException()
+        {
 
-		}
+        }
 
-	protected:
-		const char* m_error;
-		const int m_errorCode;
-	};
+    protected:
+        const char* m_error;
+        const int m_errorCode;
+    };
 
-	class OSError : public UDPTException
-	{
-	public:
-		OSError(int errorCode
+    class OSError : public UDPTException
+    {
+    public:
+        OSError(int errorCode
 #ifdef WIN32 
-			= ::GetLastError()
+            = ::GetLastError()
 #endif
-			) : UDPTException(errorCode)
-		{
-		}
+            ) : UDPTException(errorCode)
+        {
+        }
 
-		virtual ~OSError() {}
+        virtual ~OSError() {}
 
-		const char* what() const
-		{
-			if (m_errorMessage.length() > 0)
-			{
-				return m_errorMessage.c_str();
-			}
+        const char* what() const
+        {
+            if (m_errorMessage.length() > 0)
+            {
+                return m_errorMessage.c_str();
+            }
 
 #ifdef WIN32 
-			char *buffer = nullptr;
-			DWORD msgLen = ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, m_errorCode, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), reinterpret_cast(&buffer), 1, NULL);
-			std::shared_ptr formatStr = std::shared_ptr(
-				buffer,
-				::LocalFree);
-			m_errorMessage = std::string(reinterpret_cast(formatStr.get()));
+            char *buffer = nullptr;
+            DWORD msgLen = ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, m_errorCode, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), reinterpret_cast(&buffer), 1, NULL);
+            std::shared_ptr formatStr = std::shared_ptr(
+                buffer,
+                ::LocalFree);
+            m_errorMessage = std::string(reinterpret_cast(formatStr.get()));
 
-			return m_errorMessage.c_str();
+            return m_errorMessage.c_str();
 #else 
-			return "OSError";
+            return "OSError";
 #endif
-		}
-	private:
-		// allow to generate a message only when needed.
-		mutable std::string m_errorMessage;
-	};
+        }
+    private:
+        // allow to generate a message only when needed.
+        mutable std::string m_errorMessage;
+    };
 }
diff --git a/src/http/httpserver.cpp b/src/http/httpserver.cpp
index 27ac298..e4e6312 100644
--- a/src/http/httpserver.cpp
+++ b/src/http/httpserver.cpp
@@ -1,535 +1,535 @@
-/*
- *	Copyright © 2013-2016 Naim A.
- *
- *	This file is part of UDPT.
- *
- *		UDPT is free software: you can redistribute it and/or modify
- *		it under the terms of the GNU General Public License as published by
- *		the Free Software Foundation, either version 3 of the License, or
- *		(at your option) any later version.
- *
- *		UDPT 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 UDPT.  If not, see .
- */
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include "httpserver.hpp"
-#include 
-
-using namespace std;
-
-namespace UDPT
-{
-	namespace Server
-	{
-		/* HTTPServer */
-		HTTPServer::HTTPServer (uint16_t port, int threads)
-		{
-			SOCKADDR_IN sa;
-
-			memset((void*)&sa, 0, sizeof(sa));
-			sa.sin_addr.s_addr = 0L;
-			sa.sin_family = AF_INET;
-			sa.sin_port = htons (port);
-			
-			this->init(sa, threads);
-		}
-
-		HTTPServer::HTTPServer(const boost::program_options::variables_map& conf)
-		{
-			list localEndpoints;
-			uint16_t port;
-			int threads;
-
-			port = conf["apiserver.port"].as();
-			threads = conf["apiserver.threads"].as();
-
-			if (threads <= 0)
-				threads = 1;
-			
-			if (localEndpoints.empty())
-			{
-				SOCKADDR_IN sa;
-				memset((void*)&sa, 0, sizeof(sa));
-				sa.sin_family = AF_INET;
-				sa.sin_port = htons (port);
-				sa.sin_addr.s_addr = 0L;
-				localEndpoints.push_front(sa);
-			}
-
-			this->init(localEndpoints.front(), threads);
-		}
-
-		void HTTPServer::init (SOCKADDR_IN &localEndpoint, int threads)
-		{
-			int r;
-			this->thread_count = threads;
-			this->threads = new HANDLE[threads];
-			this->isRunning = false;
-
-			this->rootNode.callback = NULL;
-
-			this->srv = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
-			if (this->srv == INVALID_SOCKET)
-			{
-				throw ServerException (1, "Failed to create Socket");
-			}
-
-			r = ::bind(this->srv, (SOCKADDR*)&localEndpoint, sizeof(localEndpoint));
-			if (r == SOCKET_ERROR)
-			{
-				throw ServerException(2, "Failed to bind socket");
-			}
-
-			this->isRunning = true;
-			for (int i = 0;i < threads;i++)
-			{
-#ifdef WIN32
-				this->threads[i] = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, this, 0, NULL);
-#else
-				pthread_create (&this->threads[i], NULL, &HTTPServer::_thread_start, this);
-#endif
-			}
-		}
-
-#ifdef WIN32
-		DWORD HTTPServer::_thread_start (LPVOID arg)
-#else
-		void* HTTPServer::_thread_start (void *arg)
-#endif
-		{
-			HTTPServer *s = (HTTPServer*)arg;
-doSrv:
-			try {
-				HTTPServer::handleConnections (s);
-			} catch (const ServerException &se)
-			{
-				cerr << "SRV ERR #" << se.getErrorCode() << ": " << se.getErrorMsg () << endl;
-				goto doSrv;
-			}
-			return 0;
-		}
-
-		void HTTPServer::handleConnections (HTTPServer *server)
-		{
-			int r;
-#ifdef WIN32
-			int addrSz;
-#else
-			socklen_t addrSz;
-#endif
-			SOCKADDR_IN addr;
-			SOCKET cli;
-
-			while (server->isRunning)
-			{
-				r = ::listen(server->srv, 50);
-				if (r == SOCKET_ERROR)
-				{
-#ifdef WIN32
-					::Sleep(500);
-#else
-					::sleep(1);
-#endif
-					continue;
-				}
-				addrSz = sizeof addr;
-				cli = accept (server->srv, (SOCKADDR*)&addr, &addrSz);
-				if (cli == INVALID_SOCKET)
-					continue;
-				
-				Response resp (cli); // doesn't throw exceptions.
-
-				try {
-					Request req (cli, &addr);	// may throw exceptions.
-					reqCallback *cb = getRequestHandler (&server->rootNode, req.getPath());
-					if (cb == NULL)
-					{
-						// error 404
-						resp.setStatus (404, "Not Found");
-						resp.addHeader ("Content-Type", "text/html; charset=US-ASCII");
-						stringstream stream;
-						stream << "";
-						stream << "Not Found";
-						stream << "

Not Found

The server couldn't find the request resource.


"; - stream << ""; - string str = stream.str(); - resp.write (str.c_str(), str.length()); - } - else - { - try { - cb (server, &req, &resp); - } catch (...) - { - resp.setStatus(500, "Internal Server Error"); - resp.addHeader ("Content-Type", "text/html; charset=US-ASCII"); - stringstream stream; - stream << ""; - stream << "Internal Server Error"; - stream << "

Internal Server Error

An Error Occurred while trying to process your request.


"; - stream << ""; - string str = stream.str(); - resp.write (str.c_str(), str.length()); - } - } - resp.finalize(); - } catch (ServerException &e) - { - // Error 400 Bad Request! - } - - closesocket (cli); - } - } - - void HTTPServer::addApp (list *path, reqCallback *cb) - { - list::iterator it = path->begin(); - appNode *node = &this->rootNode; - while (it != path->end()) - { - map::iterator se; - se = node->nodes.find (*it); - if (se == node->nodes.end()) - { - node->nodes[*it].callback = NULL; - } - node = &node->nodes[*it]; - it++; - } - node->callback = cb; - } - - HTTPServer::reqCallback* HTTPServer::getRequestHandler (appNode *node, list *path) - { - appNode *cn = node; - list::iterator it = path->begin(), - end = path->end(); - map::iterator n; - while (true) - { - if (it == end) - { - return cn->callback; - } - - n = cn->nodes.find (*it); - if (n == cn->nodes.end()) - return NULL; // node not found! - cn = &n->second; - - it++; - } - return NULL; - } - - void HTTPServer::setData(string k, void *d) - { - this->customData[k] = d; - } - - void* HTTPServer::getData(string k) - { - map::iterator it = this->customData.find(k); - if (it == this->customData.end()) - return NULL; - return it->second; - } - - HTTPServer::~HTTPServer () - { - if (this->srv != INVALID_SOCKET) - closesocket (this->srv); - - if (this->isRunning) - { - for (int i = 0;i < this->thread_count;i++) - { -#ifdef WIN32 - TerminateThread (this->threads[i], 0x00); -#else - pthread_detach (this->threads[i]); - pthread_cancel (this->threads[i]); -#endif - } - } - - delete[] this->threads; - } - - /* HTTPServer::Request */ - HTTPServer::Request::Request (SOCKET cli, const SOCKADDR_IN *addr) - { - this->conn = cli; - this->addr = addr; - - this->parseRequest (); - } - - inline static char* nextReqLine (int &cPos, char *buff, int len) - { - for (int i = cPos;i < len - 1;i++) - { - if (buff[i] == '\r' && buff[i + 1] == '\n') - { - buff[i] = '\0'; - - int r = cPos; - cPos = i + 2; - return (buff + r); - } - } - - return (buff + len); // end - } - - inline void parseURL (string request, list *path, map *params) - { - string::size_type p; - string query, url; - p = request.find ('?'); - if (p == string::npos) - { - p = request.length(); - } - else - { - query = request.substr (p + 1); - } - url = request.substr (0, p); - - path->clear (); - string::size_type s, e; - s = 0; - while (true) - { - e = url.find ('/', s); - if (e == string::npos) - e = url.length(); - - string x = url.substr (s, e - s); - if (!(x.length() == 0 || x == ".")) - { - if (x == "..") - { - if (path->empty()) - throw ServerException (1, "Hack attempt"); - else - path->pop_back (); - } - path->push_back (x); - } - - if (e == url.length()) - break; - s = e + 1; - } - - string::size_type vS, vE, kS, kE; - vS = vE = kS = kE = 0; - while (kS < query.length()) - { - kE = query.find ('=', kS); - if (kE == string::npos) break; - vS = kE + 1; - vE = query.find ('&', vS); - if (vE == string::npos) vE = query.length(); - - params->insert (pair( query.substr (kS, kE - kS), query.substr (vS, vE - vS) )); - - kS = vE + 1; - } - } - - inline void setCookies (string &data, map *cookies) - { - string::size_type kS, kE, vS, vE; - kS = 0; - while (kS < data.length ()) - { - kE = data.find ('=', kS); - if (kE == string::npos) - break; - vS = kE + 1; - vE = data.find ("; ", vS); - if (vE == string::npos) - vE = data.length(); - - (*cookies) [data.substr (kS, kE-kS)] = data.substr (vS, vE-vS); - - kS = vE + 2; - } - } - - void HTTPServer::Request::parseRequest () - { - char buffer [REQUEST_BUFFER_SIZE]; - int r; - r = recv (this->conn, buffer, REQUEST_BUFFER_SIZE, 0); - if (r == REQUEST_BUFFER_SIZE) - throw ServerException (1, "Request Size too big."); - if (r <= 0) - throw ServerException (2, "Socket Error"); - - char *cLine; - int n = 0; - int pos = 0; - string::size_type p; - while ( (cLine = nextReqLine (pos, buffer, r)) < (buffer + r)) - { - string line = string (cLine); - if (line.length() == 0) break; // CRLF CRLF = end of headers. - n++; - - if (n == 1) - { - string::size_type uS, uE; - p = line.find (' '); - if (p == string::npos) - throw ServerException (5, "Malformed request method"); - uS = p + 1; - this->requestMethod.str = line.substr (0, p); - - if (this->requestMethod.str == "GET") - this->requestMethod.rm = RM_GET; - else if (this->requestMethod.str == "POST") - this->requestMethod.rm = RM_POST; - else - this->requestMethod.rm = RM_UNKNOWN; - - uE = uS; - while (p < line.length()) - { - if (p == string::npos) - break; - p = line.find (' ', p + 1); - if (p == string::npos) - break; - uE = p; - } - if (uE + 1 >= line.length()) - throw ServerException (6, "Malformed request"); - string httpVersion = line.substr (uE + 1); - - - parseURL (line.substr (uS, uE - uS), &this->path, &this->params); - } - else - { - p = line.find (": "); - if (p == string::npos) - throw ServerException (4, "Malformed headers"); - string key = line.substr (0, p); - string value = line.substr (p + 2); - if (key != "Cookie") - this->headers.insert(pair( key, value)); - else - setCookies (value, &this->cookies); - } - } - if (n == 0) - throw ServerException (3, "No Request header."); - } - - list* HTTPServer::Request::getPath () - { - return &this->path; - } - - string HTTPServer::Request::getParam (const string key) - { - map::iterator it = this->params.find (key); - if (it == this->params.end()) - return ""; - else - return it->second; - } - - multimap::iterator HTTPServer::Request::getHeader (const string name) - { - multimap::iterator it = this->headers.find (name); - return it; - } - - HTTPServer::Request::RequestMethod HTTPServer::Request::getRequestMethod () - { - return this->requestMethod.rm; - } - - string HTTPServer::Request::getRequestMethodStr () - { - return this->requestMethod.str; - } - - string HTTPServer::Request::getCookie (const string name) - { - map::iterator it = this->cookies.find (name); - if (it == this->cookies.end()) - return ""; - else - return it->second; - } - - const SOCKADDR_IN* HTTPServer::Request::getAddress () - { - return this->addr; - } - - /* HTTPServer::Response */ - HTTPServer::Response::Response (SOCKET cli) - { - this->conn = cli; - - setStatus (200, "OK"); - } - - void HTTPServer::Response::setStatus (int c, const string m) - { - this->status_code = c; - this->status_msg = m; - } - - void HTTPServer::Response::addHeader (string key, string value) - { - this->headers.insert (pair(key, value)); - } - - void HTTPServer::Response::write (const char *data, int len) - { - if (len < 0) - len = strlen (data); - msg.write(data, len); - } - - void HTTPServer::Response::finalize () - { - stringstream x; - x << "HTTP/1.1 " << this->status_code << " " << this->status_msg << "\r\n"; - multimap::iterator it, end; - end = this->headers.end(); - for (it = this->headers.begin(); it != end;it++) - { - x << it->first << ": " << it->second << "\r\n"; - } - x << "Connection: Close\r\n"; - x << "Content-Length: " << this->msg.tellp() << "\r\n"; - x << "Server: udpt\r\n"; - x << "\r\n"; - x << this->msg.str(); - - // write to socket - send (this->conn, x.str().c_str(), x.str().length(), 0); - } - - }; -}; +/* + * Copyright © 2013-2017 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include +#include +#include +#include +#include +#include "httpserver.hpp" +#include + +using namespace std; + +namespace UDPT +{ + namespace Server + { + /* HTTPServer */ + HTTPServer::HTTPServer (uint16_t port, int threads) + { + SOCKADDR_IN sa; + + memset((void*)&sa, 0, sizeof(sa)); + sa.sin_addr.s_addr = 0L; + sa.sin_family = AF_INET; + sa.sin_port = htons (port); + + this->init(sa, threads); + } + + HTTPServer::HTTPServer(const boost::program_options::variables_map& conf) + { + list localEndpoints; + uint16_t port; + int threads; + + port = conf["apiserver.port"].as(); + threads = conf["apiserver.threads"].as(); + + if (threads <= 0) + threads = 1; + + if (localEndpoints.empty()) + { + SOCKADDR_IN sa; + memset((void*)&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons (port); + sa.sin_addr.s_addr = 0L; + localEndpoints.push_front(sa); + } + + this->init(localEndpoints.front(), threads); + } + + void HTTPServer::init (SOCKADDR_IN &localEndpoint, int threads) + { + int r; + this->thread_count = threads; + this->threads = new HANDLE[threads]; + this->isRunning = false; + + this->rootNode.callback = NULL; + + this->srv = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (this->srv == INVALID_SOCKET) + { + throw ServerException (1, "Failed to create Socket"); + } + + r = ::bind(this->srv, (SOCKADDR*)&localEndpoint, sizeof(localEndpoint)); + if (r == SOCKET_ERROR) + { + throw ServerException(2, "Failed to bind socket"); + } + + this->isRunning = true; + for (int i = 0;i < threads;i++) + { +#ifdef WIN32 + this->threads[i] = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, this, 0, NULL); +#else + pthread_create (&this->threads[i], NULL, &HTTPServer::_thread_start, this); +#endif + } + } + +#ifdef WIN32 + DWORD HTTPServer::_thread_start (LPVOID arg) +#else + void* HTTPServer::_thread_start (void *arg) +#endif + { + HTTPServer *s = (HTTPServer*)arg; +doSrv: + try { + HTTPServer::handleConnections (s); + } catch (const ServerException &se) + { + cerr << "SRV ERR #" << se.getErrorCode() << ": " << se.getErrorMsg () << endl; + goto doSrv; + } + return 0; + } + + void HTTPServer::handleConnections (HTTPServer *server) + { + int r; +#ifdef WIN32 + int addrSz; +#else + socklen_t addrSz; +#endif + SOCKADDR_IN addr; + SOCKET cli; + + while (server->isRunning) + { + r = ::listen(server->srv, 50); + if (r == SOCKET_ERROR) + { +#ifdef WIN32 + ::Sleep(500); +#else + ::sleep(1); +#endif + continue; + } + addrSz = sizeof addr; + cli = accept (server->srv, (SOCKADDR*)&addr, &addrSz); + if (cli == INVALID_SOCKET) + continue; + + Response resp (cli); // doesn't throw exceptions. + + try { + Request req (cli, &addr); // may throw exceptions. + reqCallback *cb = getRequestHandler (&server->rootNode, req.getPath()); + if (cb == NULL) + { + // error 404 + resp.setStatus (404, "Not Found"); + resp.addHeader ("Content-Type", "text/html; charset=US-ASCII"); + stringstream stream; + stream << ""; + stream << "Not Found"; + stream << "

Not Found

The server couldn't find the request resource.


"; + stream << ""; + string str = stream.str(); + resp.write (str.c_str(), str.length()); + } + else + { + try { + cb (server, &req, &resp); + } catch (...) + { + resp.setStatus(500, "Internal Server Error"); + resp.addHeader ("Content-Type", "text/html; charset=US-ASCII"); + stringstream stream; + stream << ""; + stream << "Internal Server Error"; + stream << "

Internal Server Error

An Error Occurred while trying to process your request.


"; + stream << ""; + string str = stream.str(); + resp.write (str.c_str(), str.length()); + } + } + resp.finalize(); + } catch (ServerException &e) + { + // Error 400 Bad Request! + } + + closesocket (cli); + } + } + + void HTTPServer::addApp (list *path, reqCallback *cb) + { + list::iterator it = path->begin(); + appNode *node = &this->rootNode; + while (it != path->end()) + { + map::iterator se; + se = node->nodes.find (*it); + if (se == node->nodes.end()) + { + node->nodes[*it].callback = NULL; + } + node = &node->nodes[*it]; + it++; + } + node->callback = cb; + } + + HTTPServer::reqCallback* HTTPServer::getRequestHandler (appNode *node, list *path) + { + appNode *cn = node; + list::iterator it = path->begin(), + end = path->end(); + map::iterator n; + while (true) + { + if (it == end) + { + return cn->callback; + } + + n = cn->nodes.find (*it); + if (n == cn->nodes.end()) + return NULL; // node not found! + cn = &n->second; + + it++; + } + return NULL; + } + + void HTTPServer::setData(string k, void *d) + { + this->customData[k] = d; + } + + void* HTTPServer::getData(string k) + { + map::iterator it = this->customData.find(k); + if (it == this->customData.end()) + return NULL; + return it->second; + } + + HTTPServer::~HTTPServer () + { + if (this->srv != INVALID_SOCKET) + closesocket (this->srv); + + if (this->isRunning) + { + for (int i = 0;i < this->thread_count;i++) + { +#ifdef WIN32 + TerminateThread (this->threads[i], 0x00); +#else + pthread_detach (this->threads[i]); + pthread_cancel (this->threads[i]); +#endif + } + } + + delete[] this->threads; + } + + /* HTTPServer::Request */ + HTTPServer::Request::Request (SOCKET cli, const SOCKADDR_IN *addr) + { + this->conn = cli; + this->addr = addr; + + this->parseRequest (); + } + + inline static char* nextReqLine (int &cPos, char *buff, int len) + { + for (int i = cPos;i < len - 1;i++) + { + if (buff[i] == '\r' && buff[i + 1] == '\n') + { + buff[i] = '\0'; + + int r = cPos; + cPos = i + 2; + return (buff + r); + } + } + + return (buff + len); // end + } + + inline void parseURL (string request, list *path, map *params) + { + string::size_type p; + string query, url; + p = request.find ('?'); + if (p == string::npos) + { + p = request.length(); + } + else + { + query = request.substr (p + 1); + } + url = request.substr (0, p); + + path->clear (); + string::size_type s, e; + s = 0; + while (true) + { + e = url.find ('/', s); + if (e == string::npos) + e = url.length(); + + string x = url.substr (s, e - s); + if (!(x.length() == 0 || x == ".")) + { + if (x == "..") + { + if (path->empty()) + throw ServerException (1, "Hack attempt"); + else + path->pop_back (); + } + path->push_back (x); + } + + if (e == url.length()) + break; + s = e + 1; + } + + string::size_type vS, vE, kS, kE; + vS = vE = kS = kE = 0; + while (kS < query.length()) + { + kE = query.find ('=', kS); + if (kE == string::npos) break; + vS = kE + 1; + vE = query.find ('&', vS); + if (vE == string::npos) vE = query.length(); + + params->insert (pair( query.substr (kS, kE - kS), query.substr (vS, vE - vS) )); + + kS = vE + 1; + } + } + + inline void setCookies (string &data, map *cookies) + { + string::size_type kS, kE, vS, vE; + kS = 0; + while (kS < data.length ()) + { + kE = data.find ('=', kS); + if (kE == string::npos) + break; + vS = kE + 1; + vE = data.find ("; ", vS); + if (vE == string::npos) + vE = data.length(); + + (*cookies) [data.substr (kS, kE-kS)] = data.substr (vS, vE-vS); + + kS = vE + 2; + } + } + + void HTTPServer::Request::parseRequest () + { + char buffer [REQUEST_BUFFER_SIZE]; + int r; + r = recv (this->conn, buffer, REQUEST_BUFFER_SIZE, 0); + if (r == REQUEST_BUFFER_SIZE) + throw ServerException (1, "Request Size too big."); + if (r <= 0) + throw ServerException (2, "Socket Error"); + + char *cLine; + int n = 0; + int pos = 0; + string::size_type p; + while ( (cLine = nextReqLine (pos, buffer, r)) < (buffer + r)) + { + string line = string (cLine); + if (line.length() == 0) break; // CRLF CRLF = end of headers. + n++; + + if (n == 1) + { + string::size_type uS, uE; + p = line.find (' '); + if (p == string::npos) + throw ServerException (5, "Malformed request method"); + uS = p + 1; + this->requestMethod.str = line.substr (0, p); + + if (this->requestMethod.str == "GET") + this->requestMethod.rm = RM_GET; + else if (this->requestMethod.str == "POST") + this->requestMethod.rm = RM_POST; + else + this->requestMethod.rm = RM_UNKNOWN; + + uE = uS; + while (p < line.length()) + { + if (p == string::npos) + break; + p = line.find (' ', p + 1); + if (p == string::npos) + break; + uE = p; + } + if (uE + 1 >= line.length()) + throw ServerException (6, "Malformed request"); + string httpVersion = line.substr (uE + 1); + + + parseURL (line.substr (uS, uE - uS), &this->path, &this->params); + } + else + { + p = line.find (": "); + if (p == string::npos) + throw ServerException (4, "Malformed headers"); + string key = line.substr (0, p); + string value = line.substr (p + 2); + if (key != "Cookie") + this->headers.insert(pair( key, value)); + else + setCookies (value, &this->cookies); + } + } + if (n == 0) + throw ServerException (3, "No Request header."); + } + + list* HTTPServer::Request::getPath () + { + return &this->path; + } + + string HTTPServer::Request::getParam (const string key) + { + map::iterator it = this->params.find (key); + if (it == this->params.end()) + return ""; + else + return it->second; + } + + multimap::iterator HTTPServer::Request::getHeader (const string name) + { + multimap::iterator it = this->headers.find (name); + return it; + } + + HTTPServer::Request::RequestMethod HTTPServer::Request::getRequestMethod () + { + return this->requestMethod.rm; + } + + string HTTPServer::Request::getRequestMethodStr () + { + return this->requestMethod.str; + } + + string HTTPServer::Request::getCookie (const string name) + { + map::iterator it = this->cookies.find (name); + if (it == this->cookies.end()) + return ""; + else + return it->second; + } + + const SOCKADDR_IN* HTTPServer::Request::getAddress () + { + return this->addr; + } + + /* HTTPServer::Response */ + HTTPServer::Response::Response (SOCKET cli) + { + this->conn = cli; + + setStatus (200, "OK"); + } + + void HTTPServer::Response::setStatus (int c, const string m) + { + this->status_code = c; + this->status_msg = m; + } + + void HTTPServer::Response::addHeader (string key, string value) + { + this->headers.insert (pair(key, value)); + } + + void HTTPServer::Response::write (const char *data, int len) + { + if (len < 0) + len = strlen (data); + msg.write(data, len); + } + + void HTTPServer::Response::finalize () + { + stringstream x; + x << "HTTP/1.1 " << this->status_code << " " << this->status_msg << "\r\n"; + multimap::iterator it, end; + end = this->headers.end(); + for (it = this->headers.begin(); it != end;it++) + { + x << it->first << ": " << it->second << "\r\n"; + } + x << "Connection: Close\r\n"; + x << "Content-Length: " << this->msg.tellp() << "\r\n"; + x << "Server: udpt\r\n"; + x << "\r\n"; + x << this->msg.str(); + + // write to socket + send (this->conn, x.str().c_str(), x.str().length(), 0); + } + + }; +}; diff --git a/src/http/httpserver.hpp b/src/http/httpserver.hpp index 45d48a9..a8b30b5 100644 --- a/src/http/httpserver.hpp +++ b/src/http/httpserver.hpp @@ -1,170 +1,170 @@ -/* - * Copyright © 2013-2016 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include "../multiplatform.h" -using namespace std; - -#define REQUEST_BUFFER_SIZE 2048 - -namespace UDPT -{ - namespace Server - { - class ServerException - { - public: - inline ServerException (int ec) - { - this->ec = ec; - this->em = NULL; - } - - inline ServerException (int ec, const char *em) - { - this->ec = ec; - this->em = em; - } - - inline const char *getErrorMsg () const - { - return this->em; - } - - inline int getErrorCode () const - { - return this->ec; - } - private: - int ec; - const char *em; - }; - - class HTTPServer - { - public: - class Request - { - public: - enum RequestMethod - { - RM_UNKNOWN = 0, - RM_GET = 1, - RM_POST = 2 - }; - - Request (SOCKET, const SOCKADDR_IN *); - list* getPath (); - - string getParam (const string key); - multimap::iterator getHeader (const string name); - RequestMethod getRequestMethod (); - string getRequestMethodStr (); - string getCookie (const string name); - const SOCKADDR_IN* getAddress (); - - private: - const SOCKADDR_IN *addr; - SOCKET conn; - struct { - int major; - int minor; - } httpVer; - struct { - string str; - RequestMethod rm; - } requestMethod; - list path; - map params; - map cookies; - multimap headers; - - void parseRequest (); - }; - - class Response - { - public: - Response (SOCKET conn); - - void setStatus (int, const string); - void addHeader (string key, string value); - - int writeRaw (const char *data, int len); - void write (const char *data, int len = -1); - - private: - friend class HTTPServer; - - SOCKET conn; - int status_code; - string status_msg; - multimap headers; - stringstream msg; - - void finalize (); - }; - - typedef void (reqCallback)(HTTPServer*,Request*,Response*); - - HTTPServer (uint16_t port, int threads); - HTTPServer(const boost::program_options::variables_map& conf); - - void addApp (list *path, reqCallback *); - - void setData (string, void *); - void* getData (string); - - virtual ~HTTPServer (); - - private: - typedef struct appNode - { - reqCallback *callback; - map nodes; - } appNode; - - SOCKET srv; - int thread_count; - HANDLE *threads; - bool isRunning; - appNode rootNode; - map customData; - - void init (SOCKADDR_IN &localEndpoint, int threads); - - static void handleConnections (HTTPServer *); - -#ifdef WIN32 - static DWORD _thread_start (LPVOID); -#else - static void* _thread_start (void*); -#endif - - static reqCallback* getRequestHandler (appNode *, list *); - }; - }; -}; +/* + * Copyright © 2013-2017 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include "../multiplatform.h" +using namespace std; + +#define REQUEST_BUFFER_SIZE 2048 + +namespace UDPT +{ + namespace Server + { + class ServerException + { + public: + inline ServerException (int ec) + { + this->ec = ec; + this->em = NULL; + } + + inline ServerException (int ec, const char *em) + { + this->ec = ec; + this->em = em; + } + + inline const char *getErrorMsg () const + { + return this->em; + } + + inline int getErrorCode () const + { + return this->ec; + } + private: + int ec; + const char *em; + }; + + class HTTPServer + { + public: + class Request + { + public: + enum RequestMethod + { + RM_UNKNOWN = 0, + RM_GET = 1, + RM_POST = 2 + }; + + Request (SOCKET, const SOCKADDR_IN *); + list* getPath (); + + string getParam (const string key); + multimap::iterator getHeader (const string name); + RequestMethod getRequestMethod (); + string getRequestMethodStr (); + string getCookie (const string name); + const SOCKADDR_IN* getAddress (); + + private: + const SOCKADDR_IN *addr; + SOCKET conn; + struct { + int major; + int minor; + } httpVer; + struct { + string str; + RequestMethod rm; + } requestMethod; + list path; + map params; + map cookies; + multimap headers; + + void parseRequest (); + }; + + class Response + { + public: + Response (SOCKET conn); + + void setStatus (int, const string); + void addHeader (string key, string value); + + int writeRaw (const char *data, int len); + void write (const char *data, int len = -1); + + private: + friend class HTTPServer; + + SOCKET conn; + int status_code; + string status_msg; + multimap headers; + stringstream msg; + + void finalize (); + }; + + typedef void (reqCallback)(HTTPServer*,Request*,Response*); + + HTTPServer (uint16_t port, int threads); + HTTPServer(const boost::program_options::variables_map& conf); + + void addApp (list *path, reqCallback *); + + void setData (string, void *); + void* getData (string); + + virtual ~HTTPServer (); + + private: + typedef struct appNode + { + reqCallback *callback; + map nodes; + } appNode; + + SOCKET srv; + int thread_count; + HANDLE *threads; + bool isRunning; + appNode rootNode; + map customData; + + void init (SOCKADDR_IN &localEndpoint, int threads); + + static void handleConnections (HTTPServer *); + +#ifdef WIN32 + static DWORD _thread_start (LPVOID); +#else + static void* _thread_start (void*); +#endif + + static reqCallback* getRequestHandler (appNode *, list *); + }; + }; +}; diff --git a/src/http/webapp.cpp b/src/http/webapp.cpp index d3e7c4f..0de9614 100644 --- a/src/http/webapp.cpp +++ b/src/http/webapp.cpp @@ -1,5 +1,5 @@ /* - * Copyright © 2013-2016 Naim A. + * Copyright © 2013-2017 Naim A. * * This file is part of UDPT. * @@ -25,190 +25,190 @@ using namespace std; namespace UDPT { - namespace Server - { + namespace Server + { - static uint32_t _getNextIPv4 (string::size_type &i, string &line) - { - string::size_type len = line.length(); - char c; - while (i < len) - { - c = line.at(i); - if (c >= '0' && c <= '9') - break; - i++; - } + static uint32_t _getNextIPv4 (string::size_type &i, string &line) + { + string::size_type len = line.length(); + char c; + while (i < len) + { + c = line.at(i); + if (c >= '0' && c <= '9') + break; + i++; + } - uint32_t ip = 0; - for (int n = 0;n < 4;n++) - { - int cn = 0; - while (i < len) - { - c = line.at (i++); - if (c == '.' || ((c == ' ' || c == ',' || c == ';') && n == 3)) - break; - else if (!(c >= '0' && c <= '9')) - return 0; - cn *= 10; - cn += (c - '0'); - } - ip *= 256; - ip += cn; - } - return ip; - } + uint32_t ip = 0; + for (int n = 0;n < 4;n++) + { + int cn = 0; + while (i < len) + { + c = line.at (i++); + if (c == '.' || ((c == ' ' || c == ',' || c == ';') && n == 3)) + break; + else if (!(c >= '0' && c <= '9')) + return 0; + cn *= 10; + cn += (c - '0'); + } + ip *= 256; + ip += cn; + } + return ip; + } - static bool _hex2bin (uint8_t *data, const string str) - { - int len = str.length(); + static bool _hex2bin (uint8_t *data, const string str) + { + int len = str.length(); - if (len % 2 != 0) - return false; + if (len % 2 != 0) + return false; - char a, b; - uint8_t c; - for (int i = 0;i < len;i+=2) - { - a = str.at (i); - b = str.at (i + 1); - c = 0; + char a, b; + uint8_t c; + for (int i = 0;i < len;i+=2) + { + a = str.at (i); + b = str.at (i + 1); + c = 0; - if (a >= 'a' && a <= 'f') - a = (a - 'a') + 10; - else if (a >= '0' && a <= '9') - a = (a - '0'); - else - return false; + if (a >= 'a' && a <= 'f') + a = (a - 'a') + 10; + else if (a >= '0' && a <= '9') + a = (a - '0'); + else + return false; - if (b >= 'a' && b <= 'f') - b = (b - 'a') + 10; - else if (b >= '0' && b <= '9') - b = (b - '0'); - else - return false; + if (b >= 'a' && b <= 'f') + b = (b - 'a') + 10; + else if (b >= '0' && b <= '9') + b = (b - '0'); + else + return false; - c = (a * 16) + b; + c = (a * 16) + b; - data [i / 2] = c; - } + data [i / 2] = c; + } - return true; - } + return true; + } - WebApp::WebApp(std::shared_ptr srv, DatabaseDriver *db, const boost::program_options::variables_map& conf) : m_conf(conf), m_server(srv) - { - this->db = db; - // TODO: Implement authentication by keys + WebApp::WebApp(std::shared_ptr srv, DatabaseDriver *db, const boost::program_options::variables_map& conf) : m_conf(conf), m_server(srv) + { + this->db = db; + // TODO: Implement authentication by keys - m_server->setData("webapp", this); - } + m_server->setData("webapp", this); + } - WebApp::~WebApp() - { - } + WebApp::~WebApp() + { + } - void WebApp::deploy() - { - list path; - m_server->addApp(&path, &WebApp::handleRoot); + void WebApp::deploy() + { + list path; + m_server->addApp(&path, &WebApp::handleRoot); - path.push_back("api"); - m_server->addApp(&path, &WebApp::handleAPI); // "/api" + path.push_back("api"); + m_server->addApp(&path, &WebApp::handleAPI); // "/api" - path.pop_back(); - path.push_back("announce"); - m_server->addApp(&path, &WebApp::handleAnnounce); - } + path.pop_back(); + path.push_back("announce"); + m_server->addApp(&path, &WebApp::handleAnnounce); + } - void WebApp::handleRoot(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) - { - // It would be very appreciated to keep this in the code. - resp->write("" - "UDPT Torrent Tracker" - "" - "
This tracker is running on UDPT Software.
" - "

" - "" - ""); - } + void WebApp::handleRoot(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) + { + // It would be very appreciated to keep this in the code. + resp->write("" + "UDPT Torrent Tracker" + "" + "
This tracker is running on UDPT Software.
" + "

" + "" + ""); + } - void WebApp::doRemoveTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) - { - string strHash = req->getParam("hash"); - if (strHash.length() != 40) - { - resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); - return; - } - uint8_t hash [20]; - if (!_hex2bin(hash, strHash)) - { - resp->write("{\"error\":\"invalid info_hash.\"}"); - return; - } + void WebApp::doRemoveTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) + { + string strHash = req->getParam("hash"); + if (strHash.length() != 40) + { + resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); + return; + } + uint8_t hash [20]; + if (!_hex2bin(hash, strHash)) + { + resp->write("{\"error\":\"invalid info_hash.\"}"); + return; + } - if (this->db->removeTorrent(hash)) - resp->write("{\"success\":true}"); - else - resp->write("{\"error\":\"failed to remove torrent from DB\"}"); - } + if (this->db->removeTorrent(hash)) + resp->write("{\"success\":true}"); + else + resp->write("{\"error\":\"failed to remove torrent from DB\"}"); + } - void WebApp::doAddTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) - { - std::string strHash = req->getParam("hash"); - if (strHash.length() != 40) - { - resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); - return; - } - uint8_t hash [20]; - if (!_hex2bin(hash, strHash)) - { - resp->write("{\"error\":\"invalid info_hash.\"}"); - return; - } + void WebApp::doAddTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) + { + std::string strHash = req->getParam("hash"); + if (strHash.length() != 40) + { + resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); + return; + } + uint8_t hash [20]; + if (!_hex2bin(hash, strHash)) + { + resp->write("{\"error\":\"invalid info_hash.\"}"); + return; + } - if (this->db->addTorrent(hash)) - resp->write("{\"success\":true}"); - else - resp->write("{\"error\":\"failed to add torrent to DB\"}"); - } + if (this->db->addTorrent(hash)) + resp->write("{\"success\":true}"); + else + resp->write("{\"error\":\"failed to add torrent to DB\"}"); + } - void WebApp::handleAnnounce (HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) - { - resp->write("d14:failure reason42:this is a UDP tracker, not a HTTP tracker.e"); - } + void WebApp::handleAnnounce (HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) + { + resp->write("d14:failure reason42:this is a UDP tracker, not a HTTP tracker.e"); + } - void WebApp::handleAPI(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) - { - if (req->getAddress()->sin_family != AF_INET) - { - throw ServerException (0, "IPv4 supported Only."); - } + void WebApp::handleAPI(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) + { + if (req->getAddress()->sin_family != AF_INET) + { + throw ServerException (0, "IPv4 supported Only."); + } - WebApp *app = (WebApp*)srv->getData("webapp"); - if (app == NULL) - throw ServerException(0, "WebApp object wasn't found"); + WebApp *app = (WebApp*)srv->getData("webapp"); + if (app == NULL) + throw ServerException(0, "WebApp object wasn't found"); - if (req->getAddress()->sin_addr.s_addr != 0x0100007f) - { - resp->setStatus(403, "Forbidden"); - resp->write("Access Denied. Only 127.0.0.1 can access this method."); - return; - } + if (req->getAddress()->sin_addr.s_addr != 0x0100007f) + { + resp->setStatus(403, "Forbidden"); + resp->write("Access Denied. Only 127.0.0.1 can access this method."); + return; + } - std::string action = req->getParam("action"); - if (action == "add") - app->doAddTorrent(req, resp); - else if (action == "remove") - app->doRemoveTorrent(req, resp); - else - { - resp->write("{\"error\":\"unknown action\"}"); - } - } - }; + std::string action = req->getParam("action"); + if (action == "add") + app->doAddTorrent(req, resp); + else if (action == "remove") + app->doRemoveTorrent(req, resp); + else + { + resp->write("{\"error\":\"unknown action\"}"); + } + } + }; }; diff --git a/src/http/webapp.hpp b/src/http/webapp.hpp index b764e2e..ae5a06d 100644 --- a/src/http/webapp.hpp +++ b/src/http/webapp.hpp @@ -1,5 +1,5 @@ /* - * Copyright © 2013-2016 Naim A. + * Copyright © 2013-2017 Naim A. * * This file is part of UDPT. * @@ -33,27 +33,27 @@ using namespace UDPT::Data; namespace UDPT { - namespace Server - { - class WebApp - { - public: - WebApp(std::shared_ptr , DatabaseDriver *, const boost::program_options::variables_map& conf); - virtual ~WebApp(); - void deploy (); - + namespace Server + { + class WebApp + { + public: + WebApp(std::shared_ptr , DatabaseDriver *, const boost::program_options::variables_map& conf); + virtual ~WebApp(); + void deploy (); - private: - std::shared_ptr m_server; - UDPT::Data::DatabaseDriver *db; - const boost::program_options::variables_map& m_conf; - static void handleRoot (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); - static void handleAnnounce (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); - static void handleAPI (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); + private: + std::shared_ptr m_server; + UDPT::Data::DatabaseDriver *db; + const boost::program_options::variables_map& m_conf; - void doAddTorrent (HTTPServer::Request*, HTTPServer::Response*); - void doRemoveTorrent (HTTPServer::Request*, HTTPServer::Response*); - }; - }; + static void handleRoot (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); + static void handleAnnounce (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); + static void handleAPI (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); + + void doAddTorrent (HTTPServer::Request*, HTTPServer::Response*); + void doRemoveTorrent (HTTPServer::Request*, HTTPServer::Response*); + }; + }; }; diff --git a/src/logging.cpp b/src/logging.cpp new file mode 100644 index 0000000..ceadcbf --- /dev/null +++ b/src/logging.cpp @@ -0,0 +1,140 @@ +/* +* Copyright © 2012-2017 Naim A. +* +* This file is part of UDPT. +* +* UDPT is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* UDPT 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 UDPT. If not, see . +*/ +#include "logging.hpp" +#include +#include +#include +#include + +namespace UDPT { + namespace Logging { + + Logger::Logger() : m_cleaningUp(false), m_workerThread(Logger::worker, this), m_minLogLevel(Severity::FATAL) { + } + + Logger::~Logger() { + try { + // prevent new log messages from entering queue. + m_cleaningUp = true; + + // tell thread to exit + m_runningCondition.notify_one(); + + // wait for worker to terminate + m_workerThread.join(); + // flush any remaining logs + flush(); + + // flush iostreams + for (std::vector>::const_iterator it = m_outputStreams.begin(); it != m_outputStreams.end(); ++it) { + it->first->flush(); + } + } catch (...) { + // can't do much here... this is a logging class... + } + } + + Logger& Logger::getLogger() { + static Logger instance; + + return instance; + } + + void Logger::log(Severity severity, const std::string& channel, const std::string& message) { + if (severity < m_minLogLevel) { + return; + } + + m_queue.Push(LogEntry{ + .when=std::chrono::system_clock::now(), + .severity=severity, + .channel=channel, + .message=message + }); + } + + void Logger::addStream(std::ostream *stream, Severity severity) { + m_minLogLevel = m_minLogLevel > severity ? severity : m_minLogLevel; + m_outputStreams.push_back(std::pair(stream, severity)); + } + + void Logger::flush() { + while (!m_queue.IsEmpty()) { + LogEntry entry = m_queue.Pop(); + std::stringstream sstream; + + //TODO: Write the log time in a more elegant manner. + time_t timestamp = std::chrono::system_clock::to_time_t(entry.when); + char* time_buffer = ctime(×tamp); + time_buffer[strlen(time_buffer) - 1] = '\0'; + sstream << time_buffer << "\t"; + + switch (entry.severity) { + case Severity::DEBUG: + sstream << "DEBUG"; + break; + case Severity::INFO: + sstream << "INFO "; + break; + case Severity::WARNING: + sstream << "WARN "; + break; + case Severity::ERROR: + sstream << "ERROR"; + break; + case Severity::FATAL: + sstream << "FATAL"; + break; + } + + sstream << " [" << entry.channel << "]\t" << entry.message; + + const std::string& result_log = sstream.str(); + for (std::vector>::const_iterator it = m_outputStreams.begin(); it != m_outputStreams.end(); ++it) { + + if (entry.severity < it->second) { + // message severity isn't high enough for this logger. + continue; + } + + std::ostream& current_stream = *(it->first); + + // catch an exception in case we get a broken pipe or something... + try { + current_stream << result_log << std::endl; + } catch (...) { + // do nothing. + } + } + } + } + + void Logger::worker(Logger *me) { + std::unique_lock lk (me->m_runningMutex); + + while (true) { + me->flush(); + + if (std::cv_status::no_timeout == me->m_runningCondition.wait_for(lk, std::chrono::seconds(5))) { + break; + } + } + } + } +} diff --git a/src/logging.hpp b/src/logging.hpp new file mode 100644 index 0000000..47d2104 --- /dev/null +++ b/src/logging.hpp @@ -0,0 +1,83 @@ +/* +* Copyright © 2012-2017 Naim A. +* +* This file is part of UDPT. +* +* UDPT is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* UDPT 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 UDPT. If not, see . +*/ +#pragma once +#include +#include +#include +#include +#include +#include "MessageQueue.hpp" + +#define LOG(severity, channel, message) \ + {\ + std::stringstream __sstream; \ + __sstream << message; \ + UDPT::Logging::Logger::getLogger().log(severity, channel, __sstream.str()); \ + } +#define LOG_INFO(channel, message) LOG(UDPT::Logging::Severity::INFO, channel, message) +#define LOG_DEBUG(channel, message) LOG(UDPT::Logging::Severity::DEBUG, channel, message) +#define LOG_WARN(channel, message) LOG(UDPT::Logging::Severity::WARNING, channel, message) +#define LOG_ERR(channel, message) LOG(UDPT::Logging::Severity::ERROR, channel, message) +#define LOG_FATAL(channel, message) LOG(UDPT::Logging::Severity::FATAL, channel, message) + +namespace UDPT { + namespace Logging { + + enum Severity { + UNSET = 0, + DEBUG = 10, + INFO = 20, + WARNING = 30, + ERROR = 40, + FATAL = 50 + }; + + struct LogEntry { + const std::chrono::time_point when; + Severity severity; + const std::string channel; + const std::string message; + }; + + class Logger { + public: + static Logger& getLogger(); + + void log(Severity severity, const std::string& channel, const std::string& message); + + void addStream(std::ostream *, Severity minSeverity=INFO); + + private: + + Logger(); + virtual ~Logger(); + static void worker(Logger*); + void flush(); + + std::vector> m_outputStreams; + UDPT::Utils::MessageQueue m_queue; + std::thread m_workerThread; + std::atomic_bool m_cleaningUp; + std::mutex m_runningMutex; + std::condition_variable m_runningCondition; + Severity m_minLogLevel; + }; + + } +} diff --git a/src/main.cpp b/src/main.cpp index 2aa342e..834d5a4 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright © 2012-2016 Naim A. + * Copyright © 2012-2017 Naim A. * * This file is part of UDPT. * @@ -25,8 +25,6 @@ #include #include #include -#include -#include #include "multiplatform.h" #include "udpTracker.hpp" @@ -34,35 +32,39 @@ #include "http/webapp.hpp" #include "tracker.hpp" #include "service.hpp" +#include "logging.hpp" -static void _signal_handler(int sig) +extern "C" void _signal_handler(int sig) { - switch (sig) - { - case SIGTERM: - UDPT::Tracker::getInstance().stop(); - break; - } + switch (sig) { + case SIGTERM: + case SIGQUIT: + case SIGINT: { + LOG_INFO("core", "Received signal " << sig << ", requesting to stop tracker"); + UDPT::Tracker::getInstance().stop(); + break; + } + } } #ifdef linux static void daemonize(const boost::program_options::variables_map& conf) { - if (1 == ::getppid()) return; // already a daemon - int r = ::fork(); - if (0 > r) ::exit(-1); // failed to daemonize. - if (0 < r) ::exit(0); // parent exists. + if (1 == ::getppid()) return; // already a daemon + int r = ::fork(); + if (0 > r) ::exit(-1); // failed to daemonize. + if (0 < r) ::exit(0); // parent exists. - ::umask(0); - ::setsid(); + ::umask(0); + ::setsid(); - // close all fds. - for (int i = ::getdtablesize(); i >=0; --i) - { - ::close(i); - } + // close all fds. + for (int i = ::getdtablesize(); i >=0; --i) + { + ::close(i); + } - ::chdir(conf["daemon.chdir"].as().c_str()); + ::chdir(conf["daemon.chdir"].as().c_str()); } #endif @@ -70,159 +72,163 @@ static void daemonize(const boost::program_options::variables_map& conf) #ifdef WIN32 void _close_wsa() { - ::WSACleanup(); + ::WSACleanup(); } #endif +#ifdef TEST +int real_main(int argc, char *argv[]) +#else int main(int argc, char *argv[]) +#endif { #ifdef WIN32 - WSADATA wsadata; - ::WSAStartup(MAKEWORD(2, 2), &wsadata); - ::atexit(_close_wsa); + WSADATA wsadata; + ::WSAStartup(MAKEWORD(2, 2), &wsadata); + ::atexit(_close_wsa); #endif - boost::program_options::options_description commandLine("Command line options"); - commandLine.add_options() - ("help,h", "produce help message") - ("all-help", "displays all help") - ("test,t", "test configuration file") - ("config,c", boost::program_options::value()->default_value("/etc/udpt.conf"), "configuration file to use") + boost::program_options::options_description commandLine("Command line options"); + commandLine.add_options() + ("help,h", "produce help message") + ("all-help", "displays all help") + ("test,t", "test configuration file") + ("config,c", boost::program_options::value()->default_value("/etc/udpt.conf"), "configuration file to use") #ifdef linux - ("interactive,i", "doesn't start as daemon") + ("interactive,i", "doesn't start as daemon") #endif #ifdef WIN32 - ("service,s", boost::program_options::value(), "start/stop/install/uninstall service") + ("service,s", boost::program_options::value(), "start/stop/install/uninstall service") #endif - ; + ; - const boost::program_options::options_description& configOptions = Tracker::getConfigOptions(); + const boost::program_options::options_description& configOptions = Tracker::getConfigOptions(); - boost::program_options::variables_map var_map; - boost::program_options::store(boost::program_options::parse_command_line(argc, argv, commandLine), var_map); - boost::program_options::notify(var_map); + boost::program_options::variables_map var_map; + boost::program_options::store(boost::program_options::parse_command_line(argc, argv, commandLine), var_map); + boost::program_options::notify(var_map); - if (var_map.count("help")) - { - std::cout << "UDP Tracker (UDPT) " << VERSION << " (" << PLATFORM << ")" << std::endl - << "Copyright 2012-2016 Naim A. " << std::endl - << "Build Date: " << __DATE__ << std::endl << std::endl; - - std::cout << commandLine << std::endl; - return 0; - } + if (var_map.count("help")) + { + std::cout << "UDP Tracker (UDPT) " << VERSION << " (" << PLATFORM << ")" << std::endl + << "Copyright 2012-2016 Naim A. " << std::endl + << "Build Date: " << __DATE__ << std::endl << std::endl; - if (var_map.count("all-help")) - { - std::cout << commandLine << std::endl; - std::cout << configOptions << std::endl; - return 0; - } + std::cout << commandLine << std::endl; + return 0; + } - std::string config_filename(var_map["config"].as()); - bool isTest = (0 != var_map.count("test")); + if (var_map.count("all-help")) + { + std::cout << commandLine << std::endl; + std::cout << configOptions << std::endl; + return 0; + } - if (var_map.count("config")) - { - try - { - boost::program_options::basic_parsed_options parsed_options = boost::program_options::parse_config_file(config_filename.c_str(), configOptions); - boost::program_options::store( - parsed_options, - var_map); - } - catch (const boost::program_options::error& ex) - { - std::cerr << "ERROR: " << ex.what() << std::endl; - return -1; - } + std::string config_filename(var_map["config"].as()); + bool isTest = (0 != var_map.count("test")); - if (isTest) - { - std::cout << "Config OK" << std::endl; - return 0; - } - } + if (var_map.count("config")) + { + try + { + boost::program_options::basic_parsed_options parsed_options = boost::program_options::parse_config_file(config_filename.c_str(), configOptions); + boost::program_options::store( + parsed_options, + var_map); + } + catch (const boost::program_options::error& ex) + { + std::cerr << "ERROR: " << ex.what() << std::endl; + return -1; + } - boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "main"); - Tracker::setupLogging(var_map, logger); + if (isTest) + { + std::cout << "Config OK" << std::endl; + return 0; + } + } #ifdef linux - if (!var_map.count("interactive")) - { - daemonize(var_map); - } - ::signal(SIGTERM, _signal_handler); + if (!var_map.count("interactive")) + { + daemonize(var_map); + } + ::signal(SIGTERM, _signal_handler); + ::signal(SIGINT, _signal_handler); #endif #ifdef WIN32 - UDPT::Service svc(var_map); - if (var_map.count("service")) - { - const std::string& action = var_map["service"].as(); - try - { - if ("install" == action) - { - std::cerr << "Installing service..." << std::endl; - svc.install(var_map["config"].as()); - std::cerr << "Installed." << std::endl; - } - else if ("uninstall" == action) - { - std::cerr << "Removing service..." << std::endl; - svc.uninstall(); - std::cerr << "Removed." << std::endl; - } - else if ("start" == action) - { - svc.start(); - } - else if ("stop" == action) - { - svc.stop(); - } - else - { - std::cerr << "No such service command." << std::endl; - return -1; - } - } - catch (const UDPT::OSError& ex) - { - std::cerr << "An operating system error occurred: " << ex.what() << std::endl; - return -1; - } + UDPT::Service svc(var_map); + if (var_map.count("service")) + { + const std::string& action = var_map["service"].as(); + try + { + if ("install" == action) + { + std::cerr << "Installing service..." << std::endl; + svc.install(var_map["config"].as()); + std::cerr << "Installed." << std::endl; + } + else if ("uninstall" == action) + { + std::cerr << "Removing service..." << std::endl; + svc.uninstall(); + std::cerr << "Removed." << std::endl; + } + else if ("start" == action) + { + svc.start(); + } + else if ("stop" == action) + { + svc.stop(); + } + else + { + std::cerr << "No such service command." << std::endl; + return -1; + } + } + catch (const UDPT::OSError& ex) + { + std::cerr << "An operating system error occurred: " << ex.what() << std::endl; + return -1; + } - return 0; - } + return 0; + } - try - { - svc.setup(); - return 0; - } - catch (const OSError& err) - { - if (ERROR_FAILED_SERVICE_CONTROLLER_CONNECT != err.getErrorCode()) - { - BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed to start as a Windows service: (" << err.getErrorCode() << "): " << err.what(); - return -1; - } - } + try + { + svc.setup(); + return 0; + } + catch (const OSError& err) + { + if (ERROR_FAILED_SERVICE_CONTROLLER_CONNECT != err.getErrorCode()) + { + BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed to start as a Windows service: (" << err.getErrorCode() << "): " << err.what(); + return -1; + } + } #endif - try - { - Tracker& tracker = UDPT::Tracker::getInstance(); - tracker.start(var_map); - tracker.wait(); - } - catch (const UDPT::UDPTException& ex) - { - BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "UDPT exception: (" << ex.getErrorCode() << "): " << ex.what(); - return -1; - } + try + { + Tracker& tracker = UDPT::Tracker::getInstance(); + tracker.start(var_map); + tracker.wait(); + } + catch (const UDPT::UDPTException& ex) + { + std::cerr << "UDPT exception: (" << ex.getErrorCode() << "): " << ex.what(); + return -1; + } - return 0; + LOG_INFO("core", "UDPT terminated."); + + return 0; } diff --git a/src/multiplatform.h b/src/multiplatform.h index 2471888..9069d29 100644 --- a/src/multiplatform.h +++ b/src/multiplatform.h @@ -1,5 +1,5 @@ /* - * Copyright © 2012-2016 Naim A. + * Copyright © 2012-2017 Naim A. * * This file is part of UDPT. * diff --git a/src/service.cpp b/src/service.cpp index bdd8d33..f7b8bee 100644 --- a/src/service.cpp +++ b/src/service.cpp @@ -1,5 +1,5 @@ /* -* Copyright © 2012-2016 Naim A. +* Copyright © 2012-2017 Naim A. * * This file is part of UDPT. * @@ -23,234 +23,234 @@ namespace UDPT { - SERVICE_STATUS_HANDLE Service::s_hServiceStatus = nullptr; - SERVICE_STATUS Service::s_serviceStatus = { 0 }; + SERVICE_STATUS_HANDLE Service::s_hServiceStatus = nullptr; + SERVICE_STATUS Service::s_serviceStatus = { 0 }; - Service::Service(const boost::program_options::variables_map& conf) : m_conf(conf) - { + Service::Service(const boost::program_options::variables_map& conf) : m_conf(conf) + { - } + } - Service::~Service() - { + Service::~Service() + { - } + } - void Service::install(const std::string& config_path) - { - std::string& binaryPath = getFilename(); - binaryPath = "\"" + binaryPath + "\" -c \"" + config_path + "\""; - std::shared_ptr svcMgr = getServiceManager(SC_MANAGER_CREATE_SERVICE); - { - SC_HANDLE installedService = ::CreateService(reinterpret_cast(svcMgr.get()), - m_conf["service.name"].as().c_str(), - "UDPT Tracker", - SC_MANAGER_CREATE_SERVICE, - SERVICE_WIN32_OWN_PROCESS, - SERVICE_AUTO_START, - SERVICE_ERROR_NORMAL, - binaryPath.c_str(), - NULL, - NULL, - NULL, - NULL, - NULL - ); - if (nullptr == installedService) - { - throw OSError(); - } + void Service::install(const std::string& config_path) + { + std::string& binaryPath = getFilename(); + binaryPath = "\"" + binaryPath + "\" -c \"" + config_path + "\""; + std::shared_ptr svcMgr = getServiceManager(SC_MANAGER_CREATE_SERVICE); + { + SC_HANDLE installedService = ::CreateService(reinterpret_cast(svcMgr.get()), + m_conf["service.name"].as().c_str(), + "UDPT Tracker", + SC_MANAGER_CREATE_SERVICE, + SERVICE_WIN32_OWN_PROCESS, + SERVICE_AUTO_START, + SERVICE_ERROR_NORMAL, + binaryPath.c_str(), + NULL, + NULL, + NULL, + NULL, + NULL + ); + if (nullptr == installedService) + { + throw OSError(); + } - ::CloseServiceHandle(installedService); - } - } + ::CloseServiceHandle(installedService); + } + } - void Service::uninstall() - { - std::shared_ptr service = getService(DELETE); - BOOL bRes = ::DeleteService(reinterpret_cast(service.get())); - if (FALSE == bRes) - { - throw OSError(); - } - } + void Service::uninstall() + { + std::shared_ptr service = getService(DELETE); + BOOL bRes = ::DeleteService(reinterpret_cast(service.get())); + if (FALSE == bRes) + { + throw OSError(); + } + } - void Service::start() - { - std::shared_ptr hSvc = getService(SERVICE_START); - BOOL bRes = ::StartService(reinterpret_cast(hSvc.get()), 0, NULL); - if (FALSE == bRes) - { - throw OSError(); - } - } + void Service::start() + { + std::shared_ptr hSvc = getService(SERVICE_START); + BOOL bRes = ::StartService(reinterpret_cast(hSvc.get()), 0, NULL); + if (FALSE == bRes) + { + throw OSError(); + } + } - void Service::stop() - { - SERVICE_STATUS status = { 0 }; + void Service::stop() + { + SERVICE_STATUS status = { 0 }; - std::shared_ptr hSvc = getService(SERVICE_STOP); - BOOL bRes = ::ControlService(reinterpret_cast(hSvc.get()), SERVICE_CONTROL_STOP, &status); - if (FALSE == bRes) - { - throw OSError(); - } - } + std::shared_ptr hSvc = getService(SERVICE_STOP); + BOOL bRes = ::ControlService(reinterpret_cast(hSvc.get()), SERVICE_CONTROL_STOP, &status); + if (FALSE == bRes) + { + throw OSError(); + } + } - void Service::setup() - { - SERVICE_TABLE_ENTRY service[] = { - { const_cast(m_conf["service.name"].as().c_str()), reinterpret_cast(&Service::serviceMain) }, - {0, 0} - }; + void Service::setup() + { + SERVICE_TABLE_ENTRY service[] = { + { const_cast(m_conf["service.name"].as().c_str()), reinterpret_cast(&Service::serviceMain) }, + {0, 0} + }; - if (FALSE == ::StartServiceCtrlDispatcher(service)) - { - throw OSError(); - } - } + if (FALSE == ::StartServiceCtrlDispatcher(service)) + { + throw OSError(); + } + } - DWORD Service::handler(DWORD controlCode, DWORD dwEventType, LPVOID eventData, LPVOID context) - { - switch (controlCode) - { - case SERVICE_CONTROL_INTERROGATE: - return NO_ERROR; + DWORD Service::handler(DWORD controlCode, DWORD dwEventType, LPVOID eventData, LPVOID context) + { + switch (controlCode) + { + case SERVICE_CONTROL_INTERROGATE: + return NO_ERROR; - case SERVICE_CONTROL_STOP: - { - reportServiceStatus(SERVICE_STOP_PENDING, 0, 3000); - Tracker::getInstance().stop(); + case SERVICE_CONTROL_STOP: + { + reportServiceStatus(SERVICE_STOP_PENDING, 0, 3000); + Tracker::getInstance().stop(); - return NO_ERROR; - } + return NO_ERROR; + } - default: - return ERROR_CALL_NOT_IMPLEMENTED; - } - } + default: + return ERROR_CALL_NOT_IMPLEMENTED; + } + } - void Service::reportServiceStatus(DWORD currentState, DWORD dwExitCode, DWORD dwWaitHint) - { - static DWORD checkpoint = 1; + void Service::reportServiceStatus(DWORD currentState, DWORD dwExitCode, DWORD dwWaitHint) + { + static DWORD checkpoint = 1; - if (currentState == SERVICE_STOPPED || currentState == SERVICE_RUNNING) - { - checkpoint = 0; - } - else - { - ++checkpoint; - } + if (currentState == SERVICE_STOPPED || currentState == SERVICE_RUNNING) + { + checkpoint = 0; + } + else + { + ++checkpoint; + } - switch (currentState) - { - case SERVICE_RUNNING: - s_serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; - break; + switch (currentState) + { + case SERVICE_RUNNING: + s_serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; + break; - default: - s_serviceStatus.dwControlsAccepted = 0; - } + default: + s_serviceStatus.dwControlsAccepted = 0; + } - s_serviceStatus.dwCheckPoint = checkpoint; - s_serviceStatus.dwCurrentState = currentState; - s_serviceStatus.dwWin32ExitCode = dwExitCode; - s_serviceStatus.dwWaitHint = dwWaitHint; + s_serviceStatus.dwCheckPoint = checkpoint; + s_serviceStatus.dwCurrentState = currentState; + s_serviceStatus.dwWin32ExitCode = dwExitCode; + s_serviceStatus.dwWaitHint = dwWaitHint; - ::SetServiceStatus(s_hServiceStatus, &s_serviceStatus); - } + ::SetServiceStatus(s_hServiceStatus, &s_serviceStatus); + } - VOID Service::serviceMain(DWORD argc, LPCSTR argv[]) - { - boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "service"); - - wchar_t *commandLine = ::GetCommandLineW(); - int argCount = 0; - std::shared_ptr args(::CommandLineToArgvW(commandLine, &argCount), ::LocalFree); - if (nullptr == args) - { - BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed parse command-line."; - ::exit(-1); - } + VOID Service::serviceMain(DWORD argc, LPCSTR argv[]) + { + boost::log::sources::severity_channel_logger_mt<> logger(boost::log::keywords::channel = "service"); - if (3 != argCount) - { - BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Bad command-line length (must have exactly 2 arguments)."; - ::exit(-1); - } + wchar_t *commandLine = ::GetCommandLineW(); + int argCount = 0; + std::shared_ptr args(::CommandLineToArgvW(commandLine, &argCount), ::LocalFree); + if (nullptr == args) + { + BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed parse command-line."; + ::exit(-1); + } - if (std::wstring(args.get()[1]) != L"-c") - { - BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Argument 1 must be \"-c\"."; - ::exit(-1); - } + if (3 != argCount) + { + BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Bad command-line length (must have exactly 2 arguments)."; + ::exit(-1); + } - std::wstring wFilename(args.get()[2]); - std::string cFilename(wFilename.begin(), wFilename.end()); + if (std::wstring(args.get()[1]) != L"-c") + { + BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Argument 1 must be \"-c\"."; + ::exit(-1); + } - boost::program_options::options_description& configOptions = UDPT::Tracker::getConfigOptions(); - boost::program_options::variables_map config; - boost::program_options::basic_parsed_options parsed_options = boost::program_options::parse_config_file(cFilename.c_str(), configOptions); - boost::program_options::store(parsed_options, config); + std::wstring wFilename(args.get()[2]); + std::string cFilename(wFilename.begin(), wFilename.end()); - s_hServiceStatus = ::RegisterServiceCtrlHandlerEx(config["service.name"].as().c_str(), Service::handler, NULL); - if (nullptr == s_hServiceStatus) - { - BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed to register service control handler."; - ::exit(-1); - } + boost::program_options::options_description& configOptions = UDPT::Tracker::getConfigOptions(); + boost::program_options::variables_map config; + boost::program_options::basic_parsed_options parsed_options = boost::program_options::parse_config_file(cFilename.c_str(), configOptions); + boost::program_options::store(parsed_options, config); - s_serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; - s_serviceStatus.dwServiceSpecificExitCode = 0; + s_hServiceStatus = ::RegisterServiceCtrlHandlerEx(config["service.name"].as().c_str(), Service::handler, NULL); + if (nullptr == s_hServiceStatus) + { + BOOST_LOG_SEV(logger, boost::log::trivial::fatal) << "Failed to register service control handler."; + ::exit(-1); + } - reportServiceStatus(SERVICE_START_PENDING, 0, 0); + s_serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + s_serviceStatus.dwServiceSpecificExitCode = 0; - { - UDPT::Tracker& tracker = UDPT::Tracker::getInstance(); - tracker.start(config); + reportServiceStatus(SERVICE_START_PENDING, 0, 0); - reportServiceStatus(SERVICE_RUNNING, 0, 0); + { + UDPT::Tracker& tracker = UDPT::Tracker::getInstance(); + tracker.start(config); - tracker.wait(); + reportServiceStatus(SERVICE_RUNNING, 0, 0); - reportServiceStatus(SERVICE_STOPPED, 0, 0); - } - } + tracker.wait(); - std::shared_ptr Service::getService(DWORD access) - { - std::shared_ptr serviceManager = getServiceManager(access); - { - SC_HANDLE service = ::OpenService(reinterpret_cast(serviceManager.get()), m_conf["service.name"].as().c_str(), access); - if (nullptr == service) - { - throw OSError(); - } - return std::shared_ptr(service, ::CloseServiceHandle); - } - } + reportServiceStatus(SERVICE_STOPPED, 0, 0); + } + } - std::shared_ptr Service::getServiceManager(DWORD access) - { - SC_HANDLE svcMgr = ::OpenSCManager(NULL, NULL, access); - if (nullptr == svcMgr) - { - throw OSError(); - } - return std::shared_ptr(svcMgr, ::CloseServiceHandle); - } + std::shared_ptr Service::getService(DWORD access) + { + std::shared_ptr serviceManager = getServiceManager(access); + { + SC_HANDLE service = ::OpenService(reinterpret_cast(serviceManager.get()), m_conf["service.name"].as().c_str(), access); + if (nullptr == service) + { + throw OSError(); + } + return std::shared_ptr(service, ::CloseServiceHandle); + } + } - std::string Service::getFilename() - { - char filename[MAX_PATH]; - DWORD dwRet = ::GetModuleFileName(NULL, filename, sizeof(filename) / sizeof(char)); - if (0 == dwRet) - { - throw OSError(); - } - return std::string(filename); - } + std::shared_ptr Service::getServiceManager(DWORD access) + { + SC_HANDLE svcMgr = ::OpenSCManager(NULL, NULL, access); + if (nullptr == svcMgr) + { + throw OSError(); + } + return std::shared_ptr(svcMgr, ::CloseServiceHandle); + } + + std::string Service::getFilename() + { + char filename[MAX_PATH]; + DWORD dwRet = ::GetModuleFileName(NULL, filename, sizeof(filename) / sizeof(char)); + if (0 == dwRet) + { + throw OSError(); + } + return std::string(filename); + } } #endif diff --git a/src/service.hpp b/src/service.hpp index 9c845e8..5bf96b3 100644 --- a/src/service.hpp +++ b/src/service.hpp @@ -1,5 +1,5 @@ /* -* Copyright © 2012-2016 Naim A. +* Copyright © 2012-2017 Naim A. * * This file is part of UDPT. * @@ -28,42 +28,42 @@ #ifdef WIN32 namespace UDPT { - class Service - { - public: - Service(const boost::program_options::variables_map& conf); + class Service + { + public: + Service(const boost::program_options::variables_map& conf); - virtual ~Service(); + virtual ~Service(); - void install(const std::string& config_path); + void install(const std::string& config_path); - void uninstall(); + void uninstall(); - void start(); + void start(); - void stop(); + void stop(); - void setup(); - private: - const boost::program_options::variables_map& m_conf; + void setup(); + private: + const boost::program_options::variables_map& m_conf; - static SERVICE_STATUS_HANDLE s_hServiceStatus; + static SERVICE_STATUS_HANDLE s_hServiceStatus; - static SERVICE_STATUS s_serviceStatus; + static SERVICE_STATUS s_serviceStatus; - std::shared_ptr getService(DWORD access); + std::shared_ptr getService(DWORD access); - static DWORD WINAPI handler(DWORD controlCode, DWORD dwEventType, LPVOID eventData, LPVOID context); + static DWORD WINAPI handler(DWORD controlCode, DWORD dwEventType, LPVOID eventData, LPVOID context); - static void reportServiceStatus(DWORD currentState, DWORD dwExitCode, DWORD dwWaitHint); + static void reportServiceStatus(DWORD currentState, DWORD dwExitCode, DWORD dwWaitHint); - static VOID WINAPI serviceMain(DWORD argc, LPCSTR argv[]); + static VOID WINAPI serviceMain(DWORD argc, LPCSTR argv[]); - static std::shared_ptr getServiceManager(DWORD access); + static std::shared_ptr getServiceManager(DWORD access); - static std::string getFilename(); - }; + static std::string getFilename(); + }; } #endif \ No newline at end of file diff --git a/src/tools.c b/src/tools.c index 60faa2b..4809a22 100644 --- a/src/tools.c +++ b/src/tools.c @@ -1,65 +1,65 @@ -/* - * Copyright © 2012-2016 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include "tools.h" -#include "multiplatform.h" - -void m_byteswap (void *dest, void *src, int sz) -{ - int i; - for (i = 0;i < sz;i++) - { - ((char*)dest)[i] = ((char*)src)[(sz - 1) - i]; - } -} - -uint16_t m_hton16(uint16_t n) -{ - uint16_t r; - m_byteswap (&r, &n, 2); - return r; -} - -uint64_t m_hton64 (uint64_t n) -{ - uint64_t r; - m_byteswap (&r, &n, 8); - return r; -} - -uint32_t m_hton32 (uint32_t n) -{ - uint64_t r; - m_byteswap (&r, &n, 4); - return r; -} - - -static const char hexadecimal[] = "0123456789abcdef"; - -void to_hex_str (const uint8_t *hash, char *data) -{ - int i; - for (i = 0;i < 20;i++) - { - data[i * 2] = hexadecimal[hash[i] / 16]; - data[i * 2 + 1] = hexadecimal[hash[i] % 16]; - } - data[40] = '\0'; -} +/* + * Copyright © 2012-2017 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "tools.h" +#include "multiplatform.h" + +void m_byteswap (void *dest, void *src, int sz) +{ + int i; + for (i = 0;i < sz;i++) + { + ((char*)dest)[i] = ((char*)src)[(sz - 1) - i]; + } +} + +uint16_t m_hton16(uint16_t n) +{ + uint16_t r; + m_byteswap (&r, &n, 2); + return r; +} + +uint64_t m_hton64 (uint64_t n) +{ + uint64_t r; + m_byteswap (&r, &n, 8); + return r; +} + +uint32_t m_hton32 (uint32_t n) +{ + uint64_t r; + m_byteswap (&r, &n, 4); + return r; +} + + +static const char hexadecimal[] = "0123456789abcdef"; + +void to_hex_str (const uint8_t *hash, char *data) +{ + int i; + for (i = 0;i < 20;i++) + { + data[i * 2] = hexadecimal[hash[i] / 16]; + data[i * 2 + 1] = hexadecimal[hash[i] % 16]; + } + data[40] = '\0'; +} diff --git a/src/tools.h b/src/tools.h index 39b1840..932b886 100644 --- a/src/tools.h +++ b/src/tools.h @@ -1,50 +1,50 @@ -/* - * Copyright © 2012-2016 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#ifndef TOOLS_H_ -#define TOOLS_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Swaps Bytes: - * example (htons): - * short a = 1234; - * short b; - * m_byteswap (&b, &a, sizeof(a)); - */ -void m_byteswap (void *dest, void *src, int sz); - -uint16_t m_hton16(uint16_t n); - -uint32_t m_hton32 (uint32_t n); - -uint64_t m_hton64 (uint64_t n); - -void to_hex_str (const uint8_t *hash, char *data); - -#ifdef __cplusplus -} -#endif - -#endif /* TOOLS_H_ */ +/* + * Copyright © 2012-2017 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#ifndef TOOLS_H_ +#define TOOLS_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Swaps Bytes: + * example (htons): + * short a = 1234; + * short b; + * m_byteswap (&b, &a, sizeof(a)); + */ +void m_byteswap (void *dest, void *src, int sz); + +uint16_t m_hton16(uint16_t n); + +uint32_t m_hton32 (uint32_t n); + +uint64_t m_hton64 (uint64_t n); + +void to_hex_str (const uint8_t *hash, char *data); + +#ifdef __cplusplus +} +#endif + +#endif /* TOOLS_H_ */ diff --git a/src/tracker.cpp b/src/tracker.cpp index f05e5e3..7243cf5 100644 --- a/src/tracker.cpp +++ b/src/tracker.cpp @@ -1,5 +1,5 @@ /* -* Copyright © 2012-2016 Naim A. +* Copyright © 2012-2017 Naim A. * * This file is part of UDPT. * @@ -16,52 +16,60 @@ * You should have received a copy of the GNU General Public License * along with UDPT. If not, see . */ +#include +#include #include "tracker.hpp" +#include "logging.hpp" namespace UDPT { - Tracker::Tracker() : m_logger(boost::log::keywords::channel = "TRACKER") + Tracker::Tracker() : m_logStream(nullptr) { - BOOST_LOG_SEV(m_logger, boost::log::trivial::debug) << "Initialized Tracker"; } Tracker::~Tracker() { - BOOST_LOG_SEV(m_logger, boost::log::trivial::debug) << "Destroying Tracker..."; + try { + if (nullptr != m_logStream) { + m_logStream->flush(); + delete m_logStream; + m_logStream = nullptr; + } + } catch (...) { + + } } void Tracker::stop() - { - BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Requesting Tracker to terminate."; + { + LOG_INFO("tracker", "Requesting components to terminate..."); m_udpTracker->stop(); - wait(); + // cause other components to destruct. m_apiSrv = nullptr; m_webApp = nullptr; - m_udpTracker = nullptr; } void Tracker::wait() - { - m_udpTracker->wait(); - BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Tracker terminated."; + { + m_udpTracker->wait(); } void Tracker::start(const boost::program_options::variables_map& conf) - { - BOOST_LOG_SEV(m_logger, boost::log::trivial::debug) << "Starting Tracker..."; - m_udpTracker = std::shared_ptr(new UDPTracker(conf)); + { + setupLogging(conf); + LOG_INFO("core", "Initializing..."); + + m_udpTracker = std::shared_ptr(new UDPTracker(conf)); if (conf["apiserver.enable"].as()) - { - BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Initializing and deploying WebAPI..."; + { m_apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(conf)); m_webApp = std::shared_ptr(new UDPT::Server::WebApp(m_apiSrv, m_udpTracker->m_conn.get(), conf)); m_webApp->deploy(); } - m_udpTracker->start(); - BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "Tracker started."; + m_udpTracker->start(); } Tracker& Tracker::getInstance() @@ -71,75 +79,73 @@ namespace UDPT return s_tracker; } - boost::program_options::options_description Tracker::getConfigOptions() - { - boost::program_options::options_description configOptions("Configuration options"); - configOptions.add_options() - ("db.driver", boost::program_options::value()->default_value("sqlite3"), "database driver to use") - ("db.param", boost::program_options::value()->default_value("/var/lib/udpt.db"), "database connection parameters") + boost::program_options::options_description Tracker::getConfigOptions() + { + boost::program_options::options_description configOptions("Configuration options"); + configOptions.add_options() + ("db.driver", boost::program_options::value()->default_value("sqlite3"), "database driver to use") + ("db.param", boost::program_options::value()->default_value("/var/lib/udpt.db"), "database connection parameters") - ("tracker.is_dynamic", boost::program_options::value()->default_value(true), "Sets if the tracker is dynamic") - ("tracker.port", boost::program_options::value()->default_value(6969), "UDP port to listen on") - ("tracker.threads", boost::program_options::value()->default_value(5), "threads to run (UDP only)") - ("tracker.allow_remotes", boost::program_options::value()->default_value(true), "allows clients to report remote IPs") - ("tracker.allow_iana_ips", boost::program_options::value()->default_value(false), "allows IANA reserved IPs to connect (useful for debugging)") - ("tracker.announce_interval", boost::program_options::value()->default_value(1800), "announce interval") - ("tracker.cleanup_interval", boost::program_options::value()->default_value(120), "sets database cleanup interval") + ("tracker.is_dynamic", boost::program_options::value()->default_value(true), "Sets if the tracker is dynamic") + ("tracker.port", boost::program_options::value()->default_value(6969), "UDP port to listen on") + ("tracker.threads", boost::program_options::value()->default_value(5), "threads to run (UDP only)") + ("tracker.allow_remotes", boost::program_options::value()->default_value(true), "allows clients to report remote IPs") + ("tracker.allow_iana_ips", boost::program_options::value()->default_value(false), "allows IANA reserved IPs to connect (useful for debugging)") + ("tracker.announce_interval", boost::program_options::value()->default_value(1800), "announce interval") + ("tracker.cleanup_interval", boost::program_options::value()->default_value(120), "sets database cleanup interval") - ("apiserver.enable", boost::program_options::value()->default_value(0), "Enable API server?") - ("apiserver.threads", boost::program_options::value()->default_value(1), "threads for API server") - ("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on") + ("apiserver.enable", boost::program_options::value()->default_value(0), "Enable API server?") + ("apiserver.threads", boost::program_options::value()->default_value(1), "threads for API server") + ("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on") - ("logging.filename", boost::program_options::value()->default_value("/var/log/udpt.log"), "file to write logs to") - ("logging.level", boost::program_options::value()->default_value("warning"), "log level (fatal/error/warning/info/debug/trace)") + ("logging.filename", boost::program_options::value()->default_value("/var/log/udpt.log"), "file to write logs to") + ("logging.level", boost::program_options::value()->default_value("warning"), "log level (fatal/error/warning/info/debug)") #ifdef linux - ("daemon.chdir", boost::program_options::value()->default_value("/"), "home directory for daemon") + ("daemon.chdir", boost::program_options::value()->default_value("/"), "home directory for daemon") #endif #ifdef WIN32 - ("service.name", boost::program_options::value()->default_value("udpt"), "service name to use") + ("service.name", boost::program_options::value()->default_value("udpt"), "service name to use") #endif - ; + ; - return configOptions; - } + return configOptions; + } - void Tracker::setupLogging(const boost::program_options::variables_map& config, boost::log::sources::severity_channel_logger_mt<>& logger) - { - boost::log::add_common_attributes(); - boost::shared_ptr logBackend = boost::make_shared( - boost::log::keywords::file_name = config["logging.filename"].as(), - boost::log::keywords::auto_flush = true, - boost::log::keywords::open_mode = std::ios::out | std::ios::app - ); - typedef boost::log::sinks::asynchronous_sink udptSink_t; - boost::shared_ptr async_sink(new udptSink_t(logBackend)); - async_sink->set_formatter( - boost::log::expressions::stream - << boost::log::expressions::format_date_time("TimeStamp", "%Y-%m-%d %H:%M:%S") << " " - << boost::log::expressions::attr("Severity") - << " [" << boost::log::expressions::attr("Channel") << "] \t" - << boost::log::expressions::smessage - ); - auto loggingCore = boost::log::core::get(); - loggingCore->add_sink(async_sink); + void Tracker::setupLogging(const boost::program_options::variables_map& va_map) { + Logging::Logger& logger = Logging::Logger::getLogger(); - std::string severity = config["logging.level"].as(); - std::transform(severity.begin(), severity.end(), severity.begin(), ::tolower); - int severityVal = boost::log::trivial::warning; - if ("fatal" == severity) severityVal = boost::log::trivial::fatal; - else if ("error" == severity) severityVal = boost::log::trivial::error; - else if ("warning" == severity) severityVal = boost::log::trivial::warning; - else if ("info" == severity) severityVal = boost::log::trivial::info; - else if ("debug" == severity) severityVal = boost::log::trivial::debug; - else if ("trace" == severity) severityVal = boost::log::trivial::trace; - else - { - BOOST_LOG_SEV(logger, boost::log::trivial::warning) << "Unknown debug level \"" << severity << "\" defaulting to warning"; - } + logger.addStream(&std::cerr, Logging::Severity::FATAL); - loggingCore->set_filter( - boost::log::trivial::severity >= severityVal - ); - } + Logging::Severity severity; + std::string severity_text = va_map["logging.level"].as(); + std::transform(severity_text.begin(), severity_text.end(), severity_text.begin(), ::tolower); + + if (severity_text == "fatal") { + severity = Logging::Severity::FATAL; + } else if (severity_text == "error") { + severity = Logging::Severity::ERROR; + } else if (severity_text == "warning") { + severity = Logging::Severity::WARNING; + } else if (severity_text == "info") { + severity = Logging::Severity::INFO; + } else if (severity_text == "debug") { + severity = Logging::Severity::DEBUG; + } else { + severity = Logging::Severity::UNSET; + } + + const std::string& logFileName = va_map["logging.filename"].as(); + Logging::Severity real_severity = (severity == Logging::Severity::UNSET ? Logging::Severity::INFO : severity); + if (logFileName.length() == 0 || logFileName == "--") { + logger.addStream(&std::cerr, real_severity); + } else { + m_logStream = new ofstream(logFileName, std::ios::app | std::ios::out); + logger.addStream(m_logStream, real_severity); + } + + if (severity != real_severity) { + LOG_WARN("core", "'" << severity_text << "' is invalid, log level set to " << real_severity); + } + } } diff --git a/src/tracker.hpp b/src/tracker.hpp index 43d19ff..3714372 100644 --- a/src/tracker.hpp +++ b/src/tracker.hpp @@ -1,5 +1,5 @@ /* -* Copyright © 2012-2016 Naim A. +* Copyright © 2012-2017 Naim A. * * This file is part of UDPT. * @@ -21,16 +21,7 @@ #include #include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include #include "multiplatform.h" #include "udpTracker.hpp" @@ -51,18 +42,18 @@ namespace UDPT void wait(); - static Tracker& getInstance(); + static Tracker& getInstance(); - static boost::program_options::options_description getConfigOptions(); - - static void setupLogging(const boost::program_options::variables_map& config, boost::log::sources::severity_channel_logger_mt<>& logger); + static boost::program_options::options_description getConfigOptions(); private: std::shared_ptr m_udpTracker; std::shared_ptr m_apiSrv; std::shared_ptr m_webApp; - boost::log::sources::severity_channel_logger_mt<> m_logger; Tracker(); + + void setupLogging(const boost::program_options::variables_map& va_map); + std::ostream *m_logStream; }; } diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index d5f265b..c451235 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -1,477 +1,450 @@ -/* - * Copyright © 2012-2016 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include "udpTracker.hpp" - - -using namespace UDPT::Data; - -#define UDP_BUFFER_SIZE 2048 - -namespace UDPT -{ - UDPTracker::UDPTracker(const boost::program_options::variables_map& conf) : m_conf(conf), m_logger(boost::log::keywords::channel = "UDPTracker") - { - this->m_allowRemotes = conf["tracker.allow_remotes"].as(); - this->m_allowIANA_IPs = conf["tracker.allow_iana_ips"].as(); - this->m_isDynamic = conf["tracker.is_dynamic"].as(); - - this->m_announceInterval = conf["tracker.announce_interval"].as(); - this->m_cleanupInterval = conf["tracker.cleanup_interval"].as(); - this->m_port = conf["tracker.port"].as(); - this->m_threadCount = conf["tracker.threads"].as() + 1; - - std::list addrs; - - if (addrs.empty()) - { - SOCKADDR_IN sa; - sa.sin_port = m_hton16(m_port); - sa.sin_addr.s_addr = 0L; - addrs.push_back(sa); - } - - this->m_localEndpoint = addrs.front(); - - this->m_conn = std::shared_ptr(new Data::SQLite3Driver(m_conf, this->m_isDynamic)); - } - - UDPTracker::~UDPTracker() - { - stop(); - } - - void UDPTracker::start() - { - SOCKET sock; - int r, // saves results - i, // loop index - yup; // just to set TRUE - std::string dbname;// saves the Database name. - - sock = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (sock == INVALID_SOCKET) - { - throw UDPT::UDPTException("Failed to create socket"); - } - - yup = 1; - ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); - - { - // don't block recvfrom for too long. -#if defined(linux) - timeval timeout = { 0 }; - timeout.tv_sec = 5; -#elif defined(WIN32) - DWORD timeout = 5000; -#else -#error Unsupported OS. -#endif - ::setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); - } - - this->m_localEndpoint.sin_family = AF_INET; - r = ::bind(sock, reinterpret_cast(&this->m_localEndpoint), sizeof(SOCKADDR_IN)); - - if (r == SOCKET_ERROR) - { - #ifdef WIN32 - ::closesocket(sock); - #elif defined (linux) - ::close(sock); -#endif - throw UDPT::UDPTException("Failed to bind socket."); - } - - { - char buff[INET_ADDRSTRLEN]; - BOOST_LOG_SEV(m_logger, boost::log::trivial::info) << "UDP tracker bound on " << ::inet_ntop(AF_INET, reinterpret_cast(&m_localEndpoint.sin_addr), buff, sizeof(buff)) << ":" << htons(m_localEndpoint.sin_port); - } - - this->m_sock = sock; - - // create maintainer thread. - - m_threads.push_back(boost::thread(UDPTracker::_maintainance_start, this)); - - for (i = 1;i < this->m_threadCount; i++) - { - m_threads.push_back(boost::thread(UDPTracker::_thread_start, this)); - } - } - - void UDPTracker::stop() - { -#ifdef linux - ::close(m_sock); -#elif defined (WIN32) - ::closesocket(m_sock); -#endif - - BOOST_LOG_SEV(m_logger, boost::log::trivial::warning) << "Interrupting workers..."; - for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it) - { - it->interrupt(); - } - - wait(); - } - - void UDPTracker::wait() - { - BOOST_LOG_SEV(m_logger, boost::log::trivial::warning) << "Waiting for threads to terminate..."; - - for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it) - { - it->join(); - } - } - - int UDPTracker::sendError(UDPTracker* usi, SOCKADDR_IN* remote, uint32_t transactionID, const std::string &msg) - { - struct udp_error_response error; - int msg_sz, // message size to send. - i; // copy loop - char buff [1024]; // more than reasonable message size... - - error.action = m_hton32 (3); - error.transaction_id = transactionID; - error.message = (char*)msg.c_str(); - - msg_sz = 4 + 4 + 1 + msg.length(); - - // test against overflow message. resolves issue 4. - if (msg_sz > 1024) - return -1; - - ::memcpy(buff, &error, 8); - for (i = 8;i <= msg_sz;i++) - { - buff[i] = msg[i - 8]; - } - - ::sendto(usi->m_sock, buff, msg_sz, 0, reinterpret_cast(remote), sizeof(*remote)); - - return 0; - } - - int UDPTracker::handleConnection(UDPTracker *usi, SOCKADDR_IN *remote, char *data) - { - ConnectionRequest *req = reinterpret_cast(data); - ConnectionResponse resp; - - resp.action = m_hton32(0); - resp.transaction_id = req->transaction_id; - - if (!usi->m_conn->genConnectionId(&resp.connection_id, - m_hton32(remote->sin_addr.s_addr), - m_hton16(remote->sin_port))) - { - return 1; - } - - ::sendto(usi->m_sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - - { - char buffer[INET_ADDRSTRLEN]; - BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::debug) << "Connection Request from " << ::inet_ntop(AF_INET, &remote->sin_addr, buffer, sizeof(buffer)) << "; cId=" << resp.connection_id << "; tId=" << resp.transaction_id; - } - - - return 0; - } - - int UDPTracker::handleAnnounce(UDPTracker *usi, SOCKADDR_IN *remote, char *data) - { - AnnounceRequest *req; - AnnounceResponse *resp; - int q, // peer counts - bSize, // message size - i; // loop index - DatabaseDriver::TorrentEntry tE; - - uint8_t buff[1028]; // Reasonable buffer size. (header+168 peers) - - req = (AnnounceRequest*)data; - - if (!usi->m_conn->verifyConnectionId(req->connection_id, - m_hton32(remote->sin_addr.s_addr), - m_hton16(remote->sin_port))) - { - return 1; - } - - // change byte order: - req->port = m_hton16(req->port); - req->ip_address = m_hton32(req->ip_address); - req->downloaded = m_hton64(req->downloaded); - req->event = m_hton32(req->event); // doesn't really matter for this tracker - req->uploaded = m_hton64(req->uploaded); - req->num_want = m_hton32(req->num_want); - req->left = m_hton64(req->left); - - if (!usi->m_allowRemotes && req->ip_address != 0) - { - UDPTracker::sendError(usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); - return 0; - } - - if (!usi->m_conn->isTorrentAllowed(req->info_hash)) - { - UDPTracker::sendError(usi, remote, req->transaction_id, "info_hash not registered."); - return 0; - } - - // load peers - q = 30; - if (req->num_want >= 1) - q = std::min(q, req->num_want); - - DatabaseDriver::TrackerEvents event; - - { - std::shared_ptr peersSptr = std::shared_ptr(new DatabaseDriver::PeerEntry[q]); - DatabaseDriver::PeerEntry *peers = peersSptr.get(); - - switch (req->event) - { - case 1: - event = DatabaseDriver::EVENT_COMPLETE; - break; - case 2: - event = DatabaseDriver::EVENT_START; - break; - case 3: - event = DatabaseDriver::EVENT_STOP; - break; - default: - event = DatabaseDriver::EVENT_UNSPEC; - break; - } - - if (event == DatabaseDriver::EVENT_STOP) - q = 0; // no need for peers when stopping. - - if (q > 0) - usi->m_conn->getPeers(req->info_hash, &q, peers); - - bSize = 20; // header is 20 bytes - bSize += (6 * q); // + 6 bytes per peer. - - tE.info_hash = req->info_hash; - usi->m_conn->getTorrentInfo(&tE); - - resp = (AnnounceResponse*)buff; - resp->action = m_hton32(1); - resp->interval = m_hton32(usi->m_announceInterval); - resp->leechers = m_hton32(tE.leechers); - resp->seeders = m_hton32(tE.seeders); - resp->transaction_id = req->transaction_id; - - for (i = 0; i < q; i++) - { - int x = i * 6; - // network byte order!!! - - // IP - buff[20 + x] = ((peers[i].ip & (0xff << 24)) >> 24); - buff[21 + x] = ((peers[i].ip & (0xff << 16)) >> 16); - buff[22 + x] = ((peers[i].ip & (0xff << 8)) >> 8); - buff[23 + x] = (peers[i].ip & 0xff); - - // port - buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8); - buff[25 + x] = (peers[i].port & 0xff); - - } - } - ::sendto(usi->m_sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - - // update DB. - uint32_t ip; - if (req->ip_address == 0) // default - ip = m_hton32 (remote->sin_addr.s_addr); - else - ip = req->ip_address; - usi->m_conn->updatePeer(req->peer_id, req->info_hash, ip, req->port, - req->downloaded, req->left, req->uploaded, event); - - return 0; - } - - int UDPTracker::handleScrape(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len) - { - ScrapeRequest *sR = reinterpret_cast(data); - int v, // validation helper - c, // torrent counter - i, // loop counter - j; // loop counter - uint8_t hash [20]; - ScrapeResponse *resp; - uint8_t buffer [1024]; // up to 74 torrents can be scraped at once (17*74+8) < 1024 - - // validate request length: - v = len - 16; - if (v < 0 || v % 20 != 0) - { - UDPTracker::sendError(usi, remote, sR->transaction_id, "Bad scrape request."); - return 0; - } - - if (!usi->m_conn->verifyConnectionId(sR->connection_id, - m_hton32(remote->sin_addr.s_addr), - m_hton16(remote->sin_port))) - { - return 1; - } - - // get torrent count. - c = v / 20; - - resp = reinterpret_cast(buffer); - resp->action = m_hton32(2); - resp->transaction_id = sR->transaction_id; - - for (i = 0;i < c;i++) - { - int32_t *seeders, - *completed, - *leechers; - - for (j = 0; j < 20;j++) - hash[j] = data[j + (i*20)+16]; - - seeders = (int32_t*)&buffer[i*12+8]; - completed = (int32_t*)&buffer[i*12+12]; - leechers = (int32_t*)&buffer[i*12+16]; - - DatabaseDriver::TorrentEntry tE; - tE.info_hash = hash; - if (!usi->m_conn->getTorrentInfo(&tE)) - { - sendError(usi, remote, sR->transaction_id, "Scrape Failed: couldn't retrieve torrent data"); - return 0; - } - - *seeders = m_hton32(tE.seeders); - *completed = m_hton32(tE.completed); - *leechers = m_hton32(tE.leechers); - } - - ::sendto(usi->m_sock, reinterpret_cast(buffer), sizeof(buffer), 0, reinterpret_cast(remote), sizeof(SOCKADDR_IN)); - - return 0; - } - - int UDPTracker::isIANAIP(uint32_t ip) - { - uint8_t x = (ip % 256); - if (x == 0 || x == 10 || x == 127 || x >= 224) - return 1; - return 0; - } - - int UDPTracker::resolveRequest(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r) - { - ConnectionRequest* cR = reinterpret_cast(data); - uint32_t action; - - action = m_hton32(cR->action); - - if (!usi->m_allowIANA_IPs) - { - if (isIANAIP(remote->sin_addr.s_addr)) - { - char buffer[INET_ADDRSTRLEN]; - BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::warning) << "Client ignored (IANA IP): " << ::inet_ntop(AF_INET, &remote->sin_addr, buffer, sizeof(buffer)); - return 0; // Access Denied: IANA reserved IP. - } - } - - { - - char buffer[INET_ADDRSTRLEN]; - BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::debug) << "Client request from " << ::inet_ntop(AF_INET, &remote->sin_addr, buffer, sizeof(buffer)); - } - - if (action == 0 && r >= 16) - return UDPTracker::handleConnection(usi, remote, data); - else if (action == 1 && r >= 98) - return UDPTracker::handleAnnounce(usi, remote, data); - else if (action == 2) - return UDPTracker::handleScrape(usi, remote, data, r); - else - { - UDPTracker::sendError(usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); - return -1; - } - - return 0; - } - - void UDPTracker::_thread_start(UDPTracker *usi) - { - BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::info) << "Worker thread started with PID=" << boost::this_thread::get_id() << "."; - SOCKADDR_IN remoteAddr; - char tmpBuff[UDP_BUFFER_SIZE]; - -#ifdef linux - socklen_t addrSz; -#else - int addrSz; -#endif - - addrSz = sizeof(SOCKADDR_IN); - - - while (true) - { - // peek into the first 12 bytes of data; determine if connection request or announce request. - int r = ::recvfrom(usi->m_sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); - if (r <= 0) - { - boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); - continue; - } - - { - boost::this_thread::disable_interruption di; - - UDPTracker::resolveRequest(usi, &remoteAddr, tmpBuff, r); - } - } - } - - void UDPTracker::_maintainance_start(UDPTracker* usi) - { - BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::info) << "Maintenance thread started with PID=" << boost::this_thread::get_id() << "."; - while (true) - { - { - boost::this_thread::disable_interruption di; - BOOST_LOG_SEV(usi->m_logger, boost::log::trivial::info) << "Running cleanup..."; - usi->m_conn->cleanup(); - } - - boost::this_thread::sleep_for(boost::chrono::seconds(usi->m_cleanupInterval)); - } - } - -}; +/* + * Copyright © 2012-2017 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#include "udpTracker.hpp" +#include "logging.hpp" + + +using namespace UDPT::Data; + +#define UDP_BUFFER_SIZE 2048 + +namespace UDPT +{ + UDPTracker::UDPTracker(const boost::program_options::variables_map& conf) : m_conf(conf) { + this->m_allowRemotes = conf["tracker.allow_remotes"].as(); + this->m_allowIANA_IPs = conf["tracker.allow_iana_ips"].as(); + this->m_isDynamic = conf["tracker.is_dynamic"].as(); + + this->m_announceInterval = conf["tracker.announce_interval"].as(); + this->m_cleanupInterval = conf["tracker.cleanup_interval"].as(); + this->m_port = conf["tracker.port"].as(); + this->m_threadCount = conf["tracker.threads"].as() + 1; + + this->m_localEndpoint.sin_family = AF_INET; + this->m_localEndpoint.sin_port = m_hton16(m_port); + this->m_localEndpoint.sin_addr.s_addr = 0L; + + this->m_conn = std::shared_ptr(new Data::SQLite3Driver(m_conf, this->m_isDynamic)); + } + + UDPTracker::~UDPTracker() { + } + + void UDPTracker::start() { + SOCKET sock; + int r, // saves results + i, // loop index + yup; // just to set TRUE + std::string dbname;// saves the Database name. + + sock = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sock == INVALID_SOCKET) + { + LOG_FATAL("udp-tracker", "Failed to create socket. error=" << errno); + throw UDPT::UDPTException("Failed to create socket"); + } + + yup = 1; + ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); + + { + // don't block recvfrom for too long. +#if defined(linux) + timeval timeout = { 0 }; + timeout.tv_sec = 5; +#elif defined(WIN32) + DWORD timeout = 5000; +#else +#error Unsupported OS. +#endif + ::setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); + } + + this->m_localEndpoint.sin_family = AF_INET; + r = ::bind(sock, reinterpret_cast(&this->m_localEndpoint), sizeof(SOCKADDR_IN)); + + if (r == SOCKET_ERROR) + { + LOG_FATAL("udp-tracker", "Failed to bind socket. error=" << errno); + + #ifdef WIN32 + ::closesocket(sock); + #elif defined (linux) + ::close(sock); + #endif + throw UDPT::UDPTException("Failed to bind socket."); + } + + this->m_sock = sock; + + LOG_INFO("udp-tracker", "Tracker bound to " << inet_ntoa(this->m_localEndpoint.sin_addr)); + + // create maintainer thread. + m_threads.push_back(std::thread(UDPTracker::_maintainance_start, this)); + LOG_INFO("udp-tracker", "Started maintenance thread @" << m_threads.back().get_id()); + + m_shouldRun = true; + for (i = 1;i < this->m_threadCount; i++) + { + m_threads.push_back(std::thread(UDPTracker::_thread_start, this)); + LOG_INFO("udp-tracker", "Started worker thread @" << m_threads.back().get_id()); + } + } + + void UDPTracker::stop() { + // tell workers to stop running... + m_shouldRun = false; + + // stop maintenance thread's sleep... + m_maintenanceCondition.notify_one(); + } + + /** + * @brief blocks until all threads die. + * @note This method should be called only once, preferably by the main thread. + * **/ + void UDPTracker::wait() { + LOG_INFO("udp-tracker", "Waiting for threads to terminate..."); + + for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it) + { + it->join(); + } + + LOG_INFO("udp-tracker", "UDP Tracker terminated"); + +#ifdef linux + ::close(m_sock); +#elif defined (WIN32) + ::closesocket(m_sock); +#endif + } + + int UDPTracker::sendError(UDPTracker* usi, SOCKADDR_IN* remote, uint32_t transactionID, const std::string &msg) { + struct udp_error_response error; + int msg_sz, // message size to send. + i; // copy loop + char buff [1024]; // more than reasonable message size... + + error.action = m_hton32 (3); + error.transaction_id = transactionID; + error.message = (char*)msg.c_str(); + + msg_sz = 4 + 4 + 1 + msg.length(); + + // test against overflow message. resolves issue 4. + if (msg_sz > 1024) + return -1; + + ::memcpy(buff, &error, 8); + for (i = 8;i <= msg_sz;i++) + { + buff[i] = msg[i - 8]; + } + + ::sendto(usi->m_sock, buff, msg_sz, 0, reinterpret_cast(remote), sizeof(*remote)); + + LOG_DEBUG("udp-tracker", "Error sent to " << inet_ntoa(remote->sin_addr) << ", '" << msg << "' (len=" << msg_sz << ")"); + + return 0; + } + + int UDPTracker::handleConnection(UDPTracker *usi, SOCKADDR_IN *remote, char *data) { + ConnectionRequest *req = reinterpret_cast(data); + ConnectionResponse resp; + + resp.action = m_hton32(0); + resp.transaction_id = req->transaction_id; + + if (!usi->m_conn->genConnectionId(&resp.connection_id, + m_hton32(remote->sin_addr.s_addr), + m_hton16(remote->sin_port))) + { + return 1; + } + + ::sendto(usi->m_sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + + return 0; + } + + int UDPTracker::handleAnnounce(UDPTracker *usi, SOCKADDR_IN *remote, char *data) { + AnnounceRequest *req; + AnnounceResponse *resp; + int q, // peer counts + bSize, // message size + i; // loop index + DatabaseDriver::TorrentEntry tE; + + uint8_t buff[1028]; // Reasonable buffer size. (header+168 peers) + + req = (AnnounceRequest*)data; + + if (!usi->m_conn->verifyConnectionId(req->connection_id, + m_hton32(remote->sin_addr.s_addr), + m_hton16(remote->sin_port))) + { + return 1; + } + + // change byte order: + req->port = m_hton16(req->port); + req->ip_address = m_hton32(req->ip_address); + req->downloaded = m_hton64(req->downloaded); + req->event = m_hton32(req->event); // doesn't really matter for this tracker + req->uploaded = m_hton64(req->uploaded); + req->num_want = m_hton32(req->num_want); + req->left = m_hton64(req->left); + + if (!usi->m_allowRemotes && req->ip_address != 0) + { + UDPTracker::sendError(usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); + return 0; + } + + if (!usi->m_conn->isTorrentAllowed(req->info_hash)) + { + UDPTracker::sendError(usi, remote, req->transaction_id, "info_hash not registered."); + return 0; + } + + // load peers + q = 30; + if (req->num_want >= 1) + q = std::min(q, req->num_want); + + DatabaseDriver::TrackerEvents event; + + { + std::shared_ptr peersSptr = std::shared_ptr(new DatabaseDriver::PeerEntry[q]); + DatabaseDriver::PeerEntry *peers = peersSptr.get(); + + switch (req->event) + { + case 1: + event = DatabaseDriver::EVENT_COMPLETE; + break; + case 2: + event = DatabaseDriver::EVENT_START; + break; + case 3: + event = DatabaseDriver::EVENT_STOP; + break; + default: + event = DatabaseDriver::EVENT_UNSPEC; + break; + } + + if (event == DatabaseDriver::EVENT_STOP) + q = 0; // no need for peers when stopping. + + if (q > 0) + usi->m_conn->getPeers(req->info_hash, &q, peers); + + bSize = 20; // header is 20 bytes + bSize += (6 * q); // + 6 bytes per peer. + + tE.info_hash = req->info_hash; + usi->m_conn->getTorrentInfo(&tE); + + resp = (AnnounceResponse*)buff; + resp->action = m_hton32(1); + resp->interval = m_hton32(usi->m_announceInterval); + resp->leechers = m_hton32(tE.leechers); + resp->seeders = m_hton32(tE.seeders); + resp->transaction_id = req->transaction_id; + + for (i = 0; i < q; i++) + { + int x = i * 6; + // network byte order!!! + + // IP + buff[20 + x] = ((peers[i].ip & (0xff << 24)) >> 24); + buff[21 + x] = ((peers[i].ip & (0xff << 16)) >> 16); + buff[22 + x] = ((peers[i].ip & (0xff << 8)) >> 8); + buff[23 + x] = (peers[i].ip & 0xff); + + // port + buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8); + buff[25 + x] = (peers[i].port & 0xff); + + } + } + ::sendto(usi->m_sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + LOG_DEBUG("udp-tracker", "Announce request from " << inet_ntoa(remote->sin_addr) << " (event=" << event << "), Sent " << q << " peers"); + + // update DB. + uint32_t ip; + if (req->ip_address == 0) // default + ip = m_hton32 (remote->sin_addr.s_addr); + else + ip = req->ip_address; + usi->m_conn->updatePeer(req->peer_id, req->info_hash, ip, req->port, + req->downloaded, req->left, req->uploaded, event); + + return 0; + } + + int UDPTracker::handleScrape(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len) { + ScrapeRequest *sR = reinterpret_cast(data); + int v, // validation helper + c, // torrent counter + i, // loop counter + j; // loop counter + uint8_t hash [20]; + ScrapeResponse *resp; + uint8_t buffer [1024]; // up to 74 torrents can be scraped at once (17*74+8) < 1024 + + // validate request length: + v = len - 16; + if (v < 0 || v % 20 != 0) + { + UDPTracker::sendError(usi, remote, sR->transaction_id, "Bad scrape request."); + return 0; + } + + if (!usi->m_conn->verifyConnectionId(sR->connection_id, + m_hton32(remote->sin_addr.s_addr), + m_hton16(remote->sin_port))) + { + LOG_DEBUG("udp-tracker", "Bad connection id from " << inet_ntoa(remote->sin_addr)); + return 1; + } + + // get torrent count. + c = v / 20; + + resp = reinterpret_cast(buffer); + resp->action = m_hton32(2); + resp->transaction_id = sR->transaction_id; + + for (i = 0;i < c;i++) + { + int32_t *seeders, + *completed, + *leechers; + + for (j = 0; j < 20;j++) + hash[j] = data[j + (i*20)+16]; + + seeders = (int32_t*)&buffer[i*12+8]; + completed = (int32_t*)&buffer[i*12+12]; + leechers = (int32_t*)&buffer[i*12+16]; + + DatabaseDriver::TorrentEntry tE; + tE.info_hash = hash; + if (!usi->m_conn->getTorrentInfo(&tE)) + { + sendError(usi, remote, sR->transaction_id, "Scrape Failed: couldn't retrieve torrent data"); + return 0; + } + + *seeders = m_hton32(tE.seeders); + *completed = m_hton32(tE.completed); + *leechers = m_hton32(tE.leechers); + } + + ::sendto(usi->m_sock, reinterpret_cast(buffer), sizeof(buffer), 0, reinterpret_cast(remote), sizeof(SOCKADDR_IN)); + LOG_DEBUG("udp-tracker", "Scrape request from " << inet_ntoa(remote->sin_addr) << ", Sent " << c << " torrents"); + + return 0; + } + + int UDPTracker::isIANAIP(uint32_t ip) { + uint8_t x = (ip % 256); + if (x == 0 || x == 10 || x == 127 || x >= 224) + return 1; + return 0; + } + + int UDPTracker::resolveRequest(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r) { + ConnectionRequest* cR = reinterpret_cast(data); + uint32_t action; + + action = m_hton32(cR->action); + + if (!usi->m_allowIANA_IPs) + { + if (isIANAIP(remote->sin_addr.s_addr)) + { + LOG_DEBUG("udp-tracker", "Request from IANA reserved IP rejected (" << inet_ntoa(remote->sin_addr) << ")"); + return 0; // Access Denied: IANA reserved IP. + } + } + + if (action == 0 && r >= 16) + return UDPTracker::handleConnection(usi, remote, data); + else if (action == 1 && r >= 98) + return UDPTracker::handleAnnounce(usi, remote, data); + else if (action == 2) + return UDPTracker::handleScrape(usi, remote, data, r); + else + { + UDPTracker::sendError(usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); + return -1; + } + } + + void UDPTracker::_thread_start(UDPTracker *usi) { + SOCKADDR_IN remoteAddr; + char tmpBuff[UDP_BUFFER_SIZE]; + +#ifdef linux + socklen_t addrSz; +#else + int addrSz; +#endif + + addrSz = sizeof(SOCKADDR_IN); + + while (usi->m_shouldRun) + { + // peek into the first 12 bytes of data; determine if connection request or announce request. + int r = ::recvfrom(usi->m_sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); + if (r <= 0) + { + std::this_thread::yield(); + continue; + } + + UDPTracker::resolveRequest(usi, &remoteAddr, tmpBuff, r); + } + + LOG_INFO("udp-tracker", "worker " << std::this_thread::get_id() << " exited."); + } + + void UDPTracker::_maintainance_start(UDPTracker* usi) { + std::unique_lock lk (usi->m_maintenanceMutex); + + while (true) + { + if (std::cv_status::no_timeout == usi->m_maintenanceCondition.wait_for(lk, std::chrono::seconds(usi->m_cleanupInterval))) { + break; + } + + LOG_INFO("udp-tracker", "Maintenance running..."); + usi->m_conn->cleanup(); + } + + lk.unlock(); + LOG_INFO("udp-tracker", "Maintenance thread " << std::this_thread::get_id() << " existed."); + } +}; diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index c0441c8..18dd8cc 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -1,185 +1,188 @@ -/* - * Copyright © 2012-2016 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#ifndef UDPTRACKER_H_ -#define UDPTRACKER_H_ - - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "tools.h" -#include "exceptions.h" -#include "multiplatform.h" -#include "db/driver_sqlite.hpp" - -#define UDPT_DYNAMIC (0x01) // Track Any info_hash? -#define UDPT_ALLOW_REMOTE_IP (0x02) // Allow client's to send other IPs? -#define UDPT_ALLOW_IANA_IP (0x04) // allow IP's like 127.0.0.1 or other IANA reserved IPs? -#define UDPT_VALIDATE_CLIENT (0x08) // validate client before adding to Database? (check if connection is open?) - - -namespace UDPT -{ - class UDPTracker - { - public: - typedef struct udp_connection_request - { - uint64_t connection_id; - uint32_t action; - uint32_t transaction_id; - } ConnectionRequest; - - typedef struct udp_connection_response - { - uint32_t action; - uint32_t transaction_id; - uint64_t connection_id; - } ConnectionResponse; - - typedef struct udp_announce_request - { - uint64_t connection_id; - uint32_t action; - uint32_t transaction_id; - uint8_t info_hash [20]; - uint8_t peer_id [20]; - uint64_t downloaded; - uint64_t left; - uint64_t uploaded; - uint32_t event; - uint32_t ip_address; - uint32_t key; - int32_t num_want; - uint16_t port; - } AnnounceRequest; - - typedef struct udp_announce_response - { - uint32_t action; - uint32_t transaction_id; - uint32_t interval; - uint32_t leechers; - uint32_t seeders; - - uint8_t *peer_list_data; - } AnnounceResponse; - - typedef struct udp_scrape_request - { - uint64_t connection_id; - uint32_t action; - uint32_t transaction_id; - - uint8_t *torrent_list_data; - } ScrapeRequest; - - typedef struct udp_scrape_response - { - uint32_t action; - uint32_t transaction_id; - - uint8_t *data; - } ScrapeResponse; - - typedef struct udp_error_response - { - uint32_t action; - uint32_t transaction_id; - char *message; - } ErrorResponse; - - enum StartStatus - { - START_OK = 0, - START_ESOCKET_FAILED = 1, - START_EBIND_FAILED = 2 - }; - - /** - * Initializes the UDP Tracker. - * @param settings Settings to start server with - */ - UDPTracker(const boost::program_options::variables_map& conf); - - /** - * Starts the Initialized instance. - */ - void start(); - - /** - * Terminates tracker. - */ - void stop(); - - /** - * Joins worker threads - */ - void wait(); - - /** - * Destroys resources that were created by constructor - * @param usi Instance to destroy. - */ - virtual ~UDPTracker(); - - std::shared_ptr m_conn; - - private: - SOCKET m_sock; - SOCKADDR_IN m_localEndpoint; - uint16_t m_port; - uint8_t m_threadCount; - bool m_isDynamic; - bool m_allowRemotes; - bool m_allowIANA_IPs; - std::vector m_threads; - uint32_t m_announceInterval; - uint32_t m_cleanupInterval; - boost::log::sources::severity_channel_logger_mt<> m_logger; - - const boost::program_options::variables_map& m_conf; - - static void _thread_start(UDPTracker *usi); - static void _maintainance_start(UDPTracker* usi); - - static int resolveRequest(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r); - - static int handleConnection(UDPTracker *usi, SOCKADDR_IN *remote, char *data); - static int handleAnnounce(UDPTracker *usi, SOCKADDR_IN *remote, char *data); - static int handleScrape(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len); - - static int sendError(UDPTracker *, SOCKADDR_IN *remote, uint32_t transId, const std::string &); - - static int isIANAIP(uint32_t ip); - }; -}; - -#endif /* UDPTRACKER_H_ */ +/* + * Copyright © 2012-2017 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#ifndef UDPTRACKER_H_ +#define UDPTRACKER_H_ + + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "tools.h" +#include "exceptions.h" +#include "multiplatform.h" +#include "db/driver_sqlite.hpp" + +#define UDPT_DYNAMIC (0x01) // Track Any info_hash? +#define UDPT_ALLOW_REMOTE_IP (0x02) // Allow client's to send other IPs? +#define UDPT_ALLOW_IANA_IP (0x04) // allow IP's like 127.0.0.1 or other IANA reserved IPs? +#define UDPT_VALIDATE_CLIENT (0x08) // validate client before adding to Database? (check if connection is open?) + + +namespace UDPT +{ + class UDPTracker + { + public: + typedef struct udp_connection_request + { + uint64_t connection_id; + uint32_t action; + uint32_t transaction_id; + } ConnectionRequest; + + typedef struct udp_connection_response + { + uint32_t action; + uint32_t transaction_id; + uint64_t connection_id; + } ConnectionResponse; + + typedef struct udp_announce_request + { + uint64_t connection_id; + uint32_t action; + uint32_t transaction_id; + uint8_t info_hash [20]; + uint8_t peer_id [20]; + uint64_t downloaded; + uint64_t left; + uint64_t uploaded; + uint32_t event; + uint32_t ip_address; + uint32_t key; + int32_t num_want; + uint16_t port; + } AnnounceRequest; + + typedef struct udp_announce_response + { + uint32_t action; + uint32_t transaction_id; + uint32_t interval; + uint32_t leechers; + uint32_t seeders; + + uint8_t *peer_list_data; + } AnnounceResponse; + + typedef struct udp_scrape_request + { + uint64_t connection_id; + uint32_t action; + uint32_t transaction_id; + + uint8_t *torrent_list_data; + } ScrapeRequest; + + typedef struct udp_scrape_response + { + uint32_t action; + uint32_t transaction_id; + + uint8_t *data; + } ScrapeResponse; + + typedef struct udp_error_response + { + uint32_t action; + uint32_t transaction_id; + char *message; + } ErrorResponse; + + enum StartStatus + { + START_OK = 0, + START_ESOCKET_FAILED = 1, + START_EBIND_FAILED = 2 + }; + + /** + * Initializes the UDP Tracker. + * @param settings Settings to start server with + */ + UDPTracker(const boost::program_options::variables_map& conf); + + /** + * Starts the Initialized instance. + */ + void start(); + + /** + * Terminates tracker. + */ + void stop(); + + /** + * Joins worker threads + */ + void wait(); + + /** + * Destroys resources that were created by constructor + * @param usi Instance to destroy. + */ + virtual ~UDPTracker(); + + std::shared_ptr m_conn; + + private: + SOCKET m_sock; + SOCKADDR_IN m_localEndpoint; + uint16_t m_port; + uint8_t m_threadCount; + bool m_isDynamic; + bool m_allowRemotes; + bool m_allowIANA_IPs; + std::vector m_threads; + uint32_t m_announceInterval; + uint32_t m_cleanupInterval; + std::atomic_bool m_shouldRun; + + std::mutex m_maintenanceMutex; + std::condition_variable m_maintenanceCondition; + + const boost::program_options::variables_map& m_conf; + + static void _thread_start(UDPTracker *usi); + static void _maintainance_start(UDPTracker* usi); + + static int resolveRequest(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r); + + static int handleConnection(UDPTracker *usi, SOCKADDR_IN *remote, char *data); + static int handleAnnounce(UDPTracker *usi, SOCKADDR_IN *remote, char *data); + static int handleScrape(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len); + + static int sendError(UDPTracker *, SOCKADDR_IN *remote, uint32_t transId, const std::string &); + + static int isIANAIP(uint32_t ip); + }; +}; + +#endif /* UDPTRACKER_H_ */ diff --git a/tests/main.cpp b/tests/main.cpp new file mode 100644 index 0000000..dcd985a --- /dev/null +++ b/tests/main.cpp @@ -0,0 +1,55 @@ +#include +#include "../src/tools.h" +#include "../src/db/driver_sqlite.hpp" + +TEST(Utility, SanityCheck) { + const uint32_t MAGIC = 0xDEADBEEF; + const unsigned char MAGIC_BYTES[4] = {0xEF, 0xBE, 0xAD, 0xDE}; + ASSERT_TRUE(memcmp(&MAGIC, MAGIC_BYTES, 4) == 0); +} + +TEST(Utility, CheckMTON) { + EXPECT_EQ(m_hton16(0xDEAD), 0xADDE); + EXPECT_EQ(m_hton32(0xDEADBEEF), 0xEFBEADDE); + EXPECT_EQ(m_hton64(0xDEADBEEFA1B2C3E4), 0xE4C3B2A1EFBEADDE); +} + +TEST(Utility, HashToHexStr) { + const char EXPECTED_OUTPUT[] = "c670606edd22fd0e3b432c977559a687cc5d9bd2"; + const unsigned char DATA[20] = {198, 112, 96, 110, 221, 34, 253, 14, 59, 67, 44, 151, 117, 89, 166, 135, 204, 93, 155, 210}; + + char OUTPUT_BUFFER[41] = {0}; + to_hex_str(DATA, OUTPUT_BUFFER); + + ASSERT_EQ(std::string(EXPECTED_OUTPUT), OUTPUT_BUFFER); +} + +class SQLiteDriverTest: + public ::testing::Test { +protected: + SQLiteDriverTest(): va_map(), driver(nullptr) { + va_map.insert(std::pair("db.param", boost::program_options::variable_value(std::string(":memory:"), true))); + } + + virtual void SetUp() { + if (nullptr == driver) { + driver = new UDPT::Data::SQLite3Driver(va_map, false); + } + } + + virtual void TearDown() { + if (nullptr != driver) { + delete driver; + driver = nullptr; + } + } + + UDPT::Data::SQLite3Driver *driver; + boost::program_options::variables_map va_map; +}; + + +int main(int argc, char *argv[]) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/vs/UDPT.sln b/vs/UDPT.sln deleted file mode 100644 index 5c1e620..0000000 --- a/vs/UDPT.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UDPT", "UDPT\UDPT.vcxproj", "{9F399AF8-861E-4E50-A94C-1388089E3FA0}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9F399AF8-861E-4E50-A94C-1388089E3FA0}.Debug|Win32.ActiveCfg = Debug|Win32 - {9F399AF8-861E-4E50-A94C-1388089E3FA0}.Debug|Win32.Build.0 = Debug|Win32 - {9F399AF8-861E-4E50-A94C-1388089E3FA0}.Release|Win32.ActiveCfg = Release|Win32 - {9F399AF8-861E-4E50-A94C-1388089E3FA0}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/vs/UDPT/UDPT.vcxproj b/vs/UDPT/UDPT.vcxproj deleted file mode 100644 index 22afae6..0000000 --- a/vs/UDPT/UDPT.vcxproj +++ /dev/null @@ -1,111 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {9F399AF8-861E-4E50-A94C-1388089E3FA0} - UDPT - - - - Application - true - v140_xp - MultiByte - true - - - Application - false - v140 - true - MultiByte - - - - - - - - - - - - - $(VC_IncludePath);$(WindowsSDK_IncludePath);D:\libs\sqlite3;D:\libs\boost\boost_1_59_0 - D:\libs\boost\boost_1_59_0\stage\lib;D:\libs\sqlite3\Release;$(LibraryPath) - false - - - $(VC_IncludePath);$(WindowsSDK_IncludePath);D:\libs\sqlite3;D:\libs\boost\boost_1_59_0 - D:\libs\boost\boost_1_59_0\stage\lib;D:\libs\sqlite3\Release;$(LibraryPath) - - - - Level3 - Disabled - true - MultiThreadedDebugDLL - Async - ProgramDatabase - - - true - ws2_32.lib;sqlite3.lib;advapi32.lib;shell32.lib - Console - - - - - Level3 - MaxSpeed - true - true - true - MultiThreadedDLL - Async - - - - - - - ws2_32.lib;sqlite3.lib;advapi32.lib;shell32.lib - Console - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/vs/UDPT/UDPT.vcxproj.filters b/vs/UDPT/UDPT.vcxproj.filters deleted file mode 100644 index 638b4ae..0000000 --- a/vs/UDPT/UDPT.vcxproj.filters +++ /dev/null @@ -1,90 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - {f5a85f67-2777-4fa5-828e-9c79af9f4b13} - - - {643f664e-8751-4440-8b90-fe95b15e0aac} - - - {bcb1fa9f-c9ec-4398-97f9-544baf69f2a9} - - - {f65a2e69-6a71-4cd0-ad64-36a73c6c94c4} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files\db - - - Source Files\db - - - Source Files\http - - - Source Files\http - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files\db - - - Header Files\db - - - Header Files\http - - - Header Files\http - - - Header Files - - - Header Files - - - Header Files - - - \ No newline at end of file From ccc9ad434b05fde774e29c2a125095c65e215be8 Mon Sep 17 00:00:00 2001 From: Felix Richter Date: Wed, 27 Sep 2017 13:19:58 +0200 Subject: [PATCH 88/99] add `#include ` to `src/udpTracker.hpp` Without the explicit include of from std i get the following error: ``` In file included from /tmp/nix-build-udpt-2017-09-27/src/udpTracker.hpp:166:14: error: 'atomic_bool' in namespace 'std' does not name a type std::atomic_bool m_shouldRun; ^~~~~~~~~~~ ``` --- src/udpTracker.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 18dd8cc..05e9798 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include From 6afc76942a7d27195df8ac2da8deeff8c081de3c Mon Sep 17 00:00:00 2001 From: Naim A Date: Mon, 2 Oct 2017 17:33:05 +0300 Subject: [PATCH 89/99] Sphinx documentation sources (#34) * documented UDPT with sphinx * created manpage configuration for sphinx * update README.md's referral to naim94a.github.io/udpt --- CMakeLists.txt | 8 +- README.md | 2 +- docs/Makefile | 20 +++++ docs/_static/bitcoin-qr.png | Bin 0 -> 5762 bytes docs/building.rst | 82 ++++++++++++++++++ docs/conf.py | 161 ++++++++++++++++++++++++++++++++++++ docs/index.rst | 59 +++++++++++++ docs/make.bat | 36 ++++++++ docs/restapi.rst | 48 +++++++++++ docs/udpt.conf.rst | 112 +++++++++++++++++++++++++ docs/udpt.rst | 18 ++++ 11 files changed, 544 insertions(+), 2 deletions(-) create mode 100644 docs/Makefile create mode 100644 docs/_static/bitcoin-qr.png create mode 100644 docs/building.rst create mode 100644 docs/conf.py create mode 100644 docs/index.rst create mode 100644 docs/make.bat create mode 100644 docs/restapi.rst create mode 100644 docs/udpt.conf.rst create mode 100644 docs/udpt.rst diff --git a/CMakeLists.txt b/CMakeLists.txt index 9da8e20..7d05efa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,4 +21,10 @@ target_compile_definitions(udpt_tests PRIVATE TEST=1) target_link_libraries(udpt_tests gtest ${LIBS}) -add_test(NAME udpt_tests COMMAND udpt_tests) \ No newline at end of file +add_test(NAME udpt_tests COMMAND udpt_tests) + +add_custom_target(docs + COMMAND python -msphinx -M html . _build + COMMAND python -msphinx -M man . _build + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/docs + COMMENT Building docs) diff --git a/README.md b/README.md index b0dce52..f2a93bc 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ And finally:
### Links -* Documentation can be found at our wiki: https://github.com/naim94a/udpt/wiki +* UDPT's documentation can be found in the docs directory, or the rendered version at [naim94a.github.io/udpt](https://naim94a.github.io/udpt). * If you have any suggestions or find any bugs, please report them here: https://github.com/naim94a/udpt/issues * Project Page: http://www.github.com/naim94a/udpt diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..a0b25af --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = python -msphinx +SPHINXPROJ = UDPT +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/_static/bitcoin-qr.png b/docs/_static/bitcoin-qr.png new file mode 100644 index 0000000000000000000000000000000000000000..1f8f80f41e015558746d16ce0d01404fec2ef9a7 GIT binary patch literal 5762 zcma)Adpwi<-?uT<+~^L|&5e$ZMF*!=V-7h)2(z$JR1W2I+t9R`m86pHq(#`A57XR* zVvJHz3S*Yi4@oi;i{>=Ub4~a2{P#Ss=a21ry{_+deXr~Kd_M2P=ac5)=BNnOfXc|o zC^|dYdjdzX^tVwS_`mku4Ue7Z2HuFL!BE%wVQ93QdK;r2}FOP+DcdzKd- zBrkd}%Y$d;Xni>L?pP{Vj8MzwuRi`yNsqiJPWxcb;Y>0tL6?y9xVQ7NK!+nMegNjB zz<}ddf=R?kZ$Z_x@1Wj|#~-(a1v4URv-#15+^n!CrySy#@n@;D6HQBN=hf&Ji|6Zl z;;ogAz3_$iJ>Y}bEV(a94j`y;9W8Cd!aPsWF31P2%1O#>%_Uv|t75_fiK*lvj}KY; zRGPr{+FCQ%G^4NCZ;h&+rWm ziccFxk-f*?$4<2Sq62&oRDlV94-uWIWS}z|2Rgc0d+eULY+nEVtw)m$46^?mrm}@z z1B6DO&czK)g#}fxwLdOoGRK+VNM3A(gwnO8rni9X#{Gj6qV`rm@-h_i(~|-Nu-h7& z2=BmVk5zO#3*MqK@w`|^mSklOl2ew{)g58X|(@|p5YX5?Su8O0-Y`lqd{)g2u%kmm5# zhA)9*>aNn4oiWX^4(P|3puR1nkd&3H6d3qM3PB*p&BGSU^tpQVctM3iL1f()Q zuuT`TL&$&OutWO&h!^da;tr(3J?2YO?SAO7RgNXYLQ_MTU2R12Q(j8>qkcbUlZ`?$ zEXPP&Lys7V4=$2~t(cnds&|33&RvN+iB9IU7N?~gFzpO`-h0(%w0LRY=u-jVwSBj} z@G*=NW+Z4)Y1B}QI0d}P23-1CMr1aBvwhCNfzvgtVbxOjo;_b*+@a5KS%nWcw!~s( zes4ki@5*bLuDneJ!n@3b(Cr-C*ufjHZ4tRRNC~_iR|*s|TfJ^L4qv8TGS5q^oY&#h z#gBy#VlKC$y49_Fqwgu5Ega_hU^mu2KT~*K@v^}6dC7b>U-4C?3Tmo_aG)pa6K@{| z;-+cXsa{vMP&f~~TD�K?c7Rqn3bN^Y$EQEwS?*tYNLm-KX#ePGLv~dOq!4`oTCn z^_e#>V*K@8=jSb#=YD4cu{26jn59c9K?S?9N#yiQu|81Y=6k!anDDOM=Su8A#3ojC z4zl)k@Nm=>jTArTi!UjKX5dSpCb7^L}5cmNp!4U((A*#h;COBc>Y zK7ECbuN*Tr(r2UJ=9fMak53w}Vi)ie-)Ccc9M?f242xCMUDf|)m`k4aoZU|Xvz*6K zpXEi8{wS(d?W63Dj&Hj32gSefiQ6Z>IX(Ytg2r2I1p5vqd0%00_;Q8wrOiH)4F+JA zkrz!fLt6Dh{zXUH-eIy8qc3;x38V468g3~&Gx0Y#Rtx(;E}a&+#W=dcN)+JjE@%OQ zkP6b0^d-YC;Df?W_fiT^^(0iz6>MXDi3e~t+~XyUW*09HwkHp1oXk+jhUxOs1<28g z_wA5e#`9`clrBLRes-iY-`oufjd1F-hIEb5tf=M#t~f3&Gj8{PP_J>6-tk`BqM0hg zOJWRqXad0CdSxS#LX&+=hok+wa?}SBw3}IhPpx)Pq6_R6`jn@dc#QAHGxc9~nf0DO z#cZnAkeM3|mjP+{+%-DUJ&*uq#RqTXD*{Mbrw*a($V0xq=ww@k)B&$;p_kFu7x}JpY?!&< zdg@!KK6slG9-&A2tmwml4*avbQSNd^L=LyLY@SEwB$N~JD~wqu;aH`=&3f4#=sDPv zL>UpcZRRX%+70y_SF=65r>-n>C!_J+2SHQQJNp(=>JA;7P*(Zvz7~aTf-()9V0fS!?q(`VzFU(kr(Bg^|p5Z}mGh|XI@Jpt1c4z{$<0Gzg#tWg-%nB)7@FF|` zt3nOwffbY_&Mvwgr0WT^_l>>6nXDvqZpd4-&w>zo2ETUVcP0f7y2~S0cW&xBxKh^i znB|qCIS*o+>>@(w51_|KKWZ4J(*zeaI1?TADyY4?_PT0V&$$a-G}Y?LX6nCJbTQ$$ zu^Vl}VKUMe6Abzt)B&$NS;9=aCG}bDW=way@aH@it%3RH+>*3;S~SY7I^wNZ%mj zM-`1s@)8tYUf*kj$QOx?3nH%lTtrpxGnH^J-E5TmYtiT*k!`EsuY{L%TezruLsXbw zos}sGYTT*7qcJ-Go(d?B%u93zk-`1(TZl1h}#VLSNQh^ z4S!1&4wE)WgedZXlAZH-SZ3rFJoro4>&uuqNM@_faCBE8!IL%ZuN8ufI&&TB{yfKs z+nB|uL93U(wdS?gb$D7cmwO3CG4diZsRLzBPYm3@E+#72l*kKA#i{{icK;LLK}KG4 zhN!$BX?|At={ur2ce1z(*qmx#_q0XCPM|rY1e?@oOiCHMMqDco?!;%-*H$M zV=Ffgq|SL&&hB*S9th5aeM1UUxLCxNKLOoYzUBiod@!SkFoD1wcmy zleG#PsYw9|TpL7gmnF!h~k;Qv4Z~ziF)6XAh zfS&ntCO2g=0JK{A^hfwM;57&)X)jtPrwv{EuN09&SB%%X#Ta!Cj>5{H48IT?A&TUs z1^%M>O`G_uTjD_KoG9p#6~;1tavS#8$rIO>zd^r(|Ay^>HU~E?$A+yi;V}pc6$CvA zcT%03N(z0>qQoGmV&LZZ1y@m9#>9ahGm!zE8TFe~_l(}7?lUR8AL0e?Id-McWmK83 zC(E9T#fjZ&-a5jd#)G@`H}lAzYsN$jotse3Hgel8?A?Hy;Gpi3hfLDR%!yI(wRKp^ z;}*;A@O5pb!nVr+l!*fQMdgYAUWXa+CQ&ME#CMw{83ru4F7^%ILS8)GSb3Ubspl!~ zyz=dB$-#7Pi7Y!x7rwGzgSY|8C#nJ}A_?318{Z@OeY@qrMT2X4-~aJw2#!T3dm$!b zu}k=+3i&+2L}m9atKP{cxblTt&4$Ufr_veT$QFI%90sLl>I>4kb5tQYE_|z!v8zS~ zgI<|TXEl6@S@O+N7h{ULez^s&o9*)eSEOfJ^+U?vDnlZ3(}b{W{y(;ulnKIy%3JLy z4<7QFsd@F$xvFM$9__ta#6E|AJzacO&!F;NIVh~I%mTMmM$(TK1(;a(m{5Er2>5aD zx*xS1Oy--h)He6I_~Xr}i^X)WM1o1da~FUrM5HD1Pz4x@LADqmHI*SZfH;O70X*S8 zwZ{ao)Q}V?UZtQO>ZP}%lvVlRTJX7TiXjsoy5jmh`q3bS3K4_STUene-B|Mg zN686PsB%Lb|H>U-G|xQ3()}|%1n{|C6t-z@iCzC^Fv0pLGtF3)GPV(N!`!J-8BoQf zZYLz|CB-es?{((sBkyif)Hpg+jWK5s(X);$j2!7Yn?7 zJ-6S8o>9lF-N^qj&TqSQbyh%NzEuY5-&KKgb{Lx0TO4|eHUmv#A zFBXRPZXXN&vr|@W(RT`+Tz9Nnu-u#2gUU5eC;&PA>W@~L86LK+%IBj|+qvURmPz_S z`U@Ul3`%7pe&eZhp!CpV~CpR4Hu}}Pb&8wZNts`of zVe@i{F#y2{ds^}=L$UM5qnVntpW3y!*A1*jXfo`8+ECU>KeDL7cw6WQdUArLo?gSU zs_3E;Zr{&Rf{0=Wm~_W?lh&Z#gf@$nNE?tJ-b5n=X|dYsT6Y^q$={ogLduDN9?zsr ze&?@(-zp2YsaUn7G^Duz%?gLv=1iLm|G`|8CD=LpkyTXy(dLA_ zwV-z!nnmdSN)7SJ9$9gfCpYeYmJj@|%i4U?N8J8Ii{e0Ee+i>S;HAZ9hpsTb6zCX* zsvYO>fZozZMzGBP++s(n^hb@ zY~|ZV87dWv=R8;cL*1|n0&{Y82E35ibo&If-3%8DI7)c^ivRWE(JSwjc}qdk)_wa~ zeA!F`l%{)6w*y6HE_+%VFNbSkBw+}TL_cc~duCxI>_xfTU51Q7vpqoC~ z+?VmT*>3|i$xpdYGNCITvu$5X4y}B*V;Pm6+Tk!-l`m4YBm|-laiX>W)wE_yDv@@G z41EyRUn^`xAtm}`4MW$0Z32lzjc(#IUDcKgWKMYS&y+x1#tLSD?@e(R9>o_eRL;9k z{t)}x_Ba9cPon1NUWaMSxoh48+HIYZYZ+bM?W40MU(xGekQKYvV^VZDsnB(NOPl6) z{*hC`nLzEb^)BA1o)!(_KDg^CR?;SCg@&%^BTTe1RfkX=zMR@p6sWzGbC|=u;y$0@ zevrCGCS~4jCR9CE<|}$)kX7Iwv+Q!(JvQSRdct{fa`~C`vO+ zrr^z&fzgI60U2d@YE9r~J?;AST*sB>!)}LGgY1(YCA)z&GR~`&b(g>!zlY`W#NPdO zWhANb5$@0?;g$IVjh{b48^po?nNHtFHxWBV;QsRXr&7gbv?Bi`h)w%j+M!4BbvVlp zt}y=g$ivPv7qOZl$Zq>2#+yMjS4vXKkl9;96)9wrik=E~`CQGEzzwY>R`SDoG*(^m zwqR{RPr8mCdcbD5!8Nl)AS}H267b;FO^%=v0t>p2zTkhuWt^}NC2luIDy(_e zfDg3(x>FS}>D)I0aEg@$-D^xISg5fvo1e`e%)r#1=FD~jvx9DX8okXd4NKCsm7LoG zv}ImoH#CuofG`J!AhqYSO41+t=>Ra#Ro7ad8H7j#(_kvaRwW?9eY9-el=P^1BDi!) z7Jex;-)Fw45xK^A_R#oJCD75$cqO8b0Ci_Yx7%Ftqmk^7UG%mHm)^xpDA%D%jY?FV zH+GRpiC6+kC{ZKHXW>E6MaQU1MIX+}(o+H>+<|$5sRYOm)y>0?Tsu=sK3Nan;ecH@ zs;qXiBHvVK>(qJHWoGVi;Go*0TV0$hjZhlw+w=ndl`uTlRM@sCb(lh%qNGy6ma7y` zMLD*5`Y>R_Z2j?p=oMo`h0?D}K&$!YIX}pfC1zOF>TqMBZ1T6&h2Kg4k|^2AznJsWxUJrx#fyrUz~wjKx_sn?yhd@O`X zmrc9E6LU-|FYhP)Qt+~Lm>b}{{laX1s&Qx{A&a}CC`E-+(HfALQw;=Z*zh)R!2-pF z-E)b3gzx=1Jh2}=Ttoa`1Q@aEc{|O3w?k^Ll`g}rZZm1_|r21a!w{2zqx03;*<$6dkt7RR(k^JxsC4fc+5lfgG(~G8Qr`kLiIM#pWnG~NEI>< ztO>KK?KL60AYj%me_%g0u$DMx)Z_5~-D**1BE>fO)go8}m@UgVA9b^5+Mc5P7a%h~ AQ2+n{ literal 0 HcmV?d00001 diff --git a/docs/building.rst b/docs/building.rst new file mode 100644 index 0000000..adea47c --- /dev/null +++ b/docs/building.rst @@ -0,0 +1,82 @@ +.. title:: Building UDPT from source + +************* +Building UDPT +************* + +Obtaining source code +===================== +UDPT_'s source code is hosted on GitHub, and obviously uses Git as source control. + +You can use the following command to clone the UDPT repository to your machine.:: + + git clone https://github.com/naim94a/udpt.git + +It’s as simple as that! + +If you prefer, you can head over to the project on GitHub and download a tarball and execute:: + + curl -Lo udpt-master.tgz https://github.com/naim94a/udpt/archive/master.tar.gz + tar -xvf udpt + +Building for Linux & FreeBSD +============================ +The author of UDPT used ArchLinux for development, so the documentation assumes you are using ArchLinux. You should be able to get the following instructions to work on most Linux distributions. + +.. note:: Package names vary between distributions, for example: The SQLite package (with development headers/libs) on ArchLinux is *sqlite*, where on Debian you’ll need *libsqlite3-dev*. + +Installing dependencies +----------------------- +In order to build UDPT you will need: + +*Required Dependencies:* + +* sqlite_ - Provides the storage backend, at the moment SQLite handles the In-Memory database too. +* libevent_ - Provides an asynchronous HTTP API (It can actually do more than that, be we just use it’s HTTP capabilities). +* boost_ - We just use boost-program_options, it provides configuration file parsing and command line parsing. +* cmake_ - Generates Makefiles for various platforms (and configures) +* gcc - C/C++ compiler, you can use clang if you prefer. +* binutils - Linker + +*Optional Dependencies:* + +* git_ - Get the source code, make changes and contribute! +* gtest_ - Google’s C++ Test framework. + +On ArchLinux:: + + pacman -S sqlite libevent boost cmake git gcc binutils git gtest + +On Debian:: + + sudo apt-get install libsqlite3-dev libevent-dev libboost-dev cmake git gcc binutils libgtest-dev + +On FreeBSD (11.1R):: + + pkg install sqlite3 boost-all libevent cmake git binutils llvm40 googletest + +Compiling +--------- +Okay, now that you have the source code and all the dependencies, you may execute the following:: + + cd udpt + mkdir build-release && cd build-release + cmake -DCMAKE_BUILD_TYPE=Release .. + make -j4 + +This should leave you with a udpt executable file, and optionally a udpt_tests executable. If any of the above instructions failed, please submit a issue to our `issue tracker`_. + +If everything succeeded, head over to :doc:`udpt.conf` and get your tracker running! + +Building for Windows +==================== +.. note:: This documentation is a work-in-progress. Stay tuned! + +.. _UDPT: https://github.com/naim94a/udpt +.. _sqlite: https://www.sqlite.org/ +.. _libevent: https://github.com/libevent/libevent +.. _boost: http://www.boost.org/ +.. _cmake: https://www.cmake.org/ +.. _git: https://git-scm.com/ +.. _gtest: https://github.com/google/googletest +.. _issue tracker: https://github.com/naim94a/udpt/issues diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..5439748 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +import sys + + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +needs_sphinx = '1.3' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ['sphinx.ext.githubpages'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'UDPT' +copyright = '2017, Naim A.' +author = 'Naim A.' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '2.1.0' +# The full version, including alpha/beta/rc tags. +release = '2.1.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'env'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + +primary_domain = 'cpp' + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# + +try: + import sphinx_rtd_theme + html_theme = 'sphinx_rtd_theme' + html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] +except ImportError: + sys.stderr.write('Warning: Failed to import sphinx_rtd_theme.') + +html_show_sourcelink = False + + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +html_theme_options = { + 'canonical_url': 'https://naim94a.github.io/udpt', +} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# This is required for the alabaster theme +# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars +html_sidebars = { + '**': [ + 'about.html', + 'navigation.html', + 'relations.html', # needs 'show_related': True theme option to display + 'searchbox.html', + 'donate.html', + ] +} + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'UDPT' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'UDPT.tex', 'UDPT Documentation', + 'Naim A.', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('udpt.conf', 'udpt.conf', 'UDPT Configuration', [author], 5), + ('udpt', 'udpt', 'UDP Torrent Tracker', [author], 8), +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'UDPT', 'UDPT Documentation', + author, 'UDPT', 'One line description of project.', + 'Miscellaneous'), +] diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..0e4440d --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,59 @@ +.. title:: UDPT + +UDPT +==== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + :numbered: + :hidden: + + building + udpt + udpt.conf + restapi.rst + +UDPT is a lightweight UDP torrent tracker written in C++, it implements BEP15_ of the BitTorrent protocol. +This project was developed with simplicity and security in mind. +Unlike most tracker, UDPT will save you bandwidth from all that TCP overhead. + +Features +-------- +* UDP protocol based tracker +* :doc:`Simple INI configuration file ` +* :doc:`HTTP REST API ` +* SQLite3 database, support for in-*:memory:*. +* Logging +* Linux daemon / Windows Service +* Choice of *static* or *dynamic* tracker modes +* Works with Windows, Linux and FreeBSD + +Licenses & 3rd party libraries +------------------------------ +UDPT is released under GPLv3_, and uses GPLv3 compatible libraries: + +* SQLite3, released under the public domain. +* Boost, released under the `BOOST LICENSE`_. +* libevent, released under the `3-clause BSD license`_. + +Contributing +------------ +Feel free to submit `issues `_, `PRs `_ or donations! + +.. seealso:: `CONTRIBUTING `_ + +.. image:: _static/bitcoin-qr.png + :alt: bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3 + +`bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3 `_ + +Author +------ +UDPT's development started November 20th, 2012 by Naim A. (`@naim94a`_). + +.. _BEP15: http://www.bittorrent.org/beps/bep_0015.html +.. _GPLv3: https://www.gnu.org/licenses/gpl-3.0.en.html +.. _BOOST LICENSE: http://www.boost.org/LICENSE_1_0.txt +.. _3-clause BSD license: http://libevent.org/LICENSE.txt +.. _@naim94a: https://github.com/naim94a/ diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..dfddd7b --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=python -msphinx +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=UDPT + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The Sphinx module was not found. Make sure you have Sphinx installed, + echo.then set the SPHINXBUILD environment variable to point to the full + echo.path of the 'sphinx-build' executable. Alternatively you may add the + echo.Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/docs/restapi.rst b/docs/restapi.rst new file mode 100644 index 0000000..3326b43 --- /dev/null +++ b/docs/restapi.rst @@ -0,0 +1,48 @@ +************* +HTTP Rest API +************* +.. note:: The REST API is only useful in *non-dynamic mode*. + +Security Considerations +----------------------- +The REST API of UDPT was meant for use of the tracker's owner. +It will reject any connecting with a source address other than *127.0.0.1*. + +User's of the REST API should make sure that unauthorized people won't gain access. + +Attempting to access the api server with a BitTorrent client will result in the following message: +"this is a UDP tracker, not a HTTP tracker." + +API Methods +----------- +* Adding torrents + + .. code-block:: bash + + curl "http://127.0.0.1:8081/api?action=add&hash=9228628504cc40efa57bf38e85c9e3bd2c572b5b" + +* Removing torrents + + .. code-block:: bash + + curl "http://127.0.0.1:8081/api?action=remove&hash=9228628504cc40efa57bf38e85c9e3bd2c572b5b" + +With both methods, the response should be: + +.. code-block:: json + + {"success":true} + +In case of error, you will receive: + +.. code-block:: json + + {"error":"failure reason"} + +With one of the following reasons: + +* failed to add torrent to DB +* invalid info_hash. +* Hash length must be 40 characters. +* failed to remove torrent from DB +* unknown action diff --git a/docs/udpt.conf.rst b/docs/udpt.conf.rst new file mode 100644 index 0000000..225e7eb --- /dev/null +++ b/docs/udpt.conf.rst @@ -0,0 +1,112 @@ +.. title:: UDPT Configuration + +*********************** +UDPT Configuration File +*********************** + +UDPT's configuration file is called *udpt.conf* by convention and should be located at `/etc/udpt.conf` by default. + +udpt.conf is an INI style configuration. + +Sections +======== + +* **Section [db]** - Controls the backend database. + + +-------------------+------------+-------------------------+-------------------------------------------------------+ + | **Key** | **Type** | **Example** | **Description** | + +-------------------+------------+-------------------------+-------------------------------------------------------+ + | driver | enum | "*sqlite*" is currently | Selects the storage backend. | + | | | the only option. | | + +-------------------+------------+-------------------------+-------------------------------------------------------+ + | param | string | /var/lib/udpt.db | Parameter for the storage backend. For SQLite, it's | + | | | | a filename. *:memory:* can be used for in-memory DB. | + +-------------------+------------+-------------------------+-------------------------------------------------------+ + +* **Section [tracker]** - Settings for the UDP tracker component. + + +-------------------+---------------+----------------+----------------------------------------------------------+ + | **Key** | **Type** | **Example** | **Description** | + +-------------------+---------------+----------------+----------------------------------------------------------+ + | is_dynamic | boolean | *yes* | Sets the tracker mode to dynamic. | + +-------------------+---------------+----------------+----------------------------------------------------------+ + | port | int | *6969* | UDP port to listen on. | + +-------------------+---------------+----------------+----------------------------------------------------------+ + | threads | int | *4* | Amount of threads the UDP tracker should use. | + +-------------------+---------------+----------------+----------------------------------------------------------+ + | allow_remotes | boolean | *yes* | Allows clients to report IPs other than themselves. | + +-------------------+---------------+----------------+----------------------------------------------------------+ + | allow_iana_ips | boolean | *no* | Sets if packets from reserved IPs should be allowed. | + +-------------------+---------------+----------------+----------------------------------------------------------+ + | announce_interval | int | *3600* | Time for client to wait before asking for peers again. | + +-------------------+---------------+----------------+----------------------------------------------------------+ + | cleanup_interval | int | *60* | Timeout to run a database cleanup. | + +-------------------+---------------+----------------+----------------------------------------------------------+ + +* **Section [apiserver]** - Settings for the backend HTTP REST service. + + +-----------+-----------+---------------+-------------------------------------------+ + | **Key** | **Type** | **Example** | **Description** | + +-----------+-----------+---------------+-------------------------------------------+ + | enable | boolean | *yes* | Sets if the HTTP API should be enabled. | + +-----------+-----------+---------------+-------------------------------------------+ + | port | int | *8081* | The port the HTTP API should listen on. | + +-----------+-----------+---------------+-------------------------------------------+ + | threads | int | *2* | Thread allocation for the HTTP API. | + +-----------+-----------+---------------+-------------------------------------------+ + +* **Section [logging]** - Logging preferences. + + +-----------+-----------+-------------------+---------------------------------------------------+ + | **Key** | **Type** | **Example** | **Description** | + +-----------+-----------+-------------------+---------------------------------------------------+ + | filename | string | /var/log/udpt.log | The file the log should be appended to. | + +-----------+-----------+-------------------+---------------------------------------------------+ + | level | enum | info | Log Level, should be one of: | + | | | | *fatal*, *error*, *warning*, *info* or *debug*. | + +-----------+-----------+-------------------+---------------------------------------------------+ + +* **Section [daemon]** - Daemon settings. + + +---------------+---------------+-------------------+-------------------------------------------------------+ + | **Key** | **Type** | **Example** | **Description** | + +---------------+---------------+-------------------+-------------------------------------------------------+ + | chdir | string | /opt/udpt | The directory to chroot to when running as a daemon. | + +---------------+---------------+-------------------+-------------------------------------------------------+ + +Example +======= + +.. code-block:: ini + + # This will use a volatile in-memory database. + [db] + driver = sqlite + params = :memory: + + # UDP Tracker configuration + [tracker] + is_dynamic = yes + port = 6969 + threads = 5 + allow_remotes = yes + allow_iana_ips = no + announce_interval = 1800 + cleanup_interval = 120 + + # API Server + [apiserver] + enable = yes + port = 8081 + threads = 2 + + # Daemon chroot settings + [daemon] + chdir = /home/udpt/ + + # Logging + [logging] + filename = /var/log/udpt.log + level = warning + +.. seealso:: :doc:`udpt(8) ` diff --git a/docs/udpt.rst b/docs/udpt.rst new file mode 100644 index 0000000..fc44f51 --- /dev/null +++ b/docs/udpt.rst @@ -0,0 +1,18 @@ +.. title:: udpt usage + +********** +UDPT Usage +********** + +./udpt *[options]* + +Options +------- +-h, --help Displays the help message. +--all-help Displays all configurable values from the configuration file. +-t, --test Tests the given configuration file is valid. +-c, --config Sets the configuration file path (default: /etc/udpt.conf). +-i, --interactive Don't fork to background (Linux only). +-s, --service Controls UDPT Windows Server (Windows Only). + +.. seealso:: :doc:`udpt.conf(5) ` From 391824234235cfb006a255ae5bdadd77133bf153 Mon Sep 17 00:00:00 2001 From: Naim A Date: Mon, 2 Oct 2017 18:09:08 +0300 Subject: [PATCH 90/99] doc: minor changes --- README.md | 2 +- docs/conf.py | 2 +- docs/index.rst | 7 ++++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f2a93bc..be9e4cd 100644 --- a/README.md +++ b/README.md @@ -38,4 +38,4 @@ And finally: UDPT was developed by [Naim A.](http://www.github.com/naim94a) at for fun at his free time. The development started on November 20th, 2012. -If you find the project useful, please consider a donation to the following bitcoin address: 1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3. +If you find the project useful, please consider a donation to the following bitcoin address: 1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3. diff --git a/docs/conf.py b/docs/conf.py index 5439748..6e5ac76 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -80,7 +80,7 @@ html_show_sourcelink = False # documentation. # html_theme_options = { - 'canonical_url': 'https://naim94a.github.io/udpt', + 'canonical_url': 'https://naim94a.github.io/udpt/', } # Add any paths that contain custom static files (such as style sheets) here, diff --git a/docs/index.rst b/docs/index.rst index 0e4440d..8a4feee 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -14,7 +14,7 @@ UDPT udpt.conf restapi.rst -UDPT is a lightweight UDP torrent tracker written in C++, it implements BEP15_ of the BitTorrent protocol. +UDPT_ is a lightweight UDP torrent tracker written in C++, it implements BEP15_ of the BitTorrent protocol. This project was developed with simplicity and security in mind. Unlike most tracker, UDPT will save you bandwidth from all that TCP overhead. @@ -44,14 +44,15 @@ Feel free to submit `issues `_, `PRs `_ .. image:: _static/bitcoin-qr.png - :alt: bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3 + :alt: bitcoin://1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3 -`bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3 `_ +`bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3 `_ Author ------ UDPT's development started November 20th, 2012 by Naim A. (`@naim94a`_). +.. _UDPT: https://github.com/naim94a/udpt .. _BEP15: http://www.bittorrent.org/beps/bep_0015.html .. _GPLv3: https://www.gnu.org/licenses/gpl-3.0.en.html .. _BOOST LICENSE: http://www.boost.org/LICENSE_1_0.txt From 9f0d1f495c8cbfbc990cd1c37a78e3135703053d Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 5 Oct 2017 22:16:18 +0300 Subject: [PATCH 91/99] docs: some fixes, analytics + typos --- docs/_templates/layout.html | 12 ++++++++++++ docs/udpt.conf.rst | 4 ++-- 2 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 docs/_templates/layout.html diff --git a/docs/_templates/layout.html b/docs/_templates/layout.html new file mode 100644 index 0000000..822a4c9 --- /dev/null +++ b/docs/_templates/layout.html @@ -0,0 +1,12 @@ +{% extends "!layout.html" %} +{%- block extrahead %} +{{ super() }} + + + +{% endblock %} \ No newline at end of file diff --git a/docs/udpt.conf.rst b/docs/udpt.conf.rst index 225e7eb..9febd58 100644 --- a/docs/udpt.conf.rst +++ b/docs/udpt.conf.rst @@ -71,7 +71,7 @@ Sections +---------------+---------------+-------------------+-------------------------------------------------------+ | **Key** | **Type** | **Example** | **Description** | +---------------+---------------+-------------------+-------------------------------------------------------+ - | chdir | string | /opt/udpt | The directory to chroot to when running as a daemon. | + | chdir | string | /opt/udpt | The directory to chdir to when running as a daemon. | +---------------+---------------+-------------------+-------------------------------------------------------+ Example @@ -100,7 +100,7 @@ Example port = 8081 threads = 2 - # Daemon chroot settings + # Daemon chdir settings [daemon] chdir = /home/udpt/ From da7f91b6b9ad04ea6d45c1898893b6963a14df8d Mon Sep 17 00:00:00 2001 From: Naim A Date: Tue, 31 Oct 2017 01:29:57 +0200 Subject: [PATCH 92/99] Improvements to REST API (#33) * API Server re-implemented with libevent. * Code & CMake organization. --- .github/CONTRIBUTING.md | 2 +- CMakeLists.txt | 35 ++- README.md | 78 ++++-- docs/udpt.conf.rst | 23 +- src/WebApp.cpp | 283 +++++++++++++++++++++ src/WebApp.hpp | 82 ++++++ src/db/driver_sqlite.cpp | 14 +- src/exceptions.h | 21 +- src/http/httpserver.cpp | 535 --------------------------------------- src/http/httpserver.hpp | 170 ------------- src/http/webapp.cpp | 214 ---------------- src/http/webapp.hpp | 59 ----- src/logging.cpp | 2 + src/logging.hpp | 2 +- src/main.cpp | 83 ++++-- src/multiplatform.h | 72 ------ src/service.cpp | 3 +- src/service.hpp | 1 - src/tools.c | 34 ++- src/tools.h | 10 +- src/tracker.cpp | 29 ++- src/tracker.hpp | 7 +- src/udpTracker.cpp | 77 +++--- src/udpTracker.hpp | 35 ++- src/version.h.in | 4 + tests/main.cpp | 16 +- 26 files changed, 663 insertions(+), 1228 deletions(-) create mode 100644 src/WebApp.cpp create mode 100644 src/WebApp.hpp delete mode 100644 src/http/httpserver.cpp delete mode 100644 src/http/httpserver.hpp delete mode 100644 src/http/webapp.cpp delete mode 100644 src/http/webapp.hpp delete mode 100644 src/multiplatform.h create mode 100644 src/version.h.in diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 3ead340..6eb1ba1 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -35,7 +35,7 @@ addressed. Pull requests that add new features should be first mentioned in issues in order to verify that the project owner will allow such changes to the project. -Code in pull requests should meet the following requirements: +Code in pull requests should meet the following standards: * Class names should be CamelCase, and the first letter should be capital. * Functions should be camelCase, and the first letter should be lower-case. diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d05efa..2a41dc7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,27 +2,52 @@ project(udpt) cmake_minimum_required(VERSION 3.2) enable_testing() +set(CMAKE_BUILD_TYPE Release) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) file(GLOB src_files "src/*.c" "src/*.cpp" - "src/db/*.cpp" - "src/http/*.cpp") + "src/db/*.cpp") -LIST(APPEND LIBS "pthread" "sqlite3" "boost_program_options" "boost_system") +if(CMAKE_SYSTEM_NAME STREQUAL FreeBSD) + include_directories("/usr/include" "/usr/local/include") +endif() +find_library(PTHREADS NAMES "pthread") +find_library(SQLITE NAMES "sqlite3" "libsqlite" "libsqlite3") +find_library(BOOST_PROG_OPTS NAMES "boost_program_options") +find_library(BOOST_SYSTEM NAMES "boost_system") +find_library(LIBEVENT NAMES "event") +find_library(LIBEVENTP NAMES "event_pthreads") +find_library(GTEST NAMES "gtest") + +LIST(APPEND LIBS ${PTHREADS} ${SQLITE} ${BOOST_PROG_OPTS} ${BOOST_SYSTEM} ${LIBEVENT} ${LIBEVENTP}) +add_definitions(-Wall) add_executable(udpt ${src_files}) target_link_libraries(udpt ${LIBS}) -add_executable(udpt_tests tests/main.cpp ${src_files}) +add_executable(udpt_tests EXCLUDE_FROM_ALL tests/main.cpp ${src_files}) target_compile_definitions(udpt_tests PRIVATE TEST=1) -target_link_libraries(udpt_tests gtest ${LIBS}) +target_link_libraries(udpt_tests ${GTEST} ${LIBS}) add_test(NAME udpt_tests COMMAND udpt_tests) +# Add version to code +execute_process( + COMMAND git log -1 --format="%h" + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_VARIABLE GIT_COMMIT + OUTPUT_STRIP_TRAILING_WHITESPACE +) +configure_file( + ${CMAKE_SOURCE_DIR}/src/version.h.in + ${CMAKE_CURRENT_BINARY_DIR}/generated/version.h +) +include_directories(${CMAKE_CURRENT_BINARY_DIR}/generated) + add_custom_target(docs COMMAND python -msphinx -M html . _build COMMAND python -msphinx -M man . _build diff --git a/README.md b/README.md index be9e4cd..cea5364 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,67 @@ - # UDPT -The UDPT project is a BitTorrent Tracking software. -It uses the UDP protocol (instead of the HTTP protocol) to track -peers downloading the same software. UDPT was written according -to [BEP 15](http://www.bittorrent.org/beps/bep_0015.html) of the BitTorrent standard. +**UDP**-**T**racker is a torrent tracker that implements [BEP15](http://www.bittorrent.org/beps/bep_0015.html), +the UDP torrent tracker protocol. -UDPT is designed to run on both Windows and Linux-based platform (It may run on Apple systems too). +The UDP tracker protocol is light compared to HTTP(s) based torrent +trackers since it doesnt have TCP's overhead. -### License -UDPT is released under the [GPL](http://www.gnu.org/licenses/gpl-3.0.en.html) license, a copy is included in this repository. -We use [SQLite3](http://www.sqlite.org/) which is public-domain, and [Boost](http://www.boost.org/) which is released under the [boost license](http://www.boost.org/LICENSE_1_0.txt). +This project was developed with simplicity and security in mind. +Development started November 20th, 2012 by [@naim94a](https://github.com/naim94a). -### Building -We didn't really work on creating any installer, at the moment you can just run udpt from anywhere on your filesystem. -Building udpt is pretty straightforward, just download the project or clone the repo: +## Features +* UDP torrent tracking server +* SQLite3 database, with in-memory support (volatile) +* Choice of static or dynamic tracker modes +* HTTP REST API +* Logging +* Windows Service / Linux Daemon +* INI like configuration syntax -UDPT requires the SQLite3, boost_program_options and boost_thread develpment packages to be installed. +## Getting Started +The easiest way is to download binaries from the [Releases Section](https://github.com/naim94a/udpt/releases), +but releases don't get updated as often as the master branch... -
-    $ git clone https://github.com/naim94a/udpt.git
-    $ cd udpt
-    $ make
-
+### Getting the code +1. Make sure you have the following binaries, they are required to build UDPT: *All packages should be in most linux disto's official repositories* + * cmake + * make + * g++, gcc, ld + * boost_program-options, boost_system + * libsqlite3 + * libevent + * gtest - optional + +2. Obtain the code: `git clone https://github.com/naim94a/udpt.git` -And finally: +3. And start building! + ```sh + cd udpt + mkdir build && cd build + cmake .. + make udpt + ``` -
-    $ ./udpt
-
+4. Finally, start the server: + ```sh + ./udpt -ic ../udpt.conf + ``` + Now you can get people to use your tracker at: udp://**:6969/ + +You should note that the default configuration does not use a persistent database. ### Links * UDPT's documentation can be found in the docs directory, or the rendered version at [naim94a.github.io/udpt](https://naim94a.github.io/udpt). * If you have any suggestions or find any bugs, please report them here: https://github.com/naim94a/udpt/issues * Project Page: http://www.github.com/naim94a/udpt -### Author(s) -UDPT was developed by [Naim A.](http://www.github.com/naim94a) at for fun at his free time. -The development started on November 20th, 2012. +## How to Contribute +**Donations** are the best way to contribute, we accept BitCoin: -If you find the project useful, please consider a donation to the following bitcoin address: 1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3. +bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3 + +![bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3](.github/bitcoin-qr.png) + +[**Issues**](https://github.com/naim94a/udpt/issues), +[**Pull-Requests**](https://github.com/naim94a/udpt/pulls) +and suggestions are welcome as well. +See our [CONTRIBUTING](.github/CONTRIBUTING.md) page for more information. diff --git a/docs/udpt.conf.rst b/docs/udpt.conf.rst index 9febd58..c86f6cd 100644 --- a/docs/udpt.conf.rst +++ b/docs/udpt.conf.rst @@ -45,15 +45,16 @@ Sections * **Section [apiserver]** - Settings for the backend HTTP REST service. - +-----------+-----------+---------------+-------------------------------------------+ - | **Key** | **Type** | **Example** | **Description** | - +-----------+-----------+---------------+-------------------------------------------+ - | enable | boolean | *yes* | Sets if the HTTP API should be enabled. | - +-----------+-----------+---------------+-------------------------------------------+ - | port | int | *8081* | The port the HTTP API should listen on. | - +-----------+-----------+---------------+-------------------------------------------+ - | threads | int | *2* | Thread allocation for the HTTP API. | - +-----------+-----------+---------------+-------------------------------------------+ + +-----------+-----------+---------------+-----------------------------------------------+ + | **Key** | **Type** | **Example** | **Description** | + +-----------+-----------+---------------+-----------------------------------------------+ + | enable | boolean | *yes* | Sets if the HTTP API should be enabled. | + +-----------+-----------+---------------+-----------------------------------------------+ + | port | int | *8081* | The port the HTTP API should listen on. | + +-----------+-----------+---------------+-----------------------------------------------+ + | iface | string | *127.0.0.1* | IP of interface to listen on. | + | | | | Should only be accessible by a trusted client.| + +-----------+-----------+---------------+-----------------------------------------------+ * **Section [logging]** - Logging preferences. @@ -97,8 +98,8 @@ Example # API Server [apiserver] enable = yes - port = 8081 - threads = 2 + iface = 127.0.0.1 + port = 1122 # Daemon chdir settings [daemon] diff --git a/src/WebApp.cpp b/src/WebApp.cpp new file mode 100644 index 0000000..c19a0d2 --- /dev/null +++ b/src/WebApp.cpp @@ -0,0 +1,283 @@ +/* + * Copyright © 2012-2017 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ +#include +#include +#include +#include +#include "WebApp.hpp" +#include "logging.hpp" +#include "db/driver_sqlite.hpp" +#include "tools.h" + + +namespace UDPT { + WebApp::WebApp(UDPT::Data::DatabaseDriver &db, + const std::string& listenIP, + uint16_t listenPort): m_db(db), + m_listenIP(listenIP), + m_listenPort(listenPort) { + +#ifdef WIN32 + ::evthread_use_windows_threads(); +#elif defined(__linux__) || defined(__FreeBSD__) + ::evthread_use_pthreads(); +#else +#error evthread threading required, no compatible library was found. +#endif + + m_eventBase = std::shared_ptr(::event_base_new(), ::event_base_free); + if (nullptr == m_eventBase) { + LOG_ERR("webapp", "Failed to create event base"); + throw std::exception(); + } + + m_httpServer = std::shared_ptr(::evhttp_new(m_eventBase.get()), ::evhttp_free); + if (nullptr == m_httpServer) { + LOG_ERR("webapp", "Failed to create http base"); + throw std::exception(); + } + + if (0 != ::evhttp_bind_socket(m_httpServer.get(), m_listenIP.c_str(), m_listenPort)) { + LOG_ERR("webapp", "Failed to bind socket"); + throw std::exception(); + } + + LOG_INFO("webapp", "HTTP server bound to " << m_listenIP.c_str() << ":" << m_listenPort); + + ::evhttp_set_allowed_methods(m_httpServer.get(), EVHTTP_REQ_GET | EVHTTP_REQ_POST | EVHTTP_REQ_DELETE); + + ::evhttp_set_gencb(m_httpServer.get(), viewNotFound, this); + ::evhttp_set_cb(m_httpServer.get(), "/", [](struct evhttp_request *req, void *){ + setCommonHeaders(req); + sendReply(req, 200, "OK", HOME_PAGE); + }, this); + ::evhttp_set_cb(m_httpServer.get(), "/announce", [](struct evhttp_request *req, void *){ + setCommonHeaders(req); + sendReply(req, 200, "OK", ANNOUNCE_PAGE); + }, this); + ::evhttp_set_cb(m_httpServer.get(), "/api/torrents", viewApiTorrents, this); + } + + WebApp::~WebApp() { + try { + if (m_workerThread.joinable()) { + m_workerThread.join(); + } + } catch (...) { + LOG_FATAL("webapp", "exception thrown @ WebApp termination."); + } + } + + void WebApp::start() { + LOG_INFO("webapp", "Starting WebApp"); + LOG_INFO("webapp", "compiled with libevent " << LIBEVENT_VERSION << ", running with " << event_get_version()); + m_workerThread = std::thread(workerThread, this); + } + + void WebApp::stop() { + if (!m_isRunning) { + return; + } + m_isRunning = false; + + LOG_INFO("webapp", "Requesting WebApp to stop"); + ::event_base_loopbreak(m_eventBase.get()); + } + + const std::string WebApp::ANNOUNCE_PAGE = "d14:failure reason41:udpt: This is a udp tracker, not HTTP(s).e"; + const std::string WebApp::NOT_FOUND_PAGE = "

Not Found

"; + const std::string WebApp::HOME_PAGE = "" + "" + "UDPT" + "" + "" + "

UDPT Tracker

" + "" + "" + ""; + const std::string WebApp::JSON_INVALID_METHOD = "{\"error\": \"Invalid method\"}"; + const std::string WebApp::JSON_INTERNAL_ERROR = "{\"error\": \"Internal Server Error\"}"; + const std::string WebApp::JSON_PARAMS_REQUIRED = "{\"error\": \"This method requires parameters.\"}"; + const std::string WebApp::JSON_INFOHASH_REQUIRED = "{\"error\": \"exactly one info_hash argument is required.\"}"; + const std::string WebApp::JSON_INFOHASH_INVALID = "{\"error\": \"info_hash length is incorrect.\"}"; + const std::string WebApp::JSON_TORRENT_ADD_FAIL = "{\"error\": \"Failed to add torrent.\"}"; + const std::string WebApp::JSON_TORRENT_REMOVE_FAIL = "{\"error\": \"Failed to remove torrent.\"}"; + const std::string WebApp::JSON_OKAY = "{\"result\": \"Okay\"}"; + const std::string WebApp::JSON_OKAY_DYNAMIC = "{\"result\": \"Okay\", \"note\": \"tracker is in dynamic mode.\"}"; + + + void WebApp::workerThread(WebApp *app) { + app->m_isRunning = true; + ::event_base_dispatch(app->m_eventBase.get()); + + LOG_INFO("webapp", "Worker " << std::this_thread::get_id() << " exited"); + } + + void WebApp::viewApiTorrents(struct ::evhttp_request *req, void *app_) { + WebApp *app = reinterpret_cast(app_); + + setCommonHeaders(req); + addHeaders(req, std::multimap( { {"Content-Type", "text/json"} } )); + + enum evhttp_cmd_type requestMethod = ::evhttp_request_get_command(req); + if (requestMethod != EVHTTP_REQ_POST && requestMethod != EVHTTP_REQ_DELETE) { + sendReply(req, HTTP_BADMETHOD, "Bad Method", JSON_INVALID_METHOD); + return; + } + + const struct evhttp_uri *requestUri = ::evhttp_request_get_evhttp_uri(req); + if (nullptr == requestUri) { + LOG_ERR("webapp", "evhttp_request_get_evhttp_uri() returned NULL."); + sendReply(req, HTTP_INTERNAL, "Internal Server Error", JSON_INTERNAL_ERROR); + return; + } + + const char *query = ::evhttp_uri_get_query(requestUri); + if (nullptr == query) { + sendReply(req, HTTP_BADREQUEST, "Bad Request", JSON_PARAMS_REQUIRED); + return; + } + + const std::multimap ¶ms = parseQueryParameters(query); + std::vector hashes; + + for (std::multimap::const_iterator it = params.find("info_hash"); it != params.end(); it++) { + hashes.push_back(it->second); + } + + if (hashes.size() != 1) { + sendReply(req, HTTP_BADREQUEST, "Bad Request", JSON_INFOHASH_REQUIRED); + return; + } + + const std::string &info_hash = hashes.front(); + + if (info_hash.length() != 40) { + sendReply(req, HTTP_BADREQUEST, "Bad Request", JSON_INFOHASH_INVALID); + return; + } + + uint8_t hash [20] = {0}; + if (0 != ::str_to_hash(info_hash.c_str(), hash)) { + sendReply(req, HTTP_BADREQUEST, "Bad Request", JSON_INFOHASH_INVALID); + return; + } + + if (requestMethod == EVHTTP_REQ_POST) { + // add torrent + if (!app->m_db.addTorrent(hash)) { + sendReply(req, HTTP_INTERNAL, "Internal Server Error", JSON_TORRENT_ADD_FAIL); + return; + } + } + else if (requestMethod == EVHTTP_REQ_DELETE) { + // remove torrent + if (!app->m_db.removeTorrent(hash)) { + sendReply(req, HTTP_INTERNAL, "Internal Server Error", JSON_TORRENT_REMOVE_FAIL); + return; + } + } + + if (app->m_db.isDynamic()) { + sendReply(req, HTTP_OK, "OK", JSON_OKAY_DYNAMIC); + } else { + sendReply(req, HTTP_OK, "OK", JSON_OKAY); + } + return; + } + + void WebApp::viewNotFound(struct ::evhttp_request *req, void *app) { + setCommonHeaders(req); + sendReply(req, HTTP_NOTFOUND, "Not Found", NOT_FOUND_PAGE); + } + + void WebApp::addHeaders(struct ::evhttp_request *req, const std::multimap& headers) { + struct evkeyvalq *resp_headers = ::evhttp_request_get_output_headers(req); + + for(std::multimap::const_iterator it = headers.begin(); it != headers.end(); it++) { + ::evhttp_add_header(resp_headers, it->first.c_str(), it->second.c_str()); + } + } + + void WebApp::setCommonHeaders(struct ::evhttp_request *req) { + std::multimap headers; + headers.insert(std::pair("Server", "udpt")); + + addHeaders(req, headers); + } + + std::multimap WebApp::parseQueryParameters(const std::string& query) { + std::string::size_type key_begin = 0, key_end = 0, value_begin = 0, value_end = 0; + std::multimap result; + + while (key_begin <= query.length()) { + key_end = query.find('=', key_begin); + if (key_end == std::string::npos) { + // a key by itself is unacceptable... + break; + } + + value_begin = key_end + 1; + value_end = query.find('&', value_begin); + + if (value_end == std::string::npos) { + // this is the last value... + value_end = query.length(); + } + + // insert parsed param into map: + const std::string &key = query.substr(key_begin, key_end - key_begin); + const std::string &value = query.substr(value_begin, value_end - value_begin); + + result.insert(std::pair(key, value)); + + // get ready for next iteration... + key_begin = value_end + 1; + + } + return result; + }; + + void WebApp::sendReply(struct ::evhttp_request *req, int code, const char *reason, const std::string &response) { + sendReply(req, code, reason, response.c_str(), response.length()); + } + + void WebApp::sendReply(struct ::evhttp_request *req, int code, const char *reason, const char *response, size_t len) { + std::shared_ptr resp (::evbuffer_new(), ::evbuffer_free); + + if (nullptr == resp) { + LOG_ERR("webapp", "evbuffer_new() failed to allocate buffer"); + goto error; + } + + { + int result = ::evbuffer_add_reference(resp.get(), response, len, nullptr, nullptr); + if (0 != result) { + LOG_ERR("webapp", "evbuffer_add_reference() returned " << result); + goto error; + } + } + + ::evhttp_send_reply(req, code, reason, resp.get()); + + // This is C++, and this is the C approach, maybe fix this in the future? + error: + ::evhttp_send_error(req, HTTP_INTERNAL, "Internal Server Error"); + } +} diff --git a/src/WebApp.hpp b/src/WebApp.hpp new file mode 100644 index 0000000..91d5aa2 --- /dev/null +++ b/src/WebApp.hpp @@ -0,0 +1,82 @@ +/* + * Copyright © 2012-2017 Naim A. + * + * This file is part of UDPT. + * + * UDPT is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * UDPT 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 UDPT. If not, see . + */ + +#pragma once +#include +#include +#include + +#include "db/database.hpp" + +namespace UDPT +{ + class WebApp { + public: + WebApp(UDPT::Data::DatabaseDriver& db, const std::string& listenIP, uint16_t listenPort); + + virtual ~WebApp(); + + void start(); + + void stop(); + + private: + static const std::string ANNOUNCE_PAGE; + static const std::string NOT_FOUND_PAGE; + static const std::string HOME_PAGE; + static const std::string JSON_INVALID_METHOD; + static const std::string JSON_INTERNAL_ERROR; + static const std::string JSON_PARAMS_REQUIRED; + static const std::string JSON_INFOHASH_REQUIRED; + static const std::string JSON_INFOHASH_INVALID; + static const std::string JSON_TORRENT_ADD_FAIL; + static const std::string JSON_TORRENT_REMOVE_FAIL; + static const std::string JSON_OKAY; + static const std::string JSON_OKAY_DYNAMIC; + + UDPT::Data::DatabaseDriver& m_db; + + const std::string m_listenIP; + uint16_t m_listenPort; + + std::thread m_workerThread; + std::atomic_bool m_isRunning; + + // Be Aware: The order of these members are important + // we wouldn't want to free event_base before http_server... + std::shared_ptr m_eventBase; + std::shared_ptr m_httpServer; + + static void workerThread(WebApp *); + + static void viewApiTorrents(struct ::evhttp_request *, void *); + + static void viewNotFound(struct ::evhttp_request *, void *); + + static void addHeaders(struct ::evhttp_request *, const std::multimap& headers); + + static void setCommonHeaders(struct ::evhttp_request *); + + static std::multimap parseQueryParameters(const std::string& query); + + // these methods are currently only safe for static strings... + static void sendReply(struct ::evhttp_request *req, int code, const char *reason, const std::string &response); + static void sendReply(struct ::evhttp_request *req, int code, const char *reason, const char *response, size_t len); + }; +} \ No newline at end of file diff --git a/src/db/driver_sqlite.cpp b/src/db/driver_sqlite.cpp index 36374fd..7fb3133 100644 --- a/src/db/driver_sqlite.cpp +++ b/src/db/driver_sqlite.cpp @@ -17,15 +17,15 @@ * along with UDPT. If not, see . */ -#include "driver_sqlite.hpp" -#include "../tools.h" #include #include #include #include #include -#include // memcpy -#include "../multiplatform.h" +#include + +#include "driver_sqlite.hpp" +#include "../tools.h" #include "../logging.hpp" using namespace std; @@ -72,6 +72,8 @@ namespace UDPT int r; bool doSetup; + LOG_INFO("db-sqlite", "compiled with sqlite " << SQLITE_VERSION << ", running with " << sqlite3_libversion()); + fstream fCheck; string filename = m_conf["db.param"].as(); @@ -151,7 +153,7 @@ namespace UDPT sqlite3_stmt *stmt; int r, i; - to_hex_str(info_hash, hash); + hash_to_str(info_hash, hash); sql = "SELECT ip,port FROM 't"; sql += hash; @@ -195,7 +197,7 @@ namespace UDPT int r; char *hash = xHash; - to_hex_str(info_hash, hash); + hash_to_str(info_hash, hash); addTorrent (info_hash); diff --git a/src/exceptions.h b/src/exceptions.h index 2f52cd2..8fac2c3 100644 --- a/src/exceptions.h +++ b/src/exceptions.h @@ -1,34 +1,29 @@ #pragma once -#include "multiplatform.h" +#ifdef WIN32 +#include +#endif namespace UDPT { class UDPTException { public: - UDPTException(const char* errorMsg, int errorCode = 0) : m_error(errorMsg), m_errorCode(errorCode) - { - + UDPTException(const char* errorMsg, int errorCode = 0): m_error(errorMsg), m_errorCode(errorCode) { } - UDPTException(int errorCode = 0) : m_errorCode(errorCode), m_error("") - { + UDPTException(int errorCode = 0): m_error(""), m_errorCode(errorCode) { } - virtual const char* what() const - { + virtual const char* what() const { return m_error; } - virtual int getErrorCode() const - { + virtual int getErrorCode() const { return m_errorCode; } - virtual ~UDPTException() - { - + virtual ~UDPTException() { } protected: diff --git a/src/http/httpserver.cpp b/src/http/httpserver.cpp deleted file mode 100644 index e4e6312..0000000 --- a/src/http/httpserver.cpp +++ /dev/null @@ -1,535 +0,0 @@ -/* - * Copyright © 2013-2017 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include -#include -#include -#include -#include -#include "httpserver.hpp" -#include - -using namespace std; - -namespace UDPT -{ - namespace Server - { - /* HTTPServer */ - HTTPServer::HTTPServer (uint16_t port, int threads) - { - SOCKADDR_IN sa; - - memset((void*)&sa, 0, sizeof(sa)); - sa.sin_addr.s_addr = 0L; - sa.sin_family = AF_INET; - sa.sin_port = htons (port); - - this->init(sa, threads); - } - - HTTPServer::HTTPServer(const boost::program_options::variables_map& conf) - { - list localEndpoints; - uint16_t port; - int threads; - - port = conf["apiserver.port"].as(); - threads = conf["apiserver.threads"].as(); - - if (threads <= 0) - threads = 1; - - if (localEndpoints.empty()) - { - SOCKADDR_IN sa; - memset((void*)&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; - sa.sin_port = htons (port); - sa.sin_addr.s_addr = 0L; - localEndpoints.push_front(sa); - } - - this->init(localEndpoints.front(), threads); - } - - void HTTPServer::init (SOCKADDR_IN &localEndpoint, int threads) - { - int r; - this->thread_count = threads; - this->threads = new HANDLE[threads]; - this->isRunning = false; - - this->rootNode.callback = NULL; - - this->srv = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (this->srv == INVALID_SOCKET) - { - throw ServerException (1, "Failed to create Socket"); - } - - r = ::bind(this->srv, (SOCKADDR*)&localEndpoint, sizeof(localEndpoint)); - if (r == SOCKET_ERROR) - { - throw ServerException(2, "Failed to bind socket"); - } - - this->isRunning = true; - for (int i = 0;i < threads;i++) - { -#ifdef WIN32 - this->threads[i] = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, this, 0, NULL); -#else - pthread_create (&this->threads[i], NULL, &HTTPServer::_thread_start, this); -#endif - } - } - -#ifdef WIN32 - DWORD HTTPServer::_thread_start (LPVOID arg) -#else - void* HTTPServer::_thread_start (void *arg) -#endif - { - HTTPServer *s = (HTTPServer*)arg; -doSrv: - try { - HTTPServer::handleConnections (s); - } catch (const ServerException &se) - { - cerr << "SRV ERR #" << se.getErrorCode() << ": " << se.getErrorMsg () << endl; - goto doSrv; - } - return 0; - } - - void HTTPServer::handleConnections (HTTPServer *server) - { - int r; -#ifdef WIN32 - int addrSz; -#else - socklen_t addrSz; -#endif - SOCKADDR_IN addr; - SOCKET cli; - - while (server->isRunning) - { - r = ::listen(server->srv, 50); - if (r == SOCKET_ERROR) - { -#ifdef WIN32 - ::Sleep(500); -#else - ::sleep(1); -#endif - continue; - } - addrSz = sizeof addr; - cli = accept (server->srv, (SOCKADDR*)&addr, &addrSz); - if (cli == INVALID_SOCKET) - continue; - - Response resp (cli); // doesn't throw exceptions. - - try { - Request req (cli, &addr); // may throw exceptions. - reqCallback *cb = getRequestHandler (&server->rootNode, req.getPath()); - if (cb == NULL) - { - // error 404 - resp.setStatus (404, "Not Found"); - resp.addHeader ("Content-Type", "text/html; charset=US-ASCII"); - stringstream stream; - stream << ""; - stream << "Not Found"; - stream << "

Not Found

The server couldn't find the request resource.


"; - stream << ""; - string str = stream.str(); - resp.write (str.c_str(), str.length()); - } - else - { - try { - cb (server, &req, &resp); - } catch (...) - { - resp.setStatus(500, "Internal Server Error"); - resp.addHeader ("Content-Type", "text/html; charset=US-ASCII"); - stringstream stream; - stream << ""; - stream << "Internal Server Error"; - stream << "

Internal Server Error

An Error Occurred while trying to process your request.


"; - stream << ""; - string str = stream.str(); - resp.write (str.c_str(), str.length()); - } - } - resp.finalize(); - } catch (ServerException &e) - { - // Error 400 Bad Request! - } - - closesocket (cli); - } - } - - void HTTPServer::addApp (list *path, reqCallback *cb) - { - list::iterator it = path->begin(); - appNode *node = &this->rootNode; - while (it != path->end()) - { - map::iterator se; - se = node->nodes.find (*it); - if (se == node->nodes.end()) - { - node->nodes[*it].callback = NULL; - } - node = &node->nodes[*it]; - it++; - } - node->callback = cb; - } - - HTTPServer::reqCallback* HTTPServer::getRequestHandler (appNode *node, list *path) - { - appNode *cn = node; - list::iterator it = path->begin(), - end = path->end(); - map::iterator n; - while (true) - { - if (it == end) - { - return cn->callback; - } - - n = cn->nodes.find (*it); - if (n == cn->nodes.end()) - return NULL; // node not found! - cn = &n->second; - - it++; - } - return NULL; - } - - void HTTPServer::setData(string k, void *d) - { - this->customData[k] = d; - } - - void* HTTPServer::getData(string k) - { - map::iterator it = this->customData.find(k); - if (it == this->customData.end()) - return NULL; - return it->second; - } - - HTTPServer::~HTTPServer () - { - if (this->srv != INVALID_SOCKET) - closesocket (this->srv); - - if (this->isRunning) - { - for (int i = 0;i < this->thread_count;i++) - { -#ifdef WIN32 - TerminateThread (this->threads[i], 0x00); -#else - pthread_detach (this->threads[i]); - pthread_cancel (this->threads[i]); -#endif - } - } - - delete[] this->threads; - } - - /* HTTPServer::Request */ - HTTPServer::Request::Request (SOCKET cli, const SOCKADDR_IN *addr) - { - this->conn = cli; - this->addr = addr; - - this->parseRequest (); - } - - inline static char* nextReqLine (int &cPos, char *buff, int len) - { - for (int i = cPos;i < len - 1;i++) - { - if (buff[i] == '\r' && buff[i + 1] == '\n') - { - buff[i] = '\0'; - - int r = cPos; - cPos = i + 2; - return (buff + r); - } - } - - return (buff + len); // end - } - - inline void parseURL (string request, list *path, map *params) - { - string::size_type p; - string query, url; - p = request.find ('?'); - if (p == string::npos) - { - p = request.length(); - } - else - { - query = request.substr (p + 1); - } - url = request.substr (0, p); - - path->clear (); - string::size_type s, e; - s = 0; - while (true) - { - e = url.find ('/', s); - if (e == string::npos) - e = url.length(); - - string x = url.substr (s, e - s); - if (!(x.length() == 0 || x == ".")) - { - if (x == "..") - { - if (path->empty()) - throw ServerException (1, "Hack attempt"); - else - path->pop_back (); - } - path->push_back (x); - } - - if (e == url.length()) - break; - s = e + 1; - } - - string::size_type vS, vE, kS, kE; - vS = vE = kS = kE = 0; - while (kS < query.length()) - { - kE = query.find ('=', kS); - if (kE == string::npos) break; - vS = kE + 1; - vE = query.find ('&', vS); - if (vE == string::npos) vE = query.length(); - - params->insert (pair( query.substr (kS, kE - kS), query.substr (vS, vE - vS) )); - - kS = vE + 1; - } - } - - inline void setCookies (string &data, map *cookies) - { - string::size_type kS, kE, vS, vE; - kS = 0; - while (kS < data.length ()) - { - kE = data.find ('=', kS); - if (kE == string::npos) - break; - vS = kE + 1; - vE = data.find ("; ", vS); - if (vE == string::npos) - vE = data.length(); - - (*cookies) [data.substr (kS, kE-kS)] = data.substr (vS, vE-vS); - - kS = vE + 2; - } - } - - void HTTPServer::Request::parseRequest () - { - char buffer [REQUEST_BUFFER_SIZE]; - int r; - r = recv (this->conn, buffer, REQUEST_BUFFER_SIZE, 0); - if (r == REQUEST_BUFFER_SIZE) - throw ServerException (1, "Request Size too big."); - if (r <= 0) - throw ServerException (2, "Socket Error"); - - char *cLine; - int n = 0; - int pos = 0; - string::size_type p; - while ( (cLine = nextReqLine (pos, buffer, r)) < (buffer + r)) - { - string line = string (cLine); - if (line.length() == 0) break; // CRLF CRLF = end of headers. - n++; - - if (n == 1) - { - string::size_type uS, uE; - p = line.find (' '); - if (p == string::npos) - throw ServerException (5, "Malformed request method"); - uS = p + 1; - this->requestMethod.str = line.substr (0, p); - - if (this->requestMethod.str == "GET") - this->requestMethod.rm = RM_GET; - else if (this->requestMethod.str == "POST") - this->requestMethod.rm = RM_POST; - else - this->requestMethod.rm = RM_UNKNOWN; - - uE = uS; - while (p < line.length()) - { - if (p == string::npos) - break; - p = line.find (' ', p + 1); - if (p == string::npos) - break; - uE = p; - } - if (uE + 1 >= line.length()) - throw ServerException (6, "Malformed request"); - string httpVersion = line.substr (uE + 1); - - - parseURL (line.substr (uS, uE - uS), &this->path, &this->params); - } - else - { - p = line.find (": "); - if (p == string::npos) - throw ServerException (4, "Malformed headers"); - string key = line.substr (0, p); - string value = line.substr (p + 2); - if (key != "Cookie") - this->headers.insert(pair( key, value)); - else - setCookies (value, &this->cookies); - } - } - if (n == 0) - throw ServerException (3, "No Request header."); - } - - list* HTTPServer::Request::getPath () - { - return &this->path; - } - - string HTTPServer::Request::getParam (const string key) - { - map::iterator it = this->params.find (key); - if (it == this->params.end()) - return ""; - else - return it->second; - } - - multimap::iterator HTTPServer::Request::getHeader (const string name) - { - multimap::iterator it = this->headers.find (name); - return it; - } - - HTTPServer::Request::RequestMethod HTTPServer::Request::getRequestMethod () - { - return this->requestMethod.rm; - } - - string HTTPServer::Request::getRequestMethodStr () - { - return this->requestMethod.str; - } - - string HTTPServer::Request::getCookie (const string name) - { - map::iterator it = this->cookies.find (name); - if (it == this->cookies.end()) - return ""; - else - return it->second; - } - - const SOCKADDR_IN* HTTPServer::Request::getAddress () - { - return this->addr; - } - - /* HTTPServer::Response */ - HTTPServer::Response::Response (SOCKET cli) - { - this->conn = cli; - - setStatus (200, "OK"); - } - - void HTTPServer::Response::setStatus (int c, const string m) - { - this->status_code = c; - this->status_msg = m; - } - - void HTTPServer::Response::addHeader (string key, string value) - { - this->headers.insert (pair(key, value)); - } - - void HTTPServer::Response::write (const char *data, int len) - { - if (len < 0) - len = strlen (data); - msg.write(data, len); - } - - void HTTPServer::Response::finalize () - { - stringstream x; - x << "HTTP/1.1 " << this->status_code << " " << this->status_msg << "\r\n"; - multimap::iterator it, end; - end = this->headers.end(); - for (it = this->headers.begin(); it != end;it++) - { - x << it->first << ": " << it->second << "\r\n"; - } - x << "Connection: Close\r\n"; - x << "Content-Length: " << this->msg.tellp() << "\r\n"; - x << "Server: udpt\r\n"; - x << "\r\n"; - x << this->msg.str(); - - // write to socket - send (this->conn, x.str().c_str(), x.str().length(), 0); - } - - }; -}; diff --git a/src/http/httpserver.hpp b/src/http/httpserver.hpp deleted file mode 100644 index a8b30b5..0000000 --- a/src/http/httpserver.hpp +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright © 2013-2017 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include "../multiplatform.h" -using namespace std; - -#define REQUEST_BUFFER_SIZE 2048 - -namespace UDPT -{ - namespace Server - { - class ServerException - { - public: - inline ServerException (int ec) - { - this->ec = ec; - this->em = NULL; - } - - inline ServerException (int ec, const char *em) - { - this->ec = ec; - this->em = em; - } - - inline const char *getErrorMsg () const - { - return this->em; - } - - inline int getErrorCode () const - { - return this->ec; - } - private: - int ec; - const char *em; - }; - - class HTTPServer - { - public: - class Request - { - public: - enum RequestMethod - { - RM_UNKNOWN = 0, - RM_GET = 1, - RM_POST = 2 - }; - - Request (SOCKET, const SOCKADDR_IN *); - list* getPath (); - - string getParam (const string key); - multimap::iterator getHeader (const string name); - RequestMethod getRequestMethod (); - string getRequestMethodStr (); - string getCookie (const string name); - const SOCKADDR_IN* getAddress (); - - private: - const SOCKADDR_IN *addr; - SOCKET conn; - struct { - int major; - int minor; - } httpVer; - struct { - string str; - RequestMethod rm; - } requestMethod; - list path; - map params; - map cookies; - multimap headers; - - void parseRequest (); - }; - - class Response - { - public: - Response (SOCKET conn); - - void setStatus (int, const string); - void addHeader (string key, string value); - - int writeRaw (const char *data, int len); - void write (const char *data, int len = -1); - - private: - friend class HTTPServer; - - SOCKET conn; - int status_code; - string status_msg; - multimap headers; - stringstream msg; - - void finalize (); - }; - - typedef void (reqCallback)(HTTPServer*,Request*,Response*); - - HTTPServer (uint16_t port, int threads); - HTTPServer(const boost::program_options::variables_map& conf); - - void addApp (list *path, reqCallback *); - - void setData (string, void *); - void* getData (string); - - virtual ~HTTPServer (); - - private: - typedef struct appNode - { - reqCallback *callback; - map nodes; - } appNode; - - SOCKET srv; - int thread_count; - HANDLE *threads; - bool isRunning; - appNode rootNode; - map customData; - - void init (SOCKADDR_IN &localEndpoint, int threads); - - static void handleConnections (HTTPServer *); - -#ifdef WIN32 - static DWORD _thread_start (LPVOID); -#else - static void* _thread_start (void*); -#endif - - static reqCallback* getRequestHandler (appNode *, list *); - }; - }; -}; diff --git a/src/http/webapp.cpp b/src/http/webapp.cpp deleted file mode 100644 index 0de9614..0000000 --- a/src/http/webapp.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright © 2013-2017 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#include "webapp.hpp" -#include "../tools.h" -#include -#include -using namespace std; - -namespace UDPT -{ - namespace Server - { - - static uint32_t _getNextIPv4 (string::size_type &i, string &line) - { - string::size_type len = line.length(); - char c; - while (i < len) - { - c = line.at(i); - if (c >= '0' && c <= '9') - break; - i++; - } - - uint32_t ip = 0; - for (int n = 0;n < 4;n++) - { - int cn = 0; - while (i < len) - { - c = line.at (i++); - if (c == '.' || ((c == ' ' || c == ',' || c == ';') && n == 3)) - break; - else if (!(c >= '0' && c <= '9')) - return 0; - cn *= 10; - cn += (c - '0'); - } - ip *= 256; - ip += cn; - } - return ip; - } - - static bool _hex2bin (uint8_t *data, const string str) - { - int len = str.length(); - - if (len % 2 != 0) - return false; - - char a, b; - uint8_t c; - for (int i = 0;i < len;i+=2) - { - a = str.at (i); - b = str.at (i + 1); - c = 0; - - if (a >= 'a' && a <= 'f') - a = (a - 'a') + 10; - else if (a >= '0' && a <= '9') - a = (a - '0'); - else - return false; - - if (b >= 'a' && b <= 'f') - b = (b - 'a') + 10; - else if (b >= '0' && b <= '9') - b = (b - '0'); - else - return false; - - c = (a * 16) + b; - - data [i / 2] = c; - } - - return true; - } - - WebApp::WebApp(std::shared_ptr srv, DatabaseDriver *db, const boost::program_options::variables_map& conf) : m_conf(conf), m_server(srv) - { - this->db = db; - // TODO: Implement authentication by keys - - m_server->setData("webapp", this); - } - - WebApp::~WebApp() - { - } - - void WebApp::deploy() - { - list path; - m_server->addApp(&path, &WebApp::handleRoot); - - path.push_back("api"); - m_server->addApp(&path, &WebApp::handleAPI); // "/api" - - path.pop_back(); - path.push_back("announce"); - m_server->addApp(&path, &WebApp::handleAnnounce); - } - - void WebApp::handleRoot(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) - { - // It would be very appreciated to keep this in the code. - resp->write("" - "UDPT Torrent Tracker" - "" - "
This tracker is running on UDPT Software.
" - "

" - "" - ""); - } - - void WebApp::doRemoveTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) - { - string strHash = req->getParam("hash"); - if (strHash.length() != 40) - { - resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); - return; - } - uint8_t hash [20]; - if (!_hex2bin(hash, strHash)) - { - resp->write("{\"error\":\"invalid info_hash.\"}"); - return; - } - - - if (this->db->removeTorrent(hash)) - resp->write("{\"success\":true}"); - else - resp->write("{\"error\":\"failed to remove torrent from DB\"}"); - } - - void WebApp::doAddTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) - { - std::string strHash = req->getParam("hash"); - if (strHash.length() != 40) - { - resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); - return; - } - uint8_t hash [20]; - if (!_hex2bin(hash, strHash)) - { - resp->write("{\"error\":\"invalid info_hash.\"}"); - return; - } - - if (this->db->addTorrent(hash)) - resp->write("{\"success\":true}"); - else - resp->write("{\"error\":\"failed to add torrent to DB\"}"); - } - - void WebApp::handleAnnounce (HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) - { - resp->write("d14:failure reason42:this is a UDP tracker, not a HTTP tracker.e"); - } - - void WebApp::handleAPI(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) - { - if (req->getAddress()->sin_family != AF_INET) - { - throw ServerException (0, "IPv4 supported Only."); - } - - WebApp *app = (WebApp*)srv->getData("webapp"); - if (app == NULL) - throw ServerException(0, "WebApp object wasn't found"); - - if (req->getAddress()->sin_addr.s_addr != 0x0100007f) - { - resp->setStatus(403, "Forbidden"); - resp->write("Access Denied. Only 127.0.0.1 can access this method."); - return; - } - - std::string action = req->getParam("action"); - if (action == "add") - app->doAddTorrent(req, resp); - else if (action == "remove") - app->doRemoveTorrent(req, resp); - else - { - resp->write("{\"error\":\"unknown action\"}"); - } - } - }; -}; diff --git a/src/http/webapp.hpp b/src/http/webapp.hpp deleted file mode 100644 index ae5a06d..0000000 --- a/src/http/webapp.hpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright © 2013-2017 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ - -#pragma once - -#include "httpserver.hpp" -#include "../db/database.hpp" -#include -#include -#include -#include -#include -using namespace std; - -using namespace UDPT; -using namespace UDPT::Data; - -namespace UDPT -{ - namespace Server - { - class WebApp - { - public: - WebApp(std::shared_ptr , DatabaseDriver *, const boost::program_options::variables_map& conf); - virtual ~WebApp(); - void deploy (); - - - private: - std::shared_ptr m_server; - UDPT::Data::DatabaseDriver *db; - const boost::program_options::variables_map& m_conf; - - static void handleRoot (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); - static void handleAnnounce (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); - static void handleAPI (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); - - void doAddTorrent (HTTPServer::Request*, HTTPServer::Response*); - void doRemoveTorrent (HTTPServer::Request*, HTTPServer::Response*); - }; - }; -}; diff --git a/src/logging.cpp b/src/logging.cpp index ceadcbf..9493a6c 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -101,6 +101,8 @@ namespace UDPT { case Severity::FATAL: sstream << "FATAL"; break; + default: + break; } sstream << " [" << entry.channel << "]\t" << entry.message; diff --git a/src/logging.hpp b/src/logging.hpp index 47d2104..f66a329 100644 --- a/src/logging.hpp +++ b/src/logging.hpp @@ -72,8 +72,8 @@ namespace UDPT { std::vector> m_outputStreams; UDPT::Utils::MessageQueue m_queue; - std::thread m_workerThread; std::atomic_bool m_cleaningUp; + std::thread m_workerThread; std::mutex m_runningMutex; std::condition_variable m_runningCondition; Severity m_minLogLevel; diff --git a/src/main.cpp b/src/main.cpp index 834d5a4..aae3903 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -19,23 +19,26 @@ #include -#include // atoi #include // signal -#include // strlen #include #include #include -#include "multiplatform.h" -#include "udpTracker.hpp" -#include "http/httpserver.hpp" -#include "http/webapp.hpp" +#if defined(__linux__) || defined(__FreeBSD__) +#include +#include +#elif defined(WIN32) +#include +#endif + +// this file will be generated by cmake. +#include + #include "tracker.hpp" #include "service.hpp" #include "logging.hpp" -extern "C" void _signal_handler(int sig) -{ +extern "C" void _signal_handler(int sig) { switch (sig) { case SIGTERM: case SIGQUIT: @@ -44,34 +47,58 @@ extern "C" void _signal_handler(int sig) UDPT::Tracker::getInstance().stop(); break; } + default: + // ignore other signals. + break; } } -#ifdef linux -static void daemonize(const boost::program_options::variables_map& conf) -{ - if (1 == ::getppid()) return; // already a daemon +#if defined(__linux__) || defined(__FreeBSD__) +static void daemonize(const boost::program_options::variables_map& conf) { + if (1 == ::getppid()) { + // already a daemon + + return; + } + int r = ::fork(); - if (0 > r) ::exit(-1); // failed to daemonize. - if (0 < r) ::exit(0); // parent exists. + if (0 > r) { + // failed to daemonize. + ::exit(-1); + } + else if (0 < r) { + // parent exists. + ::exit(0); + } ::umask(0); ::setsid(); // close all fds. - for (int i = ::getdtablesize(); i >=0; --i) - { + for (int i = ::getdtablesize(); i >=0; --i) { ::close(i); } ::chdir(conf["daemon.chdir"].as().c_str()); - } #endif +static std::string getPlatformName() { +#ifdef WIN32 + return "Windows"; +#elif __linux__ + return "Linux"; +#elif __FreeBSD__ + return "FreeBSD"; +#elif __APPLE__ + return "Apple"; +#else + return "Unknown"; +#endif +} + #ifdef WIN32 -void _close_wsa() -{ +void _close_wsa() { ::WSACleanup(); } #endif @@ -79,11 +106,11 @@ void _close_wsa() #ifdef TEST int real_main(int argc, char *argv[]) #else -int main(int argc, char *argv[]) +int main(int argc, const char *argv[]) #endif { #ifdef WIN32 - WSADATA wsadata; + WSADATA wsadata = {0}; ::WSAStartup(MAKEWORD(2, 2), &wsadata); ::atexit(_close_wsa); #endif @@ -94,8 +121,8 @@ int main(int argc, char *argv[]) ("all-help", "displays all help") ("test,t", "test configuration file") ("config,c", boost::program_options::value()->default_value("/etc/udpt.conf"), "configuration file to use") -#ifdef linux - ("interactive,i", "doesn't start as daemon") +#if defined(__linux__) || defined(__FreeBSD__) + ("interactive,i", "don't start as daemon") #endif #ifdef WIN32 ("service,s", boost::program_options::value(), "start/stop/install/uninstall service") @@ -103,7 +130,7 @@ int main(int argc, char *argv[]) ; - const boost::program_options::options_description& configOptions = Tracker::getConfigOptions(); + const boost::program_options::options_description& configOptions = UDPT::Tracker::getConfigOptions(); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, commandLine), var_map); @@ -111,8 +138,8 @@ int main(int argc, char *argv[]) if (var_map.count("help")) { - std::cout << "UDP Tracker (UDPT) " << VERSION << " (" << PLATFORM << ")" << std::endl - << "Copyright 2012-2016 Naim A. " << std::endl + std::cout << "UDP Tracker (UDPT) " << VERSION << "-" << UDPT_GIT_COMMIT << " (" << getPlatformName() << ")" << std::endl + << "Copyright 2012-2017 Naim A. " << std::endl << "Build Date: " << __DATE__ << std::endl << std::endl; std::cout << commandLine << std::endl; @@ -151,7 +178,7 @@ int main(int argc, char *argv[]) } } -#ifdef linux +#if defined(__linux__) || defined(__FreeBSD__) if (!var_map.count("interactive")) { daemonize(var_map); @@ -218,7 +245,7 @@ int main(int argc, char *argv[]) try { - Tracker& tracker = UDPT::Tracker::getInstance(); + UDPT::Tracker& tracker = UDPT::Tracker::getInstance(); tracker.start(var_map); tracker.wait(); } diff --git a/src/multiplatform.h b/src/multiplatform.h deleted file mode 100644 index 9069d29..0000000 --- a/src/multiplatform.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright © 2012-2017 Naim A. - * - * This file is part of UDPT. - * - * UDPT is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * UDPT 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 UDPT. If not, see . - */ -/* - * NOTE: keep this header after standard C/C++ headers - */ - -#include - -#if defined (_WIN32) && !defined (WIN32) -#define WIN32 -#elif defined (__APPLE__) || defined (__CYGWIN__) -#define linux -#endif - -#define VERSION "1.0.2-dev" - -#ifdef WIN32 -#include -#include -#include -#elif defined (linux) -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SOCKET int -#define INVALID_SOCKET 0 -#define SOCKET_ERROR -1 -#define DWORD uint64_t -#define closesocket(s) close(s) -typedef struct hostent HOSTENT; -typedef struct sockaddr SOCKADDR; -typedef struct sockaddr_in SOCKADDR_IN; -typedef struct in_addr IN_ADDR; -typedef void* LPVOID; -typedef void (LPTHREAD_START_ROUTINE)(LPVOID); -typedef pthread_t HANDLE; - -#endif - -#ifdef WIN32 -#define PLATFORM "Windows" -#elif defined (__APPLE__) -#define PLATFORM "Apple" -#elif defined (__CYGWIN__) -#define PLATFORM "Cygwin" -#else -#define PLATFORM "Linux" -#endif diff --git a/src/service.cpp b/src/service.cpp index f7b8bee..964df72 100644 --- a/src/service.cpp +++ b/src/service.cpp @@ -19,7 +19,8 @@ #include "service.hpp" #include -#ifdef WIN32 +#ifdef WIN32 +#include namespace UDPT { diff --git a/src/service.hpp b/src/service.hpp index 5bf96b3..39dce70 100644 --- a/src/service.hpp +++ b/src/service.hpp @@ -21,7 +21,6 @@ #include #include #include -#include "multiplatform.h" #include "exceptions.h" #include "tracker.hpp" diff --git a/src/tools.c b/src/tools.c index 4809a22..866e6af 100644 --- a/src/tools.c +++ b/src/tools.c @@ -16,9 +16,7 @@ * You should have received a copy of the GNU General Public License * along with UDPT. If not, see . */ - #include "tools.h" -#include "multiplatform.h" void m_byteswap (void *dest, void *src, int sz) { @@ -53,7 +51,7 @@ uint32_t m_hton32 (uint32_t n) static const char hexadecimal[] = "0123456789abcdef"; -void to_hex_str (const uint8_t *hash, char *data) +void hash_to_str(const uint8_t *hash, char *data) { int i; for (i = 0;i < 20;i++) @@ -63,3 +61,33 @@ void to_hex_str (const uint8_t *hash, char *data) } data[40] = '\0'; } + +static int hex_from_char(char c) { + if ('A' <= c && c <= 'F') { + return 0x0a + (c - 'A'); + } + else if ('a' <= c && c <= 'f') { + return 0x0a + (c - 'a'); + } + else if ('0' <= c && c <= '9') { + return c - '0'; + } + else { + return -1; + } +} + +int str_to_hash(const char *data, uint8_t *hash) { + int a, b; + for (int i = 0;i < 20; ++i) { + a = hex_from_char(data[i * 2 + 0]); + b = hex_from_char(data[i * 2 + 1]); + + if (a == -1 || b == -1) { + return -1; + } + + hash[i] = ((a & 0xff) << 8) | (b & 0xff); + } + return 0; +} \ No newline at end of file diff --git a/src/tools.h b/src/tools.h index 932b886..b78080a 100644 --- a/src/tools.h +++ b/src/tools.h @@ -16,9 +16,7 @@ * You should have received a copy of the GNU General Public License * along with UDPT. If not, see . */ - -#ifndef TOOLS_H_ -#define TOOLS_H_ +#pragma once #include @@ -41,10 +39,10 @@ uint32_t m_hton32 (uint32_t n); uint64_t m_hton64 (uint64_t n); -void to_hex_str (const uint8_t *hash, char *data); +/* NOTE: The two following methods assume that the hash is 20 bytes long */ +void hash_to_str(const uint8_t *hash, char *data); +int str_to_hash(const char *data, uint8_t *hash); #ifdef __cplusplus } #endif - -#endif /* TOOLS_H_ */ diff --git a/src/tracker.cpp b/src/tracker.cpp index 7243cf5..a7b7305 100644 --- a/src/tracker.cpp +++ b/src/tracker.cpp @@ -18,6 +18,7 @@ */ #include #include +#include #include "tracker.hpp" #include "logging.hpp" @@ -43,11 +44,10 @@ namespace UDPT void Tracker::stop() { LOG_INFO("tracker", "Requesting components to terminate..."); + if (m_webApp != nullptr) { + m_webApp->stop(); + } m_udpTracker->stop(); - - // cause other components to destruct. - m_apiSrv = nullptr; - m_webApp = nullptr; } void Tracker::wait() @@ -58,18 +58,23 @@ namespace UDPT void Tracker::start(const boost::program_options::variables_map& conf) { setupLogging(conf); - LOG_INFO("core", "Initializing..."); + LOG_INFO("core", "Initializing UDPT " << VERSION << "-" << UDPT_GIT_COMMIT); + LOG_INFO("core", "compiled with boost " << BOOST_LIB_VERSION); m_udpTracker = std::shared_ptr(new UDPTracker(conf)); if (conf["apiserver.enable"].as()) { - m_apiSrv = std::shared_ptr(new UDPT::Server::HTTPServer(conf)); - m_webApp = std::shared_ptr(new UDPT::Server::WebApp(m_apiSrv, m_udpTracker->m_conn.get(), conf)); - m_webApp->deploy(); + const std::string& listenIp = conf["apiserver.iface"].as(); + const uint16_t listenPort = conf["apiserver.port"].as(); + m_webApp = std::shared_ptr(new WebApp(*m_udpTracker->m_conn, listenIp, listenPort)); } m_udpTracker->start(); + + if (m_webApp != nullptr) { + m_webApp->start(); + } } Tracker& Tracker::getInstance() @@ -95,13 +100,13 @@ namespace UDPT ("tracker.cleanup_interval", boost::program_options::value()->default_value(120), "sets database cleanup interval") ("apiserver.enable", boost::program_options::value()->default_value(0), "Enable API server?") - ("apiserver.threads", boost::program_options::value()->default_value(1), "threads for API server") - ("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on") + ("apiserver.iface", boost::program_options::value()->default_value("127.0.0.1"), "IP to listen on") + ("apiserver.port", boost::program_options::value()->default_value(6969), "TCP port to listen on") ("logging.filename", boost::program_options::value()->default_value("/var/log/udpt.log"), "file to write logs to") ("logging.level", boost::program_options::value()->default_value("warning"), "log level (fatal/error/warning/info/debug)") -#ifdef linux +#if defined(__linux__) || defined(__FreeBSD__) ("daemon.chdir", boost::program_options::value()->default_value("/"), "home directory for daemon") #endif #ifdef WIN32 @@ -140,7 +145,7 @@ namespace UDPT if (logFileName.length() == 0 || logFileName == "--") { logger.addStream(&std::cerr, real_severity); } else { - m_logStream = new ofstream(logFileName, std::ios::app | std::ios::out); + m_logStream = new std::ofstream(logFileName, std::ios::app | std::ios::out); logger.addStream(m_logStream, real_severity); } diff --git a/src/tracker.hpp b/src/tracker.hpp index 3714372..04ffa4f 100644 --- a/src/tracker.hpp +++ b/src/tracker.hpp @@ -23,10 +23,8 @@ #include -#include "multiplatform.h" #include "udpTracker.hpp" -#include "http/httpserver.hpp" -#include "http/webapp.hpp" +#include "WebApp.hpp" namespace UDPT { @@ -48,8 +46,7 @@ namespace UDPT private: std::shared_ptr m_udpTracker; - std::shared_ptr m_apiSrv; - std::shared_ptr m_webApp; + std::shared_ptr m_webApp; Tracker(); diff --git a/src/udpTracker.cpp b/src/udpTracker.cpp index c451235..4cab04a 100644 --- a/src/udpTracker.cpp +++ b/src/udpTracker.cpp @@ -19,7 +19,14 @@ #include "udpTracker.hpp" #include "logging.hpp" +#include "tools.h" +#include "db/driver_sqlite.hpp" +#ifdef WIN32 + +#elif defined(__linux__) || defined(__FreeBSD__) +#include +#endif using namespace UDPT::Data; @@ -38,7 +45,7 @@ namespace UDPT this->m_threadCount = conf["tracker.threads"].as() + 1; this->m_localEndpoint.sin_family = AF_INET; - this->m_localEndpoint.sin_port = m_hton16(m_port); + this->m_localEndpoint.sin_port = ::m_hton16(m_port); this->m_localEndpoint.sin_addr.s_addr = 0L; this->m_conn = std::shared_ptr(new Data::SQLite3Driver(m_conf, this->m_isDynamic)); @@ -48,14 +55,14 @@ namespace UDPT } void UDPTracker::start() { - SOCKET sock; + int sock; int r, // saves results i, // loop index yup; // just to set TRUE std::string dbname;// saves the Database name. sock = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (sock == INVALID_SOCKET) + if (sock == -1) { LOG_FATAL("udp-tracker", "Failed to create socket. error=" << errno); throw UDPT::UDPTException("Failed to create socket"); @@ -66,35 +73,33 @@ namespace UDPT { // don't block recvfrom for too long. -#if defined(linux) +#if defined(__linux__) || defined(__FreeBSD__) timeval timeout = { 0 }; timeout.tv_sec = 5; #elif defined(WIN32) DWORD timeout = 5000; -#else -#error Unsupported OS. #endif ::setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); } this->m_localEndpoint.sin_family = AF_INET; - r = ::bind(sock, reinterpret_cast(&this->m_localEndpoint), sizeof(SOCKADDR_IN)); + r = ::bind(sock, reinterpret_cast(&this->m_localEndpoint), sizeof(struct sockaddr_in)); - if (r == SOCKET_ERROR) + if (r == -1) { LOG_FATAL("udp-tracker", "Failed to bind socket. error=" << errno); - #ifdef WIN32 +#ifdef WIN32 ::closesocket(sock); - #elif defined (linux) +#elif defined(__linux__) || defined(__FreeBSD__) ::close(sock); - #endif +#endif throw UDPT::UDPTException("Failed to bind socket."); } this->m_sock = sock; - LOG_INFO("udp-tracker", "Tracker bound to " << inet_ntoa(this->m_localEndpoint.sin_addr)); + LOG_INFO("udp-tracker", "Tracker bound to " << ::inet_ntoa(this->m_localEndpoint.sin_addr)); // create maintainer thread. m_threads.push_back(std::thread(UDPTracker::_maintainance_start, this)); @@ -121,8 +126,6 @@ namespace UDPT * @note This method should be called only once, preferably by the main thread. * **/ void UDPTracker::wait() { - LOG_INFO("udp-tracker", "Waiting for threads to terminate..."); - for (std::vector::iterator it = m_threads.begin(); it != m_threads.end(); ++it) { it->join(); @@ -130,14 +133,14 @@ namespace UDPT LOG_INFO("udp-tracker", "UDP Tracker terminated"); -#ifdef linux +#if defined(__linux__) || defined(__FreeBSD__) ::close(m_sock); -#elif defined (WIN32) +#elif defined(WIN32) ::closesocket(m_sock); #endif } - int UDPTracker::sendError(UDPTracker* usi, SOCKADDR_IN* remote, uint32_t transactionID, const std::string &msg) { + int UDPTracker::sendError(UDPTracker* usi, struct sockaddr_in* remote, uint32_t transactionID, const std::string &msg) { struct udp_error_response error; int msg_sz, // message size to send. i; // copy loop @@ -159,14 +162,14 @@ namespace UDPT buff[i] = msg[i - 8]; } - ::sendto(usi->m_sock, buff, msg_sz, 0, reinterpret_cast(remote), sizeof(*remote)); + ::sendto(usi->m_sock, buff, msg_sz, 0, reinterpret_cast(remote), sizeof(*remote)); - LOG_DEBUG("udp-tracker", "Error sent to " << inet_ntoa(remote->sin_addr) << ", '" << msg << "' (len=" << msg_sz << ")"); + LOG_DEBUG("udp-tracker", "Error sent to " << ::inet_ntoa(remote->sin_addr) << ", '" << msg << "' (len=" << msg_sz << ")"); return 0; } - int UDPTracker::handleConnection(UDPTracker *usi, SOCKADDR_IN *remote, char *data) { + int UDPTracker::handleConnection(UDPTracker *usi, struct sockaddr_in *remote, char *data) { ConnectionRequest *req = reinterpret_cast(data); ConnectionResponse resp; @@ -180,12 +183,12 @@ namespace UDPT return 1; } - ::sendto(usi->m_sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); + ::sendto(usi->m_sock, (char*)&resp, sizeof(ConnectionResponse), 0, reinterpret_cast(remote), sizeof(struct sockaddr_in)); return 0; } - int UDPTracker::handleAnnounce(UDPTracker *usi, SOCKADDR_IN *remote, char *data) { + int UDPTracker::handleAnnounce(UDPTracker *usi, struct sockaddr_in *remote, char *data) { AnnounceRequest *req; AnnounceResponse *resp; int q, // peer counts @@ -288,8 +291,8 @@ namespace UDPT } } - ::sendto(usi->m_sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); - LOG_DEBUG("udp-tracker", "Announce request from " << inet_ntoa(remote->sin_addr) << " (event=" << event << "), Sent " << q << " peers"); + ::sendto(usi->m_sock, (char*)buff, bSize, 0, reinterpret_cast(remote), sizeof(struct sockaddr_in)); + LOG_DEBUG("udp-tracker", "Announce request from " << ::inet_ntoa(remote->sin_addr) << " (event=" << event << "), Sent " << q << " peers"); // update DB. uint32_t ip; @@ -303,7 +306,7 @@ namespace UDPT return 0; } - int UDPTracker::handleScrape(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len) { + int UDPTracker::handleScrape(UDPTracker *usi, struct sockaddr_in *remote, char *data, int len) { ScrapeRequest *sR = reinterpret_cast(data); int v, // validation helper c, // torrent counter @@ -325,7 +328,7 @@ namespace UDPT m_hton32(remote->sin_addr.s_addr), m_hton16(remote->sin_port))) { - LOG_DEBUG("udp-tracker", "Bad connection id from " << inet_ntoa(remote->sin_addr)); + LOG_DEBUG("udp-tracker", "Bad connection id from " << ::inet_ntoa(remote->sin_addr)); return 1; } @@ -362,8 +365,8 @@ namespace UDPT *leechers = m_hton32(tE.leechers); } - ::sendto(usi->m_sock, reinterpret_cast(buffer), sizeof(buffer), 0, reinterpret_cast(remote), sizeof(SOCKADDR_IN)); - LOG_DEBUG("udp-tracker", "Scrape request from " << inet_ntoa(remote->sin_addr) << ", Sent " << c << " torrents"); + ::sendto(usi->m_sock, reinterpret_cast(buffer), sizeof(buffer), 0, reinterpret_cast(remote), sizeof(struct sockaddr_in)); + LOG_DEBUG("udp-tracker", "Scrape request from " << ::inet_ntoa(remote->sin_addr) << ", Sent " << c << " torrents"); return 0; } @@ -375,7 +378,7 @@ namespace UDPT return 0; } - int UDPTracker::resolveRequest(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r) { + int UDPTracker::resolveRequest(UDPTracker *usi, struct sockaddr_in *remote, char *data, int r) { ConnectionRequest* cR = reinterpret_cast(data); uint32_t action; @@ -385,7 +388,7 @@ namespace UDPT { if (isIANAIP(remote->sin_addr.s_addr)) { - LOG_DEBUG("udp-tracker", "Request from IANA reserved IP rejected (" << inet_ntoa(remote->sin_addr) << ")"); + LOG_DEBUG("udp-tracker", "Request from IANA reserved IP rejected (" << ::inet_ntoa(remote->sin_addr) << ")"); return 0; // Access Denied: IANA reserved IP. } } @@ -404,21 +407,17 @@ namespace UDPT } void UDPTracker::_thread_start(UDPTracker *usi) { - SOCKADDR_IN remoteAddr; + struct sockaddr_in remoteAddr; char tmpBuff[UDP_BUFFER_SIZE]; -#ifdef linux - socklen_t addrSz; -#else - int addrSz; -#endif + unsigned int addrSz; - addrSz = sizeof(SOCKADDR_IN); + addrSz = sizeof(struct sockaddr_in); while (usi->m_shouldRun) { // peek into the first 12 bytes of data; determine if connection request or announce request. - int r = ::recvfrom(usi->m_sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); + int r = ::recvfrom(usi->m_sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, reinterpret_cast(&remoteAddr), &addrSz); if (r <= 0) { std::this_thread::yield(); @@ -445,6 +444,6 @@ namespace UDPT } lk.unlock(); - LOG_INFO("udp-tracker", "Maintenance thread " << std::this_thread::get_id() << " existed."); + LOG_INFO("udp-tracker", "Maintenance thread " << std::this_thread::get_id() << " exited."); } }; diff --git a/src/udpTracker.hpp b/src/udpTracker.hpp index 05e9798..44986d2 100644 --- a/src/udpTracker.hpp +++ b/src/udpTracker.hpp @@ -16,10 +16,7 @@ * You should have received a copy of the GNU General Public License * along with UDPT. If not, see . */ - -#ifndef UDPTRACKER_H_ -#define UDPTRACKER_H_ - +#pragma once #include #include @@ -29,16 +26,20 @@ #include #include #include - #include -#include #include #include -#include "tools.h" +#include + +#ifdef WIN32 +#else +#include +#include +#endif + #include "exceptions.h" -#include "multiplatform.h" -#include "db/driver_sqlite.hpp" +#include "db/database.hpp" #define UDPT_DYNAMIC (0x01) // Track Any info_hash? #define UDPT_ALLOW_REMOTE_IP (0x02) // Allow client's to send other IPs? @@ -154,8 +155,8 @@ namespace UDPT std::shared_ptr m_conn; private: - SOCKET m_sock; - SOCKADDR_IN m_localEndpoint; + int m_sock; + struct sockaddr_in m_localEndpoint; uint16_t m_port; uint8_t m_threadCount; bool m_isDynamic; @@ -174,16 +175,14 @@ namespace UDPT static void _thread_start(UDPTracker *usi); static void _maintainance_start(UDPTracker* usi); - static int resolveRequest(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r); + static int resolveRequest(UDPTracker *usi, struct sockaddr_in *remote, char *data, int r); - static int handleConnection(UDPTracker *usi, SOCKADDR_IN *remote, char *data); - static int handleAnnounce(UDPTracker *usi, SOCKADDR_IN *remote, char *data); - static int handleScrape(UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len); + static int handleConnection(UDPTracker *usi, struct sockaddr_in *remote, char *data); + static int handleAnnounce(UDPTracker *usi, struct sockaddr_in *remote, char *data); + static int handleScrape(UDPTracker *usi, struct sockaddr_in *remote, char *data, int len); - static int sendError(UDPTracker *, SOCKADDR_IN *remote, uint32_t transId, const std::string &); + static int sendError(UDPTracker *, struct sockaddr_in *remote, uint32_t transId, const std::string &); static int isIANAIP(uint32_t ip); }; }; - -#endif /* UDPTRACKER_H_ */ diff --git a/src/version.h.in b/src/version.h.in new file mode 100644 index 0000000..52f7658 --- /dev/null +++ b/src/version.h.in @@ -0,0 +1,4 @@ +#pragma once + +#define VERSION "2.1.0" +#define UDPT_GIT_COMMIT @GIT_COMMIT@ diff --git a/tests/main.cpp b/tests/main.cpp index dcd985a..b5d4bd8 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -1,6 +1,7 @@ #include #include "../src/tools.h" #include "../src/db/driver_sqlite.hpp" +#include "../src/WebApp.hpp" TEST(Utility, SanityCheck) { const uint32_t MAGIC = 0xDEADBEEF; @@ -19,11 +20,22 @@ TEST(Utility, HashToHexStr) { const unsigned char DATA[20] = {198, 112, 96, 110, 221, 34, 253, 14, 59, 67, 44, 151, 117, 89, 166, 135, 204, 93, 155, 210}; char OUTPUT_BUFFER[41] = {0}; - to_hex_str(DATA, OUTPUT_BUFFER); + hash_to_str(DATA, OUTPUT_BUFFER); ASSERT_EQ(std::string(EXPECTED_OUTPUT), OUTPUT_BUFFER); } +TEST(Utility, HashFromHexStr) { + char DATA[] = "C670606edd22fd0e3b432c977559a687cc5d9bd2"; + const unsigned char EXPECTED_OUTPUT[20] = {198, 112, 96, 110, 221, 34, 253, 14, 59, 67, 44, 151, 117, 89, 166, 135, 204, 93, 155, 210}; + + uint8_t OUTPUT_BUFFER[20] = {0}; + ASSERT_EQ(str_to_hash(DATA, OUTPUT_BUFFER), 0); + + DATA[0] = 'x'; // set invalid hex char + ASSERT_EQ(str_to_hash(DATA, OUTPUT_BUFFER), -1); +} + class SQLiteDriverTest: public ::testing::Test { protected: @@ -44,8 +56,8 @@ protected: } } - UDPT::Data::SQLite3Driver *driver; boost::program_options::variables_map va_map; + UDPT::Data::SQLite3Driver *driver; }; From 6c084ca9854138d4f338edb016085299a8781914 Mon Sep 17 00:00:00 2001 From: Alfonso Montero Date: Thu, 2 Nov 2017 13:41:14 +0100 Subject: [PATCH 93/99] Add Docker workflow to hacking options (#37) * Adds Dockerfile & docker-compose.yml * Additions to documentation Thanks to @pataquets for the PR! --- Dockerfile | 31 +++++++++++++++++++++++++++++++ docker-compose.yml | 7 +++++++ docs/building.rst | 29 +++++++++++++++++++++++++++++ src/WebApp.hpp | 3 ++- 4 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 Dockerfile create mode 100644 docker-compose.yml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b7b6c0e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,31 @@ +FROM gcc + +RUN \ + apt-get update && \ + DEBIAN_FRONTEND=noninteractive \ + apt-get -y install \ + cmake \ + libboost-program-options-dev \ + libboost-thread-dev \ + libevent-dev \ + libgtest-dev \ + libsqlite3-dev \ + && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/ + +RUN \ + mkdir -vp /tmp/.build && cd /tmp/.build && \ + cmake -DCMAKE_BUILD_TYPE=RELEASE /usr/src/gtest/ && \ + make && \ + mv -v libgtest* /usr/lib/ && \ + rm -vrf /tmp/.build && cd - + +COPY . /usr/src/udpt +WORKDIR /usr/src/udpt + +RUN \ + cmake -DCMAKE_BUILD_TYPE=Release . && \ + make udpt -j8 + +ENTRYPOINT [ "./udpt", "--interactive" ] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..626a5bb --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,7 @@ +udpt: + build: . + ports: + - 6969:6969/udp + - 127.0.0.1:8081:8081 + volumes: + - ./udpt.conf:/etc/udpt.conf:ro diff --git a/docs/building.rst b/docs/building.rst index adea47c..c33b62c 100644 --- a/docs/building.rst +++ b/docs/building.rst @@ -68,6 +68,35 @@ This should leave you with a udpt executable file, and optionally a udpt_tests e If everything succeeded, head over to :doc:`udpt.conf` and get your tracker running! +Building with Docker +==================== +Complete working Docker workflow is possible allowing you to start hacking and building without any other requirements or dependencies. All the required libs and build tools are handled by Docker build process. + +Using the provided Dockerfile you can build a complete working image with all the required dependencies. + +If you're not familiar with Docker, better use Docker Compose to both build and run your source easy and effortlessly. + +From the ``docker-compose.yml`` directory, run:: + + docker-compose up --build + +Skip the ``--build`` switch to launch the last built container image without rebuilding again. + +The provided ``docker-compose.yml`` file is configured to: + +* Expose daemon's ports to host (using port's defaults). API server is only exposed on 127.0.0.1 to the Docker host. +* Mount your host's ``udpt.conf`` from your source tree inside the container at ``/etc/udpt.conf`` (read-only). +* Start with the ``--interactive`` switch to avoid forking to background, as required with Docker. + +To run udpt inside a Docker container, you need to: + +* Configure logging to ``/dev/stdout`` to send the program's messages to Docker's standard logging. +* Configure API server to listen to 0.0.0.0 inside the container to be able to contact it from your development host, that is from outside the container. + +See the ``docker-compose.yml`` to view and tweak the launch parameters. + +Stop the container by ``CTRL+C``'ing it. + Building for Windows ==================== .. note:: This documentation is a work-in-progress. Stay tuned! diff --git a/src/WebApp.hpp b/src/WebApp.hpp index 91d5aa2..32c94fe 100644 --- a/src/WebApp.hpp +++ b/src/WebApp.hpp @@ -21,6 +21,7 @@ #include #include #include +#include #include "db/database.hpp" @@ -79,4 +80,4 @@ namespace UDPT static void sendReply(struct ::evhttp_request *req, int code, const char *reason, const std::string &response); static void sendReply(struct ::evhttp_request *req, int code, const char *reason, const char *response, size_t len); }; -} \ No newline at end of file +} From ef208e9acc5dd56b6f4cbe49a1b64ba02de8f068 Mon Sep 17 00:00:00 2001 From: Naim A Date: Thu, 2 Nov 2017 15:04:28 +0200 Subject: [PATCH 94/99] docker: Added sample configuration for docker --- docker-compose.yml | 2 +- udpt.docker.conf | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 udpt.docker.conf diff --git a/docker-compose.yml b/docker-compose.yml index 626a5bb..214d14c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,4 +4,4 @@ udpt: - 6969:6969/udp - 127.0.0.1:8081:8081 volumes: - - ./udpt.conf:/etc/udpt.conf:ro + - ./udpt.docker.conf:/etc/udpt.conf:ro diff --git a/udpt.docker.conf b/udpt.docker.conf new file mode 100644 index 0000000..93901ae --- /dev/null +++ b/udpt.docker.conf @@ -0,0 +1,28 @@ +# This is a sample configuration file that can +# be used with docker. + +[db] +driver=sqlite3 +param=:memory: + +[tracker] +is_dynamic=yes +port=6969 +threads=5 +allow_remotes=yes +allow_iana_ips=no +announce_interval=1800 +cleanup_interval=120 + +[apiserver] +enable=yes +port=8081 + +# WARNING: This shouldn't be exposed to untrusted users! +# The following is only safe if used with docker (where docker only exposes to +# 127.0.0.1) +iface=0.0.0.0 + +[logging] +filename=/dev/stderr +level=info From 8468b965683524fb2e32685f90caa5412d2a029e Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 24 Dec 2017 21:48:09 +0200 Subject: [PATCH 95/99] Update README.md --- README.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/README.md b/README.md index cea5364..b354b42 100644 --- a/README.md +++ b/README.md @@ -55,12 +55,6 @@ You should note that the default configuration does not use a persistent databas * Project Page: http://www.github.com/naim94a/udpt ## How to Contribute -**Donations** are the best way to contribute, we accept BitCoin: - -bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3 - -![bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3](.github/bitcoin-qr.png) - [**Issues**](https://github.com/naim94a/udpt/issues), [**Pull-Requests**](https://github.com/naim94a/udpt/pulls) and suggestions are welcome as well. From cd993844a0d937507774862fdc96ecfcc23fb1a0 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 24 Dec 2017 21:48:57 +0200 Subject: [PATCH 96/99] Update CONTRIBUTING.md --- .github/CONTRIBUTING.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 6eb1ba1..6bfb1bb 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -20,11 +20,6 @@ New features are welcome, it doesn't mean they will enter immediately. Suggestions should be filed as issues along with bug reports, just add the "enhancement" label to the created issue. -## Donations -Please show us your appreciation by donating BitCoin at bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3. - -![bitcoin:1KMeZvcgnmWdHitu51yEFWBNcSTXL1eBk3](bitcoin-qr.png) - ## Pull requests Before submitting a pull request, please check that the changes don't effect other platforms or have any unwanted side-effects. From 7a41539a8fda10e21f2b1e33552d0a12f4b8ec07 Mon Sep 17 00:00:00 2001 From: Naim A Date: Sun, 24 Dec 2017 21:49:15 +0200 Subject: [PATCH 97/99] Delete bitcoin-qr.png --- .github/bitcoin-qr.png | Bin 5762 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .github/bitcoin-qr.png diff --git a/.github/bitcoin-qr.png b/.github/bitcoin-qr.png deleted file mode 100644 index 1f8f80f41e015558746d16ce0d01404fec2ef9a7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5762 zcma)Adpwi<-?uT<+~^L|&5e$ZMF*!=V-7h)2(z$JR1W2I+t9R`m86pHq(#`A57XR* zVvJHz3S*Yi4@oi;i{>=Ub4~a2{P#Ss=a21ry{_+deXr~Kd_M2P=ac5)=BNnOfXc|o zC^|dYdjdzX^tVwS_`mku4Ue7Z2HuFL!BE%wVQ93QdK;r2}FOP+DcdzKd- zBrkd}%Y$d;Xni>L?pP{Vj8MzwuRi`yNsqiJPWxcb;Y>0tL6?y9xVQ7NK!+nMegNjB zz<}ddf=R?kZ$Z_x@1Wj|#~-(a1v4URv-#15+^n!CrySy#@n@;D6HQBN=hf&Ji|6Zl z;;ogAz3_$iJ>Y}bEV(a94j`y;9W8Cd!aPsWF31P2%1O#>%_Uv|t75_fiK*lvj}KY; zRGPr{+FCQ%G^4NCZ;h&+rWm ziccFxk-f*?$4<2Sq62&oRDlV94-uWIWS}z|2Rgc0d+eULY+nEVtw)m$46^?mrm}@z z1B6DO&czK)g#}fxwLdOoGRK+VNM3A(gwnO8rni9X#{Gj6qV`rm@-h_i(~|-Nu-h7& z2=BmVk5zO#3*MqK@w`|^mSklOl2ew{)g58X|(@|p5YX5?Su8O0-Y`lqd{)g2u%kmm5# zhA)9*>aNn4oiWX^4(P|3puR1nkd&3H6d3qM3PB*p&BGSU^tpQVctM3iL1f()Q zuuT`TL&$&OutWO&h!^da;tr(3J?2YO?SAO7RgNXYLQ_MTU2R12Q(j8>qkcbUlZ`?$ zEXPP&Lys7V4=$2~t(cnds&|33&RvN+iB9IU7N?~gFzpO`-h0(%w0LRY=u-jVwSBj} z@G*=NW+Z4)Y1B}QI0d}P23-1CMr1aBvwhCNfzvgtVbxOjo;_b*+@a5KS%nWcw!~s( zes4ki@5*bLuDneJ!n@3b(Cr-C*ufjHZ4tRRNC~_iR|*s|TfJ^L4qv8TGS5q^oY&#h z#gBy#VlKC$y49_Fqwgu5Ega_hU^mu2KT~*K@v^}6dC7b>U-4C?3Tmo_aG)pa6K@{| z;-+cXsa{vMP&f~~TD�K?c7Rqn3bN^Y$EQEwS?*tYNLm-KX#ePGLv~dOq!4`oTCn z^_e#>V*K@8=jSb#=YD4cu{26jn59c9K?S?9N#yiQu|81Y=6k!anDDOM=Su8A#3ojC z4zl)k@Nm=>jTArTi!UjKX5dSpCb7^L}5cmNp!4U((A*#h;COBc>Y zK7ECbuN*Tr(r2UJ=9fMak53w}Vi)ie-)Ccc9M?f242xCMUDf|)m`k4aoZU|Xvz*6K zpXEi8{wS(d?W63Dj&Hj32gSefiQ6Z>IX(Ytg2r2I1p5vqd0%00_;Q8wrOiH)4F+JA zkrz!fLt6Dh{zXUH-eIy8qc3;x38V468g3~&Gx0Y#Rtx(;E}a&+#W=dcN)+JjE@%OQ zkP6b0^d-YC;Df?W_fiT^^(0iz6>MXDi3e~t+~XyUW*09HwkHp1oXk+jhUxOs1<28g z_wA5e#`9`clrBLRes-iY-`oufjd1F-hIEb5tf=M#t~f3&Gj8{PP_J>6-tk`BqM0hg zOJWRqXad0CdSxS#LX&+=hok+wa?}SBw3}IhPpx)Pq6_R6`jn@dc#QAHGxc9~nf0DO z#cZnAkeM3|mjP+{+%-DUJ&*uq#RqTXD*{Mbrw*a($V0xq=ww@k)B&$;p_kFu7x}JpY?!&< zdg@!KK6slG9-&A2tmwml4*avbQSNd^L=LyLY@SEwB$N~JD~wqu;aH`=&3f4#=sDPv zL>UpcZRRX%+70y_SF=65r>-n>C!_J+2SHQQJNp(=>JA;7P*(Zvz7~aTf-()9V0fS!?q(`VzFU(kr(Bg^|p5Z}mGh|XI@Jpt1c4z{$<0Gzg#tWg-%nB)7@FF|` zt3nOwffbY_&Mvwgr0WT^_l>>6nXDvqZpd4-&w>zo2ETUVcP0f7y2~S0cW&xBxKh^i znB|qCIS*o+>>@(w51_|KKWZ4J(*zeaI1?TADyY4?_PT0V&$$a-G}Y?LX6nCJbTQ$$ zu^Vl}VKUMe6Abzt)B&$NS;9=aCG}bDW=way@aH@it%3RH+>*3;S~SY7I^wNZ%mj zM-`1s@)8tYUf*kj$QOx?3nH%lTtrpxGnH^J-E5TmYtiT*k!`EsuY{L%TezruLsXbw zos}sGYTT*7qcJ-Go(d?B%u93zk-`1(TZl1h}#VLSNQh^ z4S!1&4wE)WgedZXlAZH-SZ3rFJoro4>&uuqNM@_faCBE8!IL%ZuN8ufI&&TB{yfKs z+nB|uL93U(wdS?gb$D7cmwO3CG4diZsRLzBPYm3@E+#72l*kKA#i{{icK;LLK}KG4 zhN!$BX?|At={ur2ce1z(*qmx#_q0XCPM|rY1e?@oOiCHMMqDco?!;%-*H$M zV=Ffgq|SL&&hB*S9th5aeM1UUxLCxNKLOoYzUBiod@!SkFoD1wcmy zleG#PsYw9|TpL7gmnF!h~k;Qv4Z~ziF)6XAh zfS&ntCO2g=0JK{A^hfwM;57&)X)jtPrwv{EuN09&SB%%X#Ta!Cj>5{H48IT?A&TUs z1^%M>O`G_uTjD_KoG9p#6~;1tavS#8$rIO>zd^r(|Ay^>HU~E?$A+yi;V}pc6$CvA zcT%03N(z0>qQoGmV&LZZ1y@m9#>9ahGm!zE8TFe~_l(}7?lUR8AL0e?Id-McWmK83 zC(E9T#fjZ&-a5jd#)G@`H}lAzYsN$jotse3Hgel8?A?Hy;Gpi3hfLDR%!yI(wRKp^ z;}*;A@O5pb!nVr+l!*fQMdgYAUWXa+CQ&ME#CMw{83ru4F7^%ILS8)GSb3Ubspl!~ zyz=dB$-#7Pi7Y!x7rwGzgSY|8C#nJ}A_?318{Z@OeY@qrMT2X4-~aJw2#!T3dm$!b zu}k=+3i&+2L}m9atKP{cxblTt&4$Ufr_veT$QFI%90sLl>I>4kb5tQYE_|z!v8zS~ zgI<|TXEl6@S@O+N7h{ULez^s&o9*)eSEOfJ^+U?vDnlZ3(}b{W{y(;ulnKIy%3JLy z4<7QFsd@F$xvFM$9__ta#6E|AJzacO&!F;NIVh~I%mTMmM$(TK1(;a(m{5Er2>5aD zx*xS1Oy--h)He6I_~Xr}i^X)WM1o1da~FUrM5HD1Pz4x@LADqmHI*SZfH;O70X*S8 zwZ{ao)Q}V?UZtQO>ZP}%lvVlRTJX7TiXjsoy5jmh`q3bS3K4_STUene-B|Mg zN686PsB%Lb|H>U-G|xQ3()}|%1n{|C6t-z@iCzC^Fv0pLGtF3)GPV(N!`!J-8BoQf zZYLz|CB-es?{((sBkyif)Hpg+jWK5s(X);$j2!7Yn?7 zJ-6S8o>9lF-N^qj&TqSQbyh%NzEuY5-&KKgb{Lx0TO4|eHUmv#A zFBXRPZXXN&vr|@W(RT`+Tz9Nnu-u#2gUU5eC;&PA>W@~L86LK+%IBj|+qvURmPz_S z`U@Ul3`%7pe&eZhp!CpV~CpR4Hu}}Pb&8wZNts`of zVe@i{F#y2{ds^}=L$UM5qnVntpW3y!*A1*jXfo`8+ECU>KeDL7cw6WQdUArLo?gSU zs_3E;Zr{&Rf{0=Wm~_W?lh&Z#gf@$nNE?tJ-b5n=X|dYsT6Y^q$={ogLduDN9?zsr ze&?@(-zp2YsaUn7G^Duz%?gLv=1iLm|G`|8CD=LpkyTXy(dLA_ zwV-z!nnmdSN)7SJ9$9gfCpYeYmJj@|%i4U?N8J8Ii{e0Ee+i>S;HAZ9hpsTb6zCX* zsvYO>fZozZMzGBP++s(n^hb@ zY~|ZV87dWv=R8;cL*1|n0&{Y82E35ibo&If-3%8DI7)c^ivRWE(JSwjc}qdk)_wa~ zeA!F`l%{)6w*y6HE_+%VFNbSkBw+}TL_cc~duCxI>_xfTU51Q7vpqoC~ z+?VmT*>3|i$xpdYGNCITvu$5X4y}B*V;Pm6+Tk!-l`m4YBm|-laiX>W)wE_yDv@@G z41EyRUn^`xAtm}`4MW$0Z32lzjc(#IUDcKgWKMYS&y+x1#tLSD?@e(R9>o_eRL;9k z{t)}x_Ba9cPon1NUWaMSxoh48+HIYZYZ+bM?W40MU(xGekQKYvV^VZDsnB(NOPl6) z{*hC`nLzEb^)BA1o)!(_KDg^CR?;SCg@&%^BTTe1RfkX=zMR@p6sWzGbC|=u;y$0@ zevrCGCS~4jCR9CE<|}$)kX7Iwv+Q!(JvQSRdct{fa`~C`vO+ zrr^z&fzgI60U2d@YE9r~J?;AST*sB>!)}LGgY1(YCA)z&GR~`&b(g>!zlY`W#NPdO zWhANb5$@0?;g$IVjh{b48^po?nNHtFHxWBV;QsRXr&7gbv?Bi`h)w%j+M!4BbvVlp zt}y=g$ivPv7qOZl$Zq>2#+yMjS4vXKkl9;96)9wrik=E~`CQGEzzwY>R`SDoG*(^m zwqR{RPr8mCdcbD5!8Nl)AS}H267b;FO^%=v0t>p2zTkhuWt^}NC2luIDy(_e zfDg3(x>FS}>D)I0aEg@$-D^xISg5fvo1e`e%)r#1=FD~jvx9DX8okXd4NKCsm7LoG zv}ImoH#CuofG`J!AhqYSO41+t=>Ra#Ro7ad8H7j#(_kvaRwW?9eY9-el=P^1BDi!) z7Jex;-)Fw45xK^A_R#oJCD75$cqO8b0Ci_Yx7%Ftqmk^7UG%mHm)^xpDA%D%jY?FV zH+GRpiC6+kC{ZKHXW>E6MaQU1MIX+}(o+H>+<|$5sRYOm)y>0?Tsu=sK3Nan;ecH@ zs;qXiBHvVK>(qJHWoGVi;Go*0TV0$hjZhlw+w=ndl`uTlRM@sCb(lh%qNGy6ma7y` zMLD*5`Y>R_Z2j?p=oMo`h0?D}K&$!YIX}pfC1zOF>TqMBZ1T6&h2Kg4k|^2AznJsWxUJrx#fyrUz~wjKx_sn?yhd@O`X zmrc9E6LU-|FYhP)Qt+~Lm>b}{{laX1s&Qx{A&a}CC`E-+(HfALQw;=Z*zh)R!2-pF z-E)b3gzx=1Jh2}=Ttoa`1Q@aEc{|O3w?k^Ll`g}rZZm1_|r21a!w{2zqx03;*<$6dkt7RR(k^JxsC4fc+5lfgG(~G8Qr`kLiIM#pWnG~NEI>< ztO>KK?KL60AYj%me_%g0u$DMx)Z_5~-D**1BE>fO)go8}m@UgVA9b^5+Mc5P7a%h~ AQ2+n{ From 121535ee359791923b5bbed9c056816255818285 Mon Sep 17 00:00:00 2001 From: Alfonso Montero Date: Wed, 21 Mar 2018 22:05:10 +0100 Subject: [PATCH 98/99] Add API server parameters to example udpt.conf file (#38) Added API server parameters to example udpt.conf file (using default values) --- udpt.conf | 2 ++ 1 file changed, 2 insertions(+) diff --git a/udpt.conf b/udpt.conf index 0dec3d3..940b955 100644 --- a/udpt.conf +++ b/udpt.conf @@ -16,6 +16,8 @@ cleanup_interval=120 [apiserver] enable=no +iface=127.0.0.1 +port=8081 [logging] filename=udpt-log.log From 2e0a25632c17742be376760760d306a2b4b5b5c6 Mon Sep 17 00:00:00 2001 From: Alfonso Montero Date: Mon, 18 Jun 2018 23:59:31 +0200 Subject: [PATCH 99/99] Docker image documenting (#41) * Docker sample conf: minor comment improvements. * Add public Docker image to docs (followup to #39). --- README.md | 3 +++ udpt.docker.conf | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b354b42..7022f60 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,9 @@ but releases don't get updated as often as the master branch... You should note that the default configuration does not use a persistent database. +### Docker image +There is an official [UDPT Docker image](https://hub.docker.com/r/naim94a/udpt/) on Docker Hub, built from source automatically on each commit using an [Automated Build](https://docs.docker.com/docker-hub/builds/). + ### Links * UDPT's documentation can be found in the docs directory, or the rendered version at [naim94a.github.io/udpt](https://naim94a.github.io/udpt). * If you have any suggestions or find any bugs, please report them here: https://github.com/naim94a/udpt/issues diff --git a/udpt.docker.conf b/udpt.docker.conf index 93901ae..405cc84 100644 --- a/udpt.docker.conf +++ b/udpt.docker.conf @@ -1,5 +1,5 @@ # This is a sample configuration file that can -# be used with docker. +# be used with Docker. [db] driver=sqlite3 @@ -19,8 +19,8 @@ enable=yes port=8081 # WARNING: This shouldn't be exposed to untrusted users! -# The following is only safe if used with docker (where docker only exposes to -# 127.0.0.1) +# The following is only safe if used within Docker containers +# (where Docker only exposes to 127.0.0.1) iface=0.0.0.0 [logging]