├── .gitignore ├── src ├── tools.h ├── tools.c ├── multiplatform.h ├── http │ ├── webapp.hpp │ ├── httpserver.hpp │ ├── webapp.cpp │ └── httpserver.cpp ├── db │ ├── driver_sqlite.hpp │ ├── database.cpp │ ├── database.hpp │ └── driver_sqlite.cpp ├── settings.hpp ├── udpTracker.hpp ├── main.cpp ├── settings.cpp └── udpTracker.cpp ├── Makefile ├── README.md └── gpl.txt /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | /udpt 3 | -------------------------------------------------------------------------------- /src/tools.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #ifndef TOOLS_H_ 21 | #define TOOLS_H_ 22 | 23 | #include 24 | 25 | #ifdef __cplusplus 26 | extern "C" { 27 | #endif 28 | 29 | /** 30 | * Swaps Bytes: 31 | * example (htons): 32 | * short a = 1234; 33 | * short b; 34 | * m_byteswap (&b, &a, sizeof(a)); 35 | */ 36 | void m_byteswap (void *dest, void *src, int sz); 37 | 38 | uint16_t m_hton16(uint16_t n); 39 | 40 | uint32_t m_hton32 (uint32_t n); 41 | 42 | uint64_t m_hton64 (uint64_t n); 43 | 44 | void to_hex_str (const uint8_t *hash, char *data); 45 | 46 | #ifdef __cplusplus 47 | } 48 | #endif 49 | 50 | #endif /* TOOLS_H_ */ 51 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright © 2012,2013 Naim A. 3 | # 4 | # This file is part of UDPT. 5 | # 6 | # UDPT is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # UDPT is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with UDPT. If not, see . 18 | # 19 | 20 | objects = main.o udpTracker.o database.o driver_sqlite.o \ 21 | settings.o tools.o httpserver.o webapp.o 22 | target = udpt 23 | 24 | %.o: src/%.c 25 | $(CC) -c -o $@ $< $(CFLAGS) 26 | %.o: src/%.cpp 27 | $(CXX) -c -o $@ $< $(CXXFLAGS) 28 | %.o: src/db/%.cpp 29 | $(CXX) -c -o $@ $< $(CXXFLAGS) 30 | %.o: src/http/%.cpp 31 | $(CXX) -c -o $@ $< $(CXXFLAGS) 32 | all: $(target) 33 | 34 | $(target): $(objects) 35 | @echo Linking... 36 | $(CXX) $(LDFLAGS) -O3 -o $(target) $(objects) -lsqlite3 -lpthread 37 | @echo Done. 38 | clean: 39 | @echo Cleaning Up... 40 | $(RM) $(objects) $(target) 41 | @echo Done. 42 | 43 | install: $(target) 44 | @echo Installing $(target) to '$(exec_prefix)/bin'... 45 | -------------------------------------------------------------------------------- /src/tools.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #include "tools.h" 21 | #include "multiplatform.h" 22 | 23 | void m_byteswap (void *dest, void *src, int sz) 24 | { 25 | int i; 26 | for (i = 0;i < sz;i++) 27 | { 28 | ((char*)dest)[i] = ((char*)src)[(sz - 1) - i]; 29 | } 30 | } 31 | 32 | uint16_t m_hton16(uint16_t n) 33 | { 34 | uint16_t r; 35 | m_byteswap (&r, &n, 2); 36 | return r; 37 | } 38 | 39 | uint64_t m_hton64 (uint64_t n) 40 | { 41 | uint64_t r; 42 | m_byteswap (&r, &n, 8); 43 | return r; 44 | } 45 | 46 | uint32_t m_hton32 (uint32_t n) 47 | { 48 | uint64_t r; 49 | m_byteswap (&r, &n, 4); 50 | return r; 51 | } 52 | 53 | 54 | static const char hexadecimal[] = "0123456789abcdef"; 55 | 56 | void to_hex_str (const uint8_t *hash, char *data) 57 | { 58 | int i; 59 | for (i = 0;i < 20;i++) 60 | { 61 | data[i * 2] = hexadecimal[hash[i] / 16]; 62 | data[i * 2 + 1] = hexadecimal[hash[i] % 16]; 63 | } 64 | data[40] = '\0'; 65 | } 66 | -------------------------------------------------------------------------------- /src/multiplatform.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | /* 20 | * NOTE: keep this header after standard C/C++ headers 21 | */ 22 | 23 | #include 24 | 25 | #if defined (_WIN32) && !defined (WIN32) 26 | #define WIN32 27 | #endif 28 | 29 | #ifdef WIN32 30 | #include 31 | #include 32 | #define VERSION "1.0.0-beta (Windows)" 33 | #elif defined (linux) 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | #define SOCKET int 43 | #define INVALID_SOCKET 0 44 | #define SOCKET_ERROR -1 45 | #define DWORD uint64_t 46 | #define closesocket(s) close(s) 47 | typedef struct hostent HOSTENT; 48 | typedef struct sockaddr SOCKADDR; 49 | typedef struct sockaddr_in SOCKADDR_IN; 50 | typedef struct in_addr IN_ADDR; 51 | typedef void* LPVOID; 52 | typedef void (LPTHREAD_START_ROUTINE)(LPVOID); 53 | typedef pthread_t HANDLE; 54 | 55 | #define VERSION "1.0.0-beta (Linux)" 56 | #endif 57 | 58 | -------------------------------------------------------------------------------- /src/http/webapp.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #pragma once 21 | 22 | #include "httpserver.hpp" 23 | #include "../db/database.hpp" 24 | #include "../settings.hpp" 25 | #include 26 | #include 27 | #include 28 | using namespace std; 29 | 30 | using namespace UDPT; 31 | using namespace UDPT::Data; 32 | 33 | namespace UDPT 34 | { 35 | namespace Server 36 | { 37 | class WebApp 38 | { 39 | public: 40 | WebApp (HTTPServer *, DatabaseDriver *, Settings *); 41 | ~WebApp (); 42 | void deploy (); 43 | 44 | 45 | private: 46 | HTTPServer *instance; 47 | UDPT::Data::DatabaseDriver *db; 48 | Settings::SettingClass *sc_api; 49 | std::map > ip_whitelist; 50 | 51 | static void handleRoot (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); 52 | static void handleAnnounce (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); 53 | static void handleAPI (HTTPServer*,HTTPServer::Request*, HTTPServer::Response*); 54 | static bool isAllowedIP (WebApp *, string, uint32_t); 55 | 56 | void doAddTorrent (HTTPServer::Request*, HTTPServer::Response*); 57 | void doRemoveTorrent (HTTPServer::Request*, HTTPServer::Response*); 58 | }; 59 | }; 60 | }; 61 | -------------------------------------------------------------------------------- /src/db/driver_sqlite.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #ifndef DATABASE_H_ 21 | #define DATABASE_H_ 22 | 23 | #include 24 | #include "database.hpp" 25 | #include 26 | 27 | namespace UDPT 28 | { 29 | namespace Data 30 | { 31 | class SQLite3Driver : public DatabaseDriver 32 | { 33 | public: 34 | SQLite3Driver (Settings::SettingClass *sc, bool isDyn = false); 35 | bool addTorrent (uint8_t info_hash[20]); 36 | bool removeTorrent (uint8_t info_hash[20]); 37 | bool genConnectionId (uint64_t *connId, uint32_t ip, uint16_t port); 38 | bool verifyConnectionId (uint64_t connId, uint32_t ip, uint16_t port); 39 | 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); 40 | bool removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port); 41 | bool getTorrentInfo (TorrentEntry *e); 42 | bool isTorrentAllowed (uint8_t info_hash[20]); 43 | bool getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe); 44 | void cleanup (); 45 | 46 | ~SQLite3Driver (); 47 | private: 48 | sqlite3 *db; 49 | 50 | void doSetup (); 51 | }; 52 | }; 53 | }; 54 | 55 | #endif /* DATABASE_H_ */ 56 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | UDPT - lightweight torrent tracker for linux. 2 | 3 | This is a modified experimental UDPT version 4 | Original version is at [https://github.com/naim94a/udpt][1] 5 | 6 | This modified version contains following changes: 7 | 8 | 1. Running as linux/unix daemon 9 | 2. Advertinsing local peers and remote peers seperately 10 | 3. Some minor bug fixes 11 | 12 | The main difference of this version of UDPT to an original is 13 | the ability to run this torrent tracker inside a local network 14 | and act as both local and remote network torrent tracker 15 | 16 | ## Use case: 17 | 18 | For example your local subnet is 192.168.0.x and your remote ip 19 | for this network is 192.168.1.1. You run this torrent tracker on 192.168.0.1 20 | and your torrent client that is seeding your torrent file is running on 192.168.0.2:12345 21 | Your router port forwards 192.168.1.1:12345 to your local network 192.168.0.2:12345 port (note: port should be the same) 22 | 23 | Now let's consider two seperate leecher peer situations: 24 | #### Local leecher 25 | Leecher running on 192.168.0.3 connects to your tracker from inside your network 26 | Leecher gets one seeder peer on his announce containing local network address of 192.168.0.2:12345 and successfully downloads your torrent 27 | 28 | #### Remote leecher 29 | Leecher is running on 192.168.1.2 on remote network and connects to your tracker through port forwarding on your router 30 | Tracker sees that peer that is trying to get announce for local network peer is not running on local network so tracker subsitutes your local network 31 | ip with an remote ip address specified in your configuration 32 | Leecher gets one seeder peer on his announce containing remote networkd address of 192.168.1.1:12345 instead of 192.168.0.2:12345 33 | which is correct remote peer address and successfully downloads your torrent 34 | 35 | Licensed under GNU GPLv3. 36 | The license file is attached under the name gpl.txt. 37 | 38 | Compiling under linux or linux environment (MinGW): 39 | 40 | For Linux: 41 | ``` 42 | $ sudo apt install libsqlite3-dev 43 | $ make 44 | ``` 45 | Running: 46 | ``` 47 | $ ./udpt [udpt.conf] 48 | ``` 49 | Running as daemon: 50 | ``` 51 | $ ./udpt -d [udpt.log] [udpt.conf] 52 | ``` 53 | Cleaning: 54 | ``` 55 | $ make clean 56 | ``` 57 | 58 | Adding torrent using HTTP API: 59 | https://127.0.0.1?auth=admin&action=add&hash=TORRENT_HASH 60 | you can change the ip and auth value in udpt.conf file under [api.keys] 61 | 62 | This software currently uses the Sqlite3 Library (public domain). 63 | 64 | Developed by Naim A. . 65 | Modified by Dmitry Geurkov . 66 | 67 | [1]: http://code.google.com/p/udpt/ 68 | -------------------------------------------------------------------------------- /src/db/database.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #include "database.hpp" 21 | 22 | namespace UDPT 23 | { 24 | namespace Data 25 | { 26 | DatabaseDriver::DatabaseDriver(Settings::SettingClass *sc, bool isDynamic) 27 | { 28 | this->dClass = sc; 29 | this->is_dynamic = isDynamic; 30 | } 31 | 32 | bool DatabaseDriver::addTorrent(uint8_t hash [20]) 33 | { 34 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 35 | } 36 | 37 | bool DatabaseDriver::removeTorrent(uint8_t hash[20]) 38 | { 39 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 40 | } 41 | 42 | bool DatabaseDriver::isDynamic() 43 | { 44 | return this->is_dynamic; 45 | } 46 | 47 | bool DatabaseDriver::genConnectionId(uint64_t *cid, uint32_t ip, uint16_t port) 48 | { 49 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 50 | } 51 | 52 | bool DatabaseDriver::verifyConnectionId(uint64_t cid, uint32_t ip, uint16_t port) 53 | { 54 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 55 | } 56 | 57 | bool DatabaseDriver::updatePeer(uint8_t peer_id [20], uint8_t info_hash [20], 58 | uint32_t ip, uint16_t port, 59 | int64_t downloaded, int64_t left, int64_t uploaded, 60 | enum TrackerEvents event) 61 | { 62 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 63 | } 64 | 65 | bool DatabaseDriver::removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port) 66 | { 67 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 68 | } 69 | 70 | bool DatabaseDriver::getTorrentInfo (TorrentEntry *e) 71 | { 72 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 73 | } 74 | 75 | bool DatabaseDriver::getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe) 76 | { 77 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 78 | } 79 | 80 | void DatabaseDriver::cleanup() 81 | { 82 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 83 | } 84 | 85 | bool DatabaseDriver::isTorrentAllowed(uint8_t info_hash[20]) 86 | { 87 | throw DatabaseException (DatabaseException::E_NOT_IMPLEMENTED); 88 | } 89 | 90 | DatabaseDriver::~DatabaseDriver() 91 | { 92 | } 93 | 94 | /*-- Exceptions --*/ 95 | static const char *EMessages[] = { 96 | "Unknown Error", 97 | "Not Implemented", 98 | "Failed to connect to database" 99 | }; 100 | 101 | DatabaseException::DatabaseException() 102 | { 103 | this->errorNum = E_UNKNOWN; 104 | } 105 | 106 | DatabaseException::DatabaseException(enum EType e) 107 | { 108 | this->errorNum = e; 109 | } 110 | 111 | enum DatabaseException::EType DatabaseException::getErrorType() 112 | { 113 | return this->errorNum; 114 | } 115 | 116 | const char* DatabaseException::getErrorMessage() 117 | { 118 | return EMessages[this->errorNum]; 119 | } 120 | }; 121 | }; 122 | -------------------------------------------------------------------------------- /src/settings.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Copyright © 2012,2013 Naim A. 4 | * 5 | * This file is part of UDPT. 6 | * 7 | * UDPT is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * UDPT is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with UDPT. If not, see . 19 | */ 20 | 21 | #pragma once 22 | 23 | #include 24 | #include 25 | #include 26 | using namespace std; 27 | 28 | namespace UDPT 29 | { 30 | class Settings 31 | { 32 | public: 33 | class SettingClass 34 | { 35 | public: 36 | SettingClass (const string className); 37 | bool set (const string key, const string value); 38 | string get (const string key); 39 | map* getMap (); 40 | private: 41 | friend class Settings; 42 | string className; 43 | map entries; 44 | }; 45 | 46 | /** 47 | * Initializes the settings type. 48 | * @param filename the settings filename. 49 | */ 50 | Settings (const string filename); 51 | 52 | /** 53 | * Gets a setting from a Settings type. 54 | * @param class The class of the requested setting. 55 | * @param name The name of the requested setting. 56 | * @return The value for the requested setting, NULL if not available. 57 | */ 58 | SettingClass* getClass (const string name); 59 | 60 | /** 61 | * Loads settings from file 62 | * @return true on success, otherwise false. 63 | */ 64 | bool load (); 65 | 66 | /** 67 | * Saves settings to file. 68 | * @return true on success; otherwise false. 69 | */ 70 | bool save (); 71 | 72 | /** 73 | * Sets a setting in a settings type. 74 | * @param className The class of the setting. 75 | * @param key The name of the setting. 76 | * @param value The value to set for the setting. 77 | * @return true on success, otherwise false. 78 | */ 79 | bool set (const string className, const string key, const string value); 80 | 81 | /** 82 | * Gets the requested SettingClass. 83 | * @param classname The name of the class to find (case sensitive). 84 | * @return a pointer to the found class, or NULL if not found. 85 | */ 86 | string get (const string className, const string key); 87 | 88 | /** 89 | * Destroys the settings "object" 90 | */ 91 | virtual ~Settings (); 92 | private: 93 | string filename; 94 | map classes; 95 | 96 | void parseSettings (char *data, int len); 97 | }; 98 | }; 99 | 100 | //#ifdef __cplusplus 101 | //extern "C" { 102 | //#endif 103 | // 104 | //typedef struct { 105 | // char *key; 106 | // char *values; 107 | //} KeyValue; 108 | // 109 | //typedef struct { 110 | // char *classname; 111 | // KeyValue *entries; 112 | // uint32_t entry_count, entry_size; 113 | //} SettingClass; 114 | // 115 | //typedef struct { 116 | // char *filename; 117 | // 118 | // SettingClass *classes; 119 | // uint32_t class_count, class_size; 120 | // 121 | // char *buffer; 122 | //} Settings; 123 | // 124 | // 125 | //void settings_init (Settings *s, const char *filename); 126 | // 127 | //int settings_load (Settings *s); 128 | // 129 | //int settings_save (Settings *s); 130 | // 131 | //void settings_destroy (Settings *s); 132 | // 133 | //SettingClass* settings_get_class (Settings *s, const char *classname); 134 | // 135 | //char* settingclass_get (SettingClass *s, const char *name); 136 | // 137 | //int settingclass_set (SettingClass *s, const char *name, const char *value); 138 | // 139 | //char* settings_get (Settings *s, const char *classn, const char *name); 140 | // 141 | // 142 | //int settings_set (Settings *s, const char *classn, const char *name, const char *value); 143 | // 144 | //#ifdef __cplusplus 145 | //} 146 | //#endif 147 | -------------------------------------------------------------------------------- /src/http/httpserver.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #pragma once 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "../multiplatform.h" 28 | using namespace std; 29 | 30 | #define REQUEST_BUFFER_SIZE 2048 31 | 32 | namespace UDPT 33 | { 34 | namespace Server 35 | { 36 | class ServerException 37 | { 38 | public: 39 | inline ServerException (int ec) 40 | { 41 | this->ec = ec; 42 | this->em = NULL; 43 | } 44 | 45 | inline ServerException (int ec, const char *em) 46 | { 47 | this->ec = ec; 48 | this->em = em; 49 | } 50 | 51 | inline const char *getErrorMsg () const 52 | { 53 | return this->em; 54 | } 55 | 56 | inline int getErrorCode () const 57 | { 58 | return this->ec; 59 | } 60 | private: 61 | int ec; 62 | const char *em; 63 | }; 64 | 65 | class HTTPServer 66 | { 67 | public: 68 | class Request 69 | { 70 | public: 71 | enum RequestMethod 72 | { 73 | RM_UNKNOWN = 0, 74 | RM_GET = 1, 75 | RM_POST = 2 76 | }; 77 | 78 | Request (SOCKET, const SOCKADDR_IN *); 79 | list* getPath (); 80 | 81 | string getParam (const string key); 82 | multimap::iterator getHeader (const string name); 83 | RequestMethod getRequestMethod (); 84 | string getRequestMethodStr (); 85 | string getCookie (const string name); 86 | const SOCKADDR_IN* getAddress (); 87 | 88 | private: 89 | const SOCKADDR_IN *addr; 90 | SOCKET conn; 91 | struct { 92 | int major; 93 | int minor; 94 | } httpVer; 95 | struct { 96 | string str; 97 | RequestMethod rm; 98 | } requestMethod; 99 | list path; 100 | map params; 101 | map cookies; 102 | multimap headers; 103 | 104 | void parseRequest (); 105 | }; 106 | 107 | class Response 108 | { 109 | public: 110 | Response (SOCKET conn); 111 | 112 | void setStatus (int, const string); 113 | void addHeader (string key, string value); 114 | 115 | int writeRaw (const char *data, int len); 116 | void write (const char *data, int len = -1); 117 | 118 | private: 119 | friend class HTTPServer; 120 | 121 | SOCKET conn; 122 | int status_code; 123 | string status_msg; 124 | multimap headers; 125 | stringstream msg; 126 | 127 | void finalize (); 128 | }; 129 | 130 | typedef void (reqCallback)(HTTPServer*,Request*,Response*); 131 | 132 | HTTPServer (uint16_t port, int threads); 133 | 134 | void addApp (list *path, reqCallback *); 135 | 136 | void setData (string, void *); 137 | void* getData (string); 138 | 139 | virtual ~HTTPServer (); 140 | 141 | private: 142 | typedef struct appNode 143 | { 144 | reqCallback *callback; 145 | map nodes; 146 | } appNode; 147 | 148 | SOCKET srv; 149 | int thread_count; 150 | HANDLE *threads; 151 | bool isRunning; 152 | appNode rootNode; 153 | map customData; 154 | 155 | static void handleConnections (HTTPServer *); 156 | 157 | #ifdef WIN32 158 | static DWORD _thread_start (LPVOID); 159 | #else 160 | static void* _thread_start (void*); 161 | #endif 162 | 163 | static reqCallback* getRequestHandler (appNode *, list *); 164 | }; 165 | }; 166 | }; 167 | -------------------------------------------------------------------------------- /src/udpTracker.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #ifndef UDPTRACKER_H_ 21 | #define UDPTRACKER_H_ 22 | 23 | 24 | #include 25 | #include "multiplatform.h" 26 | #include "db/driver_sqlite.hpp" 27 | #include "settings.hpp" 28 | 29 | #include 30 | using namespace std; 31 | 32 | #define UDPT_DYNAMIC 0x01 // Track Any info_hash? 33 | #define UDPT_ALLOW_REMOTE_IP 0x02 // Allow client's to send other IPs? 34 | #define UDPT_ALLOW_IANA_IP 0x04 // allow IP's like 127.0.0.1 or other IANA reserved IPs? 35 | #define UDPT_VALIDATE_CLIENT 0x08 // validate client before adding to Database? (check if connection is open?) 36 | 37 | 38 | namespace UDPT 39 | { 40 | class UDPTracker 41 | { 42 | public: 43 | typedef struct udp_connection_request 44 | { 45 | uint64_t connection_id; 46 | uint32_t action; 47 | uint32_t transaction_id; 48 | } ConnectionRequest; 49 | 50 | typedef struct udp_connection_response 51 | { 52 | uint32_t action; 53 | uint32_t transaction_id; 54 | uint64_t connection_id; 55 | } ConnectionResponse; 56 | 57 | typedef struct udp_announce_request 58 | { 59 | uint64_t connection_id; 60 | uint32_t action; 61 | uint32_t transaction_id; 62 | uint8_t info_hash [20]; 63 | uint8_t peer_id [20]; 64 | uint64_t downloaded; 65 | uint64_t left; 66 | uint64_t uploaded; 67 | uint32_t event; 68 | uint32_t ip_address; 69 | uint32_t key; 70 | int32_t num_want; 71 | uint16_t port; 72 | } AnnounceRequest; 73 | 74 | typedef struct udp_announce_response 75 | { 76 | uint32_t action; 77 | uint32_t transaction_id; 78 | uint32_t interval; 79 | uint32_t leechers; 80 | uint32_t seeders; 81 | 82 | uint8_t *peer_list_data; 83 | } AnnounceResponse; 84 | 85 | typedef struct udp_scrape_request 86 | { 87 | uint64_t connection_id; 88 | uint32_t action; 89 | uint32_t transaction_id; 90 | 91 | uint8_t *torrent_list_data; 92 | } ScrapeRequest; 93 | 94 | typedef struct udp_scrape_response 95 | { 96 | uint32_t action; 97 | uint32_t transaction_id; 98 | 99 | uint8_t *data; 100 | } ScrapeResponse; 101 | 102 | typedef struct udp_error_response 103 | { 104 | uint32_t action; 105 | uint32_t transaction_id; 106 | char *message; 107 | } ErrorResponse; 108 | 109 | enum StartStatus 110 | { 111 | START_OK = 0, 112 | START_ESOCKET_FAILED = 1, 113 | START_EBIND_FAILED = 2 114 | }; 115 | 116 | /** 117 | * Initializes the UDP Tracker. 118 | * @param settings Settings to start server with 119 | */ 120 | UDPTracker (Settings *); 121 | 122 | /** 123 | * Starts the Initialized instance. 124 | * @return 0 on success, otherwise non-zero. 125 | */ 126 | enum StartStatus start (); 127 | 128 | /** 129 | * Destroys resources that were created by constructor 130 | * @param usi Instance to destroy. 131 | */ 132 | virtual ~UDPTracker (); 133 | 134 | Data::DatabaseDriver *conn; 135 | private: 136 | SOCKET sock; 137 | uint16_t port; 138 | uint8_t thread_count; 139 | bool isRunning; 140 | bool isDynamic; 141 | string local_subnet; 142 | string remote_ip; 143 | HANDLE *threads; 144 | uint32_t announce_interval; 145 | uint32_t cleanup_interval; 146 | 147 | uint8_t settings; 148 | Settings *o_settings; 149 | 150 | #ifdef WIN32 151 | static DWORD _thread_start (LPVOID arg); 152 | static DWORD _maintainance_start (LPVOID arg); 153 | #elif defined (linux) 154 | static void* _thread_start (void *arg); 155 | static void* _maintainance_start (void *arg); 156 | #endif 157 | 158 | static int resolveRequest (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r); 159 | 160 | static int handleConnection (UDPTracker *usi, SOCKADDR_IN *remote, char *data); 161 | static int handleAnnounce (UDPTracker *usi, SOCKADDR_IN *remote, char *data); 162 | static int handleScrape (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len); 163 | 164 | static int sendError (UDPTracker *, SOCKADDR_IN *remote, uint32_t transId, const string &); 165 | 166 | }; 167 | }; 168 | 169 | #endif /* UDPTRACKER_H_ */ 170 | -------------------------------------------------------------------------------- /src/db/database.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #ifndef DATABASE_HPP_ 21 | #define DATABASE_HPP_ 22 | 23 | #include "../settings.hpp" 24 | 25 | namespace UDPT 26 | { 27 | namespace Data 28 | { 29 | class DatabaseException 30 | { 31 | public: 32 | enum EType { 33 | E_UNKNOWN = 0, // Unknown error 34 | E_NOT_IMPLEMENTED = 1, // not implemented 35 | E_CONNECTION_FAILURE = 2 36 | }; 37 | 38 | DatabaseException (); 39 | DatabaseException (EType); 40 | EType getErrorType (); 41 | const char* getErrorMessage (); 42 | private: 43 | EType errorNum; 44 | }; 45 | 46 | class DatabaseDriver 47 | { 48 | public: 49 | typedef struct { 50 | uint8_t *info_hash; 51 | int32_t seeders; 52 | int32_t leechers; 53 | int32_t completed; 54 | } TorrentEntry; 55 | typedef struct { 56 | uint32_t ip; 57 | uint16_t port; 58 | } PeerEntry; 59 | 60 | enum TrackerEvents { 61 | EVENT_UNSPEC = 0, 62 | EVENT_COMPLETE = 1, 63 | EVENT_START = 2, 64 | EVENT_STOP = 3 65 | }; 66 | 67 | /** 68 | * Opens the DB's connection 69 | * @param dClass Settings class ('database' class). 70 | */ 71 | DatabaseDriver (Settings::SettingClass *dClass, bool isDynamic = false); 72 | 73 | /** 74 | * Adds a torrent to the Database. automatically done if in dynamic mode. 75 | * @param hash The info_hash of the torrent. 76 | * @return true on success. false on failure. 77 | */ 78 | virtual bool addTorrent (uint8_t hash[20]); 79 | 80 | /** 81 | * Removes a torrent from the database. should be used only for non-dynamic trackers or by cleanup. 82 | * @param hash The info_hash to drop. 83 | * @return true if torrent's database was dropped or no longer exists. otherwise false (shouldn't happen - critical) 84 | */ 85 | virtual bool removeTorrent (uint8_t hash[20]); 86 | 87 | /** 88 | * Checks if the Database is acting as a dynamic tracker DB. 89 | * @return true if dynamic. otherwise false. 90 | */ 91 | bool isDynamic (); 92 | 93 | /** 94 | * Checks if the torrent can be used in the tracker. 95 | * @param info_hash The torrent's info_hash. 96 | * @return true if allowed. otherwise false. 97 | */ 98 | virtual bool isTorrentAllowed (uint8_t info_hash [20]); 99 | 100 | /** 101 | * Generate a Connection ID for the peer. 102 | * @param connectionId (Output) the generated connection ID. 103 | * @param ip The peer's IP (requesting peer. not remote) 104 | * @param port The peer's IP (remote port if tracker accepts) 105 | * @return 106 | */ 107 | virtual bool genConnectionId (uint64_t *connectionId, uint32_t ip, uint16_t port); 108 | 109 | virtual bool verifyConnectionId (uint64_t connectionId, uint32_t ip, uint16_t port); 110 | 111 | /** 112 | * Updates/Adds a peer to/in the database. 113 | * @param peer_id the peer's peer_id 114 | * @param info_hash the torrent info_hash 115 | * @param ip IP of peer (remote ip if tracker accepts) 116 | * @param port TCP port of peer (remote port if tracker accepts) 117 | * @param downloaded total Bytes downloaded 118 | * @param left total bytes left 119 | * @param uploaded total bytes uploaded 120 | * @return true on success, false on failure. 121 | */ 122 | virtual bool updatePeer (uint8_t peer_id [20], uint8_t info_hash [20], 123 | uint32_t ip, uint16_t port, 124 | int64_t downloaded, int64_t left, int64_t uploaded, 125 | enum TrackerEvents event); 126 | 127 | /** 128 | * Remove a peer from a torrent (if stop action occurred, or if peer is inactive in cleanup) 129 | * @param peer_id The peer's peer_id 130 | * @param info_hash Torrent's info_hash 131 | * @param ip The IP of the peer (remote IP if tracker accepts) 132 | * @param port The TCP port (remote port if tracker accepts) 133 | * @return true on success. false on failure (shouldn't happen - critical) 134 | */ 135 | virtual bool removePeer (uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port); 136 | 137 | /** 138 | * Gets stats on a torrent 139 | * @param e TorrentEntry, only this info_hash has to be set 140 | * @return true on success, false on failure. 141 | */ 142 | virtual bool getTorrentInfo (TorrentEntry *e); 143 | 144 | /** 145 | * Gets a list of peers from the database. 146 | * @param info_hash The torrent's info_hash 147 | * @param max_count The maximum amount of peers to load from the database. The amount of loaded peers is returned through this variable. 148 | * @param pe The list of peers. Must be pre-allocated to the size of max_count. 149 | * @return true on success, otherwise false (shouldn't happen). 150 | */ 151 | virtual bool getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe); 152 | 153 | /** 154 | * Cleanup the database. 155 | * Other actions may be locked when using this depending on the driver. 156 | */ 157 | virtual void cleanup (); 158 | 159 | /** 160 | * Closes the connections, and releases all other resources. 161 | */ 162 | virtual ~DatabaseDriver (); 163 | 164 | protected: 165 | Settings::SettingClass *dClass; 166 | private: 167 | bool is_dynamic; 168 | }; 169 | }; 170 | }; 171 | 172 | 173 | #endif /* DATABASE_HPP_ */ 174 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include "multiplatform.h" 26 | #include "udpTracker.hpp" 27 | #include "settings.hpp" 28 | #include "http/httpserver.hpp" 29 | #include "http/webapp.hpp" 30 | #include // atoi 31 | #include // freopen 32 | 33 | using namespace std; 34 | using namespace UDPT; 35 | using namespace UDPT::Server; 36 | 37 | static void _print_usage () 38 | { 39 | cout << "Usage: udpt [-d] [] []" << endl; 40 | } 41 | 42 | static void _doAPIStart (Settings *settings, WebApp **wa, HTTPServer **srv, DatabaseDriver *drvr) 43 | { 44 | if (settings == NULL) 45 | return; 46 | Settings::SettingClass *sc = settings->getClass("apiserver"); 47 | if (sc == NULL) 48 | return; // no settings set! 49 | 50 | if (sc->get("enable") != "1") 51 | { 52 | cerr << "API Server not enabled." << endl; 53 | return; 54 | } 55 | 56 | string s_port = sc->get("port"); 57 | string s_threads = sc->get("threads"); 58 | 59 | uint16_t port = (s_port == "" ? 6969 : atoi (s_port.c_str())); 60 | uint16_t threads = (s_threads == "" ? 1 : atoi (s_threads.c_str())); 61 | 62 | if (threads <= 0) 63 | threads = 1; 64 | 65 | try { 66 | *srv = new HTTPServer (port, threads); 67 | *wa = new WebApp (*srv, drvr, settings); 68 | (*wa)->deploy(); 69 | } catch (ServerException &e) 70 | { 71 | cerr << "ServerException #" << e.getErrorCode() << ": " << e.getErrorMsg() << endl; 72 | } 73 | } 74 | 75 | int main(int argc, char *argv[]) 76 | { 77 | bool daemon = false; 78 | 79 | // Start as daemon 80 | if(argc > 2){ 81 | if(string(argv[1]) == "-d"){ 82 | cout << "starting daemon.." ; 83 | 84 | // Forking daemon process 85 | pid_t pid = fork(); 86 | if(pid < 0){ 87 | cout << ". failed!" << endl; 88 | exit(EXIT_FAILURE); 89 | } 90 | if(pid > 0){ 91 | cout << ". started!" << endl; 92 | exit(EXIT_SUCCESS); 93 | } 94 | 95 | // Setting umask and new process group 96 | umask(0); 97 | pid_t sid = setsid(); 98 | if (sid < 0) { 99 | exit(EXIT_FAILURE); 100 | } 101 | // Changing current working directory 102 | if ((chdir("/")) < 0) { 103 | exit(EXIT_FAILURE); 104 | } 105 | // Closing unncessary file handles 106 | freopen("/dev/null", "r", stdin); 107 | freopen( argv[2], "w", stderr); 108 | freopen( argv[2], "w", stdout); 109 | 110 | daemon = true; 111 | } 112 | } 113 | 114 | Settings *settings = NULL; 115 | UDPTracker *usi = NULL; 116 | string config_file; 117 | int r; 118 | 119 | #ifdef WIN32 120 | WSADATA wsadata; 121 | WSAStartup(MAKEWORD(2, 2), &wsadata); 122 | #endif 123 | 124 | cout << "UDP Tracker (UDPT) " << VERSION << endl; 125 | cout << "Copyright 2012,2013 Naim Abda \n\tReleased under the GPLv3 License." << endl; 126 | cout << "Build Date: " << __DATE__ << endl << endl; 127 | 128 | config_file = "udpt.conf"; 129 | 130 | if (argc > 1 && string(argv[1]) == "-h") 131 | { 132 | _print_usage (); 133 | exit(EXIT_SUCCESS); 134 | } 135 | 136 | if(argc > 1){ 137 | config_file = argv[argc-1]; 138 | } 139 | 140 | settings = new Settings (config_file); 141 | 142 | if (!settings->load()) 143 | { 144 | const char strDATABASE[] = "database"; 145 | const char strTRACKER[] = "tracker"; 146 | const char strAPISRV [] = "apiserver"; 147 | const char strAPIKEY [] = "api.keys"; 148 | // set default settings: 149 | 150 | settings->set (strDATABASE, "driver", "sqlite3"); 151 | settings->set (strDATABASE, "file", "tracker.db"); 152 | 153 | settings->set (strTRACKER, "is_dynamic", "0"); 154 | settings->set (strTRACKER, "port", "6969"); // UDP PORT 155 | settings->set (strTRACKER, "threads", "5"); 156 | settings->set (strTRACKER, "allow_remotes", "1"); 157 | settings->set (strTRACKER, "allow_iana_ips", "1"); 158 | settings->set (strTRACKER, "announce_interval", "1800"); 159 | settings->set (strTRACKER, "cleanup_interval", "120"); 160 | settings->set (strTRACKER, "local_subnet", "192.168.0"); 161 | settings->set (strTRACKER, "remote_ip", "192.168.1.0"); 162 | 163 | settings->set (strAPISRV, "enable", "1"); 164 | settings->set (strAPISRV, "threads", "1"); 165 | settings->set (strAPISRV, "port", "6969"); // TCP PORT 166 | 167 | settings->set(strAPIKEY, "admin", "127.0.0.1"); 168 | 169 | 170 | settings->save(); 171 | cerr << "Failed to read from '" << config_file.c_str() << "'. Using default settings." << endl; 172 | } 173 | 174 | usi = new UDPTracker (settings); 175 | 176 | HTTPServer *apiSrv = NULL; 177 | WebApp *wa = NULL; 178 | 179 | r = usi->start(); 180 | if (r != UDPTracker::START_OK) 181 | { 182 | cerr << "Error While trying to start server." << endl; 183 | switch (r) 184 | { 185 | case UDPTracker::START_ESOCKET_FAILED: 186 | cerr << "Failed to create socket." << endl; 187 | break; 188 | case UDPTracker::START_EBIND_FAILED: 189 | cerr << "Failed to bind socket." << endl; 190 | break; 191 | default: 192 | cerr << "Unknown Error" << endl; 193 | break; 194 | } 195 | goto cleanup; 196 | } 197 | 198 | _doAPIStart(settings, &wa, &apiSrv, usi->conn); 199 | 200 | if(daemon){ 201 | while(1){ 202 | sleep(30); 203 | } 204 | }else{ 205 | cout << "Press Any key to exit." << endl; 206 | cin.get(); 207 | } 208 | 209 | cleanup: 210 | cout << endl << "Goodbye." << endl; 211 | 212 | delete usi; 213 | delete settings; 214 | delete apiSrv; 215 | delete wa; 216 | 217 | #ifdef WIN32 218 | WSACleanup(); 219 | #endif 220 | 221 | return 0; 222 | } 223 | -------------------------------------------------------------------------------- /src/settings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Copyright © 2012,2013 Naim A. 4 | * 5 | * This file is part of UDPT. 6 | * 7 | * UDPT is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * UDPT is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with UDPT. If not, see . 19 | */ 20 | 21 | #include "settings.hpp" 22 | #include // still primitive - need for strlen() 23 | #include // need for isspace() 24 | 25 | #include 26 | #include 27 | 28 | using namespace std; 29 | 30 | namespace UDPT 31 | { 32 | Settings::SettingClass* Settings::getClass(const string classname) 33 | { 34 | if (classname == "") 35 | return NULL; 36 | 37 | map::iterator it; 38 | it = this->classes.find(classname); 39 | 40 | if (it == this->classes.end()) 41 | return NULL; 42 | else 43 | return it->second; 44 | 45 | return NULL; 46 | } 47 | 48 | Settings::Settings (const string filename) 49 | { 50 | this->filename = filename; 51 | this->classes.clear(); 52 | } 53 | 54 | static 55 | void _settings_clean_string (char **str) 56 | { 57 | int len, 58 | i, 59 | offset; 60 | 61 | len = strlen(*str); 62 | 63 | //strip leading whitespaces. 64 | offset = 0; 65 | for (i = 0;i < len;i++) 66 | { 67 | if (isspace(*str[i]) == 0) 68 | break; 69 | offset++; 70 | } 71 | 72 | (*str) += offset; 73 | len -= offset; 74 | 75 | for (i = len - 1;i >= 0;i--) 76 | { 77 | if (isspace( (*str)[i] ) != 0) 78 | { 79 | (*str)[i] = '\0'; 80 | } 81 | else 82 | break; 83 | } 84 | } 85 | 86 | void Settings::parseSettings (char *data, int len) 87 | { 88 | char *className, *key, *value; 89 | int i, 90 | cil; // cil = Chars in line. 91 | char c; 92 | 93 | className = key = value = NULL; 94 | cil = 0; 95 | 96 | for (i = 0;i < len;i++) 97 | { 98 | c = data[i]; 99 | if (c == '\n') 100 | { 101 | cil = 0; 102 | continue; 103 | } 104 | if (cil == 0 && c == ';') 105 | { 106 | while (i < len) 107 | { 108 | if (data[i] == '\n') 109 | break; 110 | i++; 111 | } 112 | continue; 113 | } 114 | if (isspace(c) != 0 && cil == 0) 115 | { 116 | continue; 117 | } 118 | if (cil == 0 && c == '[') 119 | { 120 | className = (char*)(i + data + 1); 121 | while (i < len) 122 | { 123 | if (data[i] != ']') 124 | { 125 | i++; 126 | continue; 127 | } 128 | data[i] = '\0'; 129 | break; 130 | } 131 | continue; 132 | } 133 | 134 | if (isgraph(c) != 0 && cil == 0) // must be a key. 135 | { 136 | key = (char*)(i + data); 137 | while (i < len) 138 | { 139 | if (data[i] == '\n') 140 | { 141 | key = NULL; 142 | break; 143 | } 144 | if (data[i] == '=') 145 | { 146 | data[i] = '\0'; 147 | value = (char*)(data + i + 1); 148 | while (i < len) 149 | { 150 | if (data[i] == '\n') 151 | { 152 | data[i] = '\0'; 153 | 154 | _settings_clean_string(&key); 155 | _settings_clean_string(&value); 156 | 157 | // printf("KEY: '%s'\tVALUE: '%s'\n", key, value); 158 | 159 | // add to settings... 160 | this->set (className, key, value); 161 | 162 | cil = 0; 163 | break; 164 | } 165 | i++; 166 | } 167 | break; 168 | } 169 | i++; 170 | } 171 | continue; 172 | } 173 | 174 | if (isgraph(c) != 0) 175 | { 176 | cil++; 177 | } 178 | } 179 | } 180 | 181 | bool Settings::load() 182 | { 183 | int len; 184 | char *buffer; 185 | 186 | fstream cfg; 187 | cfg.open(this->filename.c_str(), ios::in | ios::binary); 188 | 189 | if (!cfg.is_open()) 190 | return false; 191 | 192 | cfg.seekg(0, ios::end); 193 | len = cfg.tellg(); 194 | cfg.seekg(0, ios::beg); 195 | 196 | buffer = new char [len]; 197 | cfg.read(buffer, len); 198 | cfg.close(); 199 | 200 | this->parseSettings(buffer, len); 201 | 202 | delete[] buffer; 203 | 204 | return true; 205 | } 206 | 207 | bool Settings::save () 208 | { 209 | SettingClass *sclass; 210 | 211 | fstream cfg (this->filename.c_str(), ios::binary | ios::out); 212 | if (!cfg.is_open()) 213 | return false; 214 | 215 | cfg << "; udpt Settings File - Created Automatically.\n"; 216 | 217 | map::iterator it; 218 | for (it = this->classes.begin();it != this->classes.end();it++) 219 | { 220 | sclass = it->second; 221 | cfg << "[" << it->first.c_str() << "]\n"; 222 | 223 | map::iterator rec; 224 | for (rec = sclass->entries.begin();rec != sclass->entries.end();rec++) 225 | { 226 | cfg << rec->first.c_str() << "=" << rec->second.c_str() << "\n"; 227 | } 228 | 229 | cfg << "\n"; 230 | } 231 | cfg.close(); 232 | 233 | return 0; 234 | } 235 | 236 | Settings::~Settings() 237 | { 238 | map::iterator it; 239 | for (it = this->classes.begin();it != this->classes.end();it++) 240 | { 241 | SettingClass *sc = it->second; 242 | delete sc; 243 | } 244 | this->classes.clear(); 245 | } 246 | 247 | string Settings::get (const string classN, const string name) 248 | { 249 | SettingClass *c; 250 | 251 | c = this->getClass(classN); 252 | if (c == NULL) 253 | return ""; 254 | return c->get(name); 255 | } 256 | 257 | bool Settings::set (const string classN, const string name, const string value) 258 | { 259 | SettingClass *c; 260 | 261 | if (classN == "" || name == "") 262 | return false; 263 | 264 | c = this->getClass (classN); 265 | 266 | if (c == NULL) 267 | { 268 | c = new SettingClass(classN); 269 | this->classes.insert(pair(classN, c)); 270 | } 271 | 272 | return c->set (name, value); 273 | } 274 | 275 | Settings::SettingClass::SettingClass(const string cn) 276 | { 277 | this->className = cn; 278 | } 279 | 280 | string Settings::SettingClass::get (const string name) 281 | { 282 | if (this->entries.find(name) == this->entries.end()) 283 | return ""; 284 | return this->entries[name]; 285 | } 286 | 287 | map* Settings::SettingClass::getMap() 288 | { 289 | return &this->entries; 290 | } 291 | 292 | bool Settings::SettingClass::set (const string name, const string value) 293 | { 294 | pair::iterator, bool> r; 295 | r = this->entries.insert(pair(name, value)); 296 | if (!r.second) 297 | { 298 | r.first->second = value; 299 | } 300 | 301 | return true; 302 | } 303 | }; 304 | -------------------------------------------------------------------------------- /src/http/webapp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #include "webapp.hpp" 21 | #include "../tools.h" 22 | #include 23 | #include 24 | using namespace std; 25 | 26 | namespace UDPT 27 | { 28 | namespace Server 29 | { 30 | 31 | static uint32_t _getNextIPv4 (string::size_type &i, string &line) 32 | { 33 | string::size_type len = line.length(); 34 | char c; 35 | while (i < len) 36 | { 37 | c = line.at(i); 38 | if (c >= '0' && c <= '9') 39 | break; 40 | i++; 41 | } 42 | 43 | uint32_t ip = 0; 44 | for (int n = 0;n < 4;n++) 45 | { 46 | int cn = 0; 47 | while (i < len) 48 | { 49 | c = line.at (i++); 50 | if (c == '.' || ((c == ' ' || c == ',' || c == ';') && n == 3)) 51 | break; 52 | else if (!(c >= '0' && c <= '9')) 53 | return 0; 54 | cn *= 10; 55 | cn += (c - '0'); 56 | } 57 | ip *= 256; 58 | ip += cn; 59 | } 60 | return ip; 61 | } 62 | 63 | static bool _hex2bin (uint8_t *data, const string str) 64 | { 65 | int len = str.length(); 66 | 67 | if (len % 2 != 0) 68 | return false; 69 | 70 | char a, b; 71 | uint8_t c; 72 | for (int i = 0;i < len;i+=2) 73 | { 74 | a = str.at (i); 75 | b = str.at (i + 1); 76 | c = 0; 77 | 78 | if (a >= 'a' && a <= 'f') 79 | a = (a - 'a') + 10; 80 | else if (a >= '0' && a <= '9') 81 | a = (a - '0'); 82 | else 83 | return false; 84 | 85 | if (b >= 'a' && b <= 'f') 86 | b = (b - 'a') + 10; 87 | else if (b >= '0' && b <= '9') 88 | b = (b - '0'); 89 | else 90 | return false; 91 | 92 | c = (a * 16) + b; 93 | 94 | data [i / 2] = c; 95 | } 96 | 97 | return true; 98 | } 99 | 100 | WebApp::WebApp(HTTPServer *srv, DatabaseDriver *db, Settings *settings) 101 | { 102 | this->instance = srv; 103 | this->db = db; 104 | this->sc_api = settings->getClass("api"); 105 | 106 | Settings::SettingClass *apiKeys = settings->getClass("api.keys"); 107 | if (apiKeys != NULL) 108 | { 109 | map* aK = apiKeys->getMap(); 110 | map::iterator it, end; 111 | end = aK->end(); 112 | for (it = aK->begin();it != end;it++) 113 | { 114 | string key = it->first; 115 | list ips; 116 | 117 | string::size_type strp = 0; 118 | uint32_t ip; 119 | while ((ip = _getNextIPv4(strp, it->second)) != 0) 120 | { 121 | ips.push_back( m_hton32(ip) ); 122 | } 123 | 124 | this->ip_whitelist.insert(pair >(key, ips)); 125 | } 126 | 127 | } 128 | 129 | srv->setData("webapp", this); 130 | } 131 | 132 | WebApp::~WebApp() 133 | { 134 | } 135 | 136 | void WebApp::deploy() 137 | { 138 | list path; 139 | this->instance->addApp(&path, &WebApp::handleRoot); 140 | 141 | path.push_back("api"); 142 | this->instance->addApp(&path, &WebApp::handleAPI); // "/api" 143 | 144 | path.pop_back(); 145 | path.push_back("announce"); 146 | this->instance->addApp(&path, &WebApp::handleAnnounce); 147 | } 148 | 149 | void WebApp::handleRoot (HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) 150 | { 151 | // It would be very appreciated to keep this in the code. 152 | resp->write("" 153 | "Powered by UDPT" 154 | "" 155 | "

The UDPT Project

" 156 | "
This tracker is running on UDPT Software.
" 157 | "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." 158 | "

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

© 2013 Naim A. | Powered by UDPT
" 162 | "" 163 | ""); 164 | } 165 | 166 | bool WebApp::isAllowedIP (WebApp *app, string key, uint32_t ip) 167 | { 168 | std::map >::iterator it, end; 169 | end = app->ip_whitelist.end (); 170 | it = app->ip_whitelist.find (key); 171 | if (it == app->ip_whitelist.end()) 172 | return false; // no such key 173 | 174 | list *lst = &it->second; 175 | list::iterator ipit; 176 | for (ipit = lst->begin();ipit != lst->end();ipit++) 177 | { 178 | if (*ipit == ip) 179 | return true; 180 | } 181 | 182 | return false; 183 | } 184 | 185 | void WebApp::doRemoveTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) 186 | { 187 | string strHash = req->getParam("hash"); 188 | if (strHash.length() != 40) 189 | { 190 | resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); 191 | return; 192 | } 193 | uint8_t hash [20]; 194 | if (!_hex2bin(hash, strHash)) 195 | { 196 | resp->write("{\"error\":\"invalid info_hash.\"}"); 197 | return; 198 | } 199 | 200 | 201 | if (this->db->removeTorrent(hash)) 202 | resp->write("{\"success\":true}"); 203 | else 204 | resp->write("{\"error\":\"failed to remove torrent from DB\"}"); 205 | } 206 | 207 | void WebApp::doAddTorrent (HTTPServer::Request *req, HTTPServer::Response *resp) 208 | { 209 | string strHash = req->getParam("hash"); 210 | if (strHash.length() != 40) 211 | { 212 | resp->write("{\"error\":\"Hash length must be 40 characters.\"}"); 213 | return; 214 | } 215 | uint8_t hash [20]; 216 | if (!_hex2bin(hash, strHash)) 217 | { 218 | resp->write("{\"error\":\"invalid info_hash.\"}"); 219 | return; 220 | } 221 | 222 | if (this->db->addTorrent(hash)) 223 | resp->write("{\"success\":true}"); 224 | else 225 | resp->write("{\"error\":\"failed to add torrent to DB\"}"); 226 | } 227 | 228 | void WebApp::handleAnnounce (HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) 229 | { 230 | resp->write("d14:failure reason42:this is a UDP tracker, not a HTTP tracker.e"); 231 | } 232 | 233 | void WebApp::handleAPI(HTTPServer *srv, HTTPServer::Request *req, HTTPServer::Response *resp) 234 | { 235 | if (req->getAddress()->sin_family != AF_INET) 236 | { 237 | throw ServerException (0, "IPv4 supported Only."); 238 | } 239 | 240 | string key = req->getParam("auth"); 241 | if (key.length() <= 0) 242 | throw ServerException (0, "Bad Authentication Key"); 243 | 244 | WebApp *app = (WebApp*)srv->getData("webapp"); 245 | if (app == NULL) 246 | throw ServerException(0, "WebApp object wasn't found"); 247 | 248 | if (!isAllowedIP(app, key, req->getAddress()->sin_addr.s_addr)) 249 | { 250 | resp->setStatus(403, "Forbidden"); 251 | resp->write("IP not whitelisted. Access Denied."); 252 | return; 253 | } 254 | 255 | string action = req->getParam("action"); 256 | if (action == "add") 257 | app->doAddTorrent(req, resp); 258 | else if (action == "remove") 259 | app->doRemoveTorrent(req, resp); 260 | else 261 | { 262 | resp->write("{\"error\":\"unknown action\"}"); 263 | } 264 | } 265 | }; 266 | }; 267 | -------------------------------------------------------------------------------- /src/db/driver_sqlite.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #include "driver_sqlite.hpp" 21 | #include "../tools.h" 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include // memcpy 28 | #include "../multiplatform.h" 29 | 30 | using namespace std; 31 | 32 | namespace UDPT 33 | { 34 | namespace Data 35 | { 36 | static const char hexadecimal[] = "0123456789abcdef"; 37 | 38 | static char* _to_hex_str (const uint8_t *hash, char *data) 39 | { 40 | int i; 41 | for (i = 0;i < 20;i++) 42 | { 43 | data[i * 2] = hexadecimal[hash[i] / 16]; 44 | data[i * 2 + 1] = hexadecimal[hash[i] % 16]; 45 | } 46 | data[40] = '\0'; 47 | return data; 48 | } 49 | 50 | static uint8_t* _hash_to_bin (const char *hash, uint8_t *data) 51 | { 52 | for (int i = 0;i < 20;i++) 53 | { 54 | data [i] = 0; 55 | char a = hash[i * 2]; 56 | char b = hash[i * 2 + 1]; 57 | 58 | assert ( (a >= 'a' && a <= 'f') || (a >= '0' && a <= '9') ); 59 | assert ( (b >= 'a' && b <= 'f') || (b >= '0' && b <= '9') ); 60 | 61 | data[i] = ( (a >= '0' && a <= 'f') ? (a - '0') : (a - 'f' + 10) ); 62 | data[i] <<= 4; 63 | data[i] = ( (b >= '0' && b <= 'f') ? (b - '0') : (b - 'f' + 10) ); 64 | } 65 | 66 | return data; 67 | } 68 | 69 | SQLite3Driver::SQLite3Driver (Settings::SettingClass *sc, bool isDyn) : DatabaseDriver(sc, isDyn) 70 | { 71 | int r; 72 | bool doSetup; 73 | 74 | fstream fCheck; 75 | string filename = sc->get("file"); 76 | 77 | fCheck.open(filename.c_str(), ios::binary | ios::in); 78 | if (fCheck.is_open()) 79 | { 80 | doSetup = false; 81 | fCheck.close(); 82 | } 83 | else 84 | doSetup = true; 85 | 86 | r = sqlite3_open(filename.c_str(), &this->db); 87 | if (r != SQLITE_OK) 88 | { 89 | sqlite3_close(this->db); 90 | throw DatabaseException (DatabaseException::E_CONNECTION_FAILURE); 91 | } 92 | 93 | if (doSetup) 94 | this->doSetup(); 95 | } 96 | 97 | void SQLite3Driver::doSetup() 98 | { 99 | // cout << "Creating DB..." << endl; 100 | char *eMsg = NULL; 101 | // for quicker stats. 102 | sqlite3_exec(this->db, "CREATE TABLE stats (" 103 | "info_hash blob(20) UNIQUE," 104 | "completed INTEGER DEFAULT 0," 105 | "leechers INTEGER DEFAULT 0," 106 | "seeders INTEGER DEFAULT 0," 107 | "last_mod INTEGER DEFAULT 0" 108 | ")", NULL, NULL, &eMsg); 109 | // cout << "stats: " << (eMsg == NULL ? "OK" : eMsg) << endl; 110 | // for non-Dynamic trackers 111 | sqlite3_exec(this->db, "CREATE TABLE torrents (" 112 | "info_hash blob(20) UNIQUE," 113 | "created INTEGER" 114 | ")", NULL, NULL, &eMsg); 115 | // cout << "torrents: " << (eMsg == NULL ? "OK" : eMsg) << endl; 116 | } 117 | 118 | bool SQLite3Driver::getTorrentInfo(TorrentEntry *e) 119 | { 120 | bool gotInfo = false; 121 | 122 | const char sql[] = "SELECT seeders,leechers,completed FROM 'stats' WHERE info_hash=?"; 123 | sqlite3_stmt *stmt; 124 | 125 | e->seeders = 0; 126 | e->leechers = 0; 127 | e->completed = 0; 128 | 129 | 130 | sqlite3_prepare (this->db, sql, -1, &stmt, NULL); 131 | sqlite3_bind_blob (stmt, 1, (void*)e->info_hash, 20, NULL); 132 | 133 | if (sqlite3_step(stmt) == SQLITE_ROW) 134 | { 135 | e->seeders = sqlite3_column_int (stmt, 0); 136 | e->leechers = sqlite3_column_int (stmt, 1); 137 | e->completed = sqlite3_column_int (stmt, 2); 138 | 139 | gotInfo = true; 140 | } 141 | 142 | sqlite3_finalize (stmt); 143 | 144 | return gotInfo; 145 | } 146 | 147 | bool SQLite3Driver::getPeers (uint8_t info_hash [20], int *max_count, PeerEntry *pe) 148 | { 149 | string sql; 150 | char hash [50]; 151 | sqlite3_stmt *stmt; 152 | int r, i; 153 | 154 | to_hex_str(info_hash, hash); 155 | 156 | sql = "SELECT ip,port FROM 't"; 157 | sql += hash; 158 | sql += "' LIMIT ?"; 159 | 160 | sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL); 161 | sqlite3_bind_int(stmt, 1, *max_count); 162 | 163 | i = 0; 164 | while (*max_count > i) 165 | { 166 | r = sqlite3_step(stmt); 167 | if (r == SQLITE_ROW) 168 | { 169 | const char *ip = (const char*)sqlite3_column_blob (stmt, 0); 170 | const char *port = (const char*)sqlite3_column_blob (stmt, 1); 171 | 172 | memcpy(&pe[i].ip, ip, 4); 173 | memcpy(&pe[i].port, port, 2); 174 | 175 | i++; 176 | } 177 | else 178 | { 179 | break; 180 | } 181 | } 182 | 183 | printf("%d Clients Dumped.\n", i); 184 | 185 | sqlite3_finalize(stmt); 186 | 187 | *max_count = i; 188 | 189 | return true; 190 | } 191 | 192 | 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) 193 | { 194 | char xHash [50]; // we just need 40 + \0 = 41. 195 | sqlite3_stmt *stmt; 196 | string sql; 197 | int r; 198 | 199 | char *hash = xHash; 200 | to_hex_str(info_hash, hash); 201 | 202 | addTorrent (info_hash); 203 | 204 | 205 | sql = "REPLACE INTO 't"; 206 | sql += hash; 207 | sql += "' (peer_id,ip,port,uploaded,downloaded,left,last_seen) VALUES (?,?,?,?,?,?,?)"; 208 | 209 | // printf("IP->%x::%u\n", pE->ip, pE->port); 210 | 211 | sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL); 212 | 213 | sqlite3_bind_blob(stmt, 1, (void*)peer_id, 20, NULL); 214 | sqlite3_bind_blob(stmt, 2, (void*)&ip, 4, NULL); 215 | sqlite3_bind_blob(stmt, 3, (void*)&port, 2, NULL); 216 | sqlite3_bind_blob(stmt, 4, (void*)&uploaded, 8, NULL); 217 | sqlite3_bind_blob(stmt, 5, (void*)&downloaded, 8, NULL); 218 | sqlite3_bind_blob(stmt, 6, (void*)&left, 8, NULL); 219 | sqlite3_bind_int(stmt, 7, time(NULL)); 220 | 221 | r = sqlite3_step(stmt); 222 | sqlite3_finalize(stmt); 223 | 224 | // calculate seeders, leechers 225 | int leechers = 0, seeders = 0; 226 | sql = "SELECT left FROM 't"; 227 | sql += hash; 228 | sql += "'"; 229 | sqlite3_prepare(this->db, sql.c_str(), sql.length(), &stmt, NULL); 230 | while(sqlite3_step(stmt) == SQLITE_ROW){ 231 | int64_t* left = (int64_t*)sqlite3_column_blob(stmt, 0); 232 | if(*left == 0) 233 | seeders += 1; 234 | else 235 | leechers += 1; 236 | } 237 | sqlite3_finalize (stmt); 238 | 239 | cout << "seeders " << seeders << " leechers " << leechers << endl; 240 | 241 | sql = "REPLACE INTO stats (info_hash,last_mod,seeders,leechers) VALUES (?,?,?,?)"; 242 | sqlite3_prepare (this->db, sql.c_str(), sql.length(), &stmt, NULL); 243 | sqlite3_bind_blob (stmt, 1, info_hash, 20, NULL); 244 | sqlite3_bind_int (stmt, 2, time(NULL)); 245 | sqlite3_bind_int (stmt, 3, seeders); 246 | sqlite3_bind_int (stmt, 4, leechers); 247 | sqlite3_step (stmt); 248 | sqlite3_finalize (stmt); 249 | 250 | return r; 251 | } 252 | 253 | bool SQLite3Driver::addTorrent (uint8_t info_hash[20]) 254 | { 255 | char xHash [41]; 256 | char *err_msg; 257 | int r; 258 | 259 | _to_hex_str(info_hash, xHash); 260 | 261 | sqlite3_stmt *stmt; 262 | sqlite3_prepare(this->db, "INSERT INTO torrents (info_hash,created) VALUES (?,?)", -1, &stmt, NULL); 263 | sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); 264 | sqlite3_bind_int(stmt, 2, time(NULL)); 265 | sqlite3_step(stmt); 266 | sqlite3_finalize(stmt); 267 | 268 | string sql = "CREATE TABLE IF NOT EXISTS 't"; 269 | sql += xHash; 270 | sql += "' ("; 271 | sql += "peer_id blob(20)," 272 | "ip blob(4)," 273 | "port blob(2)," 274 | "uploaded blob(8)," // uint64 275 | "downloaded blob(8)," 276 | "left blob(8)," 277 | "last_seen INT DEFAULT 0"; 278 | 279 | sql += ", CONSTRAINT c1 UNIQUE (ip,port) ON CONFLICT REPLACE)"; 280 | 281 | // create table. 282 | r = sqlite3_exec(this->db, sql.c_str(), NULL, NULL, &err_msg); 283 | printf("E:%s\n", err_msg); 284 | 285 | return (r == SQLITE_OK); 286 | } 287 | 288 | bool SQLite3Driver::isTorrentAllowed(uint8_t *info_hash) 289 | { 290 | if (this->isDynamic()) 291 | return true; 292 | sqlite3_stmt *stmt; 293 | sqlite3_prepare(this->db, "SELECT COUNT(*) FROM torrents WHERE info_hash=?", -1, &stmt, NULL); 294 | sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); 295 | sqlite3_step(stmt); 296 | 297 | int n = sqlite3_column_int(stmt, 0); 298 | sqlite3_finalize(stmt); 299 | 300 | return (n == 1); 301 | } 302 | 303 | void SQLite3Driver::cleanup() 304 | { 305 | int exp = time (NULL) - 7200; // 2 hours, expired. 306 | 307 | // drop all peers with no activity for 2 hours. 308 | sqlite3_stmt *getTables; 309 | // torrent table names: t 310 | sqlite3_prepare(this->db, "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 't________________________________________'", -1, &getTables, NULL); 311 | 312 | uint8_t buff [20]; 313 | sqlite3_stmt *updateStats; 314 | assert (sqlite3_prepare(this->db, "REPLACE INTO stats (info_hash,seeders,leechers,last_mod) VALUES (?,?,?,?)", -1, &updateStats, NULL) == SQLITE_OK); 315 | 316 | 317 | while (sqlite3_step(getTables) == SQLITE_ROW) 318 | { 319 | char* tblN = (char*)sqlite3_column_text(getTables, 0); 320 | stringstream sStr; 321 | sStr << "DELETE FROM " << tblN << " WHERE last_seen<" << exp; 322 | 323 | assert (sqlite3_exec(this->db, sStr.str().c_str(), NULL, NULL, NULL) == SQLITE_OK); 324 | 325 | sStr.str (string()); 326 | sStr << "SELECT left,COUNT(*) FROM " << tblN << " GROUP BY left==0"; 327 | 328 | sqlite3_stmt *collectStats; 329 | 330 | sqlite3_prepare(this->db, sStr.str().c_str(), sStr.str().length(), &collectStats, NULL); 331 | cout << "[" << sqlite3_errmsg(this->db) << "]" << endl; 332 | int seeders = 0, leechers = 0; 333 | while (sqlite3_step(collectStats) == SQLITE_ROW) // expecting two results. 334 | { 335 | if (sqlite3_column_int(collectStats, 0) == 0) 336 | seeders = sqlite3_column_int (collectStats, 1); 337 | else 338 | leechers = sqlite3_column_int (collectStats, 1); 339 | } 340 | sqlite3_finalize(collectStats); 341 | 342 | sqlite3_bind_blob(updateStats, 1, _hash_to_bin((const char*)(tblN + 1), buff), 20, NULL); 343 | sqlite3_bind_int(updateStats, 2, seeders); 344 | sqlite3_bind_int(updateStats, 3, leechers); 345 | sqlite3_bind_int(updateStats, 4, time (NULL)); 346 | 347 | sqlite3_step(updateStats); 348 | sqlite3_reset (updateStats); 349 | } 350 | sqlite3_finalize(updateStats); 351 | sqlite3_finalize(getTables); 352 | } 353 | 354 | bool SQLite3Driver::removeTorrent(uint8_t info_hash[20]) 355 | { 356 | // if non-dynamic, remove from table 357 | sqlite3_stmt *stmt; 358 | sqlite3_prepare(this->db, "DELETE FROM torrents WHERE info_hash=?", -1, &stmt, NULL); 359 | sqlite3_bind_blob(stmt, 1, info_hash, 20, NULL); 360 | sqlite3_step(stmt); 361 | sqlite3_finalize(stmt); 362 | 363 | // remove from stats 364 | sqlite3_stmt *rmS; 365 | if (sqlite3_prepare(this->db, "DELETE FROM stats WHERE info_hash=?", -1, &rmS, NULL) != SQLITE_OK) 366 | { 367 | sqlite3_finalize(rmS); 368 | return false; 369 | } 370 | sqlite3_bind_blob(rmS, 1, (const void*)info_hash, 20, NULL); 371 | sqlite3_step(rmS); 372 | sqlite3_finalize(rmS); 373 | 374 | // remove table 375 | string str = "DROP TABLE IF EXISTS 't"; 376 | char buff [41]; 377 | str += _to_hex_str(info_hash, buff); 378 | str += "'"; 379 | 380 | sqlite3_exec(this->db, str.c_str(), NULL, NULL, NULL); 381 | 382 | return true; 383 | } 384 | 385 | bool SQLite3Driver::removePeer(uint8_t peer_id [20], uint8_t info_hash [20], uint32_t ip, uint16_t port) 386 | { 387 | string sql; 388 | char xHash [50]; 389 | sqlite3_stmt *stmt; 390 | 391 | _to_hex_str (info_hash, xHash); 392 | 393 | sql += "DELETE FROM 't"; 394 | sql += xHash; 395 | sql += "' WHERE ip=? AND port=? AND peer_id=?"; 396 | 397 | sqlite3_prepare (this->db, sql.c_str(), sql.length(), &stmt, NULL); 398 | 399 | sqlite3_bind_blob(stmt, 0, (const void*)&ip, 4, NULL); 400 | sqlite3_bind_blob(stmt, 1, (const void*)&port, 2, NULL); 401 | sqlite3_bind_blob(stmt, 2, (const void*)peer_id, 20, NULL); 402 | 403 | sqlite3_step(stmt); 404 | 405 | sqlite3_finalize(stmt); 406 | 407 | return true; 408 | } 409 | 410 | static uint64_t _genCiD (uint32_t ip, uint16_t port) 411 | { 412 | uint64_t x; 413 | x = (time(NULL) / 3600) * port; // x will probably overload. 414 | x = (ip ^ port); 415 | x <<= 16; 416 | x |= (~port); 417 | return x; 418 | } 419 | 420 | bool SQLite3Driver::genConnectionId (uint64_t *connectionId, uint32_t ip, uint16_t port) 421 | { 422 | *connectionId = _genCiD(ip, port); 423 | return true; 424 | } 425 | 426 | bool SQLite3Driver::verifyConnectionId(uint64_t cId, uint32_t ip, uint16_t port) 427 | { 428 | if (cId == _genCiD(ip, port)) 429 | return true; 430 | else 431 | return false; 432 | } 433 | 434 | SQLite3Driver::~SQLite3Driver() 435 | { 436 | sqlite3_close(this->db); 437 | } 438 | }; 439 | }; 440 | -------------------------------------------------------------------------------- /src/http/httpserver.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include "httpserver.hpp" 26 | 27 | using namespace std; 28 | 29 | namespace UDPT 30 | { 31 | namespace Server 32 | { 33 | /* HTTPServer */ 34 | HTTPServer::HTTPServer (uint16_t port, int threads) 35 | { 36 | int r; 37 | SOCKADDR_IN sa; 38 | 39 | this->thread_count = threads; 40 | this->threads = new HANDLE[threads]; 41 | this->isRunning = false; 42 | 43 | this->rootNode.callback = NULL; 44 | 45 | this->srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); 46 | if (this->srv == INVALID_SOCKET) 47 | { 48 | throw ServerException (1, "Failed to create Socket"); 49 | } 50 | 51 | sa.sin_addr.s_addr = 0L; 52 | sa.sin_family = AF_INET; 53 | sa.sin_port = htons (port); 54 | 55 | r = bind (this->srv, (SOCKADDR*)&sa, sizeof(sa)); 56 | if (r == SOCKET_ERROR) 57 | { 58 | throw ServerException (2, "Failed to bind socket"); 59 | } 60 | 61 | this->isRunning = true; 62 | for (int i = 0;i < threads;i++) 63 | { 64 | #ifdef WIN32 65 | this->threads[i] = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, this, 0, NULL); 66 | #else 67 | pthread_create (&this->threads[i], NULL, &HTTPServer::_thread_start, this); 68 | #endif 69 | } 70 | } 71 | 72 | #ifdef WIN32 73 | DWORD HTTPServer::_thread_start (LPVOID arg) 74 | #else 75 | void* HTTPServer::_thread_start (void *arg) 76 | #endif 77 | { 78 | HTTPServer *s = (HTTPServer*)arg; 79 | doSrv: 80 | try { 81 | HTTPServer::handleConnections (s); 82 | } catch (ServerException &se) 83 | { 84 | cerr << "SRV ERR #" << se.getErrorCode() << ": " << se.getErrorMsg () << endl; 85 | goto doSrv; 86 | } 87 | return 0; 88 | } 89 | 90 | void HTTPServer::handleConnections (HTTPServer *server) 91 | { 92 | int r; 93 | #ifdef WIN32 94 | int addrSz; 95 | #else 96 | socklen_t addrSz; 97 | #endif 98 | SOCKADDR_IN addr; 99 | SOCKET cli; 100 | 101 | while (server->isRunning) 102 | { 103 | r = listen (server->srv, 50); 104 | if (r == SOCKET_ERROR) 105 | { 106 | #ifdef WIN32 107 | Sleep (500); 108 | #else 109 | sleep (1); 110 | #endif 111 | continue; 112 | } 113 | addrSz = sizeof addr; 114 | cli = accept (server->srv, (SOCKADDR*)&addr, &addrSz); 115 | if (cli == INVALID_SOCKET) 116 | continue; 117 | 118 | Response resp (cli); // doesn't throw exceptions. 119 | 120 | try { 121 | Request req (cli, &addr); // may throw exceptions. 122 | reqCallback *cb = getRequestHandler (&server->rootNode, req.getPath()); 123 | if (cb == NULL) 124 | { 125 | // error 404 126 | resp.setStatus (404, "Not Found"); 127 | resp.addHeader ("Content-Type", "text/html; charset=US-ASCII"); 128 | stringstream stream; 129 | stream << ""; 130 | stream << "Not Found"; 131 | stream << "

Not Found

The server couldn't find the request resource.


© 2013 Naim A. | The UDPT Project
"; 132 | stream << ""; 133 | string str = stream.str(); 134 | resp.write (str.c_str(), str.length()); 135 | } 136 | else 137 | { 138 | try { 139 | cb (server, &req, &resp); 140 | } catch (...) 141 | { 142 | resp.setStatus(500, "Internal Server Error"); 143 | resp.addHeader ("Content-Type", "text/html; charset=US-ASCII"); 144 | stringstream stream; 145 | stream << ""; 146 | stream << "Internal Server Error"; 147 | stream << "

Internal Server Error

An Error Occurred while trying to process your request.


© 2013 Naim A. | The UDPT Project
"; 148 | stream << ""; 149 | string str = stream.str(); 150 | resp.write (str.c_str(), str.length()); 151 | } 152 | } 153 | resp.finalize(); 154 | } catch (ServerException &e) 155 | { 156 | // Error 400 Bad Request! 157 | } 158 | 159 | closesocket (cli); 160 | } 161 | } 162 | 163 | void HTTPServer::addApp (list *path, reqCallback *cb) 164 | { 165 | list::iterator it = path->begin(); 166 | appNode *node = &this->rootNode; 167 | while (it != path->end()) 168 | { 169 | map::iterator se; 170 | se = node->nodes.find (*it); 171 | if (se == node->nodes.end()) 172 | { 173 | node->nodes[*it].callback = NULL; 174 | } 175 | node = &node->nodes[*it]; 176 | it++; 177 | } 178 | node->callback = cb; 179 | } 180 | 181 | HTTPServer::reqCallback* HTTPServer::getRequestHandler (appNode *node, list *path) 182 | { 183 | appNode *cn = node; 184 | list::iterator it = path->begin(), 185 | end = path->end(); 186 | map::iterator n; 187 | while (true) 188 | { 189 | if (it == end) 190 | { 191 | return cn->callback; 192 | } 193 | 194 | n = cn->nodes.find (*it); 195 | if (n == cn->nodes.end()) 196 | return NULL; // node not found! 197 | cn = &n->second; 198 | 199 | it++; 200 | } 201 | return NULL; 202 | } 203 | 204 | void HTTPServer::setData(string k, void *d) 205 | { 206 | this->customData[k] = d; 207 | } 208 | 209 | void* HTTPServer::getData(string k) 210 | { 211 | map::iterator it = this->customData.find(k); 212 | if (it == this->customData.end()) 213 | return NULL; 214 | return it->second; 215 | } 216 | 217 | HTTPServer::~HTTPServer () 218 | { 219 | if (this->srv != INVALID_SOCKET) 220 | closesocket (this->srv); 221 | 222 | if (this->isRunning) 223 | { 224 | for (int i = 0;i < this->thread_count;i++) 225 | { 226 | #ifdef WIN32 227 | TerminateThread (this->threads[i], 0x00); 228 | #else 229 | pthread_detach (this->threads[i]); 230 | pthread_cancel (this->threads[i]); 231 | #endif 232 | } 233 | } 234 | 235 | delete[] this->threads; 236 | } 237 | 238 | /* HTTPServer::Request */ 239 | HTTPServer::Request::Request (SOCKET cli, const SOCKADDR_IN *addr) 240 | { 241 | this->conn = cli; 242 | this->addr = addr; 243 | 244 | this->parseRequest (); 245 | } 246 | 247 | inline static char* nextReqLine (int &cPos, char *buff, int len) 248 | { 249 | for (int i = cPos;i < len - 1;i++) 250 | { 251 | if (buff[i] == '\r' && buff[i + 1] == '\n') 252 | { 253 | buff[i] = '\0'; 254 | 255 | int r = cPos; 256 | cPos = i + 2; 257 | return (buff + r); 258 | } 259 | } 260 | 261 | return (buff + len); // end 262 | } 263 | 264 | inline void parseURL (string request, list *path, map *params) 265 | { 266 | string::size_type p; 267 | string query, url; 268 | p = request.find ('?'); 269 | if (p == string::npos) 270 | { 271 | p = request.length(); 272 | } 273 | else 274 | { 275 | query = request.substr (p + 1); 276 | } 277 | url = request.substr (0, p); 278 | 279 | path->clear (); 280 | string::size_type s, e; 281 | s = 0; 282 | while (true) 283 | { 284 | e = url.find ('/', s); 285 | if (e == string::npos) 286 | e = url.length(); 287 | 288 | string x = url.substr (s, e - s); 289 | if (!(x.length() == 0 || x == ".")) 290 | { 291 | if (x == "..") 292 | { 293 | if (path->empty()) 294 | throw ServerException (1, "Hack attempt"); 295 | else 296 | path->pop_back (); 297 | } 298 | path->push_back (x); 299 | } 300 | 301 | if (e == url.length()) 302 | break; 303 | s = e + 1; 304 | } 305 | 306 | string::size_type vS, vE, kS, kE; 307 | vS = vE = kS = kE = 0; 308 | while (kS < query.length()) 309 | { 310 | kE = query.find ('=', kS); 311 | if (kE == string::npos) break; 312 | vS = kE + 1; 313 | vE = query.find ('&', vS); 314 | if (vE == string::npos) vE = query.length(); 315 | 316 | params->insert (pair( query.substr (kS, kE - kS), query.substr (vS, vE - vS) )); 317 | 318 | kS = vE + 1; 319 | } 320 | } 321 | 322 | inline void setCookies (string &data, map *cookies) 323 | { 324 | string::size_type kS, kE, vS, vE; 325 | kS = 0; 326 | while (kS < data.length ()) 327 | { 328 | kE = data.find ('=', kS); 329 | if (kE == string::npos) 330 | break; 331 | vS = kE + 1; 332 | vE = data.find ("; ", vS); 333 | if (vE == string::npos) 334 | vE = data.length(); 335 | 336 | (*cookies) [data.substr (kS, kE-kS)] = data.substr (vS, vE-vS); 337 | 338 | kS = vE + 2; 339 | } 340 | } 341 | 342 | void HTTPServer::Request::parseRequest () 343 | { 344 | char buffer [REQUEST_BUFFER_SIZE]; 345 | int r; 346 | r = recv (this->conn, buffer, REQUEST_BUFFER_SIZE, 0); 347 | if (r == REQUEST_BUFFER_SIZE) 348 | throw ServerException (1, "Request Size too big."); 349 | if (r <= 0) 350 | throw ServerException (2, "Socket Error"); 351 | 352 | char *cLine; 353 | int n = 0; 354 | int pos = 0; 355 | string::size_type p; 356 | while ( (cLine = nextReqLine (pos, buffer, r)) < (buffer + r)) 357 | { 358 | string line = string (cLine); 359 | if (line.length() == 0) break; // CRLF CRLF = end of headers. 360 | n++; 361 | 362 | if (n == 1) 363 | { 364 | string::size_type uS, uE; 365 | p = line.find (' '); 366 | if (p == string::npos) 367 | throw ServerException (5, "Malformed request method"); 368 | uS = p + 1; 369 | this->requestMethod.str = line.substr (0, p); 370 | 371 | if (this->requestMethod.str == "GET") 372 | this->requestMethod.rm = RM_GET; 373 | else if (this->requestMethod.str == "POST") 374 | this->requestMethod.rm = RM_POST; 375 | else 376 | this->requestMethod.rm = RM_UNKNOWN; 377 | 378 | uE = uS; 379 | while (p < line.length()) 380 | { 381 | if (p == string::npos) 382 | break; 383 | p = line.find (' ', p + 1); 384 | if (p == string::npos) 385 | break; 386 | uE = p; 387 | } 388 | if (uE + 1 >= line.length()) 389 | throw ServerException (6, "Malformed request"); 390 | string httpVersion = line.substr (uE + 1); 391 | 392 | 393 | parseURL (line.substr (uS, uE - uS), &this->path, &this->params); 394 | } 395 | else 396 | { 397 | p = line.find (": "); 398 | if (p == string::npos) 399 | throw ServerException (4, "Malformed headers"); 400 | string key = line.substr (0, p); 401 | string value = line.substr (p + 2); 402 | if (key != "Cookie") 403 | this->headers.insert(pair( key, value)); 404 | else 405 | setCookies (value, &this->cookies); 406 | } 407 | } 408 | if (n == 0) 409 | throw ServerException (3, "No Request header."); 410 | } 411 | 412 | list* HTTPServer::Request::getPath () 413 | { 414 | return &this->path; 415 | } 416 | 417 | string HTTPServer::Request::getParam (const string key) 418 | { 419 | map::iterator it = this->params.find (key); 420 | if (it == this->params.end()) 421 | return ""; 422 | else 423 | return it->second; 424 | } 425 | 426 | multimap::iterator HTTPServer::Request::getHeader (const string name) 427 | { 428 | multimap::iterator it = this->headers.find (name); 429 | return it; 430 | } 431 | 432 | HTTPServer::Request::RequestMethod HTTPServer::Request::getRequestMethod () 433 | { 434 | return this->requestMethod.rm; 435 | } 436 | 437 | string HTTPServer::Request::getRequestMethodStr () 438 | { 439 | return this->requestMethod.str; 440 | } 441 | 442 | string HTTPServer::Request::getCookie (const string name) 443 | { 444 | map::iterator it = this->cookies.find (name); 445 | if (it == this->cookies.end()) 446 | return ""; 447 | else 448 | return it->second; 449 | } 450 | 451 | const SOCKADDR_IN* HTTPServer::Request::getAddress () 452 | { 453 | return this->addr; 454 | } 455 | 456 | /* HTTPServer::Response */ 457 | HTTPServer::Response::Response (SOCKET cli) 458 | { 459 | this->conn = cli; 460 | 461 | setStatus (200, "OK"); 462 | } 463 | 464 | void HTTPServer::Response::setStatus (int c, const string m) 465 | { 466 | this->status_code = c; 467 | this->status_msg = m; 468 | } 469 | 470 | void HTTPServer::Response::addHeader (string key, string value) 471 | { 472 | this->headers.insert (pair(key, value)); 473 | } 474 | 475 | void HTTPServer::Response::write (const char *data, int len) 476 | { 477 | if (len < 0) 478 | len = strlen (data); 479 | msg.write(data, len); 480 | } 481 | 482 | void HTTPServer::Response::finalize () 483 | { 484 | stringstream x; 485 | x << "HTTP/1.1 " << this->status_code << " " << this->status_msg << "\r\n"; 486 | multimap::iterator it, end; 487 | end = this->headers.end(); 488 | for (it = this->headers.begin(); it != end;it++) 489 | { 490 | x << it->first << ": " << it->second << "\r\n"; 491 | } 492 | x << "Connection: Close\r\n"; 493 | x << "Content-Length: " << this->msg.tellp() << "\r\n"; 494 | x << "Server: udpt\r\n"; 495 | x << "\r\n"; 496 | x << this->msg.str(); 497 | 498 | // write to socket 499 | send (this->conn, x.str().c_str(), x.str().length(), 0); 500 | } 501 | 502 | }; 503 | }; 504 | -------------------------------------------------------------------------------- /src/udpTracker.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2012,2013 Naim A. 3 | * 4 | * This file is part of UDPT. 5 | * 6 | * UDPT is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * UDPT is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with UDPT. If not, see . 18 | */ 19 | 20 | #include "udpTracker.hpp" 21 | #include "tools.h" 22 | #include // atoi 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "multiplatform.h" 28 | 29 | using namespace std; 30 | using namespace UDPT::Data; 31 | 32 | #define UDP_BUFFER_SIZE 2048 33 | 34 | namespace UDPT 35 | { 36 | inline static int _isTrue (string str) 37 | { 38 | int i, // loop index 39 | len; // string's length 40 | 41 | if (str == "") 42 | return -1; 43 | len = str.length(); 44 | for (i = 0;i < len;i++) 45 | { 46 | if (str[i] >= 'A' && str[i] <= 'Z') 47 | { 48 | str[i] = (str[i] - 'A' + 'a'); 49 | } 50 | } 51 | if (str.compare ("yes") == 0) 52 | return 1; 53 | if (str.compare ("no") == 0) 54 | return 0; 55 | if (str.compare("true") == 0) 56 | return 1; 57 | if (str.compare ("false") == 0) 58 | return 0; 59 | if (str.compare("1") == 0) 60 | return 1; 61 | if (str.compare ("0") == 0) 62 | return 0; 63 | return -1; 64 | } 65 | 66 | UDPTracker::UDPTracker (Settings *settings) 67 | { 68 | Settings::SettingClass *sc_tracker; 69 | uint8_t n_settings = 0; 70 | string s_port, // port 71 | s_threads, // threads 72 | s_allow_remotes, // remotes allowed? 73 | s_allow_iana_ip, // IANA IPs allowed? 74 | s_int_announce, // announce interval 75 | s_int_cleanup, // cleanup interval 76 | s_is_dynamic, 77 | s_local_subnet, 78 | s_remote_ip; 79 | 80 | sc_tracker = settings->getClass("tracker"); 81 | 82 | s_port = sc_tracker->get ("port"); 83 | s_threads = sc_tracker->get ("threads"); 84 | s_allow_remotes = sc_tracker->get ("allow_remotes"); 85 | s_allow_iana_ip = sc_tracker->get ("allow_iana_ips"); 86 | s_int_announce = sc_tracker->get ("announce_interval"); 87 | s_int_cleanup = sc_tracker-> get ("cleanup_interval"); 88 | s_is_dynamic = sc_tracker->get("is_dynamic"); 89 | s_local_subnet = sc_tracker->get("local_subnet"); 90 | s_remote_ip = sc_tracker->get("remote_ip"); 91 | 92 | if (_isTrue(s_allow_remotes) == 1) 93 | n_settings |= UDPT_ALLOW_REMOTE_IP; 94 | 95 | if (_isTrue(s_allow_iana_ip) != 0) 96 | n_settings |= UDPT_ALLOW_IANA_IP; 97 | 98 | if (_isTrue(s_is_dynamic) == 1) 99 | this->isDynamic = true; 100 | else 101 | this->isDynamic = false; 102 | 103 | this->announce_interval = (s_int_announce == "" ? 1800 : atoi (s_int_announce.c_str())); 104 | this->cleanup_interval = (s_int_cleanup == "" ? 120 : atoi (s_int_cleanup.c_str())); 105 | this->port = (s_port == "" ? 6969 : atoi (s_port.c_str())); 106 | this->thread_count = (s_threads == "" ? 5 : atoi (s_threads.c_str())) + 1; 107 | this->local_subnet = s_local_subnet; 108 | this->remote_ip = s_remote_ip; 109 | 110 | this->threads = new HANDLE[this->thread_count]; 111 | 112 | this->isRunning = false; 113 | this->conn = NULL; 114 | this->settings = n_settings; 115 | this->o_settings = settings; 116 | } 117 | 118 | UDPTracker::~UDPTracker () 119 | { 120 | int i; // loop index 121 | 122 | this->isRunning = false; 123 | 124 | // drop listener connection to continue thread loops. 125 | // wait for request to finish (1 second max; allot of time for a computer!). 126 | 127 | #ifdef linux 128 | close (this->sock); 129 | 130 | sleep (1); 131 | #elif defined (WIN32) 132 | closesocket (this->sock); 133 | 134 | Sleep (1000); 135 | #endif 136 | 137 | for (i = 0;i < this->thread_count;i++) 138 | { 139 | #ifdef WIN32 140 | TerminateThread (this->threads[i], 0x00); 141 | #elif defined (linux) 142 | pthread_detach (this->threads[i]); 143 | pthread_cancel (this->threads[i]); 144 | #endif 145 | cout << "Thread (" << ( i + 1) << "/" << ((int)this->thread_count) << ") terminated." << endl; 146 | } 147 | if (this->conn != NULL) 148 | delete this->conn; 149 | delete[] this->threads; 150 | } 151 | 152 | enum UDPTracker::StartStatus UDPTracker::start () 153 | { 154 | SOCKET sock; 155 | SOCKADDR_IN recvAddr; 156 | int r, // saves results 157 | i, // loop index 158 | yup; // just to set TRUE 159 | string dbname;// saves the Database name. 160 | 161 | sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); 162 | if (sock == INVALID_SOCKET) 163 | return START_ESOCKET_FAILED; 164 | 165 | recvAddr.sin_addr.s_addr = 0L; 166 | recvAddr.sin_family = AF_INET; 167 | recvAddr.sin_port = m_hton16 (this->port); 168 | 169 | yup = 1; 170 | setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yup, 1); 171 | 172 | r = bind (sock, (SOCKADDR*)&recvAddr, sizeof(SOCKADDR_IN)); 173 | 174 | if (r == SOCKET_ERROR) 175 | { 176 | #ifdef WIN32 177 | closesocket (sock); 178 | #elif defined (linux) 179 | close (sock); 180 | #endif 181 | return START_EBIND_FAILED; 182 | } 183 | 184 | this->sock = sock; 185 | 186 | this->conn = new Data::SQLite3Driver (this->o_settings->getClass("database"), 187 | this->isDynamic); 188 | 189 | this->isRunning = true; 190 | cout << "Starting maintenance thread (1/" << ((int)this->thread_count) << ")" << endl; 191 | 192 | // create maintainer thread. 193 | #ifdef WIN32 194 | this->threads[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_maintainance_start, (LPVOID)this, 0, NULL); 195 | #elif defined (linux) 196 | pthread_create (&this->threads[0], NULL, _maintainance_start, (void*)this); 197 | #endif 198 | 199 | for (i = 1;i < this->thread_count; i++) 200 | { 201 | cout << "Starting thread (" << (i + 1) << "/" << ((int)this->thread_count) << ")" << endl; 202 | #ifdef WIN32 203 | this->threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_thread_start, (LPVOID)this, 0, NULL); 204 | #elif defined (linux) 205 | pthread_create (&(this->threads[i]), NULL, _thread_start, (void*)this); 206 | #endif 207 | } 208 | 209 | return START_OK; 210 | } 211 | 212 | int UDPTracker::sendError (UDPTracker *usi, SOCKADDR_IN *remote, uint32_t transactionID, const string &msg) 213 | { 214 | struct udp_error_response error; 215 | int msg_sz, // message size to send. 216 | i; // copy loop 217 | char buff [1024]; // more than reasonable message size... 218 | 219 | error.action = m_hton32 (3); 220 | error.transaction_id = transactionID; 221 | error.message = (char*)msg.c_str(); 222 | 223 | msg_sz = 4 + 4 + 1 + msg.length(); 224 | 225 | memcpy(buff, &error, 8); 226 | for (i = 8;i <= msg_sz;i++) 227 | { 228 | buff[i] = msg[i - 8]; 229 | } 230 | 231 | sendto(usi->sock, buff, msg_sz, 0, (SOCKADDR*)remote, sizeof(*remote)); 232 | 233 | return 0; 234 | } 235 | 236 | int UDPTracker::handleConnection (UDPTracker *usi, SOCKADDR_IN *remote, char *data) 237 | { 238 | ConnectionRequest *req; 239 | ConnectionResponse resp; 240 | 241 | req = (ConnectionRequest*)data; 242 | 243 | resp.action = m_hton32(0); 244 | resp.transaction_id = req->transaction_id; 245 | 246 | if (!usi->conn->genConnectionId(&resp.connection_id, 247 | m_hton32(remote->sin_addr.s_addr), 248 | m_hton16(remote->sin_port))) 249 | { 250 | return 1; 251 | } 252 | 253 | sendto(usi->sock, (char*)&resp, sizeof(ConnectionResponse), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); 254 | 255 | return 0; 256 | } 257 | 258 | static inline string _ip_to_str (uint32_t ip) 259 | { 260 | char buf[50]; 261 | sprintf(buf, "%d.%d.%d.%d", ip >> 24, ((ip >> 16) & 0xff) , ((ip >> 8) & 0xff) , (ip & 0xff)); 262 | return buf; 263 | } 264 | 265 | static inline uint32_t _str_to_ip (string ip){ 266 | int ipbytes[4]; 267 | sscanf(ip.c_str(), "%d.%d.%d.%d", &ipbytes[3], &ipbytes[2], &ipbytes[1], &ipbytes[0]); 268 | return ipbytes[0] | ipbytes[1] << 8 | ipbytes[2] << 16 | ipbytes[3] << 24; 269 | } 270 | 271 | int UDPTracker::handleAnnounce (UDPTracker *usi, SOCKADDR_IN *remote, char *data) 272 | { 273 | AnnounceRequest *req; 274 | AnnounceResponse *resp; 275 | int q, // peer counts 276 | bSize, // message size 277 | i; // loop index 278 | DatabaseDriver::PeerEntry *peers; 279 | DatabaseDriver::TorrentEntry tE; 280 | 281 | uint8_t buff [1028]; // Reasonable buffer size. (header+168 peers) 282 | 283 | req = (AnnounceRequest*)data; 284 | 285 | if (!usi->conn->verifyConnectionId(req->connection_id, 286 | m_hton32(remote->sin_addr.s_addr), 287 | m_hton16(remote->sin_port))) 288 | { 289 | return 1; 290 | } 291 | 292 | // change byte order: 293 | req->port = m_hton16 (req->port); 294 | req->ip_address = m_hton32 (req->ip_address); 295 | req->downloaded = m_hton64 (req->downloaded); 296 | req->event = m_hton32 (req->event); // doesn't really matter for this tracker 297 | req->uploaded = m_hton64 (req->uploaded); 298 | req->num_want = m_hton32 (req->num_want); 299 | req->left = m_hton64 (req->left); 300 | 301 | if ((usi->settings & UDPT_ALLOW_REMOTE_IP) == 0 && req->ip_address != 0) 302 | { 303 | UDPTracker::sendError (usi, remote, req->transaction_id, "Tracker doesn't allow remote IP's; Request ignored."); 304 | return 0; 305 | } 306 | 307 | if (!usi->conn->isTorrentAllowed(req->info_hash)) 308 | { 309 | UDPTracker::sendError(usi, remote, req->transaction_id, "info_hash not registered."); 310 | return 0; 311 | } 312 | 313 | // load peers 314 | q = 30; 315 | if (req->num_want >= 1) 316 | q = min (q, req->num_want); 317 | 318 | peers = new DatabaseDriver::PeerEntry [q]; 319 | 320 | 321 | DatabaseDriver::TrackerEvents event; 322 | switch (req->event) 323 | { 324 | case 1: 325 | event = DatabaseDriver::EVENT_COMPLETE; 326 | break; 327 | case 2: 328 | event = DatabaseDriver::EVENT_START; 329 | break; 330 | case 3: 331 | event = DatabaseDriver::EVENT_STOP; 332 | break; 333 | default: 334 | event = DatabaseDriver::EVENT_UNSPEC; 335 | break; 336 | } 337 | 338 | cout << event << endl; 339 | 340 | if (event == DatabaseDriver::EVENT_STOP) 341 | q = 0; // no need for peers when stopping. 342 | 343 | if (q > 0) 344 | usi->conn->getPeers(req->info_hash, &q, peers); 345 | 346 | bSize = 20; // header is 20 bytes 347 | bSize += (6 * q); // + 6 bytes per peer. 348 | 349 | tE.info_hash = req->info_hash; 350 | if(!usi->conn->getTorrentInfo(&tE)){ 351 | cout << "couldn't get torrent info" << endl; 352 | } 353 | 354 | char xHash [50]; 355 | to_hex_str (req->info_hash, xHash); 356 | 357 | resp = (AnnounceResponse*)buff; 358 | resp->action = m_hton32(1); 359 | resp->interval = m_hton32 ( usi->announce_interval ); 360 | resp->leechers = m_hton32(tE.leechers); 361 | resp->seeders = m_hton32 (tE.seeders); 362 | resp->transaction_id = req->transaction_id; 363 | 364 | uint32_t ip; 365 | if (req->ip_address == 0) // default 366 | ip = m_hton32 (remote->sin_addr.s_addr); 367 | else 368 | ip = req->ip_address; 369 | 370 | uint32_t remoteIp = _str_to_ip(usi->remote_ip); 371 | string clientIp = _ip_to_str(ip); 372 | bool clientIpLocal = clientIp.find(usi->local_subnet,0) == 0; 373 | cout << "Announce on: " << xHash << " from: " << clientIp << endl; 374 | cout << "Total Peers: " << q << endl; 375 | 376 | for (i = 0;i < q;i++) 377 | { 378 | uint32_t peerIpInt; 379 | string peerIp = _ip_to_str(peers[i].ip); 380 | bool peerLocal = peerIp.find(usi->local_subnet,0) == 0; 381 | if(clientIpLocal){ 382 | peerIpInt = peers[i].ip; 383 | peerIp = _ip_to_str(peerIpInt); 384 | cout << "Peer: " << peerIp << ":" << peers[i].port << endl; 385 | }else if(peerLocal){ 386 | peerIpInt = remoteIp; 387 | peerIp = usi->remote_ip; 388 | cout << "Peer: " << peerIp << ":" << peers[i].port << " (changed)" << endl; 389 | }else{ 390 | peerIpInt = peers[i].ip; 391 | peerIp = _ip_to_str(peerIpInt); 392 | cout << "Peer: " << peerIp << ":" << peers[i].port << endl; 393 | } 394 | 395 | int x = i * 6; 396 | // network byte order!!! 397 | 398 | // IP 399 | buff[20 + x] = ((peerIpInt & (0xff << 24)) >> 24); 400 | buff[21 + x] = ((peerIpInt & (0xff << 16)) >> 16); 401 | buff[22 + x] = ((peerIpInt & (0xff << 8)) >> 8); 402 | buff[23 + x] = (peerIpInt & 0xff); 403 | 404 | // port 405 | buff[24 + x] = ((peers[i].port & (0xff << 8)) >> 8); 406 | buff[25 + x] = (peers[i].port & 0xff); 407 | 408 | } 409 | delete[] peers; 410 | sendto(usi->sock, (char*)buff, bSize, 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); 411 | 412 | // update DB. 413 | usi->conn->updatePeer(req->peer_id, req->info_hash, ip, req->port, 414 | req->downloaded, req->left, req->uploaded, event); 415 | 416 | return 0; 417 | } 418 | 419 | int UDPTracker::handleScrape (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int len) 420 | { 421 | cout << "Handling scrape: " << endl; 422 | ScrapeRequest *sR; 423 | int v, // validation helper 424 | c, // torrent counter 425 | i, // loop counter 426 | j; // loop counter 427 | uint8_t hash [20]; 428 | char xHash [50]; 429 | ScrapeResponse *resp; 430 | uint8_t buffer [1024]; // up to 74 torrents can be scraped at once (17*74+8) < 1024 431 | 432 | 433 | sR = (ScrapeRequest*)data; 434 | 435 | // validate request length: 436 | v = len - 16; 437 | if (v < 0 || v % 20 != 0) 438 | { 439 | UDPTracker::sendError (usi, remote, sR->transaction_id, "Bad scrape request."); 440 | return 0; 441 | } 442 | 443 | if (!usi->conn->verifyConnectionId(sR->connection_id, 444 | m_hton32(remote->sin_addr.s_addr), 445 | m_hton16(remote->sin_port))) 446 | { 447 | cout << "scrape connection not verified" << endl; 448 | return 1; 449 | } 450 | 451 | // get torrent count. 452 | c = v / 20; 453 | 454 | resp = (ScrapeResponse*)buffer; 455 | resp->action = m_hton32 (2); 456 | resp->transaction_id = sR->transaction_id; 457 | 458 | for (i = 0;i < c;i++) 459 | { 460 | int32_t *seeders, 461 | *completed, 462 | *leechers; 463 | 464 | for (j = 0; j < 20;j++) 465 | hash[j] = data[j + (i*20)+16]; 466 | 467 | to_hex_str (hash, xHash); 468 | 469 | seeders = (int32_t*)&buffer[i*12+8]; 470 | completed = (int32_t*)&buffer[i*12+12]; 471 | leechers = (int32_t*)&buffer[i*12+16]; 472 | 473 | DatabaseDriver::TorrentEntry tE; 474 | tE.info_hash = hash; 475 | 476 | if(!usi->conn->getTorrentInfo(&tE)) 477 | { 478 | cout << "error getting torrent info: " << xHash << endl; 479 | sendError(usi, remote, sR->transaction_id, "Scrape Failed: couldn't retrieve torrent data"); 480 | return 0; 481 | } 482 | 483 | *seeders = m_hton32 (tE.seeders); 484 | *completed = m_hton32 (tE.completed); 485 | *leechers = m_hton32 (tE.leechers); 486 | 487 | cout << "\t" << xHash << " Seeders: " << *seeders << " Completed: " << *completed << " Leechers: " << *leechers << endl; 488 | } 489 | cout.flush(); 490 | 491 | sendto (usi->sock, (const char*)buffer, sizeof(buffer), 0, (SOCKADDR*)remote, sizeof(SOCKADDR_IN)); 492 | 493 | return 0; 494 | } 495 | 496 | static int _isIANA_IP (uint32_t ip) 497 | { 498 | uint8_t x = (ip % 256); 499 | if (x == 0 || x == 10 || x == 127 || x >= 224) 500 | return 1; 501 | return 0; 502 | } 503 | 504 | 505 | int UDPTracker::resolveRequest (UDPTracker *usi, SOCKADDR_IN *remote, char *data, int r) 506 | { 507 | ConnectionRequest *cR; 508 | uint32_t action; 509 | 510 | cout << "Handling request" << endl; 511 | 512 | cR = (ConnectionRequest*)data; 513 | 514 | action = m_hton32(cR->action); 515 | 516 | if ((usi->settings & UDPT_ALLOW_IANA_IP) == 0) 517 | { 518 | if (_isIANA_IP (remote->sin_addr.s_addr)) 519 | { 520 | return 0; // Access Denied: IANA reserved IP. 521 | } 522 | } 523 | 524 | cout << ":: " << (void*)m_hton32(remote->sin_addr.s_addr) << ": " << m_hton16(remote->sin_port) << " ACTION=" << action << endl; 525 | 526 | if (action == 0 && r >= 16) 527 | return UDPTracker::handleConnection (usi, remote, data); 528 | else if (action == 1 && r >= 98) 529 | return UDPTracker::handleAnnounce (usi, remote, data); 530 | else if (action == 2) 531 | return UDPTracker::handleScrape (usi, remote, data, r); 532 | else 533 | { 534 | // cout << "E: action=" << action << ", r=" << r << endl; 535 | UDPTracker::sendError (usi, remote, cR->transaction_id, "Tracker couldn't understand Client's request."); 536 | return -1; 537 | } 538 | 539 | return 0; 540 | } 541 | 542 | #ifdef WIN32 543 | DWORD UDPTracker::_thread_start (LPVOID arg) 544 | #elif defined (linux) 545 | void* UDPTracker::_thread_start (void *arg) 546 | #endif 547 | { 548 | UDPTracker *usi; 549 | SOCKADDR_IN remoteAddr; 550 | 551 | #ifdef linux 552 | socklen_t addrSz; 553 | #else 554 | int addrSz; 555 | #endif 556 | 557 | int r; 558 | char tmpBuff [UDP_BUFFER_SIZE]; 559 | 560 | usi = (UDPTracker*)arg; 561 | 562 | addrSz = sizeof (SOCKADDR_IN); 563 | 564 | 565 | while (usi->isRunning) 566 | { 567 | cout.flush(); 568 | // peek into the first 12 bytes of data; determine if connection request or announce request. 569 | r = recvfrom(usi->sock, (char*)tmpBuff, UDP_BUFFER_SIZE, 0, (SOCKADDR*)&remoteAddr, &addrSz); 570 | if (r <= 0) 571 | continue; // bad request... 572 | r = UDPTracker::resolveRequest (usi, &remoteAddr, tmpBuff, r); 573 | } 574 | 575 | #ifdef linux 576 | pthread_exit (NULL); 577 | #endif 578 | return 0; 579 | } 580 | 581 | #ifdef WIN32 582 | DWORD UDPTracker::_maintainance_start (LPVOID arg) 583 | #elif defined (linux) 584 | void* UDPTracker::_maintainance_start (void *arg) 585 | #endif 586 | { 587 | UDPTracker *usi; 588 | 589 | usi = (UDPTracker *)arg; 590 | 591 | while (usi->isRunning) 592 | { 593 | usi->conn->cleanup(); 594 | 595 | #ifdef WIN32 596 | Sleep (usi->cleanup_interval * 1000); 597 | #elif defined (linux) 598 | sleep (usi->cleanup_interval); 599 | #else 600 | #error Unsupported OS. 601 | #endif 602 | } 603 | 604 | return 0; 605 | } 606 | 607 | }; 608 | -------------------------------------------------------------------------------- /gpl.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------