Split libretroshare BitDHT and OpenPGP-SDK into submodules

This commit is contained in:
Gioacchino Mazzurco 2022-01-10 21:37:03 +01:00
parent b847caa11b
commit 48fcf70578
No known key found for this signature in database
GPG Key ID: A1FBCA3872E87051
1021 changed files with 15 additions and 306630 deletions

12
.gitmodules vendored
View File

@ -20,3 +20,15 @@
[submodule "supportlibs/jni.hpp"]
path = supportlibs/jni.hpp
url = https://github.com/RetroShare/jni.hpp.git
[submodule "openpgpsdk"]
path = openpgpsdk
url = ../OpenPGP-SDK
branch = master
[submodule "libbitdht"]
path = libbitdht
url = ../BitDHT
branch = master
[submodule "libretroshare"]
path = libretroshare
url = ../libretroshare
branch = master

1
libbitdht Submodule

@ -0,0 +1 @@
Subproject commit b7307cd0bfc2d197bd09f9cec0058bbbb4e235dc

View File

@ -1,19 +0,0 @@
# RetroShare decentralized communication platform
#
# Copyright (C) 2021 Gioacchino Mazzurco <gio@eigenlab.org>
# Copyright (C) 2021 Asociación Civil Altermundi <info@altermundi.net>
#
# SPDX-License-Identifier: CC0-1.0
cmake_minimum_required (VERSION 2.8.12)
project(bitdht)
file(
GLOB BITDHT_SOURCES
src/bitdht/*.c src/bitdht/*.cc src/udp/*.cc src/util/*.cc )
add_library(${PROJECT_NAME} ${BITDHT_SOURCES})
target_include_directories(
${PROJECT_NAME}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src )

View File

@ -1,25 +0,0 @@
# SPDX-FileCopyrightText: (C) 2004-2019 Retroshare Team <contact@retroshare.cc>
# SPDX-License-Identifier: CC0-1.0
What's in the Package
---------------------------------------------------------------
bitdht - base BitDHT Code.
util - generic utils for networking and threading.
udp - UDP interfacing code.
lib - Where the library is created.
tests - basic unit tests.
example - example code of how to use libbitdht.
libbitdht.pro - build script for Qt's qmake.
README.txt - this file.
HOWTO libbitdht.
----------------------------------------------
This version is build using Qt's qmake system.
1) Install Qt's qmake system: libqt-dev
2) type ./qmake
3) type ./make
4) check out the example and tests to learn how to interface with libbitdht.

View File

@ -1,133 +0,0 @@
/*******************************************************************************
* bitdht/bdaccount.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bitdht/bdaccount.h"
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#define LPF_FACTOR (0.90)
bdAccount::bdAccount()
:mNoStats(BDACCOUNT_NUM_ENTRIES),
mCountersOut(BDACCOUNT_NUM_ENTRIES), mCountersRecv(BDACCOUNT_NUM_ENTRIES),
mLpfOut(BDACCOUNT_NUM_ENTRIES), mLpfRecv(BDACCOUNT_NUM_ENTRIES),
mLabel(BDACCOUNT_NUM_ENTRIES)
{
mLabel[BDACCOUNT_MSG_OUTOFDATEPING] = "OUTOFDATEPING ";
mLabel[BDACCOUNT_MSG_PING] = "PING ";
mLabel[BDACCOUNT_MSG_PONG] = "PONG ";
mLabel[BDACCOUNT_MSG_QUERYNODE] = "QUERYNODE ";
mLabel[BDACCOUNT_MSG_QUERYHASH] = "QUERYHASH ";
mLabel[BDACCOUNT_MSG_REPLYFINDNODE] = "REPLYFINDNODE ";
mLabel[BDACCOUNT_MSG_REPLYQUERYHASH] = "REPLYQUERYHASH ";
mLabel[BDACCOUNT_MSG_POSTHASH] = "POSTHASH ";
mLabel[BDACCOUNT_MSG_REPLYPOSTHASH] = "REPLYPOSTHASH ";
mLabel[BDACCOUNT_MSG_CONNECTREQUEST] = "CONNECTREQUEST ";
mLabel[BDACCOUNT_MSG_CONNECTREPLY] = "CONNECTREPLY ";
mLabel[BDACCOUNT_MSG_CONNECTSTART] = "CONNECTSTART ";
mLabel[BDACCOUNT_MSG_CONNECTACK] = "CONNECTACK ";
resetStats();
}
void bdAccount::incCounter(uint32_t idx, bool out)
{
if ((signed) idx > mNoStats-1)
{
std::cerr << "bdAccount::incCounter() Invalid Index";
std::cerr << std::endl;
}
if (out)
{
mCountersOut[idx]++;
}
else
{
mCountersRecv[idx]++;
}
return;
}
void bdAccount::doStats()
{
int i;
for(i = 0; i < mNoStats; i++)
{
mLpfOut[i] *= (LPF_FACTOR) ;
mLpfOut[i] += (1.0 - LPF_FACTOR) * mCountersOut[i];
mLpfRecv[i] *= (LPF_FACTOR) ;
mLpfRecv[i] += (1.0 - LPF_FACTOR) * mCountersRecv[i];
}
resetCounters();
}
void bdAccount::printStats(std::ostream &out)
{
int i;
out << " Send Recv: ";
out << std::endl;
for(i = 0; i < mNoStats; i++)
{
out << "Send" << mLabel[i] << " : " << std::setw(10) << mLpfOut[i];
out << " ";
out << "Recv" << mLabel[i] << " : " << std::setw(10) << mLpfRecv[i];
out << std::endl;
}
}
void bdAccount::resetCounters()
{
int i;
for(i = 0; i < mNoStats; i++)
{
mCountersOut[i] = 0;
mCountersRecv[i] = 0;
}
}
void bdAccount::resetStats()
{
int i;
for(i = 0; i < mNoStats; i++)
{
mLpfOut[i] = 0;
mLpfRecv[i] = 0;
}
resetCounters();
}

View File

@ -1,76 +0,0 @@
#ifndef BITDHT_ACCOUNT_H
#define BITDHT_ACCOUNT_H
/*******************************************************************************
* bitdht/bdaccount.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include <vector>
#include <string>
#include <inttypes.h>
#define BDACCOUNT_MSG_OUTOFDATEPING 0
#define BDACCOUNT_MSG_PING 1
#define BDACCOUNT_MSG_PONG 2
#define BDACCOUNT_MSG_QUERYNODE 3
#define BDACCOUNT_MSG_QUERYHASH 4
#define BDACCOUNT_MSG_REPLYFINDNODE 5
#define BDACCOUNT_MSG_REPLYQUERYHASH 6
#define BDACCOUNT_MSG_POSTHASH 7
#define BDACCOUNT_MSG_REPLYPOSTHASH 8
#define BDACCOUNT_MSG_CONNECTREQUEST 9
#define BDACCOUNT_MSG_CONNECTREPLY 10
#define BDACCOUNT_MSG_CONNECTSTART 11
#define BDACCOUNT_MSG_CONNECTACK 12
#define BDACCOUNT_NUM_ENTRIES 13
class bdAccount
{
public:
bdAccount();
void incCounter(uint32_t idx, bool out);
void doStats();
void printStats(std::ostream &out);
void resetCounters();
void resetStats();
private:
int mNoStats;
std::vector<double> mCountersOut;
std::vector<double> mCountersRecv;
std::vector<double> mLpfOut;
std::vector<double> mLpfRecv;
std::vector<std::string> mLabel;
// Statistics.
};
#endif // BITDHT_ACCOUNT_H

View File

@ -1,267 +0,0 @@
1.162.168.21 8956
2.6.224.136 17320
5.116.142.222 13755
5.189.185.57 6968
5.202.101.3 4000
5.227.124.122 1024
5.227.124.122 20600
5.227.124.122 64196
5.39.94.218 6991
5.79.102.9 6881
5.89.120.163 2457
14.117.182.22 1091
14.8.109.32 17160
23.115.236.180 42375
24.153.98.173 1024
24.38.199.13 10583
27.150.87.242 1123
27.151.179.38 51413
27.152.212.182 1424
31.24.186.40 16143
31.36.78.93 30020
31.44.90.218 51413
37.120.213.132 19525
37.14.113.18 3815
37.146.76.158 51413
37.187.105.230 5169
37.232.184.93 6881
37.46.150.58 51413
39.111.152.200 17527
39.154.68.57 28007
42.200.116.4 18578
42.3.188.207 19771
45.176.111.21 1434
45.32.43.51 49091
45.76.218.165 52911
45.77.214.200 44350
46.172.86.23 46039
46.223.161.46 23693
46.237.96.68 16536
46.52.174.214 24012
46.7.227.47 27644
46.7.9.41 21374
49.64.73.215 51413
49.74.50.28 60893
49.75.73.147 51413
49.79.26.15 51413
49.83.226.50 20864
49.83.241.222 51413
52.9.197.152 6881
58.209.188.12 20994
59.149.118.196 51413
59.2.250.243 57099
59.6.53.18 57437
60.104.89.4 51413
60.124.114.239 16925
60.178.44.27 1050
60.99.229.14 20617
61.223.34.21 17881
61.227.127.222 22223
61.239.28.169 18873
62.210.82.193 51413
64.191.5.92 56891
65.92.141.96 58361
67.215.246.10 6881
68.151.213.83 20047
69.40.178.254 50793
71.34.2.150 8053
72.95.247.56 12956
73.157.77.166 5477
74.109.243.24 7250
74.140.153.59 24757
74.72.13.99 9613
76.29.106.98 41447
77.202.207.190 33034
77.21.64.116 22222
77.245.14.94 9910
78.131.78.35 51238
78.158.1.15 7433
78.231.125.98 12162
78.242.250.55 55946
79.164.245.5 49001
80.147.23.201 32746
80.200.171.90 16294
80.99.222.34 51414
81.171.17.30 42254
82.221.103.244 6881
82.235.78.193 44097
82.244.32.78 43518
82.64.181.170 38240
82.64.249.25 51413
82.64.44.119 51413
82.65.164.218 15726
82.65.68.9 51413
82.77.146.109 53713
83.46.92.34 50000
84.195.46.218 54600
84.40.106.115 12046
85.149.0.42 21045
86.121.194.1 51413
86.98.50.30 21455
87.123.166.45 4145
87.169.199.211 10496
88.7.217.202 31348
88.99.25.154 38051
89.135.26.33 51413
89.17.134.184 10327
89.245.86.20 32417
89.253.118.133 8621
90.101.94.104 20780
90.151.95.110 2199
90.219.241.30 51413
90.219.8.170 11916
91.121.136.132 59001
91.123.72.241 49001
91.142.65.40 51413
91.173.208.204 16300
91.211.245.40 7369
91.92.194.144 1031
91.98.96.76 5385
92.244.238.115 3115
92.97.68.210 58000
93.100.182.236 32249
93.11.175.113 22948
93.115.202.240 64493
93.152.132.9 12332
94.154.81.100 12345
94.222.188.14 29299
95.211.117.105 62086
95.219.143.102 10360
95.222.119.133 43087
95.42.138.33 16550
96.39.191.231 52000
99.192.24.198 52552
103.226.250.79 3521
103.82.242.163 8083
104.156.238.118 34731
104.237.149.26 64879
107.155.5.39 6881
109.129.202.63 11076
109.148.168.121 21651
109.24.244.111 33334
110.81.114.66 24732
111.175.84.3 6881
111.216.9.68 13493
113.105.18.227 16001
113.194.69.53 53858
113.219.200.7 12935
113.252.78.238 23474
113.68.239.87 6396
113.69.96.171 51443
114.188.193.161 22555
114.231.190.193 51413
114.232.201.253 30350
114.32.153.245 26233
114.32.1.94 7788
114.38.137.40 24062
114.75.44.238 6881
115.133.66.181 9460
115.205.157.105 51413
116.1.193.182 51413
117.247.200.35 5353
117.60.240.145 35709
117.60.62.8 51413
117.93.101.232 51413
118.123.245.182 5060
119.177.21.161 27048
119.64.245.112 56265
121.171.118.184 11566
121.178.169.67 49259
121.234.117.237 15398
122.116.102.22 14054
123.202.146.112 23118
123.217.135.139 7830
128.68.229.32 51413
134.209.114.242 8000
139.28.218.4 34826
142.113.115.71 26453
148.251.68.55 50000
148.70.53.219 2551
150.117.108.250 21902
150.117.44.190 25052
151.224.15.227 51413
157.157.157.41 51413
161.97.102.243 51902
162.208.6.211 51413
167.179.83.227 60220
168.70.68.30 18325
169.0.60.179 64494
171.5.165.129 6881
172.104.76.77 60542
172.104.93.28 35617
172.98.144.81 19186
173.176.138.246 9545
173.199.70.134 39045
173.212.205.73 51432
173.212.219.143 6881
174.89.174.228 51413
175.197.1.120 52574
176.9.8.143 58250
178.118.86.145 51413
178.162.139.87 10029
178.32.220.92 6881
178.67.121.182 49001
182.138.217.58 6881
182.138.90.72 50288
182.139.213.160 39587
183.131.239.178 57835
183.22.252.15 21568
185.126.33.59 50024
185.156.175.187 1025
185.157.221.247 25401
185.252.60.243 49001
185.45.195.156 28074
185.45.195.181 28185
185.45.195.190 28136
185.61.148.114 64879
188.133.192.123 19967
188.235.1.208 7890
188.240.208.187 51413
192.181.103.63 19627
192.241.151.29 6881
193.242.205.145 49001
193.77.153.124 59835
194.176.114.54 51413
194.35.233.206 20124
195.154.172.169 36097
195.154.172.169 38340
195.154.172.169 48043
195.154.172.169 48799
195.154.179.2 22794
195.154.179.2 41210
195.154.179.2 42687
195.154.179.2 49156
195.154.179.2 50385
195.154.179.2 50944
195.154.181.225 37558
195.191.246.240 1026
196.191.92.25 22937
197.157.219.137 22629
197.61.66.105 24612
198.13.48.70 37360
199.254.238.193 15374
200.63.107.82 13323
201.241.63.68 38705
203.130.242.178 28280
203.213.61.76 50559
207.154.222.13 51111
210.195.211.60 49771
210.6.145.50 15207
212.102.42.202 7611
212.129.19.188 27096
212.129.19.188 29812
212.129.19.188 50117
212.129.19.188 51965
212.129.33.59 6881
212.32.231.67 51413
212.86.51.7 65148
213.136.79.7 11910
218.161.100.192 51413
218.219.199.148 18753
220.189.94.56 13279
222.211.148.83 8080
222.77.110.143 46016
223.116.81.154 10655
223.16.153.107 51413
223.26.31.77 21440
223.65.101.235 25159

View File

@ -1,55 +0,0 @@
#!/bin/bash
<<LICENSE
Copyright (C) 2020 Gioacchino Mazzurco <gio@eigenlab.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
LICENSE
<<README
Generate a clean DHT bootstrap node list.
Feeds on previously known nodes from standard input and a few well known
mainline DHT bootstrap nodes. Prints only nodes that appears to be active to a
quick nmap check. Make sure your internet connection is working well before
using this.
Example usage:
--------------------------------
cat bdboot.txt | bdboot_generate.sh | tee /tmp/bdboot_generated.txt
cat /tmp/bdboot_generated.txt | sort -u > bdboot.txt
--------------------------------
README
function check_dht_host()
{
mHost="$1"
mPort="$2"
sudo nmap -oG - -sU -p $mPort $mHost | grep open | \
awk '{print $2" "$5}' | awk -F/ '{print $1}'
}
cat | while read line; do
hostIP="$(echo $line | awk '{print $1}')"
hostPort="$(echo $line | awk '{print $2}')"
check_dht_host $hostIP $hostPort
done
check_dht_host router.utorrent.com 6881
check_dht_host router.bittorrent.com 6881
check_dht_host dht.libtorrent.org 25401
check_dht_host dht.transmissionbt.com 6881

File diff suppressed because it is too large Load Diff

View File

@ -1,314 +0,0 @@
/*******************************************************************************
* bitdht/bdconnection.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_CONNECTION_H
#define BITDHT_CONNECTION_H
#include "bitdht/bdiface.h"
class bdQueryManager;
class bdNodePublisher;
/************************************************************************************************************
************************************** ProxyTuple + Connection State ****************************************
************************************************************************************************************/
#define BITDHT_CONNREQUEST_READY 1
#define BITDHT_CONNREQUEST_PAUSED 2
#define BITDHT_CONNREQUEST_INPROGRESS 3
#define BITDHT_CONNREQUEST_EXTCONNECT 4
#define BITDHT_CONNREQUEST_DONE 5
#define BITDHT_CONNREQUEST_TIMEOUT_CONNECT 300 // MAKE THIS LARGE - SHOULD NEVER HAPPEN.
#define BITDHT_CONNREQUEST_TIMEOUT_INPROGRESS 30
#define BITDHT_CONNREQUEST_MAX_AGE 60
#define BITDHT_CONNECTION_WAITING_AUTH 1
#define BITDHT_CONNECTION_WAITING_REPLY 2
#define BITDHT_CONNECTION_WAITING_START 3
#define BITDHT_CONNECTION_WAITING_ACK 4
#define BITDHT_CONNECTION_COMPLETED 5
#define BD_CONNECTION_START_RETRY_PERIOD 3 // Should only take a couple of seconds to get reply.
#define BD_CONNECTION_START_MAX_RETRY 3
#define BD_CONNECTION_MAX_TIMEOUT 20 /* should be quick */
class bdProxyTuple
{
public:
bdProxyTuple() { return; }
bdProxyTuple(bdNodeId *s, bdNodeId *p, bdNodeId *d)
:srcId(*s), proxyId(*p), destId(*d) { return; }
bdNodeId srcId;
bdNodeId proxyId;
bdNodeId destId;
};
std::ostream &operator<<(std::ostream &out, const bdProxyTuple &t);
int operator<(const bdProxyTuple &a, const bdProxyTuple &b);
int operator==(const bdProxyTuple &a, const bdProxyTuple &b);
class bdConnection
{
public:
bdConnection();
/** Functions to tweak the connection status */
// User initialised Connection.
int ConnectionSetup(bdId *proxyId, bdId *srcConnAddr, bdId *destConnAddr, int mode, int delay);
int ConnectionSetupDirect(bdId *destId, bdId *srcConnAddr);
// Initialise a new Connection. (receiving a Connection Request)
int ConnectionRequestDirect(bdId *id, bdId *srcConnAddr, bdId *destConnAddr);
int ConnectionRequestProxy(bdId *id, bdId *srcConnAddr, bdNodeId *ownId, bdId *destConnAddr, int mode, int delay);
int ConnectionRequestEnd(bdId *id, bdId *srcConnAddr, bdId *destConnAddr, int mode);
// Setup Finishing Stage, (receiving a Connection Reply).
int upgradeProxyConnectionToFinish(bdId *id, bdId *srcConnAddr, bdId *destConnAddr, int mode, int delay, int status);
int AuthoriseDirectConnection(bdId *srcId, bdId *proxyId, bdId *destId, int mode, int loc);
int AuthoriseProxyConnection(bdId *srcId, bdId *proxyId, bdId *destId, int mode, int loc, int bandwidth);
int AuthoriseEndConnection(bdId *srcId, bdId *proxyId, bdId *destId, int mode, int loc, int delay);
int CompleteConnection(bdId *id, bdId *srcConnAddr, bdId *destConnAddr, int bandwidth, int delay);
int checkForDefaultConnectAddress();
/* Connection State, and TimeStamp of Update */
int mState;
time_t mLastEvent;
/* Addresses of Start/Proxy/End Nodes */
bdId mSrcId;
bdId mDestId;
bdId mProxyId;
/* Where we are in the connection,
* and what connection mode.
*/
int mPoint;
int mMode;
/* must have ip:ports of connection ends (if proxied) */
bdId mSrcConnAddr;
bdId mDestConnAddr;
int mBandwidth;
int mMaxDelay;
time_t mConnectionStartTS;
/* START/ACK Finishing ****/
time_t mLastStart; /* timer for retries */
int mRetryCount; /* retry counter */
bool mSrcAck;
bool mDestAck;
// Completion TS.
time_t mCompletedTS;
};
#define BD_PI_SRC_UNKNOWN 0
#define BD_PI_SRC_QUERYRESULT 1
#define BD_PI_SRC_QUERYPROXY 2
#define BD_PI_SRC_NODESPACE_FRIEND 3
#define BD_PI_SRC_NODESPACE_SERVER 4
#define BD_PI_SRC_NODESPACE_ENGINEVERSION 5
#define BD_PI_SRC_ADDGOODPROXY 6
class bdProxyId
{
public:
bdProxyId(const bdId &in_id, uint32_t in_srctype, uint32_t in_errcode)
:id(in_id), srcType(in_srctype), errcode(in_errcode) { return; }
bdProxyId() :srcType(BD_PI_SRC_UNKNOWN), errcode(0) { return; }
std::string proxySrcType() const;
bdId id;
uint32_t srcType;
uint32_t errcode;
};
class bdConnectionRequest
{
public:
bdConnectionRequest() : mMode(0), mState(0), mStateTS(0), mPauseTS(0), mErrCode(0), mDelay(0), mRequestTS(0), mRecycled(0), mCurrentSrcType(0)
{
bdsockaddr_clear(&mLocalAddr);
}
public:
int setupDirectConnection(struct sockaddr_in *laddr, bdNodeId *target);
int setupProxyConnection(struct sockaddr_in *laddr, bdNodeId *target, uint32_t mode, uint32_t delay);
int addGoodProxy(const bdId *srcId);
int checkGoodProxyPeer(const bdId *Id);
bdNodeId mTarget;
struct sockaddr_in mLocalAddr;
int mMode;
int mState;
time_t mStateTS;
time_t mPauseTS;
uint32_t mErrCode;
int mDelay;
time_t mRequestTS; // reference Time for mDelay.
std::list<bdProxyId> mGoodProxies;
std::list<bdId> mPotentialProxies;
//std::list<bdId> mGoodProxies;
int mRecycled;
bdId mCurrentAttempt;
uint32_t mCurrentSrcType;
std::list<bdProxyId> mPeersTried;
//std::list<bdId> mPeersTried;
};
std::ostream &operator<<(std::ostream &out, const bdConnectionRequest &req);
std::ostream &operator<<(std::ostream &out, const bdConnection &conn);
/*********
* The Connection Management Class.
* this encapsulates all of the functionality..
* except for a couple of message in/outs + callback.
*/
class bdConnectManager
{
public:
bdConnectManager(bdNodeId *ownid, bdSpace *space, bdQueryManager *qmgr, bdDhtFunctions *fns, bdNodePublisher *pub);
/* connection functions */
void requestConnection(bdNodeId *id, uint32_t modes);
void allowConnection(bdNodeId *id, uint32_t modes);
/* high level */
void shutdownConnections();
void printConnections();
/* Connections: Configuration */
void defaultConnectionOptions();
virtual void setConnectionOptions(uint32_t allowedModes, uint32_t flags);
/* Connections: Initiation */
int requestConnection(struct sockaddr_in *laddr, bdNodeId *target, uint32_t mode, uint32_t delay, uint32_t start);
int requestConnection_direct(struct sockaddr_in *laddr, bdNodeId *target);
int requestConnection_proxy(struct sockaddr_in *laddr, bdNodeId *target, uint32_t mode, uint32_t delay);
int killConnectionRequest(struct sockaddr_in *laddr, bdNodeId *target, uint32_t mode);
int checkExistingConnectionAttempt(bdNodeId *target);
void addPotentialConnectionProxy(const bdId *srcId, const bdId *target);
void updatePotentialConnectionProxy(const bdId *id, uint32_t mode);
int checkPeerForFlag(const bdId *id, uint32_t with_flag);
int tickConnections();
void iterateConnectionRequests();
int startConnectionAttempt(bdConnectionRequest *req);
// internal Callback -> normally continues to callbackConnect().
void callbackConnectRequest(bdId *srcId, bdId *proxyId, bdId *destId,
int mode, int point, int param, int cbtype, int errcode);
/* Connections: Outgoing */
int startConnectionAttempt(bdId *proxyId, bdId *srcConnAddr, bdId *destConnAddr, int mode, int delay);
void AuthConnectionOk(bdId *srcId, bdId *proxyId, bdId *destId, int mode, int loc, int bandwidth, int delay);
void AuthConnectionNo(bdId *srcId, bdId *proxyId, bdId *destId, int mode, int loc, int errcode);
void iterateConnections();
/* Connections: Utility State */
bdConnection *findExistingConnection(bdNodeId *srcId, bdNodeId *proxyId, bdNodeId *destId);
bdConnection *newConnection(bdNodeId *srcId, bdNodeId *proxyId, bdNodeId *destId);
int cleanConnection(bdNodeId *srcId, bdNodeId *proxyId, bdNodeId *destId);
int determinePosition(bdNodeId *sender, bdNodeId *src, bdNodeId *dest);
int determineProxyId(bdNodeId *sender, bdNodeId *src, bdNodeId *dest, bdNodeId *proxyId);
bdConnection *findSimilarConnection(bdNodeId *srcId, bdNodeId *destId);
bdConnection *findExistingConnectionBySender(bdId *sender, bdId *src, bdId *dest);
bdConnection *newConnectionBySender(bdId *sender, bdId *src, bdId *dest);
int cleanConnectionBySender(bdId *sender, bdId *src, bdId *dest);
// Overloaded Generalised Connection Callback.
virtual void callbackConnect(bdId *srcId, bdId *proxyId, bdId *destId,
int mode, int point, int param, int cbtype, int errcode);
/* Connections: */
int recvedConnectionRequest(bdId *id, bdId *srcConnAddr, bdId *destConnAddr, int mode, int delay);
int recvedConnectionReply(bdId *id, bdId *srcConnAddr, bdId *destConnAddr, int mode, int delay, int status);
int recvedConnectionStart(bdId *id, bdId *srcConnAddr, bdId *destConnAddr, int mode, int delayOrBandwidth);
int recvedConnectionAck(bdId *id, bdId *srcConnAddr, bdId *destConnAddr, int mode);
/* setup Relay Mode */
void setRelayMode(uint32_t mode);
private:
std::map<bdProxyTuple, bdConnection> mConnections;
std::map<bdNodeId, bdConnectionRequest> mConnectionRequests;
uint32_t mConfigAllowedModes;
bool mConfigAutoProxy;
uint32_t mRelayMode;
/****************************** Connection Code (in bdconnection.cc) ****************************/
private:
bdNodeId mOwnId;
bdSpace *mNodeSpace;
bdQueryManager *mQueryMgr;
bdDhtFunctions *mFns;
bdNodePublisher *mPub;
};
#endif // BITDHT_CONNECTION_H

View File

@ -1,318 +0,0 @@
/*******************************************************************************
* bitdht/bdfilter.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bitdht/bdfilter.h"
#include "bitdht/bdmanager.h"
#include "util/bdfile.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <time.h>
/**
* #define DEBUG_FILTER 1
**/
#define BDFILTER_ENTRY_DROP_PERIOD (7 * 24 * 3600)
bdFilter::bdFilter(const std::string &fname, const bdNodeId *ownid, uint32_t filterFlags, bdDhtFunctions *fns, bdNodeManager *manager)
{
/* */
mOwnId = *ownid;
mFns = fns;
mFilename = fname ;
loadBannedIpFile() ;
mFilterFlags = filterFlags;
mNodeManager = manager;
}
void bdFilter::writeBannedIpFile()
{
std::string filetmp = mFilename + ".tmp" ;
FILE *fd = fopen(filetmp.c_str(), "w");
if (!fd)
{
std::cerr << "(EE) bdFilter::writeBannedIpFile() FAILED to Open File " << mFilename << std::endl;
return;
}
for( std::map<uint32_t,bdFilteredPeer>::iterator it=mFiltered.begin();it!=mFiltered.end();++it)
{
fprintf(fd, "%s %u %lu %lu\n", bdnet_inet_ntoa(it->second.mAddr.sin_addr).c_str(), it->second.mFilterFlags, it->second.mFilterTS, it->second.mLastSeen) ;
#ifdef DEBUG_FILTER
fprintf(stderr, "Storing Peer Address: %s \n", bdnet_inet_ntoa(it->second.mAddr.sin_addr).c_str()) ;
#endif
}
fclose(fd);
if(!bdFile::renameFile(filetmp,mFilename))
std::cerr << "Could not rename file !!" << std::endl;
#ifdef DEBUG_FILTER
else
std::cerr << "Successfully renamed file " << filetmp << " to " << mFilename << std::endl;
#endif
}
void bdFilter::loadBannedIpFile()
{
char line[10240];
char addr_str[10240];
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = PF_INET;
FILE *fd = fopen(mFilename.c_str(),"r") ;
if(fd == NULL)
{
std::cerr << "(EE) Cannot load filter file " << mFilename << std::endl;
return ;
}
while(line == fgets(line, 10240, fd))
{
uint32_t filter_flags ;
unsigned long long int filter_ts ;
unsigned long long int last_seen ;
if (4 == sscanf(line, "%s %u %llu %llu", addr_str, &filter_flags,&filter_ts,&last_seen))
{
if (bdnet_inet_aton(addr_str, &(addr.sin_addr)))
{
addr.sin_port = 0;
bdFilteredPeer peer;
peer.mAddr = addr;
peer.mFilterTS = filter_ts;
peer.mLastSeen = last_seen;
peer.mFilterFlags = filter_flags;
mFiltered[addr.sin_addr.s_addr] = peer ;
#ifdef DEBUG_FILTER
std::cerr << "Loaded filtered IP: " << std::string(addr_str) << " last seen: " << last_seen << ", TS=" << filter_ts << std::endl;
#endif
}
}
}
fclose(fd);
}
//bool bdFilter::filtered(std::list<bdFilteredPeer> &answer)
//{
// answer = mFiltered;
// return (answer.size() > 0);
//}
bool bdFilter::filteredIPs(std::list<struct sockaddr_in> &answer)
{
std::map<uint32_t,bdFilteredPeer>::iterator it;
for(it = mFiltered.begin(); it != mFiltered.end(); it++)
{
answer.push_back(it->second.mAddr);
}
return (answer.size() > 0);
}
int bdFilter::checkPeer(const bdId *id, uint32_t mode)
{
bool add = false;
uint32_t flags = 0;
if ((mFilterFlags & BITDHT_FILTER_REASON_OWNID) &&
isOwnIdWithoutBitDhtFlags(id, mode))
{
add = true;
flags |= BITDHT_FILTER_REASON_OWNID;
}
if (add)
{
bool isNew = addPeerToFilter(id->addr, flags);
if (isNew)
{
return 1;
}
}
return 0;
}
int bdFilter::addPeerToFilter(const struct sockaddr_in& addr, uint32_t flags)
{
std::map<uint32_t,bdFilteredPeer>::iterator it = mFiltered.find(addr.sin_addr.s_addr) ;
if(it != mFiltered.end())
{
it->second.mLastSeen = time(NULL);
it->second.mFilterFlags |= flags;
}
else
{
time_t now = time(NULL);
bdFilteredPeer fp;
fp.mAddr = addr;
fp.mAddr.sin_port = 0;
fp.mFilterFlags = flags;
fp.mFilterTS = now;
fp.mLastSeen = now;
uint32_t saddr = addr.sin_addr.s_addr;
mFiltered[saddr] = fp;
std::cerr << "Adding New Banned Ip Address: " << bdnet_inet_ntoa(addr.sin_addr);
std::cerr << std::endl;
}
writeBannedIpFile() ;
return true;
}
// void bdFilter::loadFilteredPeers(const std::list<bdFilteredPeer>& peers)
// {
// for(std::list<bdFilteredPeer>::iterator it = peers.begin(); it != peers.end();++it)
// {
// #ifdef DEBUG_FILTER
// std::cerr << "Loading filtered peer " << inet_ntoa(it->mAddr.sin_addr) << " Flags: " << it->mFilterFlags << " FilterTS: "
// << now - it->mFilterTS << " LastSeen: " << now - it->mLastSeen << std::endl;
// #endif
// uint32_t saddr = it->mAddr.sin_addr.s_addr;
// mFiltered[saddr] = *it ;
// }
// }
void bdFilter::getFilteredPeers(std::list<bdFilteredPeer>& peers)
{
for(std::map<uint32_t,bdFilteredPeer>::iterator it = mFiltered.begin(); it != mFiltered.end();++it)
peers.push_back(it->second) ;
}
/* fast check if the addr is in the structure */
int bdFilter::addrOkay(struct sockaddr_in *addr)
{
// first check upper layer
bool isAvailable, isBanned;
mNodeManager->doIsBannedCallback(addr, &isAvailable, &isBanned);
if(isAvailable) {
#ifdef DEBUG_FILTER
std::cerr << "bdFilter::addrOkay addr: " << inet_ntoa(addr->sin_addr) << " result from upper layer: " << (isBanned ? "banned" : "ok") << std::endl;
#endif
return !isBanned;
} else {
// fallback to own ban list
std::map<uint32_t,bdFilteredPeer>::const_iterator it = mFiltered.find(addr->sin_addr.s_addr);
if (it == mFiltered.end())
return 1; // Address is Okay
}
#ifdef DEBUG_FILTER
std::cerr << "Detected Packet From Banned Ip Address: " << inet_ntoa(addr->sin_addr);
std::cerr << std::endl;
#endif
return 0;
}
bool bdFilter::isOwnIdWithoutBitDhtFlags(const bdId *id, uint32_t peerFlags)
{
if (peerFlags & BITDHT_PEER_STATUS_RECV_PONG)
{
if (peerFlags & BITDHT_PEER_STATUS_DHT_ENGINE)
{
/* okay! */
return false;
}
/* now check distance */
bdMetric dist;
mFns->bdDistance(&mOwnId, &(id->id), &dist);
int bucket = mFns->bdBucketDistance(&dist);
/* if they match us... kill it */
if (bucket == 0)
{
return true;
}
}
return false;
}
/* periodically we want to cleanup the filter....
* if we haven't had an IP address reported as filtered for several hours.
* remove it from the list.
*/
bool bdFilter::cleanupFilter()
{
#ifdef DEBUG_FILTER
std::cerr << "bdFilter: Checking current filter List:" << std::endl;
#endif
time_t now = time(NULL);
time_t dropTime = now - BDFILTER_ENTRY_DROP_PERIOD;
for(std::map<uint32_t,bdFilteredPeer>::iterator it = mFiltered.begin(); it != mFiltered.end();)
{
#ifdef DEBUG_FILTER
std::cerr << "\t" << bdnet_inet_ntoa(it->second.mAddr.sin_addr);
std::cerr << " Flags: " << it->second.mFilterFlags;
std::cerr << " FilterTS: " << now - it->second.mFilterTS;
std::cerr << " LastSeen: " << now - it->second.mLastSeen;
#endif
if (it->second.mLastSeen < dropTime)
{
/* remove from filter */
#ifdef DEBUG_FILTER
std::cerr << " OLD DROPPING" << std::endl;
#endif
std::map<uint32_t,bdFilteredPeer>::iterator tmp(it) ;
++tmp ;
mFiltered.erase(it);
it = tmp ;
}
else
{
#ifdef DEBUG_FILTER
std::cerr << " OK" << std::endl;
#endif
it++;
}
}
return true;
}

View File

@ -1,84 +0,0 @@
/*******************************************************************************
* bitdht/bdfilter.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_FILTER_H
#define BITDHT_FILTER_H
#include "bitdht/bdiface.h"
#include <set>
/* Query result flags are in bdiface.h */
#define BITDHT_FILTER_REASON_OWNID 0x0001
class bdFilteredPeer
{
public:
struct sockaddr_in mAddr;
uint32_t mFilterFlags; /* reasons why we are filtering */
time_t mFilterTS;
time_t mLastSeen;
};
class bdNodeManager;
class bdFilter
{
public:
bdFilter(const std::string& fname, const bdNodeId *ownid, uint32_t filterFlags, bdDhtFunctions *fns, bdNodeManager *manager);
// get the answer.
//bool filtered(std::list<bdFilteredPeer> &answer);
bool filteredIPs(std::list<struct sockaddr_in> &answer);
//void loadFilteredPeers(const std::list<bdFilteredPeer>& peers) ;
void getFilteredPeers(std::list<bdFilteredPeer> &peers);
int checkPeer(const bdId *id, uint32_t peerFlags);
int addrOkay(struct sockaddr_in *addr);
int addPeerToFilter(const struct sockaddr_in &addr, uint32_t flags);
bool cleanupFilter();
void loadBannedIpFile() ;
void writeBannedIpFile() ;
private:
bool isOwnIdWithoutBitDhtFlags(const bdId *id, uint32_t peerFlags);
// searching for
bdNodeId mOwnId;
uint32_t mFilterFlags;
std::map<uint32_t,bdFilteredPeer> mFiltered;
bdDhtFunctions *mFns;
std::string mFilename ;
// have access to the manager for isBanned callback
bdNodeManager* mNodeManager;
};
#endif

View File

@ -1,243 +0,0 @@
/*******************************************************************************
* bitdht/bdfriendlist.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bitdht/bdfriendlist.h"
#include "bitdht/bdstddht.h"
#include "bitdht/bdpeer.h"
#include <iostream>
/*****
* #define DEBUG_FRIENDLIST 1
****/
bdFriendEntry::bdFriendEntry()
{
mFlags = 0;
mLastSeen = 0;
}
bool bdFriendEntry::addrKnown(struct sockaddr_in *addr)
{
if (mFlags & BD_FRIEND_ENTRY_ADDR_OK)
{
if (mFlags & BD_FRIEND_ENTRY_ONLINE)
{
*addr = mPeerId.addr;
return true;
}
if (time(NULL) - mLastSeen < BD_FRIEND_ENTRY_TIMEOUT)
{
*addr = mPeerId.addr;
return true;
}
}
return false;
}
uint32_t bdFriendEntry::getPeerFlags()
{
return mFlags & BD_FRIEND_ENTRY_MASK_KNOWN;
}
bdFriendList::bdFriendList(const bdNodeId *ownId)
{
bdId tmpId;
tmpId.id = *ownId;
updatePeer(&tmpId, BD_FRIEND_ENTRY_SELF);
}
/******
* Simple logic: timestamp is set with address.
* if ONLINE, then address will be dropped as soon as OFFLINE.
* if ADDR_OK, then address will be dropped after XX seconds.
*
* ONLINE - will be used with friends.
* ADDR_OK - will potentially be used for friends of friends (but not for now).
*****/
/* catch-all interface function */
bool bdFriendList::updatePeer(const bdId *id, uint32_t flags)
{
#ifdef DEBUG_FRIENDLIST
std::cerr << "bdFriendList::updatePeer() Peer(";
bdStdPrintId(std::cerr, id);
std::cerr << ") Flags: " << flags;
std::cerr << std::endl;
#endif
std::map<bdNodeId, bdFriendEntry>::iterator it;
it = mPeers.find(id->id);
if (it == mPeers.end())
{
bdFriendEntry entry;
entry.mPeerId.id = id->id;
entry.mFlags = 0;
entry.mLastSeen = 0;
mPeers[id->id] = entry;
it = mPeers.find(id->id);
}
/* update all */
it->second.mFlags = flags;
if (it->second.mFlags & (BD_FRIEND_ENTRY_ADDR_OK | BD_FRIEND_ENTRY_ONLINE))
{
it->second.mFlags |= BD_FRIEND_ENTRY_ADDR_OK;
it->second.mPeerId.addr = id->addr;
it->second.mLastSeen = time(NULL);
}
return true;
}
bool bdFriendList::removePeer(const bdNodeId *id)
{
/* see if it exists... */
std::map<bdNodeId, bdFriendEntry>::iterator it;
it = mPeers.find(*id);
if (it == mPeers.end())
{
#ifdef DEBUG_FRIENDLIST
std::cerr << "bdFriendList::removeFriend() Peer(";
bdStdPrintNodeId(std::cerr, id);
std::cerr << ") is unknown!";
std::cerr << std::endl;
#endif
return false;
}
mPeers.erase(*id);
return true;
}
bool bdFriendList::findPeerEntry(const bdNodeId *id, bdFriendEntry &entry)
{
/* see if it exists... */
std::map<bdNodeId, bdFriendEntry>::iterator it;
it = mPeers.find(*id);
if (it == mPeers.end())
{
#ifdef DEBUG_FRIENDLIST
std::cerr << "bdFriendList::getPeerEntry() Peer(";
bdStdPrintNodeId(std::cerr, id);
std::cerr << ") is unknown!";
std::cerr << std::endl;
#endif
return false;
}
entry = it->second;
return true;
}
bool bdFriendList::findPeersWithFlags(uint32_t flags, std::list<bdNodeId> &peerList)
{
#ifdef DEBUG_FRIENDLIST
std::cerr << "bdFriendList::findPeersWithFlags(" << flags << ")";
std::cerr << std::endl;
#endif
/* see if it exists... */
std::map<bdNodeId, bdFriendEntry>::iterator it;
for(it = mPeers.begin(); it != mPeers.end(); it++)
{
/* if they have ALL of the flags we specified */
if ((it->second.getPeerFlags() & flags) == flags)
{
#ifdef DEBUG_FRIENDLIST
std::cerr << "bdFriendList::findPeersWithFlags() Found: ";
bdStdPrintNodeId(std::cerr, id);
std::cerr << std::endl;
#endif
peerList.push_back(it->second.mPeerId.id);
}
}
return (peerList.size() > 0);
}
bool bdFriendList::print(std::ostream &out)
{
time_t now = time(NULL);
out << "bdFriendList::print()";
out << std::endl;
std::map<bdNodeId, bdFriendEntry>::iterator it;
for(it = mPeers.begin(); it != mPeers.end(); it++)
{
bdStdPrintId(out, &(it->second.mPeerId));
out << " Flags: " << it->second.mFlags;
out << " Seen: " << now - it->second.mLastSeen;
out << std::endl;
}
return true;
}
bdPeerQueue::bdPeerQueue()
{
return;
}
bool bdPeerQueue::queuePeer(const bdId *id, uint32_t flags)
{
bdFriendEntry entry;
entry.mPeerId = *id;
entry.mFlags = flags;
entry.mLastSeen = time(NULL);
mPeerQueue.push_back(entry);
return true;
}
bool bdPeerQueue::popPeer(bdId *id, uint32_t &flags)
{
if (mPeerQueue.size() > 0)
{
bdFriendEntry entry = mPeerQueue.front();
mPeerQueue.pop_front();
*id = entry.mPeerId;
flags = entry.mFlags;
return true;
}
return false;
}

View File

@ -1,101 +0,0 @@
/*******************************************************************************
* bitdht/bdfriendlist.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_FRIEND_LIST_H
#define BITDHT_FRIEND_LIST_H
/*
* This class maintains a list of current friends and friends-of-friends.
* It should also be updated when a peer's address has been identified.
*
* It is used for selecting preferential peers for DHT Connections.
* and for detecting bad peers that are duplicating real RS peers.
*
*/
#include "bitdht/bdiface.h"
#include <set>
#define BD_FRIEND_ENTRY_TIMEOUT 10
//#define BD_FRIEND_ENTRY_ONLINE 0x0001
//#define BD_FRIEND_ENTRY_ADDR_OK 0x0002
//#define BD_FRIEND_ENTRY_WHITELIST BITDHT_PEER_STATUS_DHT_WHITELIST
//#define BD_FRIEND_ENTRY_FOF BITDHT_PEER_STATUS_DHT_FOF
//#define BD_FRIEND_ENTRY_FRIEND BITDHT_PEER_STATUS_DHT_FRIEND
//#define BD_FRIEND_ENTRY_RELAY_SERVER BITDHT_PEER_STATUS_DHT_RELAY_SERVER
//#define BD_FRIEND_ENTRY_SELF BITDHT_PEER_STATUS_DHT_SELF
//#define BD_FRIEND_ENTRY_MASK_KNOWN BITDHT_PEER_STATUS_MASK_KNOWN
class bdFriendEntry
{
public:
bdFriendEntry();
bool addrKnown(struct sockaddr_in *addr);
uint32_t getPeerFlags();
bdId mPeerId;
uint32_t mFlags;
time_t mLastSeen;
};
class bdFriendList
{
public:
bdFriendList(const bdNodeId *ownid);
bool updatePeer(const bdId *id, uint32_t flags);
bool removePeer(const bdNodeId *id);
bool findPeerEntry(const bdNodeId *id, bdFriendEntry &entry);
bool findPeersWithFlags(uint32_t flags, std::list<bdNodeId> &peerList);
bool print(std::ostream &out);
private:
std::map<bdNodeId, bdFriendEntry> mPeers;
};
class bdPeerQueue
{
public:
bdPeerQueue();
bool queuePeer(const bdId *id, uint32_t flags);
bool popPeer(bdId *id, uint32_t &flags);
private:
std::list<bdFriendEntry> mPeerQueue;
};
#endif

View File

@ -1,283 +0,0 @@
/*******************************************************************************
* bitdht/bdhash.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bitdht/bdhash.h"
#include "bitdht/bdstddht.h"
#include <iostream>
bdHashEntry::bdHashEntry(std::string value, std::string secret, time_t lifetime, time_t store)
:mValue(value), mStoreTS(store), mSecret(secret), mLifetime(lifetime)
{
return;
}
/**************************** class bdHashSet ********************************/
bdHashSet::bdHashSet(bdNodeId *id)
:mId(*id)
{
return;
}
int bdHashSet::search(std::string key, uint32_t maxAge, std::list<bdHashEntry> &entries)
{
std::multimap<std::string, bdHashEntry>::iterator sit, eit, it;
sit = mEntries.lower_bound(key);
eit = mEntries.upper_bound(key);
time_t now = time(NULL);
for(it = sit; it != eit; it++)
{
time_t age = now - it->second.mStoreTS;
if (age < (int32_t) maxAge)
{
entries.push_back(it->second);
}
}
return (0 < entries.size());
}
/***
* With modification.
* If there is no secret -> it cannot be deleted (must timeout), but can be extended.
* If there is a secret -> must include it to modify.
*
* Therefore if identical entry without secret comes along - what do I do?
* -> create duplicate?
*/
int bdHashSet::modify(std::string key, bdHashEntry *entry, uint32_t modFlags)
{
std::multimap<std::string, bdHashEntry>::iterator sit, eit, it;
sit = mEntries.lower_bound(key);
eit = mEntries.upper_bound(key);
time_t now = time(NULL);
bool updated = false;
for(it = sit; it != eit; it++)
{
/* check it all */
if (it->second.mValue == entry->mValue)
{
bool noSecret = (it->second.mSecret == "");
bool sameSecret = (it->second.mSecret == entry->mSecret);
bool update = false;
if (noSecret && sameSecret)
{
/* only allowed to increase lifetime */
if (modFlags == BITDHT_HASH_ENTRY_ADD)
{
time_t existKillTime = it->second.mLifetime + it->second.mStoreTS;
time_t newKillTime = entry->mLifetime + now;
if (newKillTime > existKillTime)
{
update = true;
}
}
}
else if (sameSecret)
{
if (modFlags == BITDHT_HASH_ENTRY_ADD)
{
update = true;
}
else if (modFlags == BITDHT_HASH_ENTRY_DELETE)
{
/* do it here */
mEntries.erase(it);
return 1;
}
}
if (update)
{
it->second.mStoreTS = now;
it->second.mLifetime = entry->mLifetime;
updated = true;
}
}
}
if ((!updated) && (modFlags == BITDHT_HASH_ENTRY_ADD))
{
/* create a new entry */
bdHashEntry newEntry(entry->mValue, entry->mSecret, entry->mLifetime, now);
mEntries.insert(std::pair<std::string, bdHashEntry>(key, newEntry));
updated = true;
}
return updated;
}
int bdHashSet::printHashSet(std::ostream &out)
{
time_t now = time(NULL);
std::multimap<std::string, bdHashEntry>::iterator it;
out << "Hash: ";
bdStdPrintNodeId(out, &mId); // Allowing "Std" as we dont need dht functions everywhere.
out << std::endl;
for(it = mEntries.begin(); it != mEntries.end();it++)
{
time_t age = now - it->second.mStoreTS;
out << "\tK:" << bdStdConvertToPrintable(it->first);
out << " V:" << bdStdConvertToPrintable(it->second.mValue);
out << " A:" << age << " L:" << it->second.mLifetime;
out << " S:" << bdStdConvertToPrintable(it->second.mSecret);
out << std::endl;
}
return 1;
}
int bdHashSet::cleanupHashSet(uint32_t maxAge)
{
time_t now = time(NULL);
/* this is nasty... but don't know how to effectively remove from multimaps
* * Must do full repeat for each removal.
*/
std::multimap<std::string, bdHashEntry>::iterator it;
for(it = mEntries.begin(); it != mEntries.end();)
{
time_t age = now - it->second.mStoreTS;
if ((age > (int32_t) maxAge) || (age > it->second.mLifetime))
{
mEntries.erase(it);
it = mEntries.begin();
}
else
{
it++;
}
}
return 1;
}
/******************************* class bdHashSpace ***************************/
bdHashSpace::bdHashSpace()
{
return;
}
/* accessors */
int bdHashSpace::search(bdNodeId *id, std::string key, uint32_t maxAge, std::list<bdHashEntry> &entries)
{
std::map<bdNodeId, bdHashSet>::iterator it;
it = mHashTable.find(*id);
if (it == mHashTable.end())
{
/* no entry */
return 1;
}
return it->second.search(key, maxAge, entries);
}
int bdHashSpace::modify(bdNodeId *id, std::string key, bdHashEntry *entry, uint32_t modFlags)
{
std::map<bdNodeId, bdHashSet>::iterator it;
it = mHashTable.find(*id);
if (it == mHashTable.end())
{
if (modFlags == BITDHT_HASH_ENTRY_DELETE)
{
/* done already */
return 1;
}
//mHashTable[*id] = bdHashSet(id);
mHashTable.insert(std::pair<bdNodeId, bdHashSet>(*id, bdHashSet(id)));
it = mHashTable.find(*id);
}
return it->second.modify(key, entry, modFlags);
}
int bdHashSpace::printHashSpace(std::ostream &out)
{
std::map<bdNodeId, bdHashSet>::iterator it;
out << "bdHashSpace::printHashSpace()" << std::endl;
out << "--------------------------------------------" << std::endl;
for(it = mHashTable.begin(); it != mHashTable.end(); it++)
{
it->second.printHashSet(out);
}
out << "--------------------------------------------" << std::endl;
return 1;
}
int bdHashSpace::cleanHashSpace(bdNodeId *min, bdNodeId *max, time_t maxAge)
{
std::map<bdNodeId, bdHashSet>::iterator it;
std::list<bdNodeId> eraseList;
std::list<bdNodeId>::iterator eit;
for(it = mHashTable.begin(); it != mHashTable.end(); it++)
{
if ((it->first < *min) ||
(*max < it->first))
{
/* schedule for erasure */
eraseList.push_back(it->first);
}
else
{
/* clean up Hash Set */
it->second.cleanupHashSet(maxAge);
}
}
/* cleanup */
while(eraseList.size() > 0)
{
bdNodeId &eId = eraseList.front();
it = mHashTable.find(eId);
if (it != mHashTable.end())
{
mHashTable.erase(it);
}
}
return 1;
}
int bdHashSpace::clear()
{
mHashTable.clear();
return 1;
}

View File

@ -1,85 +0,0 @@
/*******************************************************************************
* bitdht/bdhash.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_HASH_SPACE_H
#define BITDHT_HASH_SPACE_H
#include "bitdht/bdpeer.h"
#include <list>
#include <string>
#include <map>
#define BITDHT_HASH_ENTRY_ADD 1
#define BITDHT_HASH_ENTRY_DELETE 2
class bdHashEntry
{
public:
bdHashEntry(std::string value, std::string secret, time_t lifetime, time_t store);
std::string mValue;
time_t mStoreTS;
/* These are nice features that OpenDHT had */
std::string mSecret;
time_t mLifetime;
};
class bdHashSet
{
public:
bdHashSet(bdNodeId *id);
int search(std::string key, uint32_t maxAge, std::list<bdHashEntry> &entries);
int modify(std::string key, bdHashEntry *entry, uint32_t modFlags);
int printHashSet(std::ostream &out);
int cleanupHashSet(uint32_t maxAge);
bdNodeId mId;
std::multimap<std::string, bdHashEntry> mEntries;
};
class bdHashSpace
{
public:
bdHashSpace();
/* accessors */
int search(bdNodeId *id, std::string key, uint32_t maxAge, std::list<bdHashEntry> &entries);
int modify(bdNodeId *id, std::string key, bdHashEntry *entry, uint32_t modFlags);
int printHashSpace(std::ostream&);
int cleanHashSpace(bdNodeId *min, bdNodeId *max, time_t maxAge);
int clear();
private:
std::map<bdNodeId, bdHashSet> mHashTable;
};
#endif

View File

@ -1,647 +0,0 @@
/*******************************************************************************
* bitdht/bdhistory.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bitdht/bdhistory.h"
#include "bitdht/bdstddht.h"
#include "bitdht/bdmsgs.h"
#include <set>
#define MIN_RESEND_PERIOD 60
bdMsgHistoryList::bdMsgHistoryList()
:mPeerVersion("Unknown")
{
return;
}
void bdMsgHistoryList::addMsg(time_t ts, uint32_t msgType, bool incoming, const bdNodeId *aboutId)
{
// std::cerr << "bdMsgHistoryList::addMsg()";
// std::cerr << std::endl;
bdMsgHistoryItem msg(msgType, incoming, aboutId);
msgHistory.insert(std::make_pair(ts, msg));
}
void bdMsgHistoryList::setPeerType(time_t /* ts */, std::string version)
{
mPeerVersion = version;
}
int bdMsgHistoryList::msgCount(time_t start_ts, time_t end_ts)
{
std::multimap<time_t, bdMsgHistoryItem>::iterator sit, eit, it;
sit = msgHistory.lower_bound(start_ts);
eit = msgHistory.upper_bound(end_ts);
int count = 0;
for (it = sit; it != eit; it++, count++) ; // empty loop.
return count;
}
bool bdMsgHistoryList::msgClear(time_t before)
{
if (before == 0)
{
msgHistory.clear();
return true;
}
// Delete the old stuff in the list.
while((msgHistory.begin() != msgHistory.end()) && (msgHistory.begin()->first < before))
{
msgHistory.erase(msgHistory.begin());
}
// return true if empty.
if (msgHistory.begin() == msgHistory.end())
{
return true;
}
return false;
}
void bdMsgHistoryList::msgClear()
{
msgHistory.clear();
}
void bdMsgHistoryList::clearHistory()
{
msgClear();
}
void bdMsgHistoryList::printHistory(std::ostream &out, int mode, time_t start_ts, time_t end_ts)
{
//out << "AGE: MSGS => incoming, <= outgoing" << std::endl;
std::multimap<time_t, bdMsgHistoryItem>::iterator sit, eit, it;
sit = msgHistory.lower_bound(start_ts);
eit = msgHistory.upper_bound(end_ts);
time_t curr_ts = 0;
bool time_changed = false;
bool first_line = true;
for(it = sit; it != eit; it++)
{
time_changed = false;
if (curr_ts != it->first)
{
curr_ts = it->first;
time_changed = true;
}
switch(mode)
{
default:
{
/* print one line per ts */
if (time_changed)
{
if (!first_line)
{
/* finish existing line */
out << " " << std::endl;
}
else
{
first_line = false;
}
out << "\tTS: " << time(NULL) - curr_ts << " ";
}
std::string name;
bitdht_msgtype(it->second.msgType, name);
if (it->second.incoming)
{
out << "( =I> ";
}
else
{
out << "( <O= ";
}
out << name << " ";
if ((it->second.aboutId.data[0] == 0)
&& (it->second.aboutId.data[3] == 0)
&& (it->second.aboutId.data[3] == 0)
&& (it->second.aboutId.data[3] == 0))
{
/* don't print anything */
}
else
{
bdStdPrintNodeId(out, &(it->second.aboutId));
}
out << " )";
}
break;
} // end of switch.
}
/* finish up last line */
if (!first_line)
{
out << " " << std::endl;
}
}
bool bdMsgHistoryList::canSend()
{
std::cerr << "bdMsgHistoryList::canSend()";
std::multimap<time_t, bdMsgHistoryItem>::reverse_iterator rit;
rit = msgHistory.rbegin();
if (rit != msgHistory.rend())
{
time_t now = time(NULL);
if (now - rit->first > MIN_RESEND_PERIOD)
{
std::cerr << " OVER RESEND_PERIOD... true";
std::cerr << std::endl;
return true;
}
}
if (msgHistory.size() % 2 == 0)
{
std::cerr << " SIZE: " << msgHistory.size() << " % 2 = 0 ... true";
std::cerr << std::endl;
return true;
}
std::cerr << " false";
std::cerr << std::endl;
return false;
}
bool bdMsgHistoryList::validPeer()
{
std::cerr << "bdMsgHistoryList::validPeer()";
std::multimap<time_t, bdMsgHistoryItem>::iterator it;
for(it = msgHistory.begin(); it != msgHistory.end(); it++)
{
if (it->second.incoming)
{
std::cerr << " Incoming Msg... so validPeer";
std::cerr << std::endl;
return true;
}
}
std::cerr << " false";
std::cerr << std::endl;
return false;
}
#define MAX_PING_PER_MINUTE 2
#define MAX_QUERY_PER_MINUTE 2
bool bdMsgHistoryList::analysePeer()
{
/* analyse and print out details of the peers messages */
bool flagged = false;
//out << "AGE: MSGS => incoming, <= outgoing" << std::endl;
std::multimap<time_t, bdMsgHistoryItem>::iterator sit, eit, it;
sit = msgHistory.begin();
eit = msgHistory.end();
if (sit == eit)
{
// nothing here.
return false;
}
time_t start_ts = sit->first;
time_t end_ts = msgHistory.rbegin()->first; // must exist.
// don't divide by zero.
if (end_ts - start_ts < 60)
{
end_ts = start_ts + 60;
}
/* what do we want to analyse? */
/* if we have sent / recved too many queries or pings */
int in_ping = 0;
int out_ping = 0;
int in_query = 0;
int out_query = 0;
int in_other = 0;
int out_other = 0;
for(it = sit; it != eit; it++)
{
if (it->second.incoming)
{
switch(it->second.msgType)
{
case BITDHT_MSG_TYPE_PING:
in_ping++;
break;
case BITDHT_MSG_TYPE_FIND_NODE:
in_query++;
break;
default:
in_other++;
break;
}
}
else
{
switch(it->second.msgType)
{
case BITDHT_MSG_TYPE_PING:
out_ping++;
break;
case BITDHT_MSG_TYPE_FIND_NODE:
out_query++;
break;
default:
out_other++;
break;
}
}
}
float in_ping_per_min = in_ping * 60.0 / (end_ts - start_ts);
float out_ping_per_min = out_ping * 60.0 / (end_ts - start_ts);
float in_query_per_min = in_query * 60.0 / (end_ts - start_ts);
float out_query_per_min = out_query * 60.0 / (end_ts - start_ts);
if ((in_ping_per_min > MAX_PING_PER_MINUTE) ||
(out_ping_per_min > MAX_PING_PER_MINUTE) ||
(in_query_per_min > MAX_PING_PER_MINUTE) ||
(out_query_per_min > MAX_PING_PER_MINUTE))
{
flagged = true;
}
if (flagged)
{
/* print header */
std::ostream &out = std::cerr;
out << "BdHistoryAnalysis has flagged peer: ";
bdStdPrintId(out, &mId);
out << std::endl;
out << "PeerType: " << mPeerVersion;
out << std::endl;
out << "Ping In Per Min : " << in_ping_per_min << std::endl;
out << "Ping Out Per Min : " << out_ping_per_min << std::endl;
out << "Query In Per Min : " << in_query_per_min << std::endl;
out << "Query Out Per Min: " << out_query_per_min << std::endl;
out << "Message History: ";
out << std::endl;
printHistory(out, 0, 0, time(NULL));
}
return true;
}
bdHistory::bdHistory(time_t store_period)
:mStorePeriod(store_period) { return; }
void bdHistory::addMsg(const bdId *id, bdToken * /*transId*/, uint32_t msgType, bool incoming, const bdNodeId *aboutId)
{
//std::cerr << "bdHistory::addMsg() ";
//bdStdPrintId(std::cerr, id);
//std::cerr << std::endl;
time_t now = time(NULL);
std::map<bdId, bdMsgHistoryList>::iterator it;
bdMsgHistoryList &histRef = mHistory[*id]; /* will instaniate empty */
histRef.mId = *id;
histRef.addMsg(now, msgType, incoming, aboutId);
/* add to mMsgTimeline */
mMsgTimeline.insert(std::make_pair(now, MsgRegister(id, msgType, incoming, aboutId)));
}
void bdHistory::setPeerType(const bdId *id, std::string version)
{
std::map<bdId, bdMsgHistoryList>::iterator it;
bdMsgHistoryList &histRef = mHistory[*id]; /* will instaniate empty */
histRef.setPeerType(time(NULL), version);
}
void bdHistory::printMsgs()
{
/* print and clear msgs */
std::ostream &out = std::cerr;
std::cerr << "bdHistory::printMsgs()";
std::cerr << std::endl;
std::map<bdId, bdMsgHistoryList> ::iterator it;
for(it = mHistory.begin(); it != mHistory.end(); it++)
{
if (it->second.msgCount(0, time(NULL))) // all msg count.
{
/* print header */
out << "Msgs for ";
bdStdPrintId(out, &(it->first));
out << " v:" << it->second.mPeerVersion;
out << std::endl;
it->second.printHistory(out, 0, 0, time(NULL));
}
}
out << "Msg Timeline:";
time_t now = time(NULL);
std::multimap<time_t, MsgRegister>::iterator hit;
for(hit = mMsgTimeline.begin(); hit != mMsgTimeline.end(); hit++)
{
out << now - hit->first << " ";
bdStdPrintId(out, &(hit->second.id));
if (hit->second.incoming)
{
out << " =I> ";
}
else
{
out << " <O= ";
}
std::string name;
if (bitdht_msgtype(hit->second.msgType, name))
{
out << name;
}
else
{
out << "UNKNOWN MSG";
}
out << std::endl;
}
}
void bdHistory::cleanupOldMsgs()
{
std::cerr << "bdHistory::cleanupOldMsgs()";
std::cerr << std::endl;
if (mStorePeriod == 0)
{
return; // no cleanup
}
std::set<bdId> to_cleanup;
std::set<bdId>::iterator cit;
time_t before = time(NULL) - mStorePeriod;
// Delete the old stuff in the list.
while((mMsgTimeline.begin() != mMsgTimeline.end()) && (mMsgTimeline.begin()->first < before))
{
std::multimap<time_t, MsgRegister>::iterator it = mMsgTimeline.begin();
to_cleanup.insert(it->second.id);
mMsgTimeline.erase(it);
}
// remove old msgs, delete entry if its empty.
std::map<bdId, bdMsgHistoryList>::iterator hit;
for(cit = to_cleanup.begin(); cit != to_cleanup.end(); cit++)
{
hit = mHistory.find(*cit);
if (hit != mHistory.end())
{
if (hit->second.msgClear(before))
{
// don't erase actual entry (so we remember peer type).
//mHistory.erase(hit);
}
}
}
}
void bdHistory::clearHistory()
{
// Switched to a alternative clear, so we don't drop peers, and remember their type.
//mHistory.clear();
std::map<bdId, bdMsgHistoryList> ::iterator it;
for(it = mHistory.begin(); it != mHistory.end(); it++)
{
it->second.clearHistory();
}
}
bool bdHistory::canSend(const bdId *id)
{
std::map<bdId, bdMsgHistoryList> ::iterator it;
it = mHistory.find(*id);
if (it != mHistory.end())
{
return (it->second.canSend());
}
/* if not found - then can send */
return true;
}
bool bdHistory::validPeer(const bdId *id)
{
std::map<bdId, bdMsgHistoryList> ::iterator it;
it = mHistory.find(*id);
if (it != mHistory.end())
{
return (it->second.validPeer());
}
/* if not found - then can send */
return false;
}
bool bdHistory::analysePeers()
{
std::map<bdId, bdMsgHistoryList> ::iterator it;
for(it = mHistory.begin(); it != mHistory.end(); it++)
{
it->second.analysePeer();
}
return true;
}
/* Temp data class. */
class TypeStats
{
public:
TypeStats() :nodes(0) { return; }
std::map<uint32_t, uint32_t> incoming, outgoing;
int nodes;
void printStats(std::ostream &out, const TypeStats *refStats)
{
std::map<uint32_t, uint32_t>::iterator it;
std::map<uint32_t, uint32_t>::const_iterator rit;
out << " Nodes: " << nodes;
if (refStats)
{
out << " (" << 100.0 * nodes / (float) refStats->nodes << " %)";
}
out << std::endl;
out << " Incoming Msgs";
out << std::endl;
for(it = incoming.begin(); it != incoming.end(); it++)
{
uint32_t count = 0;
if (refStats)
{
rit = refStats->incoming.find(it->first);
if (rit != refStats->incoming.end())
{
count = rit->second;
}
}
printStatsLine(out, it->first, it->second, count);
}
out << " Outgoing Msgs";
out << std::endl;
for(it = outgoing.begin(); it != outgoing.end(); it++)
{
uint32_t count = 0;
if (refStats)
{
rit = refStats->outgoing.find(it->first);
if (rit != refStats->outgoing.end())
{
count = rit->second;
}
}
printStatsLine(out, it->first, it->second, count);
}
}
void printStatsLine(std::ostream &out, uint32_t msgType, uint32_t count, uint32_t global)
{
std::string name;
bitdht_msgtype(msgType, name);
out << "\t" << name << " " << count;
if (global != 0)
{
out << " (" << 100.0 * count / (float) global << " %)";
}
out << std::endl;
}
}; /* end of TypeStats */
bool bdHistory::peerTypeAnalysis()
{
std::map<std::string, TypeStats> mTypeStats;
TypeStats globalStats;
std::map<bdId, bdMsgHistoryList> ::iterator it;
for(it = mHistory.begin(); it != mHistory.end(); it++)
{
if (it->second.msgHistory.empty())
{
continue;
}
std::string version = it->second.mPeerVersion;
// group be first two bytes.
version = it->second.mPeerVersion.substr(0,2);
TypeStats &stats = mTypeStats[version];
stats.nodes++;
globalStats.nodes++;
std::multimap<time_t, bdMsgHistoryItem>::iterator lit;
for (lit = it->second.msgHistory.begin(); lit != it->second.msgHistory.end(); lit++)
{
if (lit->second.incoming)
{
stats.incoming[lit->second.msgType]++;
globalStats.incoming[lit->second.msgType]++;
}
else
{
stats.outgoing[lit->second.msgType]++;
globalStats.outgoing[lit->second.msgType]++;
}
}
}
std::map<std::string, TypeStats>::iterator tit;
for(tit = mTypeStats.begin(); tit != mTypeStats.end(); tit++)
{
std::cerr << "Stats for Peer Type: " << tit->first;
std::cerr << std::endl;
tit->second.printStats(std::cerr, &globalStats);
}
std::cerr << "Global Stats: ";
std::cerr << std::endl;
globalStats.printStats(std::cerr, NULL);
return true;
}

View File

@ -1,147 +0,0 @@
/*******************************************************************************
* bitdht/bdhistory.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_HISTORY_H
#define BITDHT_HISTORY_H
#include "bitdht/bdpeer.h"
#include "bitdht/bdobj.h"
#include "bitdht/bdstddht.h"
#include <map>
#define MSG_TYPE_DIRECTION_MASK 0x000f0000
#define MSG_DIRECTION_INCOMING 0x00010000
#define MSG_DIRECTION_OUTGOING 0x00020000
/**** DEBUGGING HISTORY ****/
class MsgRegister
{
public:
MsgRegister() { return; }
MsgRegister(const bdId *inId, uint32_t inMsgType, bool inIncoming, const bdNodeId *inAboutId)
:id(*inId), msgType(inMsgType), incoming(inIncoming)
{
if (inAboutId)
{
aboutId = *inAboutId;
}
else
{
bdStdZeroNodeId(&aboutId);
}
return;
}
bdId id;
uint32_t msgType;
bool incoming;
bdNodeId aboutId; // filled in for queries.
};
class bdMsgHistoryItem
{
public:
bdMsgHistoryItem()
:msgType(0), incoming(false)
{
bdStdZeroNodeId(&aboutId);
return;
}
bdMsgHistoryItem(uint32_t inMsgType, bool inIncoming, const bdNodeId *inAboutId)
:msgType(inMsgType), incoming(inIncoming)
{
if (inAboutId)
{
aboutId = *inAboutId;
}
else
{
bdStdZeroNodeId(&aboutId);
}
return;
}
uint32_t msgType;
bool incoming;
bdNodeId aboutId; // filled in for queries.
};
class bdMsgHistoryList
{
public:
bdMsgHistoryList();
void addMsg(time_t ts, uint32_t msgType, bool incoming, const bdNodeId *aboutId);
void setPeerType(time_t ts, std::string version);
int msgCount(time_t start_ts, time_t end_ts);
bool msgClear(time_t before); // 0 => clear all.
void msgClear();
void printHistory(std::ostream &out, int mode, time_t start_ts, time_t end_ts);
bool analysePeer();
void clearHistory();
bool canSend();
bool validPeer();
std::multimap<time_t, bdMsgHistoryItem> msgHistory;
std::string mPeerVersion;
bdId mId;
};
class bdHistory
{
public:
bdHistory(time_t store_period);
void addMsg(const bdId *id, bdToken *transId, uint32_t msgType, bool incoming, const bdNodeId *aboutId);
void setPeerType(const bdId *id, std::string version);
void printMsgs();
void cleanupOldMsgs();
void clearHistory();
bool analysePeers();
bool peerTypeAnalysis();
bool canSend(const bdId *id);
bool validPeer(const bdId *id);
/* recent history */
//std::list<bdId> lastMsgs;
std::map<bdId, bdMsgHistoryList> mHistory;
std::multimap<time_t, MsgRegister> mMsgTimeline;
int mStorePeriod;
};
#endif

View File

@ -1,413 +0,0 @@
/*******************************************************************************
* bitdht/bdiface.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BIT_DHT_INTERFACE_H
#define BIT_DHT_INTERFACE_H
#include <iosfwd>
#include <map>
#include <string>
#include <list>
#include <inttypes.h>
#include "util/bdnet.h"
/*
* Functions and Classes required for Interfacing with the BitDht.
* This should be the sole header file required to talk to Dht.
* ... though setting it up will require including udpbitdht.h as well.
*
*/
#define BITDHT_KEY_LEN 20
#define BITDHT_KEY_INTLEN 5
#define BITDHT_KEY_BITLEN 160
#define BITDHT_MAX_PKTSIZE 1024
#define BITDHT_TTL 64
#define BITDHT_SEARCH_ONE_SHOT 1
#define BITDHT_SEARCH_REPEATING 2
class bdNodeId
{
public:
unsigned char data[BITDHT_KEY_LEN];
};
class bdMetric: public bdNodeId {};
class bdId
{
public:
bdId();
bdId(bdNodeId in_id, struct sockaddr_in in_addr);
struct sockaddr_in addr;
bdNodeId id;
};
#define BITDHT_LIKELY_SAME_NO 0x00000000
#define BITDHT_LIKELY_SAME_YES 0x00000001
#define BITDHT_LIKELY_SAME_PORT_CHANGED 0x00000002
#define BITDHT_LIKELY_SAME_LOC_CHANGED 0x00000004
#define BITDHT_LIKELY_SAME_IDENTICAL 0x00000008
class bdDhtFunctions
{
public:
// bdDhtFunctions();
/* setup variables */
virtual uint16_t bdNumBuckets() = 0;
virtual uint16_t bdNodesPerBucket() = 0; /* used for bdspace */
virtual uint16_t bdNumQueryNodes() = 0; /* used for queries */
virtual uint16_t bdBucketBitSize() = 0;
virtual int bdDistance(const bdNodeId *n1, const bdNodeId *n2, bdMetric *metric) = 0;
virtual int bdBucketDistance(const bdNodeId *n1, const bdNodeId *n2) = 0;
virtual int bdBucketDistance(const bdMetric *metric) = 0;
virtual bool bdSimilarId(const bdId *id1, const bdId *id2) = 0;
virtual bool bdUpdateSimilarId(bdId *dest, const bdId *src) = 0;
virtual void bdRandomMidId(const bdNodeId *target, const bdNodeId *other, bdNodeId *mid) = 0;
virtual void bdPrintId(std::ostream &out, const bdId *a) = 0;
virtual void bdPrintNodeId(std::ostream &out, const bdNodeId *a) = 0;
};
// DHT MODES
#define BITDHT_MODE_TRAFFIC_MASK 0x00000f00
#define BITDHT_MODE_RELAYSERVER_MASK 0x0000f000
// These are not ORd - only one can apply.
#define BITDHT_MODE_TRAFFIC_HIGH 0x00000100
#define BITDHT_MODE_TRAFFIC_MED 0x00000200
#define BITDHT_MODE_TRAFFIC_LOW 0x00000300
#define BITDHT_MODE_TRAFFIC_TRICKLE 0x00000400
#define BITDHT_MODE_TRAFFIC_DEFAULT BITDHT_MODE_TRAFFIC_LOW
// These are not ORd - only one can apply.
#define BITDHT_MODE_RELAYSERVERS_IGNORED 0x00001000
#define BITDHT_MODE_RELAYSERVERS_FLAGGED 0x00002000
#define BITDHT_MODE_RELAYSERVERS_ONLY 0x00003000
#define BITDHT_MODE_RELAYSERVERS_SERVER 0x00004000
/* NODE OPTIONS */
#define BITDHT_OPTIONS_MAINTAIN_UNSTABLE_PORT 0x00000001
#define BITDHT_OPTIONS_ENABLE_RELAYS 0x00000002
/* peer flags
* order is important!
* higher bits = more priority.
* BITDHT_PEER_STATUS_RECVPING
* BITDHT_PEER_STATUS_RECVPONG
* BITDHT_PEER_STATUS_RECVNODES
* BITDHT_PEER_STATUS_RECVHASHES
* BITDHT_PEER_STATUS_DHT_ENGINE (dbXXxx)
* BITDHT_PEER_STATUS_DHT_APPL (XXRSxx)
* BITDHT_PEER_STATUS_DHT_VERSION (XXxx50)
*
*/
#define BITDHT_PEER_STATUS_MASK_RECVD 0x000000ff
#define BITDHT_PEER_STATUS_MASK_DHT 0x0000ff00
#define BITDHT_PEER_STATUS_MASK_KNOWN 0x00ff0000
#define BITDHT_PEER_STATUS_RECV_PING 0x00000001
#define BITDHT_PEER_STATUS_RECV_PONG 0x00000002
#define BITDHT_PEER_STATUS_RECV_NODES 0x00000004
#define BITDHT_PEER_STATUS_RECV_HASHES 0x00000008
#define BITDHT_PEER_STATUS_RECV_CONNECT_MSG 0x00000010
#define BITDHT_PEER_STATUS_DHT_ENGINE 0x00000100
#define BITDHT_PEER_STATUS_DHT_ENGINE_VERSION 0x00000200
#define BITDHT_PEER_STATUS_DHT_APPL 0x00000400
#define BITDHT_PEER_STATUS_DHT_APPL_VERSION 0x00000800
#define BITDHT_PEER_STATUS_DHT_WHITELIST 0x00010000
#define BITDHT_PEER_STATUS_DHT_FOF 0x00020000
#define BITDHT_PEER_STATUS_DHT_FRIEND 0x00040000
#define BITDHT_PEER_STATUS_DHT_RELAY_SERVER 0x00080000 // (Flag must be enabled)
#define BITDHT_PEER_STATUS_DHT_SELF 0x00100000
// EXTRA FLAGS are our internal thoughts about the peer.
#define BITDHT_PEER_EXFLAG_MASK_BASIC 0x000000ff
#define BITDHT_PEER_EXFLAG_UNSTABLE 0x00000001 // Port changes.
#define BITDHT_PEER_EXFLAG_ATTACHED 0x00000002 // We will ping in heavily. (if unstable)
#define BITDHT_PEER_EXFLAG_BADPEER 0x00000004 // For testing, we flag rather than discard.
#define BITDHT_CONNECT_MODE_DIRECT 0x00000001
#define BITDHT_CONNECT_MODE_PROXY 0x00000002
#define BITDHT_CONNECT_MODE_RELAY 0x00000004
#define BITDHT_CONNECT_OPTION_AUTOPROXY 0x00000001
// STATUS CODES. == 0 is okay, != 0 is error.
#define BITDHT_CONNECT_ANSWER_OKAY 0x00000000
#define BITDHT_CONNECT_ERROR_NONE (BITDHT_CONNECT_ANSWER_OKAY)
#define BITDHT_CONNECT_ERROR_MASK_TYPE 0x0000ffff
#define BITDHT_CONNECT_ERROR_MASK_SOURCE 0x00ff0000
#define BITDHT_CONNECT_ERROR_MASK_CRMOVE 0xff000000
#define BITDHT_CONNECT_ERROR_SOURCE_START 0x00010000
#define BITDHT_CONNECT_ERROR_SOURCE_MID 0x00020000
#define BITDHT_CONNECT_ERROR_SOURCE_END 0x00040000
#define BITDHT_CONNECT_ERROR_SOURCE_OTHER 0x00080000
#define BITDHT_CONNECT_ERROR_CRMOVE_FATAL 0x01000000
#define BITDHT_CONNECT_ERROR_CRMOVE_NOMOREIDS 0x02000000
#define BITDHT_CONNECT_ERROR_CRMOVE_NEXTID 0x04000000
#define BITDHT_CONNECT_ERROR_CRMOVE_PAUSED 0x08000000
// ERROR CODES.
#define BITDHT_CONNECT_ERROR_GENERIC 0x00000001
#define BITDHT_CONNECT_ERROR_PROTOCOL 0x00000002
#define BITDHT_CONNECT_ERROR_TIMEOUT 0x00000003
#define BITDHT_CONNECT_ERROR_TEMPUNAVAIL 0x00000004 // Haven't got ext address yet.
#define BITDHT_CONNECT_ERROR_NOADDRESS 0x00000005 // Can't find the peer in tables.
#define BITDHT_CONNECT_ERROR_UNREACHABLE 0x00000006 // Symmetric NAT
#define BITDHT_CONNECT_ERROR_UNSUPPORTED 0x00000007
#define BITDHT_CONNECT_ERROR_OVERLOADED 0x00000008
#define BITDHT_CONNECT_ERROR_AUTH_DENIED 0x00000009
#define BITDHT_CONNECT_ERROR_DUPLICATE 0x0000000a
// These are slightly special ones used for CB_REQUEST
#define BITDHT_CONNECT_ERROR_TOOMANYRETRY 0x0000000b
#define BITDHT_CONNECT_ERROR_OUTOFPROXY 0x0000000c
#define BITDHT_CONNECT_ERROR_USER 0x0000000d
/*************/
// FRIEND_ENTRY_FLAGS... used by updateKnownPeers().
#define BD_FRIEND_ENTRY_ONLINE 0x0001
#define BD_FRIEND_ENTRY_ADDR_OK 0x0002
#define BD_FRIEND_ENTRY_WHITELIST BITDHT_PEER_STATUS_DHT_WHITELIST
#define BD_FRIEND_ENTRY_FOF BITDHT_PEER_STATUS_DHT_FOF
#define BD_FRIEND_ENTRY_FRIEND BITDHT_PEER_STATUS_DHT_FRIEND
#define BD_FRIEND_ENTRY_RELAY_SERVER BITDHT_PEER_STATUS_DHT_RELAY_SERVER
#define BD_FRIEND_ENTRY_SELF BITDHT_PEER_STATUS_DHT_SELF
#define BD_FRIEND_ENTRY_MASK_KNOWN BITDHT_PEER_STATUS_MASK_KNOWN
/* Definitions of bdSpace Peer and Bucket are publically available,
* so we can expose the bucket entries for the gui.
*/
class bdPeer
{
public:
bdPeer():mPeerFlags(0), mLastSendTime(0), mLastRecvTime(0), mFoundTime(0), mExtraFlags(0) { return; }
bdId mPeerId;
uint32_t mPeerFlags;
time_t mLastSendTime;
time_t mLastRecvTime;
time_t mFoundTime; /* time stamp that peer was found */
uint32_t mExtraFlags;
};
class bdBucket
{
public:
bdBucket();
/* list so we can queue properly */
std::list<bdPeer> entries;
};
class bdQueryStatus
{
public:
uint32_t mStatus;
uint32_t mQFlags;
std::list<bdId> mResults;
};
class bdQuerySummary
{
public:
bdNodeId mId;
bdMetric mLimit;
uint32_t mState;
time_t mQueryTS;
uint32_t mQueryFlags;
int32_t mSearchTime;
int32_t mQueryIdlePeerRetryPeriod; // seconds between retries.
// closest peers
std::multimap<bdMetric, bdPeer> mClosest;
std::multimap<bdMetric, bdPeer> mPotentialPeers;
std::list<bdPeer> mProxiesUnknown;
std::list<bdPeer> mProxiesFlagged;
};
/* Status options */
#define BITDHT_QUERY_READY 1
#define BITDHT_QUERY_QUERYING 2
#define BITDHT_QUERY_FAILURE 3
#define BITDHT_QUERY_FOUND_CLOSEST 4
#define BITDHT_QUERY_PEER_UNREACHABLE 5
#define BITDHT_QUERY_SUCCESS 6
/* Query Flags */
#define BITDHT_QFLAGS_NONE 0x0000
#define BITDHT_QFLAGS_DISGUISE 0x0001 // Don't search directly for target.
#define BITDHT_QFLAGS_DO_IDLE 0x0002
#define BITDHT_QFLAGS_INTERNAL 0x0004 // runs through startup. (limited callback)
#define BITDHT_QFLAGS_UPDATES 0x0008 // Do regular updates.
/* Connect Callback Flags */
#define BITDHT_CONNECT_CB_AUTH 1
#define BITDHT_CONNECT_CB_PENDING 2
#define BITDHT_CONNECT_CB_START 3
#define BITDHT_CONNECT_CB_PROXY 4
#define BITDHT_CONNECT_CB_FAILED 5
#define BITDHT_CONNECT_CB_REQUEST 6
#define BD_PROXY_CONNECTION_UNKNOWN_POINT 0
#define BD_PROXY_CONNECTION_START_POINT 1
#define BD_PROXY_CONNECTION_MID_POINT 2
#define BD_PROXY_CONNECTION_END_POINT 3
#define BITDHT_INFO_CB_TYPE_BADPEER 1
/* Relay Modes */
#define BITDHT_RELAYS_OFF 0
#define BITDHT_RELAYS_ON 1
#define BITDHT_RELAYS_ONLY 2
#define BITDHT_RELAYS_SERVER 3
class BitDhtCallback
{
public:
// ~BitDhtCallback();
// dummy cos not needed for standard dht behaviour;
virtual int dhtNodeCallback(const bdId * /*id*/, uint32_t /*peerflags*/) { return 0; }
// must be implemented.
virtual int dhtPeerCallback(const bdId *id, uint32_t status) = 0;
virtual int dhtValueCallback(const bdNodeId *id, std::string key, uint32_t status) = 0;
// connection callback. Not required for basic behaviour, but forced for initial development.
virtual int dhtConnectCallback(const bdId *srcId, const bdId *proxyId, const bdId *destId,
uint32_t mode, uint32_t point, uint32_t param, uint32_t cbtype, uint32_t errcode) = 0; /* { return 0; } */
// Generic Info callback - initially will be used to provide bad peers.
virtual int dhtInfoCallback(const bdId *id, uint32_t type, uint32_t flags, std::string info) = 0;
// ask upper layer whether an IP is banned or not
// must not be implemented
// when set it will be used instead of the own ban list
// return code is used to express availability/absence
virtual int dhtIsBannedCallback(const sockaddr_in */*addr*/, bool */*isBanned*/) { return 0;}
};
class BitDhtInterface
{
public:
/* bad peer notification */
virtual void addBadPeer(const struct sockaddr_in &addr, uint32_t source, uint32_t reason, uint32_t age) = 0;
/* Friend Tracking */
virtual void updateKnownPeer(const bdId *id, uint32_t type, uint32_t flags) = 0;
/***** Request Lookup (DHT Peer & Keyword) *****/
virtual void addFindNode(bdNodeId *id, uint32_t mode) = 0;
virtual void removeFindNode(bdNodeId *id) = 0;
virtual void findDhtValue(bdNodeId *id, std::string key, uint32_t mode) = 0;
/***** Connections Requests *****/
virtual bool ConnectionRequest(struct sockaddr_in *laddr, bdNodeId *target, uint32_t mode, uint32_t delay, uint32_t start) = 0;
virtual void ConnectionAuth(bdId *srcId, bdId *proxyId, bdId *destId, uint32_t mode, uint32_t loc,
uint32_t bandwidth, uint32_t delay, uint32_t answer) = 0;
virtual void ConnectionOptions(uint32_t allowedModes, uint32_t flags) = 0;
virtual bool setAttachMode(bool on) = 0;
/***** Add / Remove Callback Clients *****/
virtual void addCallback(BitDhtCallback *cb) = 0;
virtual void removeCallback(BitDhtCallback *cb) = 0;
/***** Get Results Details *****/
virtual int getDhtPeerAddress(const bdNodeId *id, struct sockaddr_in &from) = 0;
virtual int getDhtValue(const bdNodeId *id, std::string key, std::string &value) = 0;
virtual int getDhtBucket(const int idx, bdBucket &bucket) = 0;
virtual int getDhtQueries(std::map<bdNodeId, bdQueryStatus> &queries) = 0;
virtual int getDhtQueryStatus(const bdNodeId *id, bdQuerySummary &query) = 0;
/* stats and Dht state */
virtual int startDht() = 0;
virtual int stopDht() = 0;
virtual int stateDht() = 0; /* STOPPED, STARTING, ACTIVE, FAILED */
virtual uint32_t statsNetworkSize() = 0;
virtual uint32_t statsBDVersionSize() = 0; /* same version as us! */
virtual uint32_t setDhtMode(uint32_t dhtFlags) = 0;
};
// general helper functions for decoding error messages.
std::string decodeConnectionError(uint32_t errcode);
std::string decodeConnectionErrorCRMove(uint32_t errcode);
std::string decodeConnectionErrorSource(uint32_t errcode);
std::string decodeConnectionErrorType(uint32_t errcode);
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,209 +0,0 @@
/*******************************************************************************
* bitdht/bdmanager.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_MANAGER_H
#define BITDHT_MANAGER_H
/*******
* Node Manager.
******/
/******************************************
* 1) Maintains a list of ids to search for.
* 2) Sets up initial search for own node.
* 3) Checks on status of queries.
* 4) Callback on successful searches.
*
* This is pretty specific to RS requirements.
****/
#define BITDHT_PS_MASK_ACTIONS (0x000000ff)
#define BITDHT_PS_MASK_STATE (0x0000ff00)
#define BITDHT_PS_ACTION_SEARCHING (0x00000001)
#define BITDHT_PS_ACTION_WAITING (0x00000002)
#define BITDHT_PS_ACTION_PINGING (0x00000004)
#define BITDHT_PS_STATE_UNKNOWN (0x00000100)
#define BITDHT_PS_STATE_OFFLINE (0x00000200)
#define BITDHT_PS_STATE_ONLINE (0x00000400)
#define BITDHT_PS_STATE_CONNECTED (0x00000800)
#include "bitdht/bdiface.h"
#include "bitdht/bdnode.h"
#include "util/bdbloom.h"
class bdQueryPeer
{
public:
bdId mId;
uint32_t mStatus;
uint32_t mQFlags;
//time_t mLastQuery;
//time_t mLastFound;
struct sockaddr_in mDhtAddr;
time_t mCallbackTS; // for UPDATES flag.
};
#define BITDHT_MGR_STATE_OFF 0
#define BITDHT_MGR_STATE_STARTUP 1
#define BITDHT_MGR_STATE_FINDSELF 2
#define BITDHT_MGR_STATE_ACTIVE 3
#define BITDHT_MGR_STATE_REFRESH 4
#define BITDHT_MGR_STATE_QUIET 5
#define BITDHT_MGR_STATE_FAILED 6
#define MAX_STARTUP_TIME 10
#define MAX_REFRESH_TIME 10
#define BITDHT_MGR_QUERY_FAILURE 1
#define BITDHT_MGR_QUERY_PEER_OFFLINE 2
#define BITDHT_MGR_QUERY_PEER_UNREACHABLE 3
#define BITDHT_MGR_QUERY_PEER_ONLINE 4
/*** NB: Nothing in here is protected by mutexes
* must be done at a higher level!
***/
class bdNodeManager: public bdNode, public BitDhtInterface
{
public:
bdNodeManager(bdNodeId *id, std::string dhtVersion, std::string bootfile, std::string bootfilebak, const std::string &filterfile, bdDhtFunctions *fns);
void iteration();
/***** Functions to Call down to bdNodeManager ****/
/* Friend Tracking */
virtual void addBadPeer(const struct sockaddr_in &addr, uint32_t source, uint32_t reason, uint32_t age);
virtual void updateKnownPeer(const bdId *id, uint32_t type, uint32_t flags);
/* Request DHT Peer Lookup */
/* Request Keyword Lookup */
virtual void addFindNode(bdNodeId *id, uint32_t mode);
virtual void removeFindNode(bdNodeId *id);
virtual void findDhtValue(bdNodeId *id, std::string key, uint32_t mode);
/***** Add / Remove Callback Clients *****/
virtual void addCallback(BitDhtCallback *cb);
virtual void removeCallback(BitDhtCallback *cb);
/***** Get Results Details *****/
virtual int getDhtPeerAddress(const bdNodeId *id, struct sockaddr_in &from);
virtual int getDhtValue(const bdNodeId *id, std::string key, std::string &value);
virtual int getDhtBucket(const int idx, bdBucket &bucket);
virtual int getDhtQueries(std::map<bdNodeId, bdQueryStatus> &queries);
virtual int getDhtQueryStatus(const bdNodeId *id, bdQuerySummary &query);
/***** Connection Interface ****/
virtual bool ConnectionRequest(struct sockaddr_in *laddr, bdNodeId *target, uint32_t mode, uint32_t delay, uint32_t start);
virtual void ConnectionAuth(bdId *srcId, bdId *proxyId, bdId *destId,
uint32_t mode, uint32_t loc, uint32_t bandwidth, uint32_t delay, uint32_t answer);
virtual void ConnectionOptions(uint32_t allowedModes, uint32_t flags);
virtual bool setAttachMode(bool on);
/* stats and Dht state */
virtual int startDht();
virtual int stopDht();
virtual int stateDht(); /* STOPPED, STARTING, ACTIVE, FAILED */
virtual uint32_t statsNetworkSize();
virtual uint32_t statsBDVersionSize(); /* same version as us! */
virtual uint32_t setDhtMode(uint32_t dhtFlags);
/******************* Internals *************************/
// Overloaded from bdnode for external node callback.
virtual void addPeer(const bdId *id, uint32_t peerflags);
// Overloaded from bdnode for external node callback.
virtual void callbackConnect(bdId *srcId, bdId *proxyId, bdId *destId,
int mode, int point, int param, int cbtype, int errcode);
int isBitDhtPacket(char *data, int size, struct sockaddr_in &from);
// this function is used by bdFilter (must be public!)
void doIsBannedCallback(const sockaddr_in *addr, bool *isAvailable, bool* isBanned);
private:
void doNodeCallback(const bdId *id, uint32_t peerflags);
void doPeerCallback(const bdId *id, uint32_t status);
void doValueCallback(const bdNodeId *id, std::string key, uint32_t status);
void doInfoCallback(const bdId *id, uint32_t type, uint32_t flags, std::string info);
int status();
int checkStatus();
int checkPingStatus();
int checkBadPeerStatus();
int SearchOutOfDate();
void startQueries();
int QueryRandomLocalNet();
void SearchForLocalNet();
std::map<bdNodeId, bdQueryPeer> mActivePeers;
std::list<BitDhtCallback *> mCallbacks;
uint32_t mMode;
time_t mModeTS;
time_t mStartTS;
time_t mSearchTS;
bool mSearchingDone;
bdDhtFunctions *mDhtFns;
uint32_t mNetworkSize;
uint32_t mBdNetworkSize;
bdBloom mBloomFilter;
bool mLocalNetEnhancements;
/* future node functions */
//addPeerPing(foundId);
//clearPing(it->first);
//PingStatus(it->first);
};
class bdDebugCallback: public BitDhtCallback
{
public:
~bdDebugCallback();
virtual int dhtPeerCallback(const bdId *id, uint32_t status);
virtual int dhtValueCallback(const bdNodeId *id, std::string key, uint32_t status);
virtual int dhtConnectCallback(const bdId *srcId, const bdId *proxyId, const bdId *destId,
uint32_t mode, uint32_t point, uint32_t param, uint32_t cbtype, uint32_t errcode);
virtual int dhtInfoCallback(const bdId *id, uint32_t type, uint32_t flags, std::string info);
};
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,127 +0,0 @@
/*******************************************************************************
* bitdht/bdmsgs.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_MSGS_H
#define BITDHT_MSGS_H
#include <stdio.h>
#include <inttypes.h>
#include <list>
#include "bitdht/bencode.h"
#include "bitdht/bdobj.h"
#include "bitdht/bdpeer.h"
#define BITDHT_MSG_TYPE_UNKNOWN 0
#define BITDHT_MSG_TYPE_PING 1
#define BITDHT_MSG_TYPE_PONG 2
#define BITDHT_MSG_TYPE_FIND_NODE 3
#define BITDHT_MSG_TYPE_REPLY_NODE 4
#define BITDHT_MSG_TYPE_GET_HASH 5
#define BITDHT_MSG_TYPE_REPLY_HASH 6
#define BITDHT_MSG_TYPE_REPLY_NEAR 7
#define BITDHT_MSG_TYPE_POST_HASH 8
#define BITDHT_MSG_TYPE_REPLY_POST 9
// THESE ARE EXTENSIONS
#define BITDHT_MSG_TYPE_CONNECT 20
// CONNECTIONS.
#define BITDHT_MSG_TYPE_CONNECT_REQUEST 101
#define BITDHT_MSG_TYPE_CONNECT_REPLY 102
#define BITDHT_MSG_TYPE_CONNECT_START 103
#define BITDHT_MSG_TYPE_CONNECT_ACK 104
// FANCY HASHES.
#define BITDHT_COMPACTNODEID_LEN 26
#define BITDHT_COMPACTPEERID_LEN 6
#define BE_Y_UNKNOWN 0
#define BE_Y_R 1
#define BE_Y_Q 2
/****** Known BD Version Strings ******/
#define BITDHT_VID_RS1 1
#define BITDHT_VID_UT 2
int bitdht_create_ping_msg(bdToken *tid, bdNodeId *id, bdToken *vid, char *msg, int avail);
int bitdht_response_ping_msg(bdToken *tid, bdNodeId *id, bdToken *vid, char *msg, int avail);
int bitdht_find_node_msg(bdToken *tid, bdNodeId *id, bdNodeId *target, bool localnet, char *msg, int avail);
int bitdht_resp_node_msg(bdToken *tid, bdNodeId *id, std::list<bdId> &nodes,
char *msg, int avail);
int bitdht_get_peers_msg(bdToken *tid, bdNodeId *id, bdNodeId *info_hash,
char *msg, int avail);
int bitdht_peers_reply_hash_msg(bdToken *tid, bdNodeId *id,
bdToken *token, std::list<std::string> &values,
char *msg, int avail);
int bitdht_peers_reply_closest_msg(bdToken *tid, bdNodeId *id,
bdToken *token, std::list<bdId> &nodes,
char *msg, int avail);
int bitdht_announce_peers_msg(bdToken *tid, bdNodeId *id, bdNodeId *info_hash,
uint32_t port, bdToken *token, char *msg, int avail);
int bitdht_reply_announce_msg(bdToken *tid, bdNodeId *id,
char *msg, int avail);
// Extensions.
int bitdht_connect_genmsg(bdToken *tid, bdNodeId *id, int msgtype, bdId *src, bdId *dest, int mode, int param, int status, char *msg, int avail);
//int response_peers_message()
//int response_closestnodes_message()
be_node *beMsgGetDictNode(be_node *node, const char *key);
int beMsgMatchString(be_node *n, const char *str, int len);
uint32_t beMsgGetY(be_node *n);
uint32_t beMsgType(be_node *n);
bool bitdht_msgtype(uint32_t msg_type, std::string &name);
uint32_t convertBdVersionToVID(bdVersion *version);
be_node *makeCompactPeerIds(std::list<std::string> &values);
be_node *makeCompactNodeIdString(std::list<bdId> &nodes);
int beMsgGetToken(be_node *n, bdToken &token);
int beMsgGetNodeId(be_node *n, bdNodeId &nodeId);
int beMsgGetBdId(be_node *n, bdId &id);
int beMsgGetListBdIds(be_node *n, std::list<bdId> &nodes);
int beMsgGetListStrings(be_node *n, std::list<std::string> &values);
int beMsgGetUInt32(be_node *n, uint32_t *port);
/* Low Level conversion functions */
int decodeCompactPeerId(struct sockaddr_in *addr, char *enc, int len);
std::string encodeCompactPeerId(struct sockaddr_in *addr);
int decodeCompactNodeId(bdId *id, char *enc, int len);
std::string encodeCompactNodeId(bdId *id);
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,284 +0,0 @@
/*******************************************************************************
* bitdht/bdnode.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_NODE_H
#define BITDHT_NODE_H
#include "bitdht/bdpeer.h"
#include "bitdht/bdquery.h"
#include "bitdht/bdstore.h"
#include "bitdht/bdobj.h"
#include "bitdht/bdhash.h"
#include "bitdht/bdhistory.h"
#include "bitdht/bdfilter.h"
#include "bitdht/bdconnection.h"
#include "bitdht/bdaccount.h"
#include "bitdht/bdfriendlist.h"
class bdFilter;
#define BD_QUERY_NEIGHBOURS 1
#define BD_QUERY_LOCALNET 2
#define BD_QUERY_HASH 3
/**********************************
* Running a node....
*
* run().
* loops through and checks out of date peers.
* handles searches.
* prints out dht Table.
*
The node handles the i/o traffic from peers.
It
ping, return
peers, return
hash store, return
hash get, return
respond queue.
query queue.
input -> call into recvFunction()
output -> call back to Udp().
*********/
class bdFilteredPeer ;
class bdNodeManager;
class bdNodeNetMsg
{
public:
bdNodeNetMsg(char *data, int size, struct sockaddr_in *addr);
~bdNodeNetMsg();
void print(std::ostream &out);
char *data;
int mSize;
struct sockaddr_in addr;
};
class bdNodePublisher
{
public:
/* simplified outgoing msg functions (for the managers) */
virtual void send_ping(bdId *id) = 0; /* message out */
virtual void send_query(bdId *id, bdNodeId *targetNodeId, bool localnet) = 0; /* message out */
virtual void send_connect_msg(bdId *id, int msgtype,
bdId *srcAddr, bdId *destAddr, int mode, int param, int status) = 0;
// internal Callback -> normally continues to callbackConnect().
virtual void callbackConnect(bdId *srcId, bdId *proxyId, bdId *destId,
int mode, int point, int param, int cbtype, int errcode) = 0;
};
class bdNode: public bdNodePublisher
{
public:
bdNode(bdNodeId *id, std::string dhtVersion, const std::string& bootfile, const std::string& bootfilebak, const std::string& filterfile,
bdDhtFunctions *fns, bdNodeManager* manager);
void init(); /* sets up the self referential classes (mQueryMgr & mConnMgr) */
void setNodeOptions(uint32_t optFlags);
uint32_t setNodeDhtMode(uint32_t dhtFlags);
/* startup / shutdown node */
void restartNode();
void shutdownNode();
void getOwnId(bdNodeId *id);
// virtual so manager can do callback.
// peer flags defined in bdiface.h
virtual void addPeer(const bdId *id, uint32_t peerflags);
void printState();
void checkPotentialPeer(bdId *id, bdId *src);
void addPotentialPeer(bdId *id, bdId *src);
void iterationOff();
void iteration();
void processRemoteQuery();
void updateStore();
bool addressBanned(const sockaddr_in &raddr) ;
bool getFilteredPeers(std::list<bdFilteredPeer> &peers);
//void loadFilteredPeers(const std::list<bdFilteredPeer> &peers);
/* simplified outgoing msg functions (for the managers) */
virtual void send_ping(bdId *id); /* message out */
virtual void send_query(bdId *id, bdNodeId *targetNodeId, bool localnet); /* message out */
virtual void send_connect_msg(bdId *id, int msgtype,
bdId *srcAddr, bdId *destAddr, int mode, int param, int status);
// This is implemented in bdManager.
// virtual void callbackConnect(bdId *srcId, bdId *proxyId, bdId *destId,
// int mode, int point, int param, int cbtype, int errcode);
/* interaction with outside world (Accessed by controller to deliver us msgs) */
int outgoingMsg(struct sockaddr_in *addr, char *msg, int *len);
void incomingMsg(struct sockaddr_in *addr, char *msg, int len);
// For Relay Mode switching.
void dropRelayServers();
void pingRelayServers();
// Below is internal Management of incoming / outgoing messages.
private:
/* internal interaction with network */
void sendPkt(char *msg, int len, struct sockaddr_in addr);
void recvPkt(char *msg, int len, struct sockaddr_in addr);
/* output functions (send msg) */
void msgout_ping(bdId *id, bdToken *transId);
void msgout_pong(bdId *id, bdToken *transId);
void msgout_find_node(bdId *id, bdToken *transId, bdNodeId *query, bool localnet);
void msgout_reply_find_node(bdId *id, bdToken *transId,
std::list<bdId> &peers);
void msgout_get_hash(bdId *id, bdToken *transId, bdNodeId *info_hash);
void msgout_reply_hash(bdId *id, bdToken *transId,
bdToken *token, std::list<std::string> &values);
void msgout_reply_nearest(bdId *id, bdToken *transId,
bdToken *token, std::list<bdId> &peers);
void msgout_post_hash(bdId *id, bdToken *transId, bdNodeId *info_hash,
uint32_t port, bdToken *token);
void msgout_reply_post(bdId *id, bdToken *transId);
/* input functions (once mesg is parsed) */
uint32_t parseVersion(bdToken *versionId);
void msgin_ping(bdId *id, bdToken *token, bdToken *versionId);
void msgin_pong(bdId *id, bdToken *transId, bdToken *versionId);
void msgin_find_node(bdId *id, bdToken *transId, bdNodeId *query, bool localnet);
void msgin_reply_find_node(bdId *id, bdToken *transId,
std::list<bdId> &entries);
void msgin_get_hash(bdId *id, bdToken *transId, bdNodeId *nodeid);
void msgin_reply_hash(bdId *id, bdToken *transId,
bdToken *token, std::list<std::string> &values);
void msgin_reply_nearest(bdId *id, bdToken *transId,
bdToken *token, std::list<bdId> &nodes);
void msgin_post_hash(bdId *id, bdToken *transId,
bdNodeId *info_hash, uint32_t port, bdToken *token);
void msgin_reply_post(bdId *id, bdToken *transId);
void msgout_connect_genmsg(bdId *id, bdToken *transId, int msgtype,
bdId *srcAddr, bdId *destAddr, int mode, int param, int status);
void msgin_connect_genmsg(bdId *id, bdToken *transId, int msgtype,
bdId *srcAddr, bdId *destAddr, int mode, int param, int status);
/* token handling */
void genNewToken(bdToken *token);
int queueQuery(bdId *id, bdNodeId *query, bdToken *transId, uint32_t query_type);
/* transId handling */
void genNewTransId(bdToken *token);
void registerOutgoingMsg(bdId *id, bdToken *transId, uint32_t msgType, bdNodeId *aboutId);
uint32_t registerIncomingMsg(bdId *id, bdToken *transId, uint32_t msgType, bdNodeId *aboutId);
void cleanupTransIdRegister();
void doStats();
/********** Variables **********/
private:
/**** Some Variables are Protected to allow inherited classes to use *****/
protected:
bdSpace mNodeSpace;
bdFilter mFilterPeers;
bdQueryManager *mQueryMgr;
bdConnectManager *mConnMgr;
bdNodeId mOwnId;
bdId mLikelyOwnId; // Try to workout own id address.
std::string mDhtVersion;
bdAccount mAccount;
bdStore mStore;
bdDhtFunctions *mFns;
bdHashSpace mHashSpace;
bdFriendList mFriendList;
bdPeerQueue mBadPeerQueue;
bdHistory mHistory; /* for understanding the DHT */
bdQueryHistory mQueryHistory; /* for determining old peers */
private:
uint32_t mNodeOptionFlags;
uint32_t mNodeDhtMode;
uint32_t mMaxAllowedMsgs;
uint32_t mRelayMode;
std::list<bdRemoteQuery> mRemoteQueries;
std::list<bdId> mPotentialPeers;
std::list<bdNodeNetMsg *> mOutgoingMsgs;
std::list<bdNodeNetMsg *> mIncomingMsgs;
};
#endif // BITDHT_NODE_H

View File

@ -1,48 +0,0 @@
/*******************************************************************************
* bitdht/bdobj.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bitdht/bdobj.h"
void bdPrintTransId(std::ostream &out, bdToken *transId)
{
//out << transId->data;
bdPrintToken(out, transId);
return;
}
void bdPrintToken(std::ostream &out, bdToken *token)
{
for(unsigned int i = 0; i < token->len; i++)
{
out << std::hex << (uint32_t) token->data[i];
}
out << std::dec;
}
void bdPrintCompactPeerId(std::ostream &out, std::string /*cpi*/ )
{
out << "DummyCompactPeerId";
}

View File

@ -1,59 +0,0 @@
/*******************************************************************************
* bitdht/bdobj.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_OBJECTS_H
#define BITDHT_OBJECTS_H
#define BITDHT_TOKEN_MAX_LEN 20
#include <iostream>
#include <inttypes.h>
class bdToken
{
public:
bdToken() :len(0) { return; }
uint32_t len;
unsigned char data[BITDHT_TOKEN_MAX_LEN];
};
class bdCompactIds
{
public:
bdCompactIds() :len(0) { return; }
uint32_t len;
unsigned char data[BITDHT_TOKEN_MAX_LEN];
};
class bdVersion
{
public:
bdVersion() :len(0) { return; }
uint32_t len;
unsigned char data[BITDHT_TOKEN_MAX_LEN];
};
void bdPrintTransId(std::ostream &out, bdToken *transId);
void bdPrintToken(std::ostream &out, bdToken *transId);
void bdPrintCompactPeerId(std::ostream &out, std::string cpi);
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,212 +0,0 @@
/*******************************************************************************
* bitdht/bdpeer.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_PEER_H
#define BITDHT_PEER_H
#include "bitdht/bdiface.h"
#include <time.h>
/*******
* These type of parameters are now DHT Function dependent
*
#define BITDHT_BUCKET_SIZE 20
#define BITDHT_BUCKET_SIZE_BITS 5
#define BITDHT_N_BUCKETS BITDHT_KEY_BITLEN
*
*
***/
/***
* DEFINED in bdiface.h
* #define BITDHT_KEY_LEN 20
* #define BITDHT_KEY_INTLEN 5
* #define BITDHT_KEY_BITLEN 160
***/
#define BITDHT_ULLONG_BITS 64
#define BITDHT_MAX_RESPONSE_PERIOD (15)
#define BITDHT_MAX_SEND_PERIOD 300 // 5 minutes.
#define BITDHT_MAX_RECV_PERIOD (BITDHT_MAX_SEND_PERIOD + BITDHT_MAX_RESPONSE_PERIOD) // didn't respond to a ping.
// Properly out of date.
#define BITDHT_DISCARD_PERIOD (2 * BITDHT_MAX_SEND_PERIOD + BITDHT_MAX_RESPONSE_PERIOD) // didn't respond to two pings.
// Must have a FLAG by this time. (Make it really quick - so we through away the rubbish).
#include <list>
#include <string>
#include <map>
#include <vector>
/****
* DEFINED in bdiface.h
*
* class bdNodeId
* {
* public:
* unsigned char data[BITDHT_KEY_LEN];
* };
****/
/****
* DEFINED in bdiface.h
*
class bdMetric: public bdNodeId {};
class bdId
{
public:
bdId();
bdId(bdNodeId in_id, struct sockaddr_in in_addr);
struct sockaddr_in addr;
bdNodeId id;
};
*
*********/
//void bdRandomNodeId(bdNodeId *id);
// Only Functions that are common for all Dhts.
// zero, basic comparisons..
void bdZeroNodeId(bdNodeId *id);
//void bdRandomId(bdId *id);
//int bdDistance(const bdNodeId *a, const bdNodeId *b, bdMetric *r);
//int bdBucketDistance(const bdMetric *m);
//int bdBucketDistance(const bdNodeId *a, const bdNodeId *b);
//int operator<(const bdMetric &a, const bdMetric &b);
//int operator<(const struct sockaddr_in &a, const struct sockaddr_in &b);
int operator<(const bdNodeId &a, const bdNodeId &b);
int operator<(const bdId &a, const bdId &b);
int operator==(const bdNodeId &a, const bdNodeId &b);
int operator==(const bdId &a, const bdId &b);
//void bdRandomMidId(const bdNodeId *target, const bdNodeId *other, bdNodeId *mid);
//void bdPrintId(std::ostream &out, const bdId *a);
//void bdPrintNodeId(std::ostream &out, const bdNodeId *a);
//std::string bdConvertToPrintable(std::string input);
/****
* DEFINED in bdiface.h
*
class bdPeer
{
public:
bdId mPeerId;
uint32_t mPeerFlags;
time_t mLastSendTime;
time_t mLastRecvTime;
time_t mFoundTime; // time stamp that peer was found
};
class bdBucket
{
public:
bdBucket();
// list so we can queue properly
std::list<bdPeer> entries;
};
*
*
*****/
class bdSpace
{
public:
bdSpace(bdNodeId *ownId, bdDhtFunctions *fns);
int clear();
int setAttachedFlag(uint32_t withflags, int count);
/* accessors */
int find_nearest_nodes(const bdNodeId *id, int number,
std::multimap<bdMetric, bdId> &nearest);
int find_nearest_nodes_with_flags(const bdNodeId *id, int number,
std::list<bdId> excluding,
std::multimap<bdMetric, bdId> &nearest, uint32_t with_flag);
int find_node(const bdNodeId *id, int number,
std::list<bdId> &matchIds, uint32_t with_flag);
int find_exactnode(const bdId *id, bdPeer &peer);
// switched to more efficient single sweep.
//int out_of_date_peer(bdId &id); // side-effect updates, send flag on peer.
int scanOutOfDatePeers(std::list<bdId> &peerIds);
int updateAttachedPeers();
int add_peer(const bdId *id, uint32_t mode);
int printDHT();
int getDhtBucket(const int idx, bdBucket &bucket);
uint32_t calcNetworkSize();
uint32_t calcNetworkSizeWithFlag(uint32_t withFlag);
uint32_t calcNetworkSizeWithFlag_old(uint32_t withFlag);
uint32_t calcSpaceSize();
uint32_t calcSpaceSizeWithFlag(uint32_t withFlag);
/* special function to enable DHT localisation (i.e find peers from own network) */
bool findRandomPeerWithFlag(bdId &id, uint32_t withFlag);
/* strip out flags - to switch in/out of relay mode */
int clean_node_flags(uint32_t flags);
/* to add later */
int updateOwnId(bdNodeId *newOwnId);
/* flag peer */
bool flagpeer(const bdId *id, uint32_t flags, uint32_t ex_flags);
private:
std::vector<bdBucket> buckets;
bdNodeId mOwnId;
bdDhtFunctions *mFns;
uint32_t mAttachedFlags;
uint32_t mAttachedCount;
time_t mAttachTS;
};
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,157 +0,0 @@
/*******************************************************************************
* bitdht/bdquery.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_QUERY_H
#define BITDHT_QUERY_H
#include "bitdht/bdiface.h"
#include "bitdht/bdpeer.h"
#include "bitdht/bdobj.h"
/* Query result flags are in bdiface.h */
#define BITDHT_MIN_QUERY_AGE 10
#define BITDHT_MAX_QUERY_AGE 300 /* Query Should take <1 minute, so 5 minutes sounds reasonable */
class bdQuery
{
public:
bdQuery(const bdNodeId *id, std::list<bdId> &startList, uint32_t queryFlags,
bdDhtFunctions *fns);
// get the answer.
bool result(std::list<bdId> &answer);
bool proxies(std::list<bdId> &answer);
bool potentialProxies(std::list<bdId> &answer);
// returning results get passed to all queries.
//void addNode(const bdId *id, int mode);
int nextQuery(bdId &id, bdNodeId &targetId);
int addPeer(const bdId *id, uint32_t mode);
int addPotentialPeer(const bdId *id, const bdId *src, uint32_t srcmode);
int printQuery();
// searching for
bdNodeId mId;
bdMetric mLimit;
uint32_t mState;
time_t mQueryTS;
uint32_t mQueryFlags;
int32_t mSearchTime;
int32_t mQueryIdlePeerRetryPeriod; // seconds between retries.
//private:
// Closest Handling Fns.
int addClosestPeer(const bdId *id, uint32_t mode);
// Potential Handling Fns.
int worthyPotentialPeer(const bdId *id);
int updatePotentialPeer(const bdId *id, uint32_t mode, uint32_t addType);
int trimPotentialPeers_FixedLength();
int trimPotentialPeers_toClosest();
int removeOldPotentialPeers();
// Proxy Handling Fns.
int addProxy(const bdId *id, const bdId *src, uint32_t srcmode);
int updateProxy(const bdId *id, uint32_t mode);
int updateProxyList(const bdId *id, uint32_t mode, std::list<bdPeer> &searchProxyList);
int trimProxies();
// closest peers.
std::multimap<bdMetric, bdPeer> mClosest;
std::multimap<bdMetric, bdPeer> mPotentialPeers;
time_t mPotPeerCleanTS; // periodic cleanup of PotentialPeers.
uint32_t mRequiredPeerFlags;
std::list<bdPeer> mProxiesUnknown;
std::list<bdPeer> mProxiesFlagged;
int mClosestListSize;
bdDhtFunctions *mFns;
};
#if 0
class bdQueryStatus
{
public:
uint32_t mStatus;
uint32_t mQFlags;
std::list<bdId> mResults;
};
#endif
/* this is just a container class.
* we locally seach for this, once then discard.
*/
class bdRemoteQuery
{
public:
bdRemoteQuery(bdId *id, bdNodeId *query, bdToken *transId, uint32_t query_type);
bdId mId;
bdNodeId mQuery;
bdToken mTransId;
uint32_t mQueryType;
time_t mQueryTS;
};
class bdQueryHistoryList
{
public:
bdQueryHistoryList();
bool addIncomingQuery(time_t recvd, const bdNodeId *aboutId); // calcs and returns mBadPeer
bool cleanupMsgs(time_t before); // returns true if empty.
bool mBadPeer;
std::multimap<time_t, bdNodeId> mList;
};
class bdQueryHistory
{
public:
bdQueryHistory();
bool addIncomingQuery(time_t recvd, const bdId *id, const bdNodeId *aboutId);
void printMsgs();
void cleanupOldMsgs();
bool isBadPeer(const bdId *id);
int mStorePeriod;
std::map<bdId, bdQueryHistoryList> mHistory;
};
#endif

View File

@ -1,379 +0,0 @@
/*******************************************************************************
* bitdht/bdquerymgr.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bitdht/bdquerymgr.h"
#include "bitdht/bdnode.h"
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#define BITDHT_QUERY_START_PEERS 10
#define BITDHT_QUERY_NEIGHBOUR_PEERS 8
#define BITDHT_MAX_REMOTE_QUERY_AGE 10
/****
* #define DEBUG_NODE_MULTIPEER 1
* #define DEBUG_NODE_MSGS 1
* #define DEBUG_NODE_ACTIONS 1
* #define DEBUG_NODE_MSGIN 1
* #define DEBUG_NODE_MSGOUT 1
***/
//#define DEBUG_NODE_MSGS 1
bdQueryManager::bdQueryManager(bdSpace *space, bdDhtFunctions *fns, bdNodePublisher *pub)
:mNodeSpace(space), mFns(fns), mPub(pub)
{
}
/***** Startup / Shutdown ******/
void bdQueryManager::shutdownQueries()
{
/* clear the queries */
std::list<bdQuery *>::iterator it;
for(it = mLocalQueries.begin(); it != mLocalQueries.end();it++)
{
delete (*it);
}
mLocalQueries.clear();
}
void bdQueryManager::printQueries()
{
std::cerr << "bdQueryManager::printQueries()";
std::cerr << std::endl;
int i = 0;
std::list<bdQuery *>::iterator it;
for(it = mLocalQueries.begin(); it != mLocalQueries.end(); it++, i++)
{
fprintf(stderr, "Query #%d:\n", i);
(*it)->printQuery();
fprintf(stderr, "\n");
}
}
int bdQueryManager::iterateQueries(int maxQueries)
{
#ifdef DEBUG_NODE_MULTIPEER
std::cerr << "bdQueryManager::iterateQueries() of Peer: ";
mFns->bdPrintNodeId(std::cerr, &mOwnId);
std::cerr << std::endl;
#endif
/* allow each query to send up to one query... until maxMsgs has been reached */
int numQueries = mLocalQueries.size();
int sentQueries = 0;
int i = 0;
bdId id;
bdNodeId targetNodeId;
while((i < numQueries) && (sentQueries < maxQueries))
{
bdQuery *query = mLocalQueries.front();
mLocalQueries.pop_front();
mLocalQueries.push_back(query);
/* go through the possible queries */
if (query->nextQuery(id, targetNodeId))
{
#ifdef DEBUG_NODE_MSGS
std::cerr << "bdQueryManager::iteration() send_query(";
mFns->bdPrintId(std::cerr, &id);
std::cerr << ",";
mFns->bdPrintNodeId(std::cerr, &targetNodeId);
std::cerr << ")";
std::cerr << std::endl;
#endif
mPub->send_query(&id, &targetNodeId, false);
sentQueries++;
}
i++;
}
#ifdef DEBUG_NODE_ACTIONS
std::cerr << "bdQueryManager::iteration() maxMsgs: " << maxMsgs << " sentPings: " << sentPings;
std::cerr << " / " << allowedPings;
std::cerr << " sentQueries: " << sentQueries;
std::cerr << " / " << numQueries;
std::cerr << std::endl;
#endif
//printQueries();
return sentQueries;
}
bool bdQueryManager::checkPotentialPeer(bdId *id, bdId *src)
{
bool isWorthyPeer = false;
/* also push to queries */
std::list<bdQuery *>::iterator it;
for(it = mLocalQueries.begin(); it != mLocalQueries.end(); it++)
{
if ((*it)->addPotentialPeer(id, src, 0))
{
isWorthyPeer = true;
}
}
if (!isWorthyPeer)
{
isWorthyPeer = checkWorthyPeerSources(src);
}
return isWorthyPeer;
}
void bdQueryManager::addPeer(const bdId *id, uint32_t peerflags)
{
#ifdef DEBUG_NODE_ACTIONS
fprintf(stderr, "bdQueryManager::addPeer(");
mFns->bdPrintId(std::cerr, id);
fprintf(stderr, ")\n");
#endif
/* iterate through queries */
std::list<bdQuery *>::iterator it;
for(it = mLocalQueries.begin(); it != mLocalQueries.end(); it++)
{
(*it)->addPeer(id, peerflags);
}
}
/************************************ Query Details *************************/
void bdQueryManager::addQuery(const bdNodeId *id, uint32_t qflags)
{
std::list<bdId> startList;
std::multimap<bdMetric, bdId> nearest;
std::multimap<bdMetric, bdId>::iterator it;
mNodeSpace->find_nearest_nodes(id, BITDHT_QUERY_START_PEERS, nearest);
#ifdef DEBUG_NODE_ACTIONS
fprintf(stderr, "bdQueryManager::addQuery(");
mFns->bdPrintNodeId(std::cerr, id);
fprintf(stderr, ")\n");
#endif
for(it = nearest.begin(); it != nearest.end(); it++)
{
startList.push_back(it->second);
}
bdQuery *query = new bdQuery(id, startList, qflags, mFns);
mLocalQueries.push_back(query);
}
void bdQueryManager::clearQuery(const bdNodeId *rmId)
{
std::list<bdQuery *>::iterator it;
for(it = mLocalQueries.begin(); it != mLocalQueries.end();)
{
if ((*it)->mId == *rmId)
{
bdQuery *query = (*it);
it = mLocalQueries.erase(it);
delete query;
}
else
{
it++;
}
}
}
void bdQueryManager::QueryStatus(std::map<bdNodeId, bdQueryStatus> &statusMap)
{
std::list<bdQuery *>::iterator it;
for(it = mLocalQueries.begin(); it != mLocalQueries.end(); it++)
{
bdQueryStatus status;
status.mStatus = (*it)->mState;
status.mQFlags = (*it)->mQueryFlags;
(*it)->result(status.mResults);
statusMap[(*it)->mId] = status;
}
}
int bdQueryManager::QuerySummary(const bdNodeId *id, bdQuerySummary &query)
{
std::list<bdQuery *>::iterator it;
for(it = mLocalQueries.begin(); it != mLocalQueries.end(); it++)
{
if ((*it)->mId == *id)
{
query.mId = (*it)->mId;
query.mLimit = (*it)->mLimit;
query.mState = (*it)->mState;
query.mQueryTS = (*it)->mQueryTS;
query.mQueryFlags = (*it)->mQueryFlags;
query.mSearchTime = (*it)->mSearchTime;
query.mClosest = (*it)->mClosest;
query.mPotentialPeers = (*it)->mPotentialPeers;
query.mProxiesUnknown = (*it)->mProxiesUnknown;
query.mProxiesFlagged = (*it)->mProxiesFlagged;
query.mQueryIdlePeerRetryPeriod = (*it)->mQueryIdlePeerRetryPeriod;
return 1;
}
}
return 0;
}
/* Extract Results from Peer Queries */
#define BDQRYMGR_RESULTS 1
#define BDQRYMGR_PROXIES 2
#define BDQRYMGR_POTPROXIES 3
int bdQueryManager::getResults(bdNodeId *target, std::list<bdId> &answer, int querytype)
{
/* grab any peers from any existing query */
int results = 0;
std::list<bdQuery *>::iterator qit;
for(qit = mLocalQueries.begin(); qit != mLocalQueries.end(); qit++)
{
if (!((*qit)->mId == (*target)))
{
continue;
}
#ifdef DEBUG_NODE_CONNECTION
std::cerr << "bdQueryManager::getResults() Found Matching Query";
std::cerr << std::endl;
#endif
switch(querytype)
{
default:
case BDQRYMGR_RESULTS:
results = (*qit)->result(answer);
break;
case BDQRYMGR_PROXIES:
results = (*qit)->proxies(answer);
break;
case BDQRYMGR_POTPROXIES:
results = (*qit)->potentialProxies(answer);
break;
}
/* will only be one matching query.. so end loop */
return results;
}
return 0;
}
int bdQueryManager::result(bdNodeId *target, std::list<bdId> &answer)
{
return getResults(target, answer, BDQRYMGR_RESULTS);
}
int bdQueryManager::proxies(bdNodeId *target, std::list<bdId> &answer)
{
return getResults(target, answer, BDQRYMGR_PROXIES);
}
int bdQueryManager::potentialProxies(bdNodeId *target, std::list<bdId> &answer)
{
return getResults(target, answer, BDQRYMGR_POTPROXIES);
}
/************ WORTHY PEERS **********/
#define MAX_WORTHY_PEER_AGE 15
void bdQueryManager::addWorthyPeerSource(bdId *src)
{
time_t now = time(NULL);
bdPeer peer;
peer.mPeerId = *src;
peer.mFoundTime = now;
#ifdef DEBUG_NODE_ACTIONS
std::cerr << "bdQueryManager::addWorthyPeerSource(";
mFns->bdPrintId(std::cerr, src);
std::cerr << ")" << std::endl;
#endif
mWorthyPeerSources.push_back(peer);
}
bool bdQueryManager::checkWorthyPeerSources(bdId *src)
{
if (!src)
return false;
time_t now = time(NULL);
std::list<bdPeer>::iterator it;
for(it = mWorthyPeerSources.begin(); it != mWorthyPeerSources.end(); )
{
if (now - it->mFoundTime > MAX_WORTHY_PEER_AGE)
{
#ifdef DEBUG_NODE_ACTIONS
std::cerr << "bdQueryManager::checkWorthyPeerSource() Discard old Source: ";
mFns->bdPrintId(std::cerr, &(it->mPeerId));
std::cerr << std::endl;
#endif
it = mWorthyPeerSources.erase(it);
}
else
{
if (it->mPeerId == *src)
{
#ifdef DEBUG_NODE_ACTIONS
std::cerr << "bdQueryManager::checkWorthyPeerSource(";
mFns->bdPrintId(std::cerr, src);
std::cerr << ") = true" << std::endl;
#endif
return true;
}
it++;
}
}
return false;
}

View File

@ -1,73 +0,0 @@
/*******************************************************************************
* bitdht/bdquerymgr.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_QUERY_MANAGER_H
#define BITDHT_QUERY_MANAGER_H
#include "bitdht/bdquery.h"
class bdNodePublisher;
class bdQueryManager
{
public:
bdQueryManager(bdSpace *space, bdDhtFunctions *fns, bdNodePublisher *pub);
void shutdownQueries();
void printQueries();
int iterateQueries(int maxqueries);
bool checkPotentialPeer(bdId *id, bdId *src);
void addPeer(const bdId *id, uint32_t peerflags);
void addQuery(const bdNodeId *id, uint32_t qflags);
void clearQuery(const bdNodeId *id);
void QueryStatus(std::map<bdNodeId, bdQueryStatus> &statusMap);
int QuerySummary(const bdNodeId *id, bdQuerySummary &query);
int result(bdNodeId *target, std::list<bdId> &answer);
int proxies(bdNodeId *target, std::list<bdId> &answer);
int potentialProxies(bdNodeId *target, std::list<bdId> &answer);
// extra "Worthy Peers" we will want to ping.
void addWorthyPeerSource(bdId *src);
bool checkWorthyPeerSources(bdId *src);
private:
int getResults(bdNodeId *target, std::list<bdId> &answer, int querytype);
/* NB: No Mutex Protection... Single threaded, Mutex at higher level!
*/
bdSpace *mNodeSpace;
bdDhtFunctions *mFns;
bdNodePublisher *mPub;
std::list<bdQuery *> mLocalQueries;
std::list<bdPeer> mWorthyPeerSources;
};
#endif // BITDHT_QUERY_MANAGER_H

View File

@ -1,347 +0,0 @@
/*******************************************************************************
* bitdht/bdstddht.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bitdht/bdstddht.h"
#include "bitdht/bdpeer.h"
#include "util/bdrandom.h"
#include "util/bdstring.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <iostream>
#include <iomanip>
/**
* #define BITDHT_DEBUG 1
**/
void bdStdRandomId(bdId *id)
{
bdStdRandomNodeId(&(id->id));
id->addr.sin_addr.s_addr = bdRandom::random_u32();
id->addr.sin_port = (bdRandom::random_u32() % USHRT_MAX);
return;
}
void bdStdRandomNodeId(bdNodeId *id)
{
uint32_t *a_data = (uint32_t *) id->data;
for(int i = 0; i < BITDHT_KEY_INTLEN; i++)
{
a_data[i] = bdRandom::random_u32();
}
return;
}
void bdStdZeroNodeId(bdNodeId *id)
{
uint32_t *a_data = (uint32_t *) id->data;
for(int i = 0; i < BITDHT_KEY_INTLEN; i++)
{
a_data[i] = 0;
}
return;
}
// Ignore differences in port....
// must be careful which one we accept after this.
// can could end-up with the wrong port.
// However this only matters with firewalled peers anyway.
// So not too serious.
bool bdStdSimilarId(const bdId *n1, const bdId *n2)
{
if (n1->id == n2->id)
{
if (n1->addr.sin_addr.s_addr == n2->addr.sin_addr.s_addr)
{
return true;
}
}
return false;
}
bool bdStdUpdateSimilarId(bdId *dest, const bdId *src)
{
/* only difference that's currently allowed */
if (dest->addr.sin_port == src->addr.sin_port)
{
/* no update required */
return false;
}
dest->addr.sin_port = src->addr.sin_port;
return true;
}
/* fills in bdNodeId r, with XOR of a and b */
int bdStdDistance(const bdNodeId *a, const bdNodeId *b, bdMetric *r)
{
uint8_t *a_data = (uint8_t *) a->data;
uint8_t *b_data = (uint8_t *) b->data;
uint8_t *ans = (uint8_t *) r->data;
for(int i = 0; i < BITDHT_KEY_LEN; i++)
{
*(ans++) = *(a_data++) ^ *(b_data++);
}
return 1;
}
void bdStdRandomMidId(const bdNodeId *target, const bdNodeId *other, bdNodeId *midId)
{
bdMetric dist;
/* get distance between a & c */
bdStdDistance(target, other, &dist);
/* generate Random Id */
bdStdRandomNodeId(midId);
/* zero bits of Random Id until under 1/2 of distance
* done in bytes for ease... matches one extra byte than distance = 0
* -> hence wierd order of operations
*/
//bool done = false;
for(int i = 0; i < BITDHT_KEY_LEN; i++)
{
midId->data[i] = target->data[i];
if (dist.data[i] != 0)
break;
}
}
int bdStdLoadNodeId(bdNodeId *id, std::string input)
{
uint8_t *a_data = (uint8_t *) id->data;
uint32_t reqlen = BITDHT_KEY_LEN * 2;
if (input.size() < reqlen)
{
return 0;
}
for(int i = 0; i < BITDHT_KEY_LEN; i++)
{
char ch1 = input[2 * i];
char ch2 = input[2 * i + 1];
uint8_t value1 = 0;
uint8_t value2 = 0;
/* do char1 */
if (ch1 >= '0' && ch1 <= '9')
value1 = (ch1 - '0');
else if (ch1 >= 'A' && ch1 <= 'F')
value1 = (ch1 - 'A' + 10);
else if (ch1 >= 'a' && ch1 <= 'f')
value1 = (ch1 - 'a' + 10);
/* do char2 */
if (ch2 >= '0' && ch2 <= '9')
value2 = (ch2 - '0');
else if (ch2 >= 'A' && ch2 <= 'F')
value2 = (ch2 - 'A' + 10);
else if (ch2 >= 'a' && ch2 <= 'f')
value2 = (ch2 - 'a' + 10);
a_data[i] = (value1 << 4) + value2;
}
return 1;
}
std::string bdStdConvertToPrintable(std::string input)
{
std::string out;
for(uint32_t i = 0; i < input.length(); i++)
{
/* sensible chars */
if ((input[i] > 31) && (input[i] < 127))
{
out += input[i];
}
else
{
bd_sprintf_append(out, "[0x%x]", (uint32_t) input[i]);
}
}
return out;
}
void bdStdPrintNodeId(std::ostream &out, const bdNodeId *a)
{
std::string s;
bdStdPrintNodeId(s, a, true);
out << s;
}
void bdStdPrintNodeId(std::string &out, const bdNodeId *a, bool append)
{
if (!append)
{
out.clear();
}
for(int i = 0; i < BITDHT_KEY_LEN; i++)
{
bd_sprintf_append(out, "%02x", (uint32_t) (a->data)[i]);
}
}
void bdStdPrintId(std::ostream &out, const bdId *a)
{
std::string s;
bdStdPrintId(s, a, false);
out << s;
}
void bdStdPrintId(std::string &out, const bdId *a, bool append)
{
bdStdPrintNodeId(out, &(a->id), append);
bd_sprintf_append(out, " ip:%s:%u", bdnet_inet_ntoa(a->addr.sin_addr).c_str(), ntohs(a->addr.sin_port));
}
/* returns 0-160 depending on bucket */
int bdStdBucketDistance(const bdNodeId *a, const bdNodeId *b)
{
bdMetric m;
bdStdDistance(a, b, &m);
return bdStdBucketDistance(&m);
}
/* returns 0-160 depending on bucket */
int bdStdBucketDistance(const bdMetric *m)
{
for(int i = 0; i < BITDHT_KEY_BITLEN; i++)
{
int bit = BITDHT_KEY_BITLEN - i - 1;
int byte = i / 8;
int bbit = 7 - (i % 8);
unsigned char comp = (1 << bbit);
#ifdef BITDHT_DEBUG
fprintf(stderr, "bdStdBucketDistance: bit:%d byte:%d bbit:%d comp:%x, data:%x\n", bit, byte, bbit, comp, m->data[byte]);
#endif
if (comp & m->data[byte])
{
return bit;
}
}
return 0;
}
bdStdDht::bdStdDht()
{
return;
}
/* setup variables */
uint16_t bdStdDht::bdNumBuckets()
{
return BITDHT_STANDARD_N_BUCKETS;
}
uint16_t bdStdDht::bdNodesPerBucket() /* used for bdspace */
{
return BITDHT_STANDARD_BUCKET_SIZE;
}
uint16_t bdStdDht::bdNumQueryNodes() /* used for queries */
{
return BITDHT_STANDARD_BUCKET_SIZE;
}
uint16_t bdStdDht::bdBucketBitSize()
{
return BITDHT_STANDARD_BUCKET_SIZE_BITS;
}
int bdStdDht::bdDistance(const bdNodeId *n1, const bdNodeId *n2, class bdMetric *metric)
{
return bdStdDistance(n1, n2, metric);
}
int bdStdDht::bdBucketDistance(const bdNodeId *n1, const bdNodeId *n2)
{
return bdStdBucketDistance(n1, n2);
}
int bdStdDht::bdBucketDistance(const bdMetric *metric)
{
return bdStdBucketDistance(metric);
}
bool bdStdDht::bdSimilarId(const bdId *id1, const bdId *id2)
{
return bdStdSimilarId(id1, id2);
}
bool bdStdDht::bdUpdateSimilarId(bdId *dest, const bdId *src)
{
return bdStdUpdateSimilarId(dest, src);
}
void bdStdDht::bdRandomMidId(const bdNodeId *target, const bdNodeId *other, bdNodeId *mid)
{
return bdStdRandomMidId(target, other, mid);
}
void bdStdDht::bdPrintId(std::ostream &out, const bdId *a)
{
return bdStdPrintId(out, a);
}
void bdStdDht::bdPrintNodeId(std::ostream &out, const bdNodeId *a)
{
return bdStdPrintNodeId(out, a);
}
/**************************/
bdModDht::bdModDht()
:mNodesPerBucket(BITDHT_STANDARD_BUCKET_SIZE)
{
return;
}
void bdModDht::setNodesPerBucket(uint16_t nodesPerBucket)
{
mNodesPerBucket = nodesPerBucket;
return;
}
uint16_t bdModDht::bdNodesPerBucket() /* used for bdspace */
{
return mNodesPerBucket;
}

View File

@ -1,100 +0,0 @@
/*******************************************************************************
* bitdht/bdstddht.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_STANDARD_DHT_H
#define BITDHT_STANDARD_DHT_H
#include "bitdht/bdiface.h"
#define BITDHT_STANDARD_BUCKET_SIZE 10 // 20 too many per query?
#define BITDHT_STANDARD_BUCKET_SIZE_BITS 5
#define BITDHT_STANDARD_N_BUCKETS BITDHT_KEY_BITLEN
#include <list>
#include <string>
#include <map>
#include <vector>
void bdStdRandomNodeId(bdNodeId *id);
void bdStdZeroNodeId(bdNodeId *id);
void bdStdRandomId(bdId *id);
int bdStdDistance(const bdNodeId *a, const bdNodeId *b, bdMetric *r);
int bdStdBucketDistance(const bdMetric *m);
int bdStdBucketDistance(const bdNodeId *a, const bdNodeId *b);
void bdStdRandomMidId(const bdNodeId *target, const bdNodeId *other, bdNodeId *mid);
int bdStdLoadNodeId(bdNodeId *id, std::string input);
void bdStdPrintId(std::ostream &out, const bdId *a);
void bdStdPrintId(std::string &out, const bdId *a, bool append);
void bdStdPrintNodeId(std::ostream &out, const bdNodeId *a);
void bdStdPrintNodeId(std::string &out, const bdNodeId *a, bool append);
std::string bdStdConvertToPrintable(std::string input);
//uint32_t bdStdSimilarNode(const bdId*, const bdId*);
class bdStdDht: public bdDhtFunctions
{
public:
bdStdDht();
/* setup variables */
virtual uint16_t bdNumBuckets();
virtual uint16_t bdNodesPerBucket(); /* used for bdspace */
virtual uint16_t bdNumQueryNodes(); /* used for queries */
virtual uint16_t bdBucketBitSize();
virtual int bdDistance(const bdNodeId *n1, const bdNodeId *n2, bdMetric *metric);
virtual int bdBucketDistance(const bdNodeId *n1, const bdNodeId *n2);
virtual int bdBucketDistance(const bdMetric *metric);
virtual bool bdSimilarId(const bdId *id1, const bdId *id2);
virtual bool bdUpdateSimilarId(bdId *dest, const bdId *src); /* returns true if update was necessary */
virtual void bdRandomMidId(const bdNodeId *target, const bdNodeId *other, bdNodeId *mid);
virtual void bdPrintId(std::ostream &out, const bdId *a);
virtual void bdPrintNodeId(std::ostream &out, const bdNodeId *a);
};
class bdModDht: public bdStdDht
{
public:
bdModDht();
virtual void setNodesPerBucket(uint16_t nodesPerBucket);
virtual uint16_t bdNodesPerBucket(); /* used for bdspace */
private:
uint16_t mNodesPerBucket;
};
#endif

View File

@ -1,269 +0,0 @@
/*******************************************************************************
* bitdht/bdstore.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bitdht/bdstore.h"
#include "util/bdnet.h"
#include "util/bdfile.h"
#include <stdio.h>
#include <iostream>
//#define DEBUG_STORE 1
bdStore::bdStore(std::string file, std::string backupfile, bdDhtFunctions *fns)
:mFns(fns)
{
#ifdef DEBUG_STORE
std::cerr << "bdStore::bdStore(" << file << ")";
std::cerr << std::endl;
#endif
/* read data from file */
mStoreFile = file;
mStoreFileBak = backupfile;
reloadFromStore();
}
int bdStore::clear()
{
mIndex = 0;
store.clear();
return 1;
}
int bdStore::reloadFromStore()
{
int result = reloadFromStore(mStoreFile);
if( result != 0 && store.size() > 0){
return result;
} else if(mStoreFileBak != "") { //Nothing loaded, try the backup file
return reloadFromStore(mStoreFileBak);
} else {
return 0;
}
}
int bdStore::reloadFromStore(std::string file)
{
clear();
FILE *fd = fopen(file.c_str(), "r");
if (!fd)
{
fprintf(stderr, "Failed to Open File: %s ... No Peers\n", file.c_str());
return 0;
}
char line[10240];
char addr_str[10240];
struct sockaddr_in addr;
addr.sin_family = PF_INET;
unsigned short port;
while(line == fgets(line, 10240, fd))
{
if (2 == sscanf(line, "%s %hd", addr_str, &port))
{
if (bdnet_inet_aton(addr_str, &(addr.sin_addr)))
{
addr.sin_port = htons(port);
bdPeer peer;
bdZeroNodeId(&(peer.mPeerId.id));
peer.mPeerId.addr = addr;
peer.mLastSendTime = 0;
peer.mLastRecvTime = 0;
store.push_back(peer);
#ifdef DEBUG_STORE
fprintf(stderr, "Read: %s %d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
#endif
}
}
}
fclose(fd);
#ifdef DEBUG_STORE
fprintf(stderr, "Read %ld Peers\n", (long) store.size());
#endif
return 1;
}
// This is a very ugly function!
int bdStore::getPeer(bdPeer *peer)
{
#ifdef DEBUG_STORE
fprintf(stderr, "bdStore::getPeer() %ld Peers left\n", (long) store.size());
#endif
std::list<bdPeer>::iterator it;
int i = 0;
for(it = store.begin(); (it != store.end()) && (i < mIndex); it++, i++) ; /* empty loop */
if (it != store.end())
{
*peer = *it;
mIndex++;
return 1;
}
return 0;
}
int bdStore::filterIpList(const std::list<struct sockaddr_in> &filteredIPs)
{
// Nasty O(n^2) iteration over 500 entries!!!.
// hope its not used to often.
std::list<struct sockaddr_in>::const_iterator it;
for(it = filteredIPs.begin(); it != filteredIPs.end(); it++)
{
std::list<bdPeer>::iterator sit;
for(sit = store.begin(); sit != store.end();)
{
if (it->sin_addr.s_addr == sit->mPeerId.addr.sin_addr.s_addr)
{
std::cerr << "bdStore::filterIpList() Found Bad entry in Store. Erasing!";
std::cerr << std::endl;
sit = store.erase(sit);
}
else
{
sit++;
}
}
}
return 1;
}
#define MAX_ENTRIES 500
/* maintain a sorted list */
void bdStore::addStore(bdPeer *peer)
{
#ifdef DEBUG_STORE
std::cerr << "bdStore::addStore() ";
mFns->bdPrintId(std::cerr, &(peer->mPeerId));
std::cerr << std::endl;
#endif
/* remove old entry */
std::list<bdPeer>::iterator it;
for(it = store.begin(); it != store.end(); )
{
if ((it->mPeerId.addr.sin_addr.s_addr == peer->mPeerId.addr.sin_addr.s_addr) &&
(it->mPeerId.addr.sin_port == peer->mPeerId.addr.sin_port))
{
#ifdef DEBUG_STORE
std::cerr << "bdStore::addStore() Removed Existing Entry: ";
mFns->bdPrintId(std::cerr, &(it->mPeerId));
std::cerr << std::endl;
#endif
it = store.erase(it);
}
else
{
it++;
}
}
#ifdef DEBUG_STORE
std::cerr << "bdStore::addStore() Push_back";
std::cerr << std::endl;
#endif
store.push_back(*peer);
while(store.size() > MAX_ENTRIES)
{
#ifdef DEBUG_STORE
std::cerr << "bdStore::addStore() pop_front()";
std::cerr << std::endl;
#endif
store.pop_front();
}
}
void bdStore::writeStore(std::string file)
{
/* write out store */
#ifdef DEBUG_STORE
fprintf(stderr, "bdStore::writeStore(%s) = %d entries\n", file.c_str(), store.size());
#endif
if (store.size() < 0.9 * MAX_ENTRIES)
{
/* don't save yet! */
#ifdef DEBUG_STORE
fprintf(stderr, "bdStore::writeStore() Delaying until more entries\n");
#endif
return;
}
std::string filetmp = file + ".tmp" ;
FILE *fd = fopen(filetmp.c_str(), "w");
if (!fd)
{
#ifdef DEBUG_STORE
#endif
fprintf(stderr, "bdStore::writeStore() FAILED to Open File\n");
return;
}
std::list<bdPeer>::iterator it;
for(it = store.begin(); it != store.end(); it++)
{
fprintf(fd, "%s %d\n", bdnet_inet_ntoa(it->mPeerId.addr.sin_addr).c_str(), ntohs(it->mPeerId.addr.sin_port));
#ifdef DEBUG_STORE
fprintf(stderr, "Storing Peer Address: %s %d\n", inet_ntoa(it->mPeerId.addr.sin_addr), ntohs(it->mPeerId.addr.sin_port));
#endif
}
fclose(fd);
if(!bdFile::renameFile(filetmp,file))
std::cerr << "Could not rename file !!" << std::endl;
#ifdef DEBUG_STORE
else
std::cerr << "Successfully renamed file " << filetmp << " to " << file << std::endl;
#endif
}
void bdStore::writeStore()
{
#if 0
if (mStoreFile == "")
{
return;
}
#endif
return writeStore(mStoreFile);
}

View File

@ -1,54 +0,0 @@
/*******************************************************************************
* bitdht/bdstore.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_STORE_H
#define BITDHT_STORE_H
#include <string>
#include "bitdht/bdiface.h"
#include "bitdht/bdpeer.h"
class bdStore
{
public:
bdStore(std::string file, std::string backupfile, bdDhtFunctions *fns);
int reloadFromStore(); /* for restarts */
int reloadFromStore(std::string file);
int filterIpList(const std::list<struct sockaddr_in> &filteredIPs);
int clear();
int getPeer(bdPeer *peer);
void addStore(bdPeer *peer);
void writeStore(std::string file);
void writeStore();
protected:
std::string mStoreFile;
std::string mStoreFileBak;
std::list<bdPeer> store;
int mIndex;
bdDhtFunctions *mFns;
};
#endif

View File

@ -1,649 +0,0 @@
/*******************************************************************************
* bitdht/bdencode.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* by Mike Frysinger <vapier@gmail.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
/*
* This implementation isn't optimized at all as I wrote it to support
* a bogus system. I have no real interest in this format. Feel free
* to send me patches (so long as you don't copyright them and you release
* your changes into the public domain as well).
*/
#include <stdio.h>
#include <stdlib.h> /* malloc() realloc() free() strtoll() */
#include <string.h> /* memset() */
#include "util/bdstring.h"
#include "bitdht/bencode.h"
/***
* #define BE_DEBUG_DECODE 1
* #define BE_DEBUG 1 // controlled from Makefile too.
***/
#ifdef BE_DEBUG_DECODE
#include <stdio.h> /* debug */
#endif
static be_node *be_alloc(be_type type)
{
be_node *ret = (be_node *) malloc(sizeof(*ret));
if (ret) {
memset(ret, 0x00, sizeof(*ret));
ret->type = type;
}
return ret;
}
static long long _be_decode_int(const char **data, long long *data_len)
{
char *endp;
long long ret = strtoll(*data, &endp, 10);
*data_len -= (endp - *data);
*data = endp;
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode_int(pnt: %p, rem: %lld) = %lld\n", *data, *data_len, ret);
#endif
return ret;
}
long long be_str_len(be_node *node)
{
long long ret = 0;
if (node->val.s)
memcpy(&ret, node->val.s - sizeof(ret), sizeof(ret));
return ret;
}
static char *_be_decode_str(const char **data, long long *data_len)
{
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode_str(pnt: %p, rem: %lld)\n", *data, *data_len);
#endif
long long sllen = _be_decode_int(data, data_len);
long slen = sllen;
unsigned long len;
char *ret = NULL;
/* slen is signed, so negative values get rejected */
if (sllen < 0)
{
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode_str() reject bad length\n");
#endif
return ret;
}
/* reject attempts to allocate large values that overflow the
* size_t type which is used with malloc()
*/
if (sizeof(long long) != sizeof(long))
if (sllen != slen)
{
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode_str() reject large_values\n");
#endif
return ret;
}
/* make sure we have enough data left */
if (sllen > *data_len - 1)
{
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode_str() reject large_values\n");
#endif
return ret;
}
/* switch from signed to unsigned so we don't overflow below */
len = slen;
if (**data == ':') {
char *_ret = (char *) malloc(sizeof(sllen) + len + 1);
if(_ret == NULL)
{
fprintf(stderr, "(EE) bencode::_be_decode_str(): "
"ERROR. cannot allocate memory for %lu bytes.\n"
, len+1+sizeof(sllen) );
return ret;
}
memcpy(_ret, &sllen, sizeof(sllen));
ret = _ret + sizeof(sllen);
memcpy(ret, *data + 1, len);
ret[len] = '\0';
*data += len + 1;
*data_len -= len + 1;
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode_str() read %ld bytes\n", len+1);
#endif
}
else
{
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode_str() reject missing :\n");
#endif
}
return ret;
}
static be_node *_be_decode(const char **data, long long *data_len)
{
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode(pnt: %p, rem: %lld)\n", *data, *data_len);
#endif
be_node *ret = NULL;
if (!*data_len)
{
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() reject invalid datalen\n");
#endif
return ret;
}
switch (**data) {
/* lists */
case 'l': {
unsigned int i = 0;
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() found list\n");
#endif
ret = be_alloc(BE_LIST);
--(*data_len);
++(*data);
while (**data != 'e') {
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() list get item (%d)\n", i);
#endif
ret->val.l = (be_node **) realloc(ret->val.l, (i + 2) * sizeof(*ret->val.l));
ret->val.l[i] = _be_decode(data, data_len);
if (ret->val.l[i] == NULL)
{
/* failed decode - kill decode */
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() failed list decode - kill\n");
#endif
be_free(ret);
return NULL;
}
++i;
}
--(*data_len);
++(*data);
/* empty list case. */
if (i == 0)
{
ret->val.l = (be_node **) realloc(ret->val.l, 1 * sizeof(*ret->val.l));
}
ret->val.l[i] = NULL;
return ret;
}
/* dictionaries */
case 'd': {
unsigned int i = 0;
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() found dictionary\n");
#endif
ret = be_alloc(BE_DICT);
--(*data_len);
++(*data);
while (**data != 'e') {
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() dictionary get key (%d)\n", i);
#endif
ret->val.d = (be_dict *) realloc(ret->val.d, (i + 2) * sizeof(*ret->val.d));
ret->val.d[i].key = _be_decode_str(data, data_len);
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() dictionary get val\n");
#endif
ret->val.d[i ].val = _be_decode(data, data_len);
ret->val.d[i+1].val = NULL ; // ensures termination of loops based on 0x0 value, otherwise, uninitialized
// memory occurs if(ret->val.d[i].key == 0x0 && ret->val.d[i].val != NULL)
// when calling be_free 8 lines below this point...
if ((ret->val.d[i].key == NULL) || (ret->val.d[i].val == NULL))
{
/* failed decode - kill decode */
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() failed dict decode - kill\n");
#endif
be_free(ret);
return NULL;
}
++i;
}
--(*data_len);
++(*data);
/* empty dictionary case. */
if (i == 0)
{
ret->val.d = (be_dict *) realloc(ret->val.d, 1 * sizeof(*ret->val.d));
}
ret->val.d[i].val = NULL;
return ret;
}
/* integers */
case 'i': {
ret = be_alloc(BE_INT);
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() found int\n");
#endif
--(*data_len);
++(*data);
ret->val.i = _be_decode_int(data, data_len);
if (**data != 'e')
{
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() reject data != e - kill\n");
#endif
be_free(ret);
return NULL;
}
--(*data_len);
++(*data);
return ret;
}
/* byte strings */
case '0'...'9': {
ret = be_alloc(BE_STR);
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() found string\n");
#endif
ret->val.s = _be_decode_str(data, data_len);
return ret;
}
/* invalid */
default:
#ifdef BE_DEBUG_DECODE
fprintf(stderr, "bencode::_be_decode() found invalid - kill\n");
#endif
return NULL;
break;
}
return ret;
}
be_node *be_decoden(const char *data, long long len)
{
return _be_decode(&data, &len);
}
be_node *be_decode(const char *data)
{
return be_decoden(data, strlen(data));
}
static inline void _be_free_str(char *str)
{
if (str)
free(str - sizeof(long long));
}
void be_free(be_node *node)
{
switch (node->type) {
case BE_STR:
_be_free_str(node->val.s);
break;
case BE_INT:
break;
case BE_LIST: {
unsigned int i;
for (i = 0; node->val.l[i]; ++i)
be_free(node->val.l[i]);
free(node->val.l);
break;
}
case BE_DICT: {
unsigned int i;
for (i = 0; node->val.d[i].val; ++i) {
_be_free_str(node->val.d[i].key);
be_free(node->val.d[i].val);
}
free(node->val.d);
break;
}
}
free(node);
}
#ifdef BE_DEBUG
#include <stdio.h>
#include <stdint.h>
static void _be_dump_indent(ssize_t indent)
{
while (indent-- > 0)
printf(" ");
}
static void _be_dump(be_node *node, ssize_t indent)
{
size_t i;
_be_dump_indent(indent);
indent = abs(indent);
switch (node->type) {
case BE_STR:
be_dump_str(node);
//printf("str = %s (len = %lli)\n", node->val.s, be_str_len(node));
break;
case BE_INT:
printf("int = %lli\n", node->val.i);
break;
case BE_LIST:
puts("list [");
for (i = 0; node->val.l[i]; ++i)
_be_dump(node->val.l[i], indent + 1);
_be_dump_indent(indent);
puts("]");
break;
case BE_DICT:
puts("dict {");
for (i = 0; node->val.d[i].val; ++i) {
_be_dump_indent(indent + 1);
printf("%s => ", node->val.d[i].key);
_be_dump(node->val.d[i].val, -(indent + 1));
}
_be_dump_indent(indent);
puts("}");
break;
}
}
void be_dump(be_node *node)
{
_be_dump(node, 0);
}
void be_dump_str(be_node *node)
{
if (node->type != BE_STR)
{
printf("be_dump_str(): error not a string\n");
return;
}
int len = be_str_len(node);
int i = 0;
printf("str[%d] = ", len);
for(i = 0; i < len; i++)
{
/* sensible chars */
if ((node->val.s[i] > 31) && (node->val.s[i] < 127))
{
printf("%c", node->val.s[i]);
}
else
{
printf("[%d]", node->val.s[i]);
}
}
printf("\n");
}
#endif
/******************** New Functions added by drBob *************
* Output bencode
*
*/
int be_encode(be_node *node, char *str, int len)
{
size_t i;
int loc = 0;
switch (node->type) {
case BE_STR:
bd_snprintf(str, len, "%lli:", be_str_len(node));
loc += strlen(&(str[loc]));
memcpy(&(str[loc]), node->val.s, be_str_len(node));
loc += be_str_len(node);
break;
case BE_INT:
bd_snprintf(str, len, "i%llie", node->val.i);
loc += strlen(&(str[loc]));
break;
case BE_LIST:
snprintf(str, len, "l");
loc += 1;
for (i = 0; node->val.l[i]; ++i)
{
loc += be_encode(node->val.l[i], &(str[loc]), len-loc);
}
snprintf(&(str[loc]), len - loc, "e");
loc += 1;
break;
case BE_DICT:
snprintf(str, len, "d");
loc += 1;
for (i = 0; node->val.d[i].val; ++i) {
/* assumption that key must be ascii! */
snprintf(&(str[loc]), len-loc, "%i:%s",
(int) strlen(node->val.d[i].key),
node->val.d[i].key);
loc += strlen(&(str[loc]));
loc += be_encode(node->val.d[i].val, &(str[loc]), len-loc);
}
snprintf(&(str[loc]), len - loc, "e");
loc += 1;
break;
}
return loc;
}
/* hackish way to create nodes! */
be_node *be_create_dict()
{
be_node *n = be_decode("de");
return n;
}
be_node *be_create_list()
{
be_node *n = be_decode("le");
return n;
}
be_node *be_create_str(const char *str)
{
/* must */
be_node *n = NULL;
int len = strlen(str);
long long int sllen = len;
char *_ret = (char *) malloc(sizeof(sllen) + len + 1);
if(_ret == NULL)
{
fprintf(stderr, "(EE) bencode::be_create_str(): "
"ERROR. cannot allocate memory for %lu bytes.\n"
, len+1+sizeof(sllen) );
return n;
}
char *ret = NULL;
n = be_alloc(BE_STR);
memcpy(_ret, &sllen, sizeof(sllen));
ret = _ret + sizeof(sllen);
memcpy(ret, str, len);
ret[len] = '\0';
n->val.s = ret;
return n;
}
be_node *be_create_str_wlen(const char *str, int len) /* not including \0 */
{
/* must */
be_node *n = NULL;
long long int sllen = len;
char *_ret = (char *) malloc(sizeof(sllen) + len + 1);
if(_ret == NULL)
{
fprintf(stderr, "(EE) bencode::be_create_str_wlen(): "
"ERROR. cannot allocate memory for %lu bytes.\n"
, len+1+sizeof(sllen) );
return n;
}
char *ret = NULL;
n = be_alloc(BE_STR);
memcpy(_ret, &sllen, sizeof(sllen));
ret = _ret + sizeof(sllen);
memcpy(ret, str, len);
ret[len] = '\0';
n->val.s = ret;
return n;
}
be_node *be_create_int(long long int num)
{
/* must */
be_node *n = be_alloc(BE_INT);
n->val.i = num;
return n;
}
int be_add_keypair(be_node *dict, const char *str, be_node *node)
{
int i = 0;
/* only if dict type */
if (dict->type != BE_DICT)
{
return 0;
}
// get to end of dict.
for(i = 0; dict->val.d[i].val; i++)
;//Silent empty body for loop for clang
//fprintf(stderr, "be_add_keypair() i = %d\n",i);
/* realloc space */
dict->val.d = (be_dict *) realloc(dict->val.d, (i + 2) * sizeof(*dict->val.d));
/* stupid key storage system */
int len = strlen(str);
long long int sllen = len;
char *_ret = (char *) malloc(sizeof(sllen) + len + 1);
if(_ret == NULL)
{
fprintf(stderr, "(EE) bencode::be_create_str_wlen(): "
"ERROR. cannot allocate memory for %lu bytes.\n"
, len+1+sizeof(sllen) );
return 0;
}
char *ret = NULL;
//fprintf(stderr, "be_add_keypair() key len = %d\n",len);
memcpy(_ret, &sllen, sizeof(sllen));
ret = _ret + sizeof(sllen);
memcpy(ret, str, len);
ret[len] = '\0';
dict->val.d[i].key = ret;
dict->val.d[i].val = node;
i++;
dict->val.d[i].val = NULL;
return 1;
}
int be_add_list(be_node *list, be_node *node)
{
int i = 0;
/* only if dict type */
if (list->type != BE_LIST)
{
return 0;
}
// get to end of dict.
for(i = 0; list->val.l[i]; i++)
;//Silent empty body for loop for clang
/* realloc space */
list->val.l = (be_node **) realloc(list->val.l, (i + 2) * sizeof(*list->val.l));
list->val.l[i] = node;
++i;
list->val.l[i] = NULL;
return 1;
}

View File

@ -1,92 +0,0 @@
/*******************************************************************************
* bitdht/bdencode.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* by Mike Frysinger <vapier@gmail.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef _BENCODE_H
#define _BENCODE_H
/* USAGE:
* - pass the string full of the bencoded data to be_decode()
* - parse the resulting tree however you like
* - call be_free() on the tree to release resources
*/
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
BE_STR,
BE_INT,
BE_LIST,
BE_DICT,
} be_type;
struct be_dict;
struct be_node;
/*
* XXX: the "val" field of be_dict and be_node can be confusing ...
*/
typedef struct be_dict {
char *key;
struct be_node *val;
} be_dict;
typedef struct be_node {
be_type type;
union {
char *s;
long long i;
struct be_node **l;
struct be_dict *d;
} val;
} be_node;
extern long long be_str_len(be_node *node);
// This function uses strlen, so is unreliable.
//extern be_node *be_decode(const char *bencode);
extern be_node *be_decoden(const char *bencode, long long bencode_len);
extern void be_free(be_node *node);
extern void be_dump(be_node *node);
extern void be_dump_str(be_node *node);
// New Functions for the other half of the work - encoding */
extern int be_encode(be_node *node, char *str, int len);
// Creating the data structure.
extern int be_add_list(be_node *list, be_node *node);
extern int be_add_keypair(be_node *dict, const char *str, be_node *node);
extern be_node *be_create_int(long long int num);
extern be_node *be_create_list();
extern be_node *be_create_str(const char *str);
extern be_node *be_create_str_wlen(const char *str, int len); /* not including \0 */
extern be_node *be_create_dict();
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,500 +0,0 @@
77.196.18.56 22750
77.84.97.16 31837
213.174.60.46 17919
50.113.92.209 6881
184.89.243.73 43344
210.195.47.196 19861
83.49.197.212 61627
184.145.109.37 31067
180.18.98.235 29543
186.254.61.185 40200
78.213.113.102 9182
89.92.251.113 16946
195.240.45.224 6881
188.142.164.252 43063
41.45.41.123 18636
219.84.184.204 61337
95.26.91.94 6881
79.114.193.207 17966
83.213.185.157 43235
37.110.127.110 6881
178.35.204.111 6881
174.48.201.143 41918
109.214.57.82 1042
121.214.57.226 51413
90.184.93.164 22828
98.214.166.21 38072
50.0.146.178 51413
81.13.253.217 46370
81.249.29.121 7812
92.80.201.189 20026
95.37.18.51 59118
50.53.143.88 57568
180.183.213.112 11823
112.206.13.117 41825
79.169.77.54 63189
76.174.205.156 8605
2.1.187.15 50269
175.151.131.80 16001
82.7.124.219 12334
217.209.125.15 26155
93.181.201.89 54631
197.87.68.102 25317
183.109.112.49 58359
203.198.141.201 7453
82.192.32.151 58864
184.146.76.179 13586
37.107.121.203 18429
186.54.1.246 38354
184.18.8.33 8784
77.101.130.178 61762
109.8.154.28 19120
74.96.156.188 31749
94.96.167.130 64130
93.81.126.53 6881
79.136.243.46 46486
78.29.75.248 6881
114.42.47.178 9089
31.147.61.11 23853
193.253.220.184 6881
80.57.45.239 28239
72.192.215.39 30028
91.74.119.134 49246
85.250.43.217 41490
188.176.218.22 35407
98.119.4.86 1024
89.143.138.33 64606
46.138.37.148 59039
178.120.85.170 24550
67.185.95.9 32173
98.197.42.116 19866
114.38.21.113 7694
77.46.26.128 38127
93.80.96.134 23683
60.241.209.107 57588
171.97.173.243 9327
50.43.117.21 42660
87.244.169.128 55807
94.190.105.157 6881
178.122.199.251 16480
76.88.254.191 27137
112.120.144.128 60152
77.249.124.77 49187
165.132.236.14 25390
87.16.197.67 20787
80.103.109.43 55260
195.234.21.119 6881
176.212.60.108 60378
178.185.98.43 12420
124.149.151.181 33603
85.220.66.170 35131
109.130.31.27 11460
72.223.102.189 11614
111.15.147.164 16001
83.202.163.16 6881
92.246.22.40 33576
94.41.249.131 10613
95.24.101.211 6881
98.232.199.100 29721
174.101.153.252 38195
91.157.230.16 1885
109.211.143.205 13722
84.123.4.247 29043
112.209.16.158 19102
114.34.46.63 6881
85.138.230.74 56197
62.169.127.9 26665
211.217.2.251 41870
81.221.84.77 20214
109.197.191.45 19604
46.118.116.209 20711
46.42.23.240 53559
199.127.250.15 29015
78.220.115.99 49482
71.232.195.149 56530
84.123.59.159 13963
213.251.184.146 64347
67.164.23.233 7119
86.194.215.166 14316
89.224.149.142 25365
94.23.49.143 8000
78.119.193.151 55227
78.222.160.139 37995
89.209.82.248 12425
178.137.112.35 14571
94.23.0.84 51582
78.247.176.4 18105
90.41.206.239 30502
78.241.70.65 22014
98.194.6.21 51413
174.119.150.115 17065
189.5.22.202 52412
93.124.97.171 49001
186.4.42.27 20837
24.144.184.102 14888
78.173.175.56 53453
79.114.14.206 4602
109.184.163.146 11789
98.200.252.137 18502
79.82.130.49 20757
5.165.66.132 63326
46.29.147.201 20232
114.32.184.15 25962
94.21.70.206 50541
92.98.171.108 51413
188.49.25.79 46883
90.149.227.168 49241
92.99.221.105 51405
123.139.45.71 16001
68.98.108.234 24290
88.169.60.195 17108
114.37.154.22 16120
121.219.232.47 65073
46.119.196.109 19075
123.110.104.200 29499
77.73.46.124 28966
87.253.26.85 45934
176.108.146.88 6881
188.187.45.126 43757
92.2.212.97 15078
178.140.169.137 22922
114.38.14.84 16958
80.98.106.227 9773
86.169.117.185 51938
201.53.229.60 1041
65.95.191.51 51413
24.78.8.98 6884
90.204.42.12 48402
76.7.214.210 35875
88.155.36.246 15856
78.227.88.161 23191
62.83.111.85 36398
130.43.29.146 52526
88.170.61.126 32761
85.246.109.226 6890
82.237.40.39 39052
95.239.56.106 62200
71.187.209.2 22274
178.148.68.18 53318
78.163.220.242 31758
188.235.149.202 63083
119.201.103.241 62715
83.87.5.5 43317
201.83.71.123 50579
83.6.22.221 52512
95.54.76.150 56930
207.255.112.154 6881
188.121.244.133 10980
41.212.221.164 33050
178.168.58.44 23476
142.161.41.171 41788
211.133.168.214 44631
220.18.72.3 64774
70.114.155.3 34892
97.85.86.199 6890
119.74.54.94 6881
114.34.239.242 22647
67.128.168.196 11524
86.145.211.200 49330
72.230.75.87 21095
31.35.57.129 13924
190.60.48.165 41301
213.245.41.143 40018
95.104.80.193 6881
120.208.30.229 16001
93.105.81.215 21000
93.96.13.136 12181
190.88.179.253 20701
58.7.210.130 51413
195.222.95.57 51413
121.223.47.224 41563
85.219.118.111 27483
78.43.137.174 10409
77.71.220.234 62357
85.107.182.248 19486
37.235.207.247 30166
176.97.212.163 22523
88.230.184.110 25432
94.44.164.74 60966
95.188.23.129 42927
78.242.168.94 34153
62.93.99.6 28010
78.105.105.87 42127
208.101.109.128 53329
164.215.87.224 57073
87.106.187.29 20277
91.121.114.171 58846
80.42.246.251 20502
188.72.98.36 15503
176.31.248.87 6338
118.160.199.38 63400
174.71.20.57 52193
113.161.204.192 6881
2.94.72.90 27587
89.204.110.192 6881
76.121.38.23 58982
93.95.160.156 13118
122.174.156.164 15004
94.155.59.112 57833
176.49.172.107 49001
23.16.200.217 51413
60.241.87.17 24478
108.242.252.38 39304
201.252.144.11 15506
92.125.17.239 25548
114.79.138.158 60635
76.103.79.28 36151
77.71.69.65 12087
138.199.66.212 26174
119.131.41.152 1231
119.202.178.119 45249
78.141.127.164 55618
88.245.188.55 28097
217.165.53.221 24579
46.22.234.12 14916
98.199.98.228 32970
203.213.94.200 14161
66.197.135.74 9870
213.167.206.125 38106
80.83.245.36 6993
112.203.171.200 25932
105.236.34.74 43961
92.49.5.186 38678
46.61.12.234 49001
91.148.14.62 11206
95.37.162.145 14476
68.192.162.202 31159
68.209.239.148 50375
75.185.11.189 23993
178.72.159.43 47954
118.160.199.38 61182
75.142.21.2 56117
46.187.88.219 48529
98.127.163.114 53062
94.245.153.136 23040
109.174.3.81 51413
77.232.162.51 14257
94.96.112.204 35187
118.160.199.38 51651
5.13.18.103 24121
79.226.190.78 18189
95.90.236.216 41463
83.134.60.207 10267
118.160.199.38 51532
176.31.109.159 24586
99.242.88.203 21704
88.174.176.173 56969
84.151.248.98 61500
123.195.214.39 20846
94.62.25.152 39020
89.33.72.233 1398
92.37.27.83 37375
83.110.225.79 17257
178.36.198.215 22849
112.234.202.158 16001
188.231.143.20 6881
5.12.126.206 34538
62.65.216.158 13414
92.43.189.45 3140
79.9.144.222 29037
93.77.32.187 57408
91.247.142.205 58199
85.114.60.149 17582
119.196.44.47 51763
178.88.3.227 33031
76.30.131.83 49366
86.168.167.166 55451
212.45.81.173 16427
188.224.10.109 46059
82.178.114.74 50836
78.55.114.191 42839
85.54.211.184 17283
95.135.101.164 55829
209.195.77.83 34603
79.153.101.234 11154
71.63.225.31 21053
184.147.116.143 49025
88.186.230.88 12048
89.132.181.63 61498
95.84.208.14 9372
79.93.218.69 28681
64.113.125.178 61127
174.100.51.253 44460
88.3.236.194 10926
109.194.234.36 14342
68.106.225.140 47417
78.24.231.166 6881
84.40.80.3 6890
177.5.36.152 12588
68.82.32.238 18307
64.121.118.201 61270
75.40.21.238 51413
99.59.129.46 26141
79.95.171.102 11092
67.71.140.245 15582
95.32.187.214 14778
213.112.177.129 43304
81.51.97.133 40039
89.133.89.51 55846
79.18.246.192 20356
109.124.197.42 31559
182.53.45.3 14895
74.219.135.69 30239
95.111.0.20 34295
84.154.235.198 59678
93.58.14.83 51413
213.114.48.42 38511
46.48.90.11 55025
5.2.58.49 49001
92.139.252.16 36535
94.68.144.118 10009
75.187.202.104 44822
84.52.169.26 10838
114.32.211.85 30116
75.69.72.31 51413
118.160.199.38 63151
142.59.218.136 11300
118.160.199.38 63619
118.160.199.38 59277
82.47.63.231 26035
67.8.141.69 63990
223.18.249.29 7221
82.136.113.22 6881
86.100.227.142 50497
188.186.13.95 21313
24.128.39.166 5223
31.8.136.66 11996
82.137.118.90 26474
84.217.43.156 45620
217.29.187.23 62523
108.254.5.66 58192
182.177.228.43 31532
118.160.199.38 60134
67.167.180.162 11451
188.164.212.104 28566
95.196.203.111 59402
213.27.20.223 53410
178.44.187.32 52209
70.83.35.78 31982
1.172.161.190 17526
78.237.111.89 45254
188.25.246.130 16313
67.173.33.90 33134
212.49.47.32 19949
176.214.214.73 64892
173.73.46.92 52828
71.237.6.246 41304
70.113.2.167 45645
88.84.191.25 30536
87.2.74.180 6783
96.63.15.208 34651
76.181.135.146 17016
79.168.31.62 2622
95.153.169.40 19697
88.217.36.182 2924
119.96.130.9 12038
90.225.103.241 40066
78.106.178.64 46183
220.136.37.144 27075
92.87.167.73 55624
188.232.61.83 6881
183.89.3.101 10618
111.242.54.149 15979
120.146.228.149 6881
67.242.169.143 6886
31.8.71.71 10170
78.236.77.65 32026
91.137.168.238 27616
93.109.84.235 21443
77.34.44.71 35691
109.209.40.17 55542
83.157.77.228 7812
88.233.167.39 20620
69.176.171.40 11254
93.11.175.201 41027
50.71.135.98 20332
69.181.169.181 7313
46.8.136.196 57085
180.64.39.48 14708
46.211.113.5 49001
142.163.53.182 58144
90.38.76.72 4699
83.252.23.84 10699
78.163.181.120 16519
221.118.191.176 17563
184.41.75.34 57537
99.192.77.139 33333
88.174.167.76 30032
46.116.177.103 22754
94.103.196.139 54378
188.77.246.133 35496
217.76.184.18 51413
108.160.185.132 31530
50.83.34.19 23846
193.77.159.24 43611
80.14.161.164 51789
114.185.184.10 23151
82.235.101.26 7816
92.83.188.95 10477
46.180.245.79 53580
46.37.83.122 37389
86.29.220.199 28527
92.137.208.191 29253
85.167.249.218 55649
221.127.216.99 21461
130.89.165.24 10110
99.60.78.40 18894
49.145.59.194 38935
92.247.248.50 23666
5.149.211.210 22277
176.226.153.243 61967
174.117.49.59 13052
121.141.14.57 30323
83.155.218.188 51413
129.21.122.81 32785
46.118.83.183 12324
92.255.208.221 34798
212.21.13.209 56909
220.120.236.151 11393
37.218.190.131 35691
46.41.109.26 39584
2.51.116.185 63433
67.86.174.199 33605
212.74.222.13 38345
115.240.98.113 51413
37.59.55.58 51413
109.72.144.240 41290
207.224.196.66 10731
78.128.52.177 24574
79.138.67.151 47942
50.201.138.122 10228
176.9.113.77 61059
94.21.30.143 63448
178.89.100.227 6881
91.67.129.216 1210
82.232.212.66 55826
78.228.230.130 12577
79.175.106.234 12684
213.231.145.208 12306
97.106.156.54 63552
79.176.173.50 33043
75.70.84.67 52856
31.220.168.41 35190
1.161.107.196 31811
80.98.158.177 29436
88.148.233.194 38081
184.166.72.229 63472
93.186.192.165 39020
151.25.110.226 49289
178.45.159.135 31825
98.225.11.98 51769
109.28.82.4 33620
90.16.53.195 31338
223.219.73.227 17107
92.96.51.71 56237
112.173.11.227 63314
37.229.60.103 6881
90.29.226.250 14329
182.210.49.84 11993
177.32.251.226 27655
189.54.195.49 50555

View File

@ -1,349 +0,0 @@
/*
* libretroshare/src/dht: bdhandler.h
*
* BitDht example interface
*
* Copyright 2009-2010 by Robert Fernie.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 2 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include <udp/udpstack.h>
#include <udp/udpbitdht.h>
#include <bitdht/bdstddht.h>
#include <string.h>
#include <string.h>
#include "bdhandler.h"
/****
* This example bitdht app is designed to perform a single shot DHT search.
* Ww want to minimise the dht work, and number of UDP packets sent.
*
* This means we need to add:
* - don't search for App network. (libbitdht option)
* - don't bother filling up Space. (libbitdht option)
* - Programmatically add bootstrap peers. (libbitdht option)
*
*/
/* This is a conversion callback class
*/
class BdCallback: public BitDhtCallback
{
public:
BdCallback(BitDhtHandler *parent)
:mParent(parent) { return; }
virtual int dhtNodeCallback(const bdId *id, uint32_t peerflags)
{
return mParent->NodeCallback(id, peerflags);
}
virtual int dhtPeerCallback(const bdId *id, uint32_t status)
{
return mParent->PeerCallback(id, status);
}
virtual int dhtValueCallback(const bdNodeId *id, std::string key, uint32_t status)
{
return mParent->ValueCallback(id, key, status);
}
virtual int dhtConnectCallback(const bdId*, const bdId*, const bdId*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
{
return 1;
}
virtual int dhtInfoCallback(const bdId*, uint32_t, uint32_t, std::string)
{
return 1;
}
private:
BitDhtHandler *mParent;
};
BitDhtHandler::BitDhtHandler(bdNodeId *ownId, uint16_t port, std::string appId, std::string bootstrapfile)
{
std::cerr << "BitDhtHandler::BitDhtHandler()" << std::endl;
std::cerr << "Using Id: ";
bdStdPrintNodeId(std::cerr, ownId);
std::cerr << std::endl;
std::cerr << "Using Bootstrap File: " << bootstrapfile;
std::cerr << std::endl;
std::cerr << "Converting OwnId to bdNodeId....";
std::cerr << std::endl;
/* standard dht behaviour */
bdDhtFunctions *stdfns = new bdStdDht();
std::cerr << "BitDhtHandler() startup ... creating UdpBitDht";
std::cerr << std::endl;
/* create dht */
struct sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_addr.s_addr = 0;
local.sin_port = htons(port);
mStack = new UdpStack(local);
mUdpBitDht = new UdpBitDht(mStack, ownId, appId, bootstrapfile, stdfns);
mStack->addReceiver(mUdpBitDht);
/* setup callback to here */
BdCallback *bdcb = new BdCallback(this);
mUdpBitDht->addCallback(bdcb);
std::cerr << "BitDhtHandler() starting threads and dht";
std::cerr << std::endl;
mUdpBitDht->start(); /* starts up the bitdht thread */
/* setup best mode for quick search */
uint32_t dhtFlags = BITDHT_MODE_TRAFFIC_MED | BITDHT_MODE_RELAYSERVERS_IGNORED;
mUdpBitDht->setDhtMode(dhtFlags);
mUdpBitDht->setAttachMode(false);
/* switch on the dht too */
mUdpBitDht->startDht();
}
/* pqiNetAssist - external interface functions */
void BitDhtHandler::enable(bool on)
{
std::cerr << "p3BitDht::enable(" << on << ")";
std::cerr << std::endl;
if (on)
{
mUdpBitDht->startDht();
}
else
{
mUdpBitDht->stopDht();
}
}
void BitDhtHandler::shutdown() /* blocking call */
{
mUdpBitDht->stopDht();
}
void BitDhtHandler::restart()
{
mUdpBitDht->stopDht();
mUdpBitDht->startDht();
}
bool BitDhtHandler::getEnabled()
{
return (mUdpBitDht->stateDht() != 0);
}
bool BitDhtHandler::getActive()
{
return (mUdpBitDht->stateDht() >= BITDHT_MGR_STATE_ACTIVE);
}
/* pqiNetAssistConnect - external interface functions */
/* add / remove peers */
bool BitDhtHandler::FindNode(bdNodeId *peerId)
{
std::cerr << "BitDhtHandler::FindNode(";
bdStdPrintNodeId(std::cerr, peerId);
std::cerr << ")" << std::endl;
BssResult res;
res.id.id = *peerId;
res.mode = BSS_SINGLE_SHOT;
res.status = 0;
{
bdStackMutex stack(resultsMtx); /********** MUTEX LOCKED *************/
mSearchNodes[*peerId] = res;
}
/* add in peer */
mUdpBitDht->addFindNode(peerId, BITDHT_QFLAGS_DISGUISE);
return true ;
}
bool BitDhtHandler::DropNode(bdNodeId *peerId)
{
std::cerr << "BitDhtHandler::DropNode(";
bdStdPrintNodeId(std::cerr, peerId);
std::cerr << ")" << std::endl;
std::cerr << std::endl;
/* remove in peer */
mUdpBitDht->removeFindNode(peerId);
bdStackMutex stack(resultsMtx); /********** MUTEX LOCKED *************/
/* find the node from our list */
std::map<bdNodeId, BssResult>::iterator it;
it = mSearchNodes.find(*peerId);
if (it != mSearchNodes.end())
{
std::cerr << "BitDhtHandler::DropNode() Found NodeId, removing";
std::cerr << std::endl;
mSearchNodes.erase(it);
}
return true ;
}
bool BitDhtHandler::SearchResult(bdId *id, uint32_t &status)
{
bdStackMutex stack(resultsMtx); /********** MUTEX LOCKED *************/
/* find the node from our list */
std::map<bdNodeId, BssResult>::iterator it;
it = mSearchNodes.find(id->id);
if (it != mSearchNodes.end())
{
if (it->second.status != 0)
{
std::cerr << "BitDhtHandler::SearchResults() Found Results";
std::cerr << std::endl;
status = it->second.status;
*id = it->second.id;
return true;
}
std::cerr << "BitDhtHandler::SearchResults() No Results Yet";
std::cerr << std::endl;
return false;
}
std::cerr << "BitDhtHandler::SearchResults() ERROR: No Search Entry";
std::cerr << std::endl;
return false;
}
/********************** Callback Functions **************************/
int BitDhtHandler::NodeCallback(const bdId *id, uint32_t peerflags)
{
#ifdef DEBUG_BITDHT
std::cerr << "BitDhtHandler::NodeCallback()";
bdStdPrintNodeId(std::cerr, &(id->id));
std::cerr << " flags: " << peerflags;
std::cerr << std::endl;
#endif
return 0;
}
int BitDhtHandler::PeerCallback(const bdId *id, uint32_t status)
{
std::cerr << "BitDhtHandler::PeerCallback() NodeId: ";
bdStdPrintId(std::cerr, id);
std::cerr << std::endl;
bdStackMutex stack(resultsMtx); /********** MUTEX LOCKED *************/
/* find the node from our list */
std::map<bdNodeId, BssResult>::iterator it;
it = mSearchNodes.find(id->id);
if (it == mSearchNodes.end())
{
std::cerr << "BitDhtHandler::PeerCallback() Unknown NodeId !!! ";
std::cerr << std::endl;
return 1;
}
it->second.status = status;
bool connect = false;
switch(status)
{
case BITDHT_MGR_QUERY_FAILURE:
/* do nothing */
std::cerr << "BitDhtHandler::PeerCallback() QUERY FAILURE ... do nothin ";
std::cerr << std::endl;
break;
case BITDHT_MGR_QUERY_PEER_OFFLINE:
/* do nothing */
std::cerr << "BitDhtHandler::PeerCallback() QUERY PEER OFFLINE ... do nothin ";
std::cerr << std::endl;
break;
case BITDHT_MGR_QUERY_PEER_UNREACHABLE:
/* do nothing */
std::cerr << "BitDhtHandler::PeerCallback() QUERY PEER UNREACHABLE ... saving address ";
std::cerr << std::endl;
it->second.id = *id;
break;
case BITDHT_MGR_QUERY_PEER_ONLINE:
/* do something */
std::cerr << "BitDhtHandler::PeerCallback() QUERY PEER ONLINE ... saving address";
std::cerr << std::endl;
it->second.id = *id;
break;
}
return 1;
}
int BitDhtHandler::ValueCallback(const bdNodeId *id, std::string key, uint32_t status)
{
std::cerr << "BitDhtHandler::ValueCallback() NOOP for NOW";
std::cerr << std::endl;
std::cerr << "BitDhtHandler::ValueCallback()";
bdStdPrintNodeId(std::cerr, id);
std::cerr << " key: " << key;
std::cerr << " status: " << status;
std::cerr << std::endl;
/* ignore for now */
return 0;
}

View File

@ -1,88 +0,0 @@
/*
* libbitdht/src/example/bdhandler.h
*
* BitDht interface example
*
* Copyright 2009-2010 by Robert Fernie.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 2 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#ifndef BITDHT_HANDLER_H
#define BITDHT_HANDLER_H
#include <string>
#include <map>
#include "udp/udpstack.h"
#include "udp/udpbitdht.h"
#include "bitdht/bdiface.h"
/*** This class can be overloaded to use the XXXXCallback() Functions *****/
class BitDhtIntCallback;
class BssResult
{
public:
bdId id;
uint32_t mode; // single shot
uint32_t status; // SEARCHING, FAILURE, FOUND, MULTIPLE HITS.
};
#define BSS_SINGLE_SHOT 0x0001
class BitDhtHandler
{
public:
BitDhtHandler(bdNodeId *ownId, uint16_t port, std::string appId, std::string bootstrapfile);
void enable(bool on);
void shutdown(); /* blocking call */
void restart();
bool getEnabled();
bool getActive();
bool FindNode(bdNodeId *peerId);
bool DropNode(bdNodeId *peerId);
virtual int NodeCallback(const bdId *id, uint32_t peerflags);
virtual int PeerCallback(const bdId *id, uint32_t status);
virtual int ValueCallback(const bdNodeId *id, std::string key, uint32_t status);
bool SearchResult(bdId *id, uint32_t &status);
private:
/* real DHT classes */
UdpStack *mStack;
UdpBitDht *mUdpBitDht;
bdMutex resultsMtx; /* for all class data (below) */
std::map<bdNodeId, BssResult> mSearchNodes;
};
#endif /* BITDHT_HANDLER_H */

View File

@ -1,84 +0,0 @@
#include "bitdht/bdiface.h"
#include "bitdht/bdstddht.h"
#include "bdhandler.h"
#include "bootstrap_fn.h"
bool bdSingleShotFindPeer(const std::string bootstrapfile, const std::string peerId, std::string &peer_ip, uint16_t &peer_port)
{
/* startup dht : with a random id! */
bdNodeId ownId;
bdStdRandomNodeId(&ownId);
uint16_t port = 6775;
std::string appId = "bsId";
BitDhtHandler dht(&ownId, port, appId, bootstrapfile);
/* install search node */
bdNodeId searchId;
if (!bdStdLoadNodeId(&searchId, peerId))
{
std::cerr << "bdSingleShotFindPeer(): Invalid Input Id: " << peerId;
return false;
}
std::cerr << "bssdht: searching for Id: ";
bdStdPrintNodeId(std::cerr, &searchId);
std::cerr << std::endl;
dht.FindNode(&searchId);
/* run your program */
bdId resultId;
uint32_t status;
resultId.id = searchId;
while(false == dht.SearchResult(&resultId, status))
{
sleep(10);
}
std::cerr << "bdSingleShotFindPeer(): Found Result:" << std::endl;
std::cerr << "\tId: ";
bdStdPrintId(std::cerr, &resultId);
std::cerr << std::endl;
std::cerr << "\tstatus: " << status;
std::cerr << std::endl;
dht.shutdown();
if ((status == BITDHT_QUERY_PEER_UNREACHABLE) ||
(status == BITDHT_QUERY_SUCCESS))
{
peer_ip = bdnet_inet_ntoa(resultId.addr.sin_addr);
peer_port = ntohs(resultId.addr.sin_port);
std::cerr << "Answer: ";
std::cerr << std::endl;
std::cerr << "\tPeer IpAddress: " << peer_ip;
std::cerr << std::endl;
std::cerr << "\tPeer Port: " << peer_port;
std::cerr << std::endl;
}
else
{
std::cerr << "Sorry, Cant be found!";
std::cerr << std::endl;
}
return true;
}

View File

@ -1,17 +0,0 @@
#include <string>
#include <inttypes.h>
/* NOTE. At the moment only the bootstrapfile is actually used.
* peerId is ignored (a random peerId is searched for). ip & port are not filled in either.
*
* This is mainly to finish testing.
*
* Once the best form of the return functions is decided (ipv4 structure, or strings).
* this can be finished off.
*
*/
bool bdSingleShotFindPeer(const std::string bootstrapfile, const std::string peerId, std::string &ip, uint16_t &port);

View File

@ -1,72 +0,0 @@
#include "bootstrap_fn.h"
#include <iostream>
#include <inttypes.h>
void args(char *name)
{
std::cerr << std::endl;
std::cerr << "Dht Single Shot Searcher";
std::cerr << std::endl;
std::cerr << "Usage:";
std::cerr << std::endl;
std::cerr << "\t" << name << " -p <peerId> ";
std::cerr << std::endl;
std::cerr << std::endl;
std::cerr << "NB: The PeerId is Required to Run";
std::cerr << std::endl;
std::cerr << std::endl;
}
int main(int argc, char **argv)
{
std::string bootstrapfile = "bdboot.txt";
std::string peerId;
std::string ip;
uint16_t port;
int c;
bool havePeerId = false;
while((c = getopt(argc, argv,"p:")) != -1)
{
switch (c)
{
case 'p':
peerId = optarg;
havePeerId = true;
break;
default:
args(argv[0]);
return 1;
break;
}
}
if (!havePeerId)
{
args(argv[0]);
return 1;
}
std::cerr << "bssdht: starting up";
std::cerr << std::endl;
bdSingleShotFindPeer(bootstrapfile, peerId, ip, port);
std::cerr << "bssdht: finished";
std::cerr << std::endl;
return 1;
}

View File

@ -1,177 +0,0 @@
# RetroShare main qmake build script
#
# Copyright (C) 2004-2019, Retroshare Team <contact@retroshare.cc>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-FileCopyrightText: Retroshare Team <contact@retroshare.cc>
# SPDX-License-Identifier: LGPL-3.0-or-later
!include("../../retroshare.pri"): error("Could not include file ../../retroshare.pri")
TEMPLATE = lib
CONFIG += staticlib
CONFIG -= qt
TARGET = bitdht
DESTDIR = lib
!include("use_libbitdht.pri"):error("Including")
QMAKE_CXXFLAGS *= -DBE_DEBUG
################################# Linux ##########################################
linux-* {
QMAKE_CC = $${QMAKE_CXX}
}
linux-g++ {
OBJECTS_DIR = temp/linux-g++/obj
}
linux-g++-64 {
OBJECTS_DIR = temp/linux-g++-64/obj
}
unix {
data_files.path = "$${DATA_DIR}"
data_files.files = bitdht/bdboot.txt
INSTALLS += data_files
}
android-* {
# see https://community.kde.org/Necessitas/Assets
bdboot.files=bitdht/bdboot.txt
bdboot.path=/assets/values
INSTALLS += bdboot
}
#################### Cross compilation for windows under Linux ####################
win32-x-g++ {
OBJECTS_DIR = temp/win32xgcc/obj
# These have been replaced by _WIN32 && __MINGW32__
# DEFINES *= WINDOWS_SYS WIN32 WIN_CROSS_UBUNTU
QMAKE_CXXFLAGS *= -Wmissing-include-dirs
QMAKE_CC = i586-mingw32msvc-g++
QMAKE_LIB = i586-mingw32msvc-ar
QMAKE_AR = i586-mingw32msvc-ar
DEFINES *= STATICLIB WIN32
INCLUDEPATH *= /usr/i586-mingw32msvc/include ${HOME}/.wine/drive_c/pthreads/include/
}
################################# Windows ##########################################
win32 {
QMAKE_CC = $${QMAKE_CXX}
OBJECTS_DIR = temp/obj
MOC_DIR = temp/moc
DEFINES *= STATICLIB WIN32_LEAN_AND_MEAN
# These have been replaced by _WIN32 && __MINGW32__
#DEFINES *= WINDOWS_SYS WIN32 STATICLIB MINGW
# Switch off optimization for release version
QMAKE_CXXFLAGS_RELEASE -= -O2
QMAKE_CXXFLAGS_RELEASE += -O0
QMAKE_CFLAGS_RELEASE -= -O2
QMAKE_CFLAGS_RELEASE += -O0
# Switch on optimization for debug version
#QMAKE_CXXFLAGS_DEBUG += -O2
#QMAKE_CFLAGS_DEBUG += -O2
}
################################# MacOSX ##########################################
mac {
QMAKE_CC = $${QMAKE_CXX}
OBJECTS_DIR = temp/obj
MOC_DIR = temp/moc
}
################################# FreeBSD ##########################################
freebsd-* {
}
################################# OpenBSD ##########################################
openbsd-* {
}
################################# Haiku ##########################################
haiku-* {
DESTDIR = lib
}
################################### COMMON stuff ##################################
################################### COMMON stuff ##################################
DEPENDPATH += .
INCLUDEPATH += .
HEADERS += \
bitdht/bdiface.h \
bitdht/bencode.h \
bitdht/bdobj.h \
bitdht/bdmsgs.h \
bitdht/bdpeer.h \
bitdht/bdquery.h \
bitdht/bdhash.h \
bitdht/bdstore.h \
bitdht/bdnode.h \
bitdht/bdmanager.h \
bitdht/bdstddht.h \
bitdht/bdhistory.h \
util/bdnet.h \
util/bdthreads.h \
util/bdrandom.h \
util/bdfile.h \
util/bdstring.h \
udp/udplayer.h \
udp/udpstack.h \
udp/udpbitdht.h \
bitdht/bdconnection.h \
bitdht/bdfilter.h \
bitdht/bdaccount.h \
bitdht/bdquerymgr.h \
util/bdbloom.h \
bitdht/bdfriendlist.h \
SOURCES += \
bitdht/bencode.c \
bitdht/bdobj.cc \
bitdht/bdmsgs.cc \
bitdht/bdpeer.cc \
bitdht/bdquery.cc \
bitdht/bdhash.cc \
bitdht/bdstore.cc \
bitdht/bdnode.cc \
bitdht/bdmanager.cc \
bitdht/bdstddht.cc \
bitdht/bdhistory.cc \
util/bdnet.cc \
util/bdthreads.cc \
util/bdrandom.cc \
util/bdfile.cc \
util/bdstring.cc \
udp/udplayer.cc \
udp/udpstack.cc \
udp/udpbitdht.cc \
bitdht/bdconnection.cc \
bitdht/bdfilter.cc \
bitdht/bdaccount.cc \
bitdht/bdquerymgr.cc \
util/bdbloom.cc \
bitdht/bdfriendlist.cc \

View File

@ -1,90 +0,0 @@
/*
* bitdht/bdbloom_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include <stdio.h>
#include "util/bdbloom.h"
#include "bitdht/bdstddht.h"
#include <iostream>
#define N_TESTS 100
int main(int argc, char **argv)
{
/* read from the file */
if (argc < 2)
{
std::cerr << "Missing Hash File";
std::cerr << std::endl;
}
FILE *fd = fopen(argv[1], "r");
if (!fd)
{
std::cerr << "Failed to Open File: " << argv[1];
std::cerr << std::endl;
return 1;
}
char line[1000];
bdBloom filter;
int nHashes = 0;
while(fgets(line, 1000-1, fd))
{
std::string hash = line;
std::cerr << "Read Hash: " << hash;
std::cerr << std::endl;
filter.add(hash);
nHashes++;
}
fclose(fd);
filter.printFilter(std::cerr);
int bits = filter.countBits();
int filterBits = filter.filterBits();
std::cerr << "Filter Bits Set: " << bits;
std::cerr << std::endl;
double possible = ((double) bits) * bits;
double max = ((double) filterBits) * filterBits;
std::cerr << "Therefore Possible Finds: " << possible << "/" << max << " = %" << 100 * possible / max;
std::cerr << std::endl;
std::cerr << "With Insertions: " << nHashes;
std::cerr << std::endl;
std::cerr << std::endl;
std::cerr << std::endl;
std::cerr << "Filter String: " << filter.getFilter() << std::endl;
std::cerr << std::endl;
std::cerr << std::endl;
return 1;
}

View File

@ -1,164 +0,0 @@
/*
* bitdht/bdbloom_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include <sstream>
#include "util/bdbloom.h"
#include "bitdht/bdstddht.h"
#include <iostream>
#define N_TESTS 100
int main(int argc, char **argv)
{
/* Do this multiple times */
int i;
bdBloom filter;
std::list<bdNodeId> testIds;
std::list<bdNodeId>::iterator it;
for(i = 0; i < N_TESTS; i++)
{
bdNodeId targetId;
bdStdRandomNodeId(&targetId);
testIds.push_back(targetId);
}
std::cerr << "Test bdBloom Filter...." << std::endl;
for(it = testIds.begin(); it != testIds.end(); it++)
{
bdNodeId targetId = *it;
std::cerr << "-------------------------------------------------" << std::endl;
std::cerr << "Inserting : ";
std::ostringstream str;
bdStdPrintNodeId(str, &targetId);
std::cerr << str.str();
std::cerr << std::endl;
filter.add(str.str());
filter.printFilter(std::cerr);
}
std::string fs1 = filter.getFilter();
/* now extract, and reinsert filter */
bdBloom filter2;
filter2.setFilterBits(fs1);
std::string fs2 = filter2.getFilter();
filter2.printFilter(std::cerr);
if (fs1 == fs2)
{
std::cerr << "SUCCESS: Filter Correctly Transferred!";
std::cerr << std::endl;
}
else
{
std::cerr << "FAILURE: Filter Not Transferred!";
std::cerr << std::endl;
}
for(it = testIds.begin(); it != testIds.end(); it++)
{
bdNodeId targetId = *it;
std::cerr << "-------------------------------------------------" << std::endl;
std::cerr << "Testing : ";
std::cerr << std::endl;
std::ostringstream str;
bdStdPrintNodeId(str, &targetId);
std::cerr << str.str() << std::endl;
if (filter2.test(str.str()))
{
std::cerr << "SUCCESS: Filter Found Entry";
std::cerr << std::endl;
}
else
{
std::cerr << "FAILURE: Filter Didn't Found Entry";
std::cerr << std::endl;
}
}
int bits = filter.countBits();
int filterBits = filter.filterBits();
std::cerr << "Filter Bits Set: " << bits;
std::cerr << std::endl;
double possible = ((double) bits) * bits;
double max = ((double) filterBits) * filterBits;
std::cerr << "Therefore Possible Finds: " << possible << "/" << max << " = %" << 100 * possible / max;
std::cerr << std::endl;
std::cerr << "With Insertions: " << N_TESTS;
std::cerr << std::endl;
#define FINAL_TESTS (1000000)
int found = 0;
int didnt = 0;
for(i = 0; i < FINAL_TESTS; i++)
{
if ((i != 0) && (i % 100000 == 0))
{
std::cerr << "Run " << i << " Checks" << std::endl;
}
bdNodeId targetId;
bdStdRandomNodeId(&targetId);
std::ostringstream str;
bdStdPrintNodeId(str, &targetId);
if (filter2.test(str.str()))
{
found++;
}
else
{
didnt++;
}
}
std::cerr << "Final Stats: " << FINAL_TESTS << " random checks done";
std::cerr << std::endl;
std::cerr << "\t" << found << " " << 100.0 * ((double) found) / FINAL_TESTS << "% found";
std::cerr << std::endl;
std::cerr << "\t" << didnt << " " << 100.0 * ((double) didnt) / FINAL_TESTS << "% didnt";
std::cerr << std::endl;
return 1;
}

View File

@ -1,500 +0,0 @@
50.193.28.158 36327
88.181.96.123 11328
99.37.188.41 29653
88.72.55.221 12254
76.103.79.28 36151
78.219.65.122 18814
50.80.44.10 60059
82.66.32.246 39882
89.88.138.23 50082
93.9.151.183 41948
60.35.23.158 12641
93.181.45.102 62514
41.249.53.96 52932
82.227.12.97 46602
89.156.177.7 29920
178.236.129.166 56294
46.173.64.63 44300
86.73.179.122 59624
209.195.101.75 44444
76.114.41.44 13750
188.103.108.41 1580
74.192.244.156 23315
91.217.90.22 58541
27.32.169.219 57166
175.196.134.95 6890
99.229.202.165 36801
119.14.195.27 60485
112.206.13.117 41825
87.89.253.70 52870
203.186.173.169 22508
122.168.241.122 16167
113.250.99.211 3319
87.106.249.208 4281
97.90.151.69 54641
81.249.29.121 7812
24.122.0.38 5007
79.119.57.255 48324
84.237.250.67 60736
72.208.178.104 46970
93.7.211.121 35220
82.126.138.5 31165
98.21.67.18 56158
174.101.153.252 38195
70.184.208.133 1664
173.12.200.5 5996
5.39.78.183 7777
212.178.8.49 61787
81.38.140.98 37021
189.4.28.74 28817
90.55.204.2 38814
183.89.101.187 63939
175.208.45.169 32911
124.86.6.169 14743
58.168.9.105 36962
89.178.158.14 54494
86.23.51.76 44444
111.119.227.15 26632
68.82.46.243 31651
91.20.211.178 57166
89.85.171.145 32926
75.126.109.30 15009
88.170.61.126 32761
82.237.40.39 39052
80.101.24.220 17412
95.84.208.14 9372
109.212.31.106 4662
80.98.106.227 9773
67.197.115.77 33457
212.43.36.251 20273
129.21.122.81 32785
109.187.235.96 49414
93.66.62.37 59880
81.169.151.138 42157
67.252.30.196 41576
77.176.247.93 7812
178.65.138.159 52160
178.17.18.206 8028
96.53.93.210 56028
80.236.120.181 14451
37.24.108.103 2000
95.171.138.138 42342
88.72.55.221 37933
89.133.71.20 14968
96.250.108.15 45291
86.74.221.169 36035
111.50.223.158 16001
46.33.251.143 11789
159.224.9.168 57529
74.4.200.21 45569
77.224.214.10 7886
91.237.165.36 55393
71.65.115.24 60705
180.245.74.54 10065
89.229.5.2 1040
178.129.19.231 53510
76.23.105.94 47088
76.121.226.114 47476
108.77.112.69 51413
24.246.67.233 55806
95.25.123.108 17701
142.161.104.76 16956
90.56.162.201 53163
62.99.25.102 22309
116.14.209.177 59826
213.87.123.121 20587
83.165.11.132 9481
122.150.77.71 6890
77.236.180.89 24819
84.24.96.215 6881
98.176.147.218 62776
79.82.130.49 20757
78.43.137.174 10409
74.136.3.207 43112
95.133.243.200 7509
71.232.162.47 10580
209.195.104.126 6881
178.82.162.111 36190
175.173.87.138 16001
72.218.218.39 6881
84.252.26.117 10264
46.166.104.222 50700
86.52.88.196 52333
188.186.142.97 22222
63.227.112.135 40297
110.171.80.30 50831
62.16.187.208 60193
41.221.124.3 12720
122.86.88.153 5831
46.29.209.84 6881
83.165.111.199 63885
80.98.162.185 51413
176.73.16.252 34976
24.188.113.226 42817
88.207.42.112 51187
85.230.147.123 58371
50.92.78.248 41837
94.212.214.204 52385
86.52.180.140 6881
94.23.198.174 51413
212.198.182.174 18060
78.234.129.171 33797
125.186.188.58 6881
94.210.26.194 16981
109.64.246.237 23252
86.201.102.163 51413
75.82.14.204 37960
172.1.72.173 31558
86.71.169.12 32682
37.110.130.32 61724
61.64.143.4 59026
202.79.36.129 58060
88.254.55.5 53323
84.39.4.247 6881
31.151.104.160 51413
201.87.14.68 50129
24.246.26.61 51151
101.103.182.123 36511
95.111.64.209 10076
89.224.149.142 25365
46.21.211.0 18488
49.49.27.110 13392
60.185.230.42 64770
188.27.125.50 51464
212.21.6.250 64885
114.243.240.207 53212
89.40.161.33 29112
14.145.16.208 18746
186.204.50.237 17198
124.115.12.153 2043
47.54.129.97 47411
109.200.116.239 17972
213.16.182.12 25128
217.20.73.188 35691
182.177.193.44 10083
80.222.111.127 35847
79.94.175.146 41542
74.141.87.159 55574
95.37.172.1 11051
77.100.104.142 54078
80.184.19.34 35010
94.180.203.42 6881
37.201.168.34 48690
95.28.111.83 11777
84.208.143.35 50422
188.186.45.35 17670
90.146.80.87 26792
122.121.191.214 47448
31.181.0.236 6881
99.242.88.203 21704
176.31.109.159 32450
62.93.99.6 28010
95.90.236.216 41463
95.132.145.53 17125
222.216.168.211 50260
182.96.166.223 4565
111.92.19.48 46488
88.170.61.126 7465
216.49.152.239 59312
108.46.182.176 23053
59.19.172.14 58485
159.224.26.228 13839
184.147.15.149 64385
41.98.81.187 10109
90.5.180.162 18619
81.198.134.16 6881
66.229.51.242 51413
82.11.60.187 55393
62.194.99.138 18011
178.151.1.128 20702
84.98.19.169 36650
84.224.105.232 13220
68.115.149.90 49710
37.205.70.166 35691
85.232.130.42 62207
83.158.230.144 55555
83.246.216.234 49001
92.233.249.147 55582
41.108.95.129 12262
83.152.236.89 58730
115.220.147.35 7076
78.106.26.128 26900
84.101.22.120 55512
89.142.253.198 10520
151.64.241.149 51346
95.168.12.60 63676
213.46.147.163 38512
85.130.52.88 25279
90.193.28.149 22222
79.132.25.126 59243
111.250.206.117 25332
99.230.144.57 34023
112.192.66.172 1242
58.170.183.148 16308
110.76.72.49 13412
80.9.174.99 58943
84.98.243.248 13291
91.148.138.106 17006
173.193.242.231 25025
173.193.242.231 37448
84.244.2.193 27947
78.45.13.229 19014
173.193.242.231 22859
119.154.190.187 43623
213.65.128.142 55595
78.234.140.58 8080
92.142.60.155 6881
189.59.195.217 64931
122.169.6.171 35672
178.47.227.162 33893
46.246.67.243 64453
46.119.144.241 49001
174.36.55.75 18688
94.243.89.164 57848
209.140.255.87 20785
62.77.128.245 51413
91.211.177.3 20588
81.84.65.143 12157
68.228.230.85 20862
108.90.48.119 51413
24.212.131.70 48665
85.23.70.134 53440
217.55.204.253 12652
31.180.94.141 35691
109.152.61.125 57213
92.136.246.118 13888
178.34.229.72 30185
94.24.202.64 30012
123.202.103.167 33351
109.71.206.215 6881
89.70.19.188 26238
59.180.22.196 20921
189.73.206.149 55505
46.130.66.188 60070
183.10.152.135 47269
41.233.124.184 13394
112.139.59.213 12821
89.2.143.130 18263
217.210.76.120 30274
178.149.61.10 19539
96.233.255.79 50924
124.121.88.187 63778
119.204.207.162 30894
103.14.61.48 53600
46.63.62.162 10219
77.41.141.187 6881
83.110.90.167 42603
61.78.82.158 29484
85.0.20.26 6881
94.236.128.96 50907
99.230.119.14 1755
108.13.168.252 62118
84.125.19.21 42646
74.141.87.159 55998
86.125.209.88 62846
37.43.117.187 40595
95.104.110.103 47173
76.78.36.229 36258
97.94.141.117 63650
49.49.90.217 14706
94.6.23.192 39715
46.232.228.161 5439
186.133.30.205 15189
46.186.48.179 61088
31.134.17.73 32518
98.229.16.76 13046
89.211.153.176 63047
95.16.10.140 12057
46.149.41.106 49001
178.204.78.171 28106
94.51.214.102 6881
178.127.223.150 23171
203.141.138.201 42247
95.53.43.124 19988
66.11.189.123 16723
178.46.157.54 54330
85.87.178.219 23203
83.114.210.35 51413
178.78.33.173 49001
95.191.57.183 28277
111.241.72.105 63166
190.213.94.37 13819
114.34.93.16 6881
80.201.144.250 16648
217.148.57.194 52856
46.180.187.212 20308
59.143.213.135 36841
115.241.104.112 54040
58.182.18.125 11840
202.160.16.7 58808
78.230.94.4 63082
188.254.157.48 40307
78.162.174.165 24173
88.196.203.160 47372
182.164.124.199 48810
121.102.203.62 20440
219.246.57.153 16001
2.61.38.78 25590
99.98.96.67 13178
125.114.50.210 1056
90.193.128.203 61929
94.14.5.83 58485
37.193.160.216 57423
58.115.35.67 11257
182.235.129.91 16001
186.36.145.147 42376
128.68.147.228 6881
200.119.228.231 17654
88.89.110.64 26602
115.79.234.94 36463
80.193.158.59 49348
78.73.114.77 11385
90.54.174.104 20963
218.151.52.146 16617
46.161.143.220 49735
188.18.80.97 6881
37.212.44.31 10638
89.223.99.150 49001
65.4.130.12 50221
186.74.22.89 45612
95.58.93.119 28709
209.6.69.225 56332
85.103.248.197 27524
174.45.1.123 6881
118.171.185.18 19917
87.90.247.194 39695
213.222.142.58 28962
69.253.233.190 44895
88.172.121.96 30728
222.226.45.246 26333
82.245.33.128 25515
178.44.235.211 19597
121.168.129.77 60375
121.45.206.235 23987
217.162.186.254 39835
83.222.112.119 58903
178.74.53.50 22389
61.70.254.221 62238
119.56.48.165 16001
93.148.114.59 12721
88.251.154.23 17808
188.79.87.245 15489
46.119.165.133 58378
76.94.95.223 25698
88.188.193.27 26118
123.211.1.4 27072
101.68.107.193 25086
95.147.47.122 26085
123.243.64.132 35587
186.89.157.161 15024
174.106.96.168 56049
109.148.234.144 60557
89.178.224.73 28557
85.104.92.129 10002
99.228.252.24 37108
61.62.254.10 32181
2.50.255.118 36581
176.49.163.194 23892
90.23.214.138 63347
119.36.38.104 62888
109.122.3.81 6881
86.99.199.68 25025
84.120.63.7 11837
188.60.197.229 16629
89.110.207.136 13761
213.57.37.242 44892
75.90.96.145 31951
99.247.185.46 36957
76.227.224.238 24196
217.27.215.96 6882
213.33.236.230 65360
77.5.35.67 43398
83.108.63.210 61452
24.12.46.116 23073
173.193.242.231 36660
71.94.186.218 10322
109.228.185.71 6881
175.205.72.185 59696
200.120.153.187 57279
1.64.32.1 11212
89.233.243.128 33881
89.3.35.16 8010
219.99.6.250 54921
79.95.171.102 11092
126.13.14.150 17431
58.208.74.237 6600
114.245.149.20 9371
78.233.157.35 40874
84.226.253.50 6881
69.14.60.243 61616
50.33.142.137 52383
188.242.78.174 33213
71.237.6.246 41304
41.107.85.131 10010
89.222.164.45 39809
88.186.107.212 42344
195.132.158.234 22855
82.122.102.50 25612
76.255.133.138 31677
24.130.61.50 28383
98.165.83.165 3661
99.55.140.166 50473
75.109.50.114 25562
87.106.187.29 20277
24.247.183.167 2365
82.228.100.167 42278
109.214.57.82 1042
77.196.18.56 22750
66.177.205.21 8086
82.231.237.146 9517
176.31.248.87 6338
2.6.66.21 45350
79.153.101.234 11154
24.247.179.164 8929
71.63.225.31 21053
83.157.77.228 7812
108.59.72.193 2398
88.127.44.139 15998
64.121.118.201 61270
90.38.76.72 4699
67.173.33.90 33134
88.217.36.182 2924
2.236.14.214 55556
109.194.233.11 6881
178.187.47.44 53127
126.29.214.91 42242
41.178.247.176 24977
37.59.34.186 41497
82.225.11.196 38136
195.132.158.49 61570
78.105.105.87 42127
94.23.204.135 30392
178.63.84.76 51413
78.237.111.89 45254
76.189.121.236 31548
24.85.183.150 9646
88.181.149.119 5018
126.130.125.117 24435
65.15.247.19 51319
176.31.109.159 24586
176.31.127.140 44137
89.93.149.195 57218
88.165.34.61 51449
188.242.97.188 35390
107.15.22.183 10392
24.211.20.89 62868
74.108.4.175 17391
80.185.95.18 18365
146.247.80.210 38204
27.4.216.128 57962
88.238.170.69 26026
74.215.38.97 50596
87.89.75.85 42176
115.188.217.116 62348
98.250.89.141 13038
93.11.175.201 41027
174.109.14.220 51413
114.79.170.114 27462
84.22.157.13 28498
180.183.210.31 21257
42.113.246.104 10775

View File

@ -1,264 +0,0 @@
/*
* bitdht/bdmetric_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdpeer.h"
#include "bitdht/bdstddht.h"
#include <iostream>
#include <stdio.h>
#include "utest.h"
bool test_metric_explicit();
bool test_metric_random();
INITTEST();
int main(int argc, char **argv)
{
std::cerr << "libbitdht: " << argv[0] << std::endl;
test_metric_explicit();
FINALREPORT("libbitdht: Metric Tests");
return TESTRESULT();
}
bool test_metric_explicit()
{
std::cerr << "test_metric_explicit:" << std::endl;
#define NUM_IDS 6
/* create some ids */
bdId id[NUM_IDS];
int i, j;
/* create a set of known ids ... and
* check the metrics are what we expect.
*/
for(i = 0; i < NUM_IDS; i++)
{
bdZeroNodeId(&(id[i].id));
}
/* test the zero node works */
for(i = 0; i < NUM_IDS; i++)
{
for(j = 0; j < BITDHT_KEY_LEN; j++)
{
CHECK(id[i].id.data[j] == 0);
}
}
for(i = 0; i < NUM_IDS; i++)
{
for(j = i; j < NUM_IDS; j++)
{
id[j].id.data[BITDHT_KEY_LEN - i - 1] = 1;
}
}
for(i = 0; i < NUM_IDS; i++)
{
fprintf(stderr, "id[%d]:", i+1);
bdStdPrintId(std::cerr,&(id[i]));
fprintf(stderr, "\n");
}
/* now do the sums */
bdMetric met;
bdMetric met2;
int bdist = 0;
for(i = 0; i < 6; i++)
{
for(j = i+1; j < 6; j++)
{
bdStdDistance(&(id[i].id), &(id[j].id), &met);
fprintf(stderr, "%d^%d:", i, j);
bdStdPrintNodeId(std::cerr,&met);
fprintf(stderr, "\n");
bdist = bdStdBucketDistance(&met);
fprintf(stderr, " bucket: %d\n", bdist);
}
}
#if 0
int c1 = met < met2;
int c2 = met2 < met;
fprintf(stderr, "1^2<1^3? : %d 1^3<1^2?: %d\n", c1, c2);
#endif
REPORT("Test Byte Manipulation");
//FAILED("Couldn't Bind to socket");
return 1;
}
bool test_metric_random()
{
std::cerr << "test_metric_random:" << std::endl;
/* create some ids */
bdId id1;
bdId id2;
bdId id3;
bdId id4;
bdId id5;
bdId id6;
bdStdRandomId(&id1);
bdStdRandomId(&id2);
bdStdRandomId(&id3);
bdStdRandomId(&id4);
bdStdRandomId(&id5);
bdStdRandomId(&id6);
fprintf(stderr, "id1:");
bdStdPrintId(std::cerr,&id1);
fprintf(stderr, "\n");
fprintf(stderr, "id2:");
bdStdPrintId(std::cerr,&id2);
fprintf(stderr, "\n");
fprintf(stderr, "id3:");
bdStdPrintId(std::cerr,&id3);
fprintf(stderr, "\n");
fprintf(stderr, "id4:");
bdStdPrintId(std::cerr,&id4);
fprintf(stderr, "\n");
fprintf(stderr, "id5:");
bdStdPrintId(std::cerr,&id5);
fprintf(stderr, "\n");
fprintf(stderr, "id6:");
bdStdPrintId(std::cerr,&id6);
fprintf(stderr, "\n");
/* now do the sums */
bdMetric met;
bdMetric met2;
int bdist = 0;
bdStdDistance(&(id1.id), &(id2.id), &met);
fprintf(stderr, "1^2:");
bdStdPrintNodeId(std::cerr,&met);
fprintf(stderr, "\n");
bdist = bdStdBucketDistance(&met);
fprintf(stderr, " bucket: %d\n", bdist);
bdStdDistance(&(id1.id), &(id3.id), &met2);
bdist = bdStdBucketDistance(&met2);
fprintf(stderr, "1^3:");
bdStdPrintNodeId(std::cerr,&met2);
fprintf(stderr, "\n");
fprintf(stderr, " bucket: %d\n", bdist);
int c1 = met < met2;
int c2 = met2 < met;
fprintf(stderr, "1^2<1^3? : %d 1^3<1^2?: %d\n", c1, c2);
bdStdDistance(&(id1.id), &(id4.id), &met2);
bdist = bdStdBucketDistance(&met2);
fprintf(stderr, "1^4:");
bdStdPrintNodeId(std::cerr,&met2);
fprintf(stderr, "\n");
fprintf(stderr, " bucket: %d\n", bdist);
c1 = met < met2;
c2 = met2 < met;
fprintf(stderr, "1^2<1^4? : %d 1^4<1^2?: %d\n", c1, c2);
bdStdDistance(&(id1.id), &(id5.id), &met);
bdist = bdStdBucketDistance(&met);
fprintf(stderr, "1^5:");
bdStdPrintNodeId(std::cerr,&met);
fprintf(stderr, "\n");
fprintf(stderr, " bucket: %d\n", bdist);
bdStdDistance(&(id1.id), &(id6.id), &met);
bdist = bdStdBucketDistance(&met);
fprintf(stderr, "1^6:");
bdStdPrintNodeId(std::cerr,&met);
fprintf(stderr, "\n");
fprintf(stderr, " bucket: %d\n", bdist);
bdStdDistance(&(id2.id), &(id3.id), &met);
bdist = bdStdBucketDistance(&met);
fprintf(stderr, "2^3:");
bdStdPrintNodeId(std::cerr,&met);
fprintf(stderr, "\n");
fprintf(stderr, " bucket: %d\n", bdist);
fprintf(stderr, "id1:");
bdStdPrintId(std::cerr,&id1);
fprintf(stderr, "\n");
fprintf(stderr, "id2:");
bdStdPrintId(std::cerr,&id2);
fprintf(stderr, "\n");
fprintf(stderr, "id3:");
bdStdPrintId(std::cerr,&id3);
fprintf(stderr, "\n");
fprintf(stderr, "id4:");
bdStdPrintId(std::cerr,&id4);
fprintf(stderr, "\n");
fprintf(stderr, "id5:");
bdStdPrintId(std::cerr,&id5);
fprintf(stderr, "\n");
fprintf(stderr, "id6:");
bdStdPrintId(std::cerr,&id6);
fprintf(stderr, "\n");
return 1;
}

View File

@ -1,186 +0,0 @@
/*
* bitdht/bdmgr_multitest.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdmanager.h"
#include "bitdht/bdstddht.h"
#include "udp/udplayer.h"
#include "util/bdrandom.h"
#include <stdlib.h>
/**********************************************************************************
* tests of multi bdnodes all connected together.
* in these cases, the networking step is shortcut and the ip addresses ignored.
* instead the port number is used as an index to peers.
*
* test1()
* Small cross seeding, and static list of peers.
* Set it going - and see what happens.
*/
std::map<bdId, bdNodeManager *> nodes;
std::map<struct sockaddr_in, bdId> addrIdx;
int main(int argc, char **argv)
{
time_t sim_time = 600;
time_t starttime = time(NULL);
int n_nodes = 1000;
std::map<bdId, bdNodeManager *>::iterator it;
std::map<bdId, bdNodeManager *>::iterator nit;
std::map<struct sockaddr_in, bdId>::iterator ait;
int i, j;
bdDhtFunctions *fns = new bdStdDht();
std::cerr << "bdmgr_multitest() Setting up Nodes" << std::endl;
/* setup nodes */
for(i = 0; i < n_nodes; i++)
{
bdId id;
bdStdRandomId(&id);
//id.addr.sin_port = htons(i);
//((uint32_t *) (id.id.data))[0] = i * 16 * 16; /* force this so the sort order is maintained! */
std::cerr << "bdmgr_multitest() Id: ";
fns->bdPrintId(std::cerr, &id);
std::cerr << std::endl;
bdNodeManager *mgr = new bdNodeManager(&(id.id), "bdTEST", "", fns);
/* Store in nodes */
nodes[id] = mgr;
/* Store in indices */
addrIdx[id.addr] = id;
}
std::cerr << "bdmgr_multitest() Cross Seeding" << std::endl;
/* do a little cross seeding */
for(nit = nodes.begin(); nit != nodes.end(); nit++)
{
for(j = 0; j < 2; j++)
{
int peeridx = bdRandom::random_u32() % n_nodes;
for(i = 0, it = nodes.begin();
(i < peeridx) && (it != nodes.end()); i++, it++)
{
/* empty */
}
if (it != nodes.end())
{
nit->second->addPotentialPeer((bdId *) &(it->first), NULL);
}
}
}
/* ready to run */
std::cerr << "bdmgr_multitest() Simulation Time....." << std::endl;
i = 0;
while(time(NULL) < starttime + sim_time)
{
i++;
std::cerr << "bdmgr_multitest() Iteration: " << i << std::endl;
for(it = nodes.begin(), j = 0; it != nodes.end(); it++, j++)
{
/* extract messages to go -> and deliver */
#define MAX_MSG_SIZE 10240
struct sockaddr_in addr;
char data[MAX_MSG_SIZE];
int len = MAX_MSG_SIZE;
while(it->second->outgoingMsg(&addr, data, &len))
{
std::cerr << "bdmgr_multitest() Msg from Peer: " << j;
/* find the peer */
ait = addrIdx.find(addr);
nit = nodes.end();
if (ait != addrIdx.end())
{
nit = nodes.find(ait->second);
std::cerr << " For: ";
fns->bdPrintId(std::cerr, &(nit->first));
std::cerr << std::endl;
}
else
{
std::cerr << " For Unknown Destination";
std::cerr << std::endl;
}
if (nit != nodes.end())
{
/* set from address */
nit->second->incomingMsg( (sockaddr_in *) &(it->first.addr), data, len);
}
/* reset message size */
len = MAX_MSG_SIZE;
}
}
for(it = nodes.begin(), j = 0; it != nodes.end(); it++, j++)
{
/* tick */
std::cerr << "bdmgr_multitest() Ticking peer: " << j << std::endl;
it->second->iteration();
}
/* have a rest */
sleep(1);
}
std::cerr << "bdmgr_multitest() Displying States"<< std::endl;
for(it = nodes.begin(), j = 0; it != nodes.end(); it++, j++)
{
/* tick */
std::cerr << "bdmgr_multitest() Peer State: " << j << std::endl;
it->second->printState();
}
}

View File

@ -1,96 +0,0 @@
/*
* bitdht/bdmidids_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdpeer.h"
#include "bitdht/bdstddht.h"
#include <iostream>
int main(int argc, char **argv)
{
/* Do this multiple times */
int i, j;
std::cerr << "Test Mid Peer Intersection....." << std::endl;
for(i = 0; i < 10; i++)
{
bdNodeId targetId;
bdNodeId peerId;
bdStdRandomNodeId(&targetId);
bdStdRandomNodeId(&peerId);
std::cerr << "-------------------------------------------------" << std::endl;
for(j = 0; j < 10; j++)
{
bdNodeId midId;
bdStdRandomMidId(&targetId, &peerId, &midId);
bdMetric TPmetric;
bdMetric TMmetric;
bdMetric PMmetric;
bdStdDistance(&targetId, &peerId, &TPmetric);
bdStdDistance(&targetId, &midId, &TMmetric);
bdStdDistance(&peerId, &midId, &PMmetric);
int TPdist = bdStdBucketDistance(&TPmetric);
int TMdist = bdStdBucketDistance(&TMmetric);
int PMdist = bdStdBucketDistance(&PMmetric);
std::cerr << "Target: ";
bdStdPrintNodeId(std::cerr,&targetId);
std::cerr << " Peer: ";
bdStdPrintNodeId(std::cerr,&peerId);
std::cerr << std::endl;
std::cerr << "\tTarget ^ Peer: ";
bdStdPrintNodeId(std::cerr,&TPmetric);
std::cerr << " Bucket: " << TPdist;
std::cerr << std::endl;
std::cerr << "\tTarget ^ Mid: ";
bdStdPrintNodeId(std::cerr,&TMmetric);
std::cerr << " Bucket: " << TMdist;
std::cerr << std::endl;
std::cerr << "\tPeer ^ Mid: ";
bdStdPrintNodeId(std::cerr,&PMmetric);
std::cerr << " Bucket: " << PMdist;
std::cerr << std::endl;
/* now save mid to peer... and repeat */
peerId = midId;
}
}
return 1;
}

View File

@ -1,102 +0,0 @@
/*
* bitdht/bdmsgs_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdmsgs.h"
#include "bitdht/bdstddht.h"
#include <string.h>
/*******************************************************************
* Test of bencode message creation functions in bdmsgs.cc
*
* Create a couple of each type.
*/
#define MAX_MESSAGE_LEN 10240
int main(int argc, char **argv)
{
/***** create messages *****/
char msg[MAX_MESSAGE_LEN];
int avail = MAX_MESSAGE_LEN -1;
bdToken tid;
bdToken vid;
bdToken token;
bdNodeId ownId;
bdNodeId peerId;
bdNodeId target;
bdNodeId info_hash;
bdStdRandomNodeId(&ownId);
bdStdRandomNodeId(&peerId);
bdStdRandomNodeId(&target);
bdStdRandomNodeId(&info_hash);
std::list<bdId> nodes;
std::list<std::string> values;
/* setup tokens */
strncpy((char*)tid.data, "tid", 4);
strncpy((char*)vid.data, "RS50", 5);
strncpy((char*)token.data, "ToKEn", 6);
tid.len = 3;
vid.len = 4;
token.len = 5;
/* setup lists */
for(int i = 0; i < 8; i++)
{
bdId rndId;
bdStdRandomId(&rndId);
nodes.push_back(rndId);
values.push_back("values");
}
uint32_t port = 1234;
bitdht_create_ping_msg(&tid, &ownId, msg, avail);
bitdht_response_ping_msg(&tid, &ownId, &vid, msg, avail);
bitdht_find_node_msg(&tid, &ownId, &target, msg, avail);
bitdht_resp_node_msg(&tid, &ownId, nodes, msg, avail);
bitdht_get_peers_msg(&tid, &ownId, &info_hash, msg, avail);
bitdht_peers_reply_hash_msg(&tid, &ownId, &token, values, msg, avail);
bitdht_peers_reply_closest_msg(&tid, &ownId, &token, nodes, msg, avail);
bitdht_announce_peers_msg(&tid, &ownId, &info_hash, port, &token, msg, avail);
bitdht_reply_announce_msg(&tid, &ownId, msg, avail);
return 1;
}

View File

@ -1,185 +0,0 @@
/*
* bitdht/bdnode_multitest1.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdnode.h"
#include "bitdht/bdstddht.h"
#include "util/bdrandom.h"
#include <stdlib.h>
/**********************************************************************************
* tests of multi bdnodes all connected together.
* in these cases, the networking step is shortcut and the ip addresses ignored.
* instead the port number is used as an index to peers.
*
* test1()
* Small cross seeding, and static list of peers.
* Set it going - and see what happens.
*/
std::map<bdId, bdNode *> nodes;
std::map<uint16_t, bdId> portIdx;
int main(int argc, char **argv)
{
time_t sim_time = 60;
time_t starttime = time(NULL);
int n_nodes = 10;
std::map<bdId, bdNode *>::iterator it;
std::map<bdId, bdNode *>::iterator nit;
std::map<uint16_t, bdId>::iterator pit;
int i, j;
bdDhtFunctions *fns = new bdStdDht();
std::cerr << "bdnode_multitest1() Setting up Nodes" << std::endl;
/* setup nodes */
for(i = 0; i < n_nodes; i++)
{
bdId id;
bdStdRandomId(&id);
id.addr.sin_port = htons(i);
((uint32_t *) (id.id.data))[0] = i * 16 * 16; /* force this so the sort order is maintained! */
std::cerr << "bdnode_multitest1() Id: ";
fns->bdPrintId(std::cerr, &id);
std::cerr << std::endl;
bdNode *node = new bdNode(&(id.id), "bdTEST", "", fns);
/* Store in nodes */
nodes[id] = node;
/* Store in indices */
portIdx[i] = id;
}
std::cerr << "bdnode_multitest1() Cross Seeding" << std::endl;
/* do a little cross seeding */
for(i = 0; i < n_nodes; i++)
{
bdId nid = portIdx[i];
bdNode *node = nodes[nid];
for(j = 0; j < 5; j++)
{
int peeridx = bdRandom::random_u32() % n_nodes;
bdId pid = portIdx[peeridx];
node->addPotentialPeer(&pid, NULL);
}
}
/* ready to run */
std::cerr << "bdnode_multitest1() Simulation Time....." << std::endl;
i = 0;
while(time(NULL) < starttime + sim_time)
{
i++;
std::cerr << "bdnode_multitest1() Iteration: " << i << std::endl;
for(it = nodes.begin(), j = 0; it != nodes.end(); it++, j++)
{
/* extract messages to go -> and deliver */
#define MAX_MSG_SIZE 10240
struct sockaddr_in addr;
char data[MAX_MSG_SIZE];
int len = MAX_MSG_SIZE;
while(it->second->outgoingMsg(&addr, data, &len))
{
std::cerr << "bdnode_multitest1() Msg from Peer: " << j;
/* find the peer */
int peeridx = htons(addr.sin_port);
pit = portIdx.find(peeridx);
nit = nodes.end();
if (pit != portIdx.end())
{
nit = nodes.find(pit->second);
std::cerr << " For: ";
fns->bdPrintId(std::cerr, &(nit->first));
std::cerr << std::endl;
}
else
{
std::cerr << " For Unknown Destination";
std::cerr << std::endl;
}
if (nit != nodes.end())
{
/* set from address */
nit->second->incomingMsg( (sockaddr_in *) &(it->first.addr), data, len);
}
/* reset message size */
len = MAX_MSG_SIZE;
}
}
for(it = nodes.begin(), j = 0; it != nodes.end(); it++, j++)
{
/* tick */
std::cerr << "bdnode_multitest1() Ticking peer: " << j << std::endl;
it->second->iteration();
}
if (i % 5 == 0)
{
std::cerr << "bdnode_multitest1() Displying States"<< std::endl;
for(it = nodes.begin(), j = 0; it != nodes.end(); it++, j++)
{
/* tick */
std::cerr << "bdnode_multitest1() Peer State: " << j << std::endl;
it->second->printState();
}
}
/* have a rest */
sleep(1);
}
}

View File

@ -1,90 +0,0 @@
/*
* bitdht/bdnode_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdpeer.h"
#include "bitdht/bdstddht.h"
#include "bitdht/bdquery.h"
#include "bitdht/bdnode.h"
#define N_PEERS_TO_ADD_INIT 10
#define N_PEERS_TO_ADD 11
#define N_PEERS_TO_START 10
#define N_PEERS_TO_PRINT 1
#define N_QUERIES 2
int main(int argc, char **argv)
{
/* create some ids */
bdDhtFunctions *fns = new bdStdDht();
bdNodeId ownId;
bdStdRandomNodeId(&ownId);
bdNode node(&ownId, "bdTEST","./dht.log", fns);
int i = 0;
for (i = 0; i < N_PEERS_TO_ADD_INIT; i++)
{
bdId tmpId;
bdStdRandomId(&tmpId);
node.addPeer(&tmpId, 0);
}
node.printState();
#if 0
for(i = 0; i < N_QUERIES; i++)
{
/* create a query */
bdNodeId queryId;
bdStdRandomNodeId(&queryId);
node.addQuery(&queryId, 0);
}
#endif
node.printState();
for (i = 0; i < N_PEERS_TO_ADD; i++)
{
bdId tmpId;
bdStdRandomId(&tmpId);
node.addPeer(&tmpId, 0);
if (i % N_PEERS_TO_PRINT == 0)
{
node.printState();
node.iteration();
sleep(5);
}
}
return 1;
}

View File

@ -1,56 +0,0 @@
/*
* bitdht/bdnode_test2.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdpeer.h"
#include "bitdht/bdstddht.h"
#include "bitdht/bdquery.h"
#include "bitdht/bdnode.h"
#define N_PEERS_TO_ADD_INIT 10
#define N_PEERS_TO_ADD 11
#define N_PEERS_TO_START 10
#define N_PEERS_TO_PRINT 1
#define N_QUERIES 2
int main(int argc, char **argv)
{
/* create some ids */
bdNodeId ownId;
bdStdRandomNodeId(&ownId);
bdDhtFunctions *fns = new bdStdDht();
bdNode node(&ownId, "bdTEST", "./dht.log", fns);
while(1)
{
node.iteration();
sleep(1);
}
return 1;
}

View File

@ -1,83 +0,0 @@
/*
* bitdht/bdquery_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdpeer.h"
#include "bitdht/bdstddht.h"
#include "bitdht/bdquery.h"
#define N_PEERS_TO_ADD 10000
#define N_PEERS_TO_PRINT 1000
#define N_PEERS_TO_START 10
int main(int argc, char **argv)
{
/* create some ids */
bdNodeId ownId;
bdStdRandomNodeId(&ownId);
bdDhtFunctions *fns = new bdStdDht();
bdSpace space(&ownId, fns);
int i = 0;
for (i = 0; i < N_PEERS_TO_ADD; i++)
{
bdId tmpId;
bdStdRandomId(&tmpId);
space.add_peer(&tmpId, 0);
}
space.printDHT();
/* create a query */
bdId queryId;
bdStdRandomId(&queryId);
std::list<bdId> startList;
std::multimap<bdMetric, bdId> nearest;
std::multimap<bdMetric, bdId>::iterator it;
space.find_nearest_nodes(&(queryId.id), N_PEERS_TO_START, nearest);
for(it = nearest.begin(); it != nearest.end(); it++)
{
startList.push_back(it->second);
}
bdQuery query(&(queryId.id), startList, BITDHT_QFLAGS_DISGUISE, fns);
/* */
query.printQuery();
return 1;
}

View File

@ -1,60 +0,0 @@
/*
* bitdht/bdspace_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdpeer.h"
#include "bitdht/bdstddht.h"
#define N_PEERS_TO_ADD 10000
#define N_PEERS_TO_PRINT 1000
int main(int argc, char **argv)
{
/* create some ids */
bdNodeId ownId;
bdStdRandomNodeId(&ownId);
bdDhtFunctions *fns = new bdStdDht();
bdSpace space(&ownId, fns);
int i = 0;
for (i = 0; i < N_PEERS_TO_ADD; i++)
{
bdId tmpId;
bdStdRandomId(&tmpId);
space.add_peer(&tmpId, 0);
if (i % N_PEERS_TO_PRINT == 0)
{
space.printDHT();
}
}
space.printDHT();
return 1;
}

View File

@ -1,67 +0,0 @@
/*
* bitdht/bdspace_test2.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdpeer.h"
#include "bitdht/bdstddht.h"
#define N_PEERS_TO_ADD 10000
#define N_PEERS_TO_TEST 100
#define N_PEERS_TO_FIND 10
int main(int argc, char **argv)
{
/* create some ids */
bdNodeId ownId;
bdStdRandomNodeId(&ownId);
bdDhtFunctions *fns = new bdStdDht();
bdSpace space(&ownId, fns);
int i = 0;
for (i = 0; i < N_PEERS_TO_ADD; i++)
{
bdId tmpId;
bdStdRandomId(&tmpId);
space.add_peer(&tmpId, 0);
}
space.printDHT();
/* now generate random id's and test closeness */
for(i = 0; i < N_PEERS_TO_TEST; i++)
{
bdId tmpId;
bdStdRandomId(&tmpId);
std::multimap<bdMetric, bdId> list2;
space.find_nearest_nodes(&(tmpId.id), N_PEERS_TO_FIND, list2);
}
return 1;
}

View File

@ -1,47 +0,0 @@
/*
* bitdht/bdstore_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdstore.h"
#include "bitdht/bdstddht.h"
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
/* load store */
if (argc < 2)
{
fprintf(stderr, "Missing Store File\n");
exit(1);
}
bdDhtFunctions *fns = new bdStdDht();
bdStore store(argv[1], fns);
return 1;
}

View File

@ -1,66 +0,0 @@
/*
* bitdht/bdudp_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bdpeer.h"
#include "bitdht/bdquery.h"
#include "udp/udpbitdht.h"
#define N_PEERS_TO_ADD 10000
#define N_PEERS_TO_PRINT 1000
#define N_PEERS_TO_START 10
int main(int argc, char **argv)
{
/* create some ids */
bdId ownId;
bdRandomId(&ownId);
struct sockaddr_in local;
local.sin_addr.s_addr = 0;
local.sin_port = htons(7812);
std::string bootstrapfile = "dht.log";
bdId bid;
bid.addr = local;
bid.id = ownId.id;
UdpBitDht ubd(local, 0, &bid, bootstrapfile);
while(1)
{
ubd.tick();
sleep(1);
}
return 1;
}

View File

@ -1,182 +0,0 @@
/*
* bitdht/bencode_test.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "bitdht/bencode.h"
#include <stdio.h>
int main(int argc, char **argv)
{
char msg[100];
msg[0] = 'd';
msg[1] = '1';
msg[2] = ':';
msg[3] = 't';
msg[4] = 'L';
msg[5] = 'b';
msg[6] = 'U';
msg[7] = 0xd9;
msg[8] = 0xfa;
msg[9] = 0xff;
msg[10] = 0xff;
msg[11] = 0xff;
msg[12] = 0xff;
msg[13] = '\n';
msg[14] = 'H';
msg[15] = '#';
msg[16] = '#';
msg[17] = '#';
msg[18] = '#';
msg[19] = '#';
msg[20] = '#';
msg[21] = '#';
be_node *n = be_decoden(msg, 16);
if (n)
{
be_dump(n);
be_free(n);
}
else
{
fprintf(stderr, "didn't crash!\n");
}
msg[0] = 'd';
msg[1] = '1';
msg[2] = ':';
msg[3] = 'a';
msg[4] = 'L';
msg[5] = 0x8d;
msg[6] = 0xd6;
msg[7] = '\r';
msg[8] = 0x9d;
msg[9] = ';';
msg[10] = 0xff;
msg[11] = 0xff;
msg[12] = 0xff;
msg[13] = 0xff;
msg[14] = 'H';
msg[15] = '#';
msg[16] = '#';
msg[17] = '#';
msg[18] = '#';
msg[19] = '#';
msg[20] = '#';
msg[21] = '#';
n = be_decoden(msg, 14);
if (n)
{
be_dump(n);
be_free(n);
}
else
{
fprintf(stderr, "didn't crash!\n");
}
msg[0] = 'd';
msg[1] = '1';
msg[2] = ':';
msg[3] = 't';
msg[4] = '4';
msg[5] = ':';
msg[6] = 'a';
msg[7] = 'b';
msg[8] = 'c';
msg[9] = 'd';
msg[10] = '1';
msg[11] = ':';
msg[12] = 'y';
msg[13] = '1';
msg[14] = ':';
msg[15] = 'r';
msg[16] = '1';
msg[17] = ':';
msg[18] = 'r';
msg[19] = 'd';
msg[20] = '2';
msg[21] = ':';
msg[22] = 'i';
msg[23] = 'd';
msg[24] = '2';
msg[25] = '0';
msg[26] = ':';
msg[27] = '1';
msg[28] = '2';
msg[29] = '3';
msg[30] = '4';
msg[31] = '5';
msg[32] = '6';
msg[33] = '7';
msg[34] = '8';
msg[35] = '9';
msg[36] = '0';
msg[37] = 'a';
msg[38] = 'b';
msg[39] = 'c';
msg[40] = 'd';
msg[41] = 'e';
msg[42] = 'f';
msg[43] = 'g';
msg[44] = 'h';
msg[45] = 'i';
msg[46] = '.';
msg[47] = '5';
msg[48] = ':';
msg[49] = 'n';
msg[50] = 'o';
msg[51] = 'd';
msg[52] = 'e';
msg[53] = 's';
msg[54] = '2';
msg[55] = '0';
msg[56] = '8';
msg[57] = ':';
msg[58] = '\0';
msg[59] = '\0';
msg[60] = '\0';
n = be_decoden(msg, 58);
if (n)
{
be_dump(n);
be_free(n);
}
else
{
fprintf(stderr, "didn't crash!\n");
}
return 1;
}

View File

@ -1,19 +0,0 @@
#Basic checks
ifndef TEST_TOP_DIR
dummy:
echo "TEST_TOP_DIR is not defined in your makefile"
endif
ifneq ($(OS),Linux)
ifneq ($(OS),MacOSX)
ifndef PTHREADS_DIR
dummy:
echo "you must define PTHREADS_DIR before you can compile"
endif
endif
endif

View File

@ -1,118 +0,0 @@
ifneq ($(OS),Cygwin)
dummy:
echo "ERROR Cygwin configuration file included, but (OS != Cygwin)
endif
############ LINUX CONFIGURATION ########################
# flags for components....
PQI_USE_XPGP = 1
#PQI_USE_PROXY = 1
#PQI_USE_CHANNELS = 1
#USE_FILELOOK = 1
###########################################################################
#### DrBobs Versions.... Please Don't Delete.
### Comment out if needed.
ALT_SRC_ROOT=/cygdrive/c/home/rmfern/prog/MinGW
SRC_ROOT=../../../..
PTHREADS_DIR=$(ALT_SRC_ROOT)/pthreads/pthreads.2
###################
#ALT_SRC_ROOT=/cygdrive/c/RetroShareBuild/src
#SRC_ROOT=/cygdrive/c/RetroShareBuild/src
#PTHREADS_DIR=$(ALT_SRC_ROOT)/pthreads-w32-2-8-0-release
###################
ZLIB_DIR=$(ALT_SRC_ROOT)/zlib-1.2.3
SSL_DIR=$(SRC_ROOT)/openssl-0.9.7g-xpgp-0.1c
UPNPC_DIR=$(SRC_ROOT)/miniupnpc-1.0
include $(RS_TOP_DIR)/scripts/checks.mk
############ ENFORCE DIRECTORY NAMING ########################
CC = g++
RM = /bin/rm
RANLIB = ranlib
LIBDIR = $(RS_TOP_DIR)/lib
LIBRS = $(LIBDIR)/libretroshare.a
# Unix: Linux/Cygwin
INCLUDE = -I $(RS_TOP_DIR)
ifdef PQI_DEBUG
CFLAGS = -Wall -g $(INCLUDE)
else
CFLAGS = -Wall -O2 $(INCLUDE)
endif
ifdef PQI_USE_XPGP
INCLUDE += -I $(SSL_DIR)/include
endif
ifdef PQI_USE_XPGP
CFLAGS += -DPQI_USE_XPGP
endif
ifdef PQI_USE_PROXY
CFLAGS += -DPQI_USE_PROXY
endif
ifdef PQI_USE_CHANNELS
CFLAGS += -DPQI_USE_CHANNELS
endif
ifdef USE_FILELOOK
CFLAGS += -DUSE_FILELOOK
endif
RSCFLAGS = -Wall -g $(INCLUDE)
#########################################################################
# OS Compile Options
#########################################################################
# For the SSL BIO compilation. (Copied from OpenSSL compilation flags)
BIOCC = gcc
# Cygwin - ?same? as Linux flags
BIOCFLAGS = -I $(SSL_DIR)/include -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -DOPENSSL_NO_KRB5 -DL_ENDIAN -DTERMIO -O3 -fomit-frame-pointer -m486 -Wall -DSHA1_ASM -DMD5_ASM -DRMD160_ASM
#########################################################################
# OS specific Linking.
#########################################################################
# for static pthread libs....
WININC += -DPTW32_STATIC_LIB
WININC += -mno-cygwin -mwindows -fno-exceptions
WININC += -DWINDOWS_SYS
WINLIB = -lws2_32 -luuid -lole32 -liphlpapi
WINLIB += -lcrypt32 -lwinmm
CFLAGS += -I$(PTHREADS_DIR) $(WININC)
CFLAGS += -I$(ZLIB_DIR)
LIBS = -L$(LIBDIR) -lretroshare
ifdef PQI_USE_XPGP
LIBS += -L$(SSL_DIR)
endif
LIBS += -lssl -lcrypto
LIBS += -L$(UPNPC_DIR) -lminiupnpc
LIBS += -L$(ZLIB_DIR) -lz
LIBS += -L$(PTHREADS_DIR) -lpthreadGC2d
LIBS += $(WINLIB)
RSCFLAGS += $(WININC)

View File

@ -1,41 +0,0 @@
ifneq ($(OS),Linux)
dummy:
echo "ERROR Linux configuration file included, but (OS != Linux)
endif
############ LINUX CONFIGURATION ########################
include $(TEST_TOP_DIR)/scripts/checks.mk
############ ENFORCE DIRECTORY NAMING ########################
CC = g++
RM = /bin/rm
RANLIB = ranlib
LIBDIR = $(LIB_TOP_DIR)/lib
LIBRS = $(LIBDIR)/libretroshare.a
# Unix: Linux/Cygwin
INCLUDE = -I $(LIB_TOP_DIR)
CFLAGS = -Wall -g $(INCLUDE)
CFLAGS += ${DEFINES} -D BE_DEBUG
#########################################################################
# OS Compile Options
#########################################################################
#########################################################################
# OS specific Linking.
#########################################################################
LIBS = -L$(LIBDIR) -lbitdht
LIBS += -lpthread
#LIBS += $(XLIB) -ldl -lz
#LIBS += -lupnp
#LIBS += -lgpgme
#
#RSLIBS = $(LIBS)

View File

@ -1,81 +0,0 @@
ifneq ($(OS),MacOSX)
dummy:
echo "ERROR MacOSX configuration file included, but (OS != MacOSX)
endif
############ MACOSX CONFIGURATION ########################
# FLAGS to decide if we want i386 Build or ppc Build
#
#
# MAC_I386_BUILD = 1
# MAC_PPC_BUILD = 1
MAC_I386_BUILD = 1
#MAC_PPC_BUILD = 1
ifndef MAC_I386_BUILD
MAC_PPC_BUILD = 1
endif
include $(TEST_TOP_DIR)/scripts/checks.mk
############ ENFORCE DIRECTORY NAMING ########################
CC = g++
RM = /bin/rm
RANLIB = ranlib
# Dummy ranlib -> can't do it until afterwards with universal binaries.
# RANLIB = ls -l
LIBDIR = $(LIB_TOP_DIR)/lib
LIBRS = $(LIBDIR)/libretroshare.a
OPT_DIR = /opt/local
OPT_INCLUDE = $(OPT_DIR)/include
OPT_LIBS = $(OPT_DIR)/lib
INCLUDE = -I $(LIB_TOP_DIR)
#-I $(OPT_INCLUDE)
#CFLAGS = -Wall -O3
CFLAGS = -Wall -g
# Flags for architecture builds.
ifdef MAC_I386_BUILD
CFLAGS += -arch i386
endif
ifdef MAC_PPC_BUILD
CFLAGS += -arch ppc
endif
CFLAGS += $(INCLUDE)
# This Line is for Universal BUILD for 10.4 + 10.5
# (but unlikely to work unless Qt Libraries are build properly)
#CFLAGS += -isysroot /Developer/SDKs/MacOSX10.5.sdk
#########################################################################
# OS Compile Options
#########################################################################
#########################################################################
# OS specific Linking.
#########################################################################
#LIBS = -Wl,-search_paths_first
# for Univeral BUILD
# LIBS += -arch ppc -arch i386
# LIBS += -Wl,-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk -arch ppc -arch i386
#LIBS += -Wl,-syslibroot,/Developer/SDKs/MacOSX10.5.sdk
LIBS += -L$(LIBDIR) -lbitdht

View File

@ -1,138 +0,0 @@
#ifneq ($(OS),"Win ")
#dummy:
# echo "ERROR OS = $(OS)"
# echo "ERROR MinGW configuration file included, but (OS != Win)
#
#endif
############ LINUX CONFIGURATION ########################
# flags for components....
#PQI_USE_XPGP = 1
#PQI_USE_PROXY = 1
#PQI_USE_CHANNELS = 1
#USE_FILELOOK = 1
###########################################################################
#### DrBobs Versions.... Please Don't Delete.
### Comment out if needed.
SRC_ROOT_PKG=/home/Mark/prog/retroshare/package/rs-win-v0.5.0/src
SRC_ROOT_GPG=/local
#ALT_SRC_ROOT=/cygdrive/c/home/rmfern/prog/MinGW
#SRC_ROOT=../../../..
PTHREADS_DIR=$(SRC_ROOT_PKG)/pthreads-w32-2-8-0/Pre-built.2
ZLIB_DIR=$(SRC_ROOT_PKG)/zlib-1.2.3
SSL_DIR=$(SRC_ROOT_PKG)/openssl-tmp
UPNPC_DIR=$(SRC_ROOT_PKG)/miniupnpc-1.3
###########################################################################
#### Enable this section for compiling with MSYS/MINGW compile
#SRC_ROOT=/home/linux
#SSL_DIR=$(SRC_ROOT)/OpenSSL
#GPGME_DIR=$(SRC_ROOT)/gpgme-1.1.8
#GPG_ERROR_DIR=$(SRC_ROOT)/libgpg-error-1.7
#ZLIB_DIR=$(SRC_ROOT)/zlib-1.2.3
#UPNPC_DIR=$(SRC_ROOT)/miniupnpc-1.0
#PTHREADS_DIR=$(SRC_ROOT)/pthreads-w32-2-8-0-release
include $(RS_TOP_DIR)/scripts/checks.mk
############ ENFORCE DIRECTORY NAMING #######################################
CC = g++
RM = /bin/rm
RANLIB = ranlib
LIBDIR = $(RS_TOP_DIR)/lib
LIBRS = $(LIBDIR)/libretroshare.a
# Unix: Linux/Cygwin
INCLUDE = -I $(RS_TOP_DIR)
ifdef PQI_DEBUG
CFLAGS = -Wall -g $(INCLUDE)
else
CFLAGS = -Wall -O2 $(INCLUDE)
endif
# These aren't used anymore.... really.
ifdef PQI_USE_XPGP
CFLAGS += -DPQI_USE_XPGP
endif
ifdef PQI_USE_PROXY
CFLAGS += -DPQI_USE_PROXY
endif
ifdef PQI_USE_CHANNELS
CFLAGS += -DPQI_USE_CHANNELS
endif
ifdef USE_FILELOOK
CFLAGS += -DUSE_FILELOOK
endif
# SSL / pthreads / Zlib
# included by default for Windows compilation.
INCLUDE += -I $(SSL_DIR)/include
INCLUDE += -I$(PTHREADS_DIR)
INCLUDE += -I$(ZLIB_DIR)
#########################################################################
# OS Compile Options
#########################################################################
# For the SSL BIO compilation. (Copied from OpenSSL compilation flags)
BIOCC = gcc
# Cygwin - ?same? as Linux flags
BIOCFLAGS = -I $(SSL_DIR)/include -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -DOPENSSL_NO_KRB5 -DL_ENDIAN -DTERMIO -O3 -fomit-frame-pointer -m486 -Wall -DSHA1_ASM -DMD5_ASM -DRMD160_ASM
BIOCFLAGS += -DWINDOWS_SYS
#########################################################################
# OS specific Linking.
#########################################################################
# for static pthread libs....
#WININC += -DPTW32_STATIC_LIB
#WININC += -mno-cygwin -mwindows -fno-exceptions
WININC += -DWINDOWS_SYS
WINLIB = -lws2_32 -luuid -lole32 -liphlpapi
WINLIB += -lcrypt32 -lwinmm
CFLAGS += -I$(SSL_DIR)/include
CFLAGS += -I$(PTHREADS_DIR)/include
CFLAGS += -I$(ZLIB_DIR)
CFLAGS += -I$(SRC_ROOT_GPG)/include
### Enable this for GPGME and GPG ERROR dirs
#CFLAGS += -I$(GPGME_DIR)/src
#CFLAGS += -I$(GPG_ERROR_DIR)/src
CFLAGS += $(WININC)
LIBS = -L$(LIBDIR) -lretroshare
LIBS += -L$(SSL_DIR)
LIBS += -lssl -lcrypto
LIBS += -L$(UPNPC_DIR) -lminiupnpc
LIBS += -L$(ZLIB_DIR) -lz
LIBS += -L$(PTHREADS_DIR) -lpthreadGC2d
LIBS += $(WINLIB)
#RSCFLAGS = -Wall -g $(INCLUDE)
#RSCFLAGS += $(WININC)

View File

@ -1,27 +0,0 @@
# determine which operating system
#
###########################################################################
#Define OS.
#
OS = Linux
#OS = MacOSX
#OS = Cygwin
#OS = Win # MinGw.
###########################################################################
ifeq ($(OS),Linux)
include $(TEST_TOP_DIR)/scripts/config-linux.mk
else
ifeq ($(OS),MacOSX)
include $(TEST_TOP_DIR)/scripts/config-macosx.mk
else
ifeq ($(OS),Cygwin)
include $(TEST_TOP_DIR)/scripts/config-cygwin.mk
else
include $(TEST_TOP_DIR)/scripts/config-mingw.mk
endif
endif
endif
###########################################################################

View File

@ -1,25 +0,0 @@
testoutputfiles = $(foreach tt,$(1),$(tt).tstout)
%.tstout : %.sh
-sh ./$< > $@ 2>&1
%.tstout : %
-./$< > $@ 2>&1
TESTOUT = $(call testoutputfiles,$(TESTS))
.phony : tests regress retest clobber
tests: $(TESTS)
regress: $(TESTOUT)
@-echo "--------------- SUCCESS (count):"
@-grep -c SUCCESS $(TESTOUT)
@-echo "--------------- FAILURE REPORTS:"
@-grep FAILURE $(TESTOUT) || echo no failures
@-echo "--------------- end"
retest:
-/bin/rm $(TESTOUT)

View File

@ -1,19 +0,0 @@
# defines required / used.
#
# CFLAGS
#
#
.cc.o:
$(CC) $(CFLAGS) -c $<
clean:
-/bin/rm $(EXECOBJ) $(TESTOBJ)
clobber: clean retest
-/bin/rm $(EXEC) $(TESTS)
include $(TEST_TOP_DIR)/scripts/regress.mk

View File

@ -1,278 +0,0 @@
/*
* bitdht/udpbitdht_nettest.cc
*
* BitDHT: An Flexible DHT library.
*
* Copyright 2010 by Robert Fernie
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 3 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "bitdht@lunamutt.com".
*
*/
#include "udp/udpbitdht.h"
#include "udp/udpstack.h"
#include "bitdht/bdstddht.h"
#include <string.h>
#include <stdlib.h>
/*******************************************************************
* DHT test program.
*
*
* Create a couple of each type.
*/
#define MAX_MESSAGE_LEN 10240
int args(char *name)
{
std::cerr << "Usage: " << name;
std::cerr << " -p <port> ";
std::cerr << " -b </path/to/bootfile> ";
std::cerr << " -u <uid> ";
std::cerr << " -q <num_queries>";
std::cerr << " -r (do dht restarts) ";
std::cerr << " -j (do join test) ";
std::cerr << std::endl;
return 1;
}
#define DEF_PORT 7500
#define MIN_DEF_PORT 1001
#define MAX_DEF_PORT 16000
#define DEF_BOOTFILE "bdboot.txt"
int main(int argc, char **argv)
{
int c;
int port = DEF_PORT;
std::string bootfile = DEF_BOOTFILE;
std::string uid;
bool setUid = false;
bool doRandomQueries = false;
bool doRestart = false;
bool doThreadJoin = false;
int noQueries = 0;
while((c = getopt(argc, argv,"rjp:b:u:q:")) != -1)
{
switch (c)
{
case 'r':
doRestart = true;
break;
case 'j':
doThreadJoin = true;
break;
case 'p':
{
int tmp_port = atoi(optarg);
if ((tmp_port > MIN_DEF_PORT) && (tmp_port < MAX_DEF_PORT))
{
port = tmp_port;
std::cerr << "Port: " << port;
std::cerr << std::endl;
}
else
{
std::cerr << "Invalid Port";
std::cerr << std::endl;
args(argv[0]);
return 1;
}
}
break;
case 'b':
{
bootfile = optarg;
std::cerr << "Bootfile: " << bootfile;
std::cerr << std::endl;
}
break;
case 'u':
{
setUid = true;
uid = optarg;
std::cerr << "UID: " << uid;
std::cerr << std::endl;
}
break;
case 'q':
{
doRandomQueries = true;
noQueries = atoi(optarg);
std::cerr << "Doing Random Queries";
std::cerr << std::endl;
}
break;
default:
{
args(argv[0]);
return 1;
}
break;
}
}
bdDhtFunctions *fns = new bdStdDht();
bdNodeId id;
/* start off with a random id! */
bdStdRandomNodeId(&id);
if (setUid)
{
int len = uid.size();
if (len > 20)
{
len = 20;
}
for(int i = 0; i < len; i++)
{
id.data[i] = uid[i];
}
}
std::cerr << "Using NodeId: ";
fns->bdPrintNodeId(std::cerr, &id);
std::cerr << std::endl;
/* setup the udp port */
struct sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_addr.s_addr = 0;
local.sin_port = htons(port);
UdpStack *udpstack = new UdpStack(local);
/* create bitdht component */
std::string dhtVersion = "dbTEST";
UdpBitDht *bitdht = new UdpBitDht(udpstack, &id, dhtVersion, bootfile, fns);
/* add in the stack */
udpstack->addReceiver(bitdht);
/* register callback display */
bdDebugCallback *cb = new bdDebugCallback();
bitdht->addCallback(cb);
/* startup threads */
//udpstack->start();
bitdht->start();
/* do a couple of random continuous searchs. */
uint32_t mode = BITDHT_QFLAGS_DO_IDLE;
int count = 0;
int running = 1;
std::cerr << "Starting Dht: ";
std::cerr << std::endl;
bitdht->startDht();
if (doRandomQueries)
{
for(int i = 0; i < noQueries; i++)
{
bdNodeId rndId;
bdStdRandomNodeId(&rndId);
std::cerr << "BitDht Launching Random Search: ";
bdStdPrintNodeId(std::cerr, &rndId);
std::cerr << std::endl;
bitdht->addFindNode(&rndId, mode);
}
}
while(1)
{
sleep(60);
std::cerr << "BitDht State: ";
std::cerr << bitdht->stateDht();
std::cerr << std::endl;
std::cerr << "Dht Network Size: ";
std::cerr << bitdht->statsNetworkSize();
std::cerr << std::endl;
std::cerr << "BitDht Network Size: ";
std::cerr << bitdht->statsBDVersionSize();
std::cerr << std::endl;
if (++count == 2)
{
/* switch to one-shot searchs */
mode = 0;
}
if (doThreadJoin)
{
/* change address */
if (count % 2 == 0)
{
std::cerr << "Resetting UdpStack: ";
std::cerr << std::endl;
udpstack->resetAddress(local);
}
}
if (doRestart)
{
if (count % 2 == 1)
{
if (running)
{
std::cerr << "Stopping Dht: ";
std::cerr << std::endl;
bitdht->stopDht();
running = 0;
}
else
{
std::cerr << "Starting Dht: ";
std::cerr << std::endl;
bitdht->startDht();
running = 1;
}
}
}
}
return 1;
}

View File

@ -1,23 +0,0 @@
#ifndef _UNIT_TEST_MACROS_H__
#define _UNIT_TEST_MACROS_H__
#include <stdio.h>
#define TFAILURE( s ) printf( "FAILURE: " __FILE__ ":%-4d %s\n", __LINE__, s )
#define TSUCCESS( s ) printf( "SUCCESS: " __FILE__ ":%-4d %s\n", __LINE__, s )
/* careful with this line (no protection) */
#define INITTEST() int ok = 1; int gok = 1;
/* declare the variables */
extern int ok;
extern int gok;
#define CHECK( b ) do { if ( ! (b) ) { ok = 0; TFAILURE( #b ); } } while(0)
#define FAILED( s ) do { ok = 0; TFAILURE( s ); } while(0)
#define REPORT( s ) do { if ( ! (ok) ) { ok = 0; TFAILURE( s ); } else { TSUCCESS( s );} gok &= ok; ok = 1; } while(0)
#define REPORT2( b, s ) do { if ( ! (b) ) { ok = 0; TFAILURE( s ); } else { TSUCCESS( s );} gok &= ok; ok = 1; } while(0)
#define FINALREPORT( s ) do { gok &= ok; ok = 1; if ( ! (gok) ) { TFAILURE( s ); } else { TSUCCESS( s );} } while(0)
#define TESTRESULT() (!gok)
#endif

View File

@ -1,373 +0,0 @@
/*******************************************************************************
* bitdht/udpbitdht.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "udp/udpbitdht.h"
#include "bitdht/bdpeer.h"
#include "bitdht/bdstore.h"
#include "bitdht/bdmsgs.h"
#include "bitdht/bencode.h"
#include <stdlib.h>
#include <unistd.h> /* for usleep() */
#include <iostream>
#include <iomanip>
#include <string.h>
#include "util/bdnet.h"
/*
* #define DEBUG_UDP_BITDHT 1
*
* #define BITDHT_VERSION_ANONYMOUS 1
*/
//#define DEBUG_UDP_BITDHT 1
#define BITDHT_VERSION_IDENTIFER 1
// Original RS 0.5.0/0.5.1 version, is un-numbered.
//#define BITDHT_VERSION "00" // First Release of BitDHT with Connections (Proxy Support + Dht Stun)
//#define BITDHT_VERSION "01" // Testing Connections (Proxy Only)
#define BITDHT_VERSION "02" // Completed Relay Connections from svn 4766
//#define BITDHT_VERSION "04" // Full DHT implementation.?
/*************************************/
UdpBitDht::UdpBitDht(UdpPublisher *pub, bdNodeId *id, std::string appVersion, std::string bootstrapfile, std::string bootstrapfilebak, const std::string& filteredipfile, bdDhtFunctions *fns)
:UdpSubReceiver(pub), dhtMtx(true)//, mFns(fns)
{
std::string usedVersion;
#ifdef BITDHT_VERSION_IDENTIFER
usedVersion = "BD";
usedVersion += BITDHT_VERSION;
#endif
usedVersion += appVersion;
#ifdef BITDHT_VERSION_ANONYMOUS
usedVersion = ""; /* blank it */
#endif
clearDataTransferred();
/* setup nodeManager */
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager = new bdNodeManager(id, usedVersion, bootstrapfile, bootstrapfilebak, filteredipfile, fns);
}
UdpBitDht::~UdpBitDht()
{
return;
}
/*********** External Interface to the World ************/
/***** Functions to Call down to bdNodeManager ****/
/* Friend Tracking */
void UdpBitDht::addBadPeer(const struct sockaddr_in &addr, uint32_t source, uint32_t reason, uint32_t age)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->addBadPeer(addr, source, reason, age);
}
void UdpBitDht::updateKnownPeer(const bdId *id, uint32_t type, uint32_t flags)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->updateKnownPeer(id, type, flags);
}
/* Request DHT Peer Lookup */
/* Request Keyword Lookup */
void UdpBitDht::addFindNode(bdNodeId *id, uint32_t mode)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->addFindNode(id, mode);
}
void UdpBitDht::removeFindNode(bdNodeId *id)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->removeFindNode(id);
}
void UdpBitDht::findDhtValue(bdNodeId *id, std::string key, uint32_t mode)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->findDhtValue(id, key, mode);
}
/***** Add / Remove Callback Clients *****/
void UdpBitDht::addCallback(BitDhtCallback *cb)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->addCallback(cb);
}
void UdpBitDht::removeCallback(BitDhtCallback *cb)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->removeCallback(cb);
}
bool UdpBitDht::ConnectionRequest(struct sockaddr_in *laddr, bdNodeId *target, uint32_t mode, uint32_t delay, uint32_t start)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->ConnectionRequest(laddr, target, mode, delay, start);
}
void UdpBitDht::ConnectionAuth(bdId *srcId, bdId *proxyId, bdId *destId, uint32_t mode, uint32_t loc,
uint32_t bandwidth, uint32_t delay, uint32_t answer)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->ConnectionAuth(srcId, proxyId, destId, mode, loc, bandwidth, delay, answer);
}
void UdpBitDht::ConnectionOptions(uint32_t allowedModes, uint32_t flags)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->ConnectionOptions(allowedModes, flags);
}
bool UdpBitDht::setAttachMode(bool on)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->setAttachMode(on);
}
int UdpBitDht::getDhtPeerAddress(const bdNodeId *id, struct sockaddr_in &from)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->getDhtPeerAddress(id, from);
}
int UdpBitDht::getDhtValue(const bdNodeId *id, std::string key, std::string &value)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->getDhtValue(id, key, value);
}
int UdpBitDht::getDhtBucket(const int idx, bdBucket &bucket)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->getDhtBucket(idx, bucket);
}
int UdpBitDht::getDhtQueries(std::map<bdNodeId, bdQueryStatus> &queries)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->getDhtQueries(queries);
}
int UdpBitDht::getDhtQueryStatus(const bdNodeId *id, bdQuerySummary &query)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->getDhtQueryStatus(id, query);
}
bool UdpBitDht::isAddressBanned(const sockaddr_in &raddr)
{
return mBitDhtManager->addressBanned(raddr) ;
}
bool UdpBitDht::getListOfBannedIps(std::list<bdFilteredPeer>& ipl)
{
return mBitDhtManager->getFilteredPeers(ipl) ;
}
/* stats and Dht state */
int UdpBitDht:: startDht()
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->startDht();
}
int UdpBitDht:: stopDht()
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->stopDht();
}
int UdpBitDht::stateDht()
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->stateDht();
}
uint32_t UdpBitDht::statsNetworkSize()
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->statsNetworkSize();
}
uint32_t UdpBitDht::statsBDVersionSize()
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->statsBDVersionSize();
}
uint32_t UdpBitDht::setDhtMode(uint32_t dhtFlags)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->setDhtMode(dhtFlags);
}
/******************* Internals *************************/
/***** Iteration / Loop Management *****/
/*** Overloaded from UdpSubReceiver ***/
int UdpBitDht::recvPkt(void *data, int size, struct sockaddr_in &from)
{
/* pass onto bitdht */
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
/* check packet suitability */
if (mBitDhtManager->isBitDhtPacket((char *) data, size, from))
{
mReadBytes += size;
mBitDhtManager->incomingMsg(&from, (char *) data, size);
return 1;
}
return 0;
}
int UdpBitDht::status(std::ostream &out)
{
out << "UdpBitDht::status()" << std::endl;
return 1;
}
void UdpBitDht::clearDataTransferred()
{
/* pass onto bitdht */
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mReadBytes = 0;
mWriteBytes = 0;
}
void UdpBitDht::getDataTransferred(uint32_t &read, uint32_t &write)
{
{
/* pass onto bitdht */
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
read = mReadBytes;
write = mWriteBytes;
}
clearDataTransferred();
}
/*** Overloaded from iThread ***/
#define MAX_MSG_PER_TICK 100
#define TICK_PAUSE_USEC 20000 /* 20ms secs .. max messages = 50 x 100 = 5000 */
void UdpBitDht::run()
{
while(1)
{
while(tick())
{
usleep(TICK_PAUSE_USEC);
}
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager->iteration();
}
sleep(1);
}
}
int UdpBitDht::tick()
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
/* pass on messages from the node */
int i = 0;
char data[BITDHT_MAX_PKTSIZE];
struct sockaddr_in toAddr;
int size = BITDHT_MAX_PKTSIZE;
while((i < MAX_MSG_PER_TICK) && (mBitDhtManager->outgoingMsg(&toAddr, data, &size)))
{
#ifdef DEBUG_UDP_BITDHT
std::cerr << "UdpBitDht::tick() outgoing msg(" << size << ") to " << toAddr;
std::cerr << std::endl;
#endif
mWriteBytes += size;
sendPkt(data, size, toAddr, BITDHT_TTL);
// iterate
i++;
size = BITDHT_MAX_PKTSIZE; // reset msg size!
}
if (i == MAX_MSG_PER_TICK)
{
return 1; /* keep on ticking */
}
return 0;
}

View File

@ -1,127 +0,0 @@
/*******************************************************************************
* udp/udpbitdht.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef UDP_BIT_DHT_CLASS_H
#define UDP_BIT_DHT_CLASS_H
#include <iosfwd>
#include <map>
#include <string>
#include "udp/udpstack.h"
#include "bitdht/bdiface.h"
#include "bitdht/bdmanager.h"
/*
* This implements a UdpSubReceiver class to allow the DHT to talk to the network.
* The parser is very strict - and will try to not pick up anyone else's messages.
*
* Mutexes are implemented at this level protecting the whole of the DHT code.
* This class is also a thread - enabling it to do callback etc.
*/
// class BitDhtCallback defined in bdiface.h
class UdpBitDht: public UdpSubReceiver, public bdThread, public BitDhtInterface
{
public:
UdpBitDht(UdpPublisher *pub, bdNodeId *id, std::string dhtVersion, std::string bootstrapfile, std::string bootstrapfilebak, const std::string& filteredipfile,bdDhtFunctions *fns);
virtual ~UdpBitDht();
/*********** External Interface to the World (BitDhtInterface) ************/
/***** Functions to Call down to bdNodeManager ****/
/* Friend Tracking */
virtual void addBadPeer(const struct sockaddr_in &addr, uint32_t source, uint32_t reason, uint32_t age);
virtual void updateKnownPeer(const bdId *id, uint32_t type, uint32_t flags);
/* Request DHT Peer Lookup */
/* Request Keyword Lookup */
virtual void addFindNode(bdNodeId *id, uint32_t mode);
virtual void removeFindNode(bdNodeId *id);
virtual void findDhtValue(bdNodeId *id, std::string key, uint32_t mode);
/***** Add / Remove Callback Clients *****/
virtual void addCallback(BitDhtCallback *cb);
virtual void removeCallback(BitDhtCallback *cb);
/***** Connections Requests *****/
virtual bool ConnectionRequest(struct sockaddr_in *laddr, bdNodeId *target, uint32_t mode, uint32_t delay, uint32_t start);
virtual void ConnectionAuth(bdId *srcId, bdId *proxyId, bdId *destId, uint32_t mode, uint32_t loc,
uint32_t bandwidth, uint32_t delay, uint32_t answer);
virtual void ConnectionOptions(uint32_t allowedModes, uint32_t flags);
virtual bool setAttachMode(bool on);
/***** Get Results Details *****/
virtual int getDhtPeerAddress(const bdNodeId *id, struct sockaddr_in &from);
virtual int getDhtValue(const bdNodeId *id, std::string key, std::string &value);
virtual int getDhtBucket(const int idx, bdBucket &bucket);
virtual int getDhtQueries(std::map<bdNodeId, bdQueryStatus> &queries);
virtual int getDhtQueryStatus(const bdNodeId *id, bdQuerySummary &query);
virtual bool isAddressBanned(const sockaddr_in &raddr) ;
virtual bool getListOfBannedIps(std::list<bdFilteredPeer> &ipl);
/* stats and Dht state */
virtual int startDht();
virtual int stopDht();
virtual int stateDht();
virtual uint32_t statsNetworkSize();
virtual uint32_t statsBDVersionSize();
virtual uint32_t setDhtMode(uint32_t dhtFlags);
void getDataTransferred(uint32_t &read, uint32_t &write);
/******************* Internals *************************/
/***** Iteration / Loop Management *****/
/*** Overloaded from UdpSubReceiver ***/
virtual int recvPkt(void *data, int size, struct sockaddr_in &from);
virtual int status(std::ostream &out);
/*** Overloaded from iThread ***/
virtual void run();
/**** do whats to be done ***/
int tick();
private:
void clearDataTransferred();
bdMutex dhtMtx; /* for all class data (below) */
bdNodeManager *mBitDhtManager;
//bdDhtFunctions *mFns;
uint32_t mReadBytes;
uint32_t mWriteBytes;
};
#endif

View File

@ -1,772 +0,0 @@
/*******************************************************************************
* udp/udplayer.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2004-2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "udp/udplayer.h"
#include "util/bdrandom.h"
#include "util/bdstring.h"
#include <iostream>
#include <iomanip>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#ifndef WIN32
#include <sys/select.h>
#endif
/***
* #define UDP_ENABLE_BROADCAST 1
* #define UDP_LOOPBACK_TESTING 1
* #define DEBUG_UDP_LAYER 1
***/
//#define DEBUG_UDP_LAYER 1
static const int UDP_DEF_TTL = 64;
/* NB: This #define makes the listener open 0.0.0.0:X port instead
* of a specific port - this helps library communicate on systems
* with multiple interfaces or unique network setups.
*
* - It should always be used!
*
* #define OPEN_UNIVERSAL_PORT 1
*
*/
#define OPEN_UNIVERSAL_PORT 1
class udpPacket
{
public:
udpPacket(struct sockaddr_in *addr, void *dta, int dlen)
:raddr(*addr), len(dlen)
{
data = malloc(len);
if(data != NULL)
memcpy(data, dta, len);
else
std::cerr << "(EE) error in memory allocation in " << __PRETTY_FUNCTION__ << std::endl;
}
~udpPacket()
{
if (data)
{
free(data);
data = NULL;
len = 0;
}
}
struct sockaddr_in raddr;
void *data;
int len;
};
//std::ostream &operator<<(std::ostream &out, const struct sockaddr_in &addr)
std::ostream &operator<<(std::ostream &out, struct sockaddr_in &addr)
{
out << "[" << bdnet_inet_ntoa(addr.sin_addr) << ":";
out << htons(addr.sin_port) << "]";
return out;
}
bool operator==(const struct sockaddr_in &addr, const struct sockaddr_in &addr2)
{
if (addr.sin_family != addr2.sin_family)
return false;
if (addr.sin_addr.s_addr != addr2.sin_addr.s_addr)
return false;
if (addr.sin_port != addr2.sin_port)
return false;
return true;
}
bool operator<(const struct sockaddr_in &addr, const struct sockaddr_in &addr2)
{
if (addr.sin_family != addr2.sin_family)
return (addr.sin_family < addr2.sin_family);
if (addr.sin_addr.s_addr != addr2.sin_addr.s_addr)
return (addr.sin_addr.s_addr < addr2.sin_addr.s_addr);
if (addr.sin_port != addr2.sin_port)
return (addr.sin_port < addr2.sin_port);
return false;
}
std::string printPkt(void *d, int size)
{
std::string out = "Packet:**********************";
for(int i = 0; i < size; i++)
{
if (i % 16 == 0)
out += "\n";
bd_sprintf_append(out, "%2x ", (unsigned int) ((unsigned char *) d)[i]);
}
out += "\n**********************\n";
return out;
}
std::string printPktOffset(unsigned int offset, void *d, unsigned int size)
{
std::string out = "Packet:**********************\n";
bd_sprintf_append(out, "Offset: %x -> %x\n", offset, offset + size);
out += "Packet:**********************";
unsigned int j = offset % 16;
if (j != 0)
{
out += "\n";
bd_sprintf_append(out, "%6x: ", (unsigned int) offset - j);
for(unsigned int i = 0; i < j; i++)
{
out += "xx ";
}
}
for(unsigned int i = offset; i < offset + size; i++)
{
if (i % 16 == 0)
{
out += "\n";
bd_sprintf_append(out, "%6x: ", (unsigned int) i);
}
bd_sprintf(out, "%2x ", (unsigned int) ((unsigned char *) d)[i-offset]);
}
out += "\n**********************\n";
return out;
}
UdpLayer::UdpLayer(UdpReceiver *udpr, struct sockaddr_in &local)
:recv(udpr), laddr(local), errorState(0), ttl(UDP_DEF_TTL)
{
openSocket();
return;
}
int UdpLayer::status(std::ostream &out)
{
out << "UdpLayer::status()" << std::endl;
out << "localaddr: " << laddr << std::endl;
out << "sockfd: " << sockfd << std::endl;
out << std::endl;
return 1;
}
int UdpLayer::reset(struct sockaddr_in &local)
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::reset()" << std::endl;
#endif
/* stop the old thread */
{
bdStackMutex stack(sockMtx); /********** LOCK MUTEX *********/
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::reset() setting stopThread flag" << std::endl;
#endif
stopThread = true;
}
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::reset() joining" << std::endl;
#endif
join();
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::reset() closing socket" << std::endl;
#endif
closeSocket();
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::reset() resetting variables" << std::endl;
#endif
laddr = local;
errorState = 0;
ttl = UDP_DEF_TTL;
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::reset() opening socket" << std::endl;
#endif
openSocket();
return 1 ;
}
int UdpLayer::closeSocket()
{
/* close socket if open */
sockMtx.lock(); /********** LOCK MUTEX *********/
if (sockfd > 0)
{
bdnet_close(sockfd);
}
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
return 1;
}
void UdpLayer::run()
{
return recv_loop();
}
/* higher level interface */
void UdpLayer::recv_loop()
{
size_t maxsize = 16000;
void *inbuf = malloc(maxsize);
if(inbuf == NULL)
{
std::cerr << "(EE) Error in memory allocation of size " << maxsize
<< " in " << __PRETTY_FUNCTION__ << std::endl;
return;
}
int status;
struct timeval timeout;
while(1)
{
for(;;)
{
/* check if we need to stop */
bool toStop = false;
{
bdStackMutex stack(sockMtx); (void) stack;
toStop = stopThread;
}
if (toStop)
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::recv_loop() stopping thread" << std::endl;
#endif
free(inbuf);
stop();
return; // Avoid compiler warning about usage of inbuf after free
}
fd_set rset;
FD_ZERO(&rset);
FD_SET(sockfd, &rset);
timeout.tv_sec = 0;
timeout.tv_usec = 500000; // 500 ms timeout
status = select(sockfd+1, &rset, NULL, NULL, &timeout);
if (status > 0) break; // data available, go read it
#ifdef DEBUG_UDP_LAYER
else if (status < 0) std::cerr << "UdpLayer::recv_loop() Error: "
<< bdnet_errno() << std::endl;
#endif
};
int nsize = static_cast<int>(maxsize);
struct sockaddr_in from;
if (0 < receiveUdpPacket(inbuf, &nsize, from))
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::readPkt() from : " << from << std::endl
<< printPkt(inbuf, nsize);
#endif
recv->recvPkt(inbuf, nsize, from); // pass to reciever.
}
#ifdef DEBUG_UDP_LAYER
else std::cerr << "UdpLayer::readPkt() not ready" << from << std::endl;
#endif
}
}
int UdpLayer::sendPkt(const void *data, int size, const sockaddr_in &to, int ttl)
{
/* if ttl is different -> set it */
if (ttl != getTTL())
{
setTTL(ttl);
}
/* and send! */
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::sendPkt() to: " << to << std::endl;
std::cerr << printPkt((void *) data, size);
#endif
sendUdpPacket(data, size, to);
return size;
}
/* setup connections */
int UdpLayer::openSocket()
{
sockMtx.lock(); /********** LOCK MUTEX *********/
/* make a socket */
sockfd = bdnet_socket(PF_INET, SOCK_DGRAM, 0);
#ifdef DEBUG_UDP_LAYER
std::cerr << "UpdStreamer::openSocket()" << std::endl;
#endif
/* bind to address */
#ifdef UDP_LOOPBACK_TESTING
bdnet_inet_aton("127.0.0.1", &(laddr.sin_addr));
#endif
#ifdef OPEN_UNIVERSAL_PORT
struct sockaddr_in tmpaddr = laddr;
tmpaddr.sin_addr.s_addr = 0;
if (0 != bdnet_bind(sockfd, (struct sockaddr *) (&tmpaddr), sizeof(tmpaddr)))
#else
if (0 != bdnet_bind(sockfd, (struct sockaddr *) (&laddr), sizeof(laddr)))
#endif
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "Socket Failed to Bind to : " << laddr << std::endl;
std::cerr << "Error: " << bdnet_errno() << std::endl;
#endif
errorState = EADDRINUSE;
//exit(1);
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
return -1;
}
if (-1 == bdnet_fcntl(sockfd, F_SETFL, O_NONBLOCK))
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "Failed to Make Non-Blocking" << std::endl;
#endif
}
#ifdef UDP_ENABLE_BROADCAST
/* Setup socket for broadcast. */
int val = 1;
if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &val, sizeof(int)))
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "Failed to Make Socket Broadcast" << std::endl;
#endif
}
#endif
errorState = 0;
#ifdef DEBUG_UDP_LAYER
std::cerr << "Socket Bound to : " << laddr << std::endl;
#endif
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
#ifdef DEBUG_UDP_LAYER
std::cerr << "Setting TTL to " << UDP_DEF_TTL << std::endl;
#endif
setTTL(UDP_DEF_TTL);
clearDataTransferred(); // clear statistics.
// start up our thread.
{
bdStackMutex stack(sockMtx); /********** LOCK MUTEX *********/
stopThread = false;
}
start();
return 1;
}
int UdpLayer::setTTL(int t)
{
sockMtx.lock(); /********** LOCK MUTEX *********/
int err = bdnet_setsockopt(sockfd, IPPROTO_IP, IP_TTL, &t, sizeof(int));
ttl = t;
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::setTTL(" << t << ") returned: " << err;
std::cerr << std::endl;
#endif
return err;
}
int UdpLayer::getTTL()
{
sockMtx.lock(); /********** LOCK MUTEX *********/
int t = ttl;
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
return t;
}
/* monitoring / updates */
int UdpLayer::okay()
{
sockMtx.lock(); /********** LOCK MUTEX *********/
bool nonFatalError = ((errorState == 0) ||
(errorState == EAGAIN) ||
(errorState == EINPROGRESS));
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
#ifdef DEBUG_UDP_LAYER
if (!nonFatalError)
{
std::cerr << "UdpLayer::NOT okay(): Error: " << errorState << std::endl;
}
#endif
return nonFatalError;
}
int UdpLayer::tick()
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::tick()" << std::endl;
#endif
return 1;
}
void UdpLayer::getDataTransferred(uint32_t &read, uint32_t &write)
{
sockMtx.lock(); /********** LOCK MUTEX *********/
read = readBytes;
write = writeBytes;
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
clearDataTransferred();
}
void UdpLayer::clearDataTransferred()
{
sockMtx.lock(); /********** LOCK MUTEX *********/
readBytes = 0;
writeBytes = 0;
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
}
/******************* Internals *************************************/
int UdpLayer::receiveUdpPacket(void *data, int *size, struct sockaddr_in &from)
{
struct sockaddr_in fromaddr;
socklen_t fromsize = sizeof(fromaddr);
int insize = *size;
sockMtx.lock(); /********** LOCK MUTEX *********/
insize = bdnet_recvfrom(sockfd,data,insize,0,
(struct sockaddr*)&fromaddr,&fromsize);
if (0 < insize)
{
readBytes += insize;
}
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
if (0 < insize)
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "receiveUdpPacket() from: " << fromaddr;
std::cerr << " Size: " << insize;
std::cerr << std::endl;
#endif
*size = insize;
from = fromaddr;
return insize;
}
return -1;
}
int UdpLayer::sendUdpPacket(const void *data, int size, const struct sockaddr_in &to)
{
/* send out */
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::sendUdpPacket(): size: " << size;
std::cerr << " To: " << to << std::endl;
#endif
struct sockaddr_in toaddr = to;
sockMtx.lock(); /********** LOCK MUTEX *********/
bdnet_sendto(sockfd, data, size, 0,
(struct sockaddr *) &(toaddr),
sizeof(toaddr));
writeBytes += size;
sockMtx.unlock(); /******** UNLOCK MUTEX *********/
return 1;
}
/**************************** LossyUdpLayer - for Testing **************/
LossyUdpLayer::LossyUdpLayer(UdpReceiver *udpr,
struct sockaddr_in &local, double frac)
:UdpLayer(udpr, local), lossFraction(frac)
{
return;
}
LossyUdpLayer::~LossyUdpLayer() { return; }
int LossyUdpLayer::receiveUdpPacket(void *data, int *size, struct sockaddr_in &from)
{
if (0 < UdpLayer::receiveUdpPacket(data, size, from))
{
float prob = bdRandom::random_f32();
if (prob < lossFraction)
{
/* discard */
//std::cerr << "LossyUdpLayer::receiveUdpPacket() Dropping packet!";
//std::cerr << std::endl;
//std::cerr << printPkt(data, *size);
//std::cerr << std::endl;
std::cerr << "LossyUdpLayer::receiveUdpPacket() Packet (" << *size << ") Dropped!";
std::cerr << std::endl;
*size = 0;
return -1;
}
return *size;
}
return -1;
}
int LossyUdpLayer::sendUdpPacket(const void *data, int size, const struct sockaddr_in &to)
{
double prob = (1.0 * (rand() / (RAND_MAX + 1.0)));
if (prob < lossFraction)
{
/* discard */
//std::cerr << "LossyUdpLayer::sendUdpPacket() Dropping packet!";
//std::cerr << std::endl;
//std::cerr << printPkt((void *) data, size);
//std::cerr << std::endl;
std::cerr << "LossyUdpLayer::sendUdpPacket() Packet (" << size << ") Dropped!";
std::cerr << std::endl;
return size;
}
// otherwise read normally;
return UdpLayer::sendUdpPacket(data, size, to);
}
/**************************** LossyUdpLayer - for Testing **************/
PortRange::PortRange() :lport(0), uport(0) { return; }
PortRange::PortRange(uint16_t lp, uint16_t up) :lport(lp), uport(up) { return; }
bool PortRange::inRange(uint16_t port)
{
if (port < lport)
{
return false;
}
if (port > uport)
{
return false;
}
return true;
}
RestrictedUdpLayer::RestrictedUdpLayer(UdpReceiver *udpr,
struct sockaddr_in &local)
:UdpLayer(udpr, local)
{
return;
}
RestrictedUdpLayer::~RestrictedUdpLayer() { return; }
void RestrictedUdpLayer::addRestrictedPortRange(int lp, int up)
{
PortRange pr(lp, up);
mLostPorts.push_back(pr);
}
int RestrictedUdpLayer::receiveUdpPacket(void *data, int *size, struct sockaddr_in &from)
{
if (0 < UdpLayer::receiveUdpPacket(data, size, from))
{
/* check the port against list */
uint16_t inPort = ntohs(from.sin_port);
std::list<PortRange>::iterator it;
for(it = mLostPorts.begin(); it != mLostPorts.end(); it++)
{
if (it->inRange(inPort))
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "RestrictedUdpLayer::receiveUdpPacket() Dropping packet";
std::cerr << ", Port(" << inPort << ") in restricted range!";
std::cerr << std::endl;
//std::cerr << printPkt(data, *size);
//std::cerr << std::endl;
#endif
*size = 0;
return -1;
}
}
#ifdef DEBUG_UDP_LAYER
std::cerr << "RestrictedUdpLayer::receiveUdpPacket() Accepting packet";
std::cerr << ", Port(" << inPort << ") in Okay range!";
std::cerr << std::endl;
#endif
/* acceptable port */
return *size;
}
return -1;
}
int RestrictedUdpLayer::sendUdpPacket(const void *data, int size, const struct sockaddr_in &to)
{
/* check the port against list */
uint16_t outPort = ntohs(to.sin_port);
std::list<PortRange>::iterator it;
for(it = mLostPorts.begin(); it != mLostPorts.end(); it++)
{
if (it->inRange(outPort))
{
/* drop */
#ifdef DEBUG_UDP_LAYER
std::cerr << "RestrictedUdpLayer::sendUdpPacket() Dropping packet";
std::cerr << ", Port(" << outPort << ") in restricted range!";
std::cerr << std::endl;
//std::cerr << printPkt(data, *size);
//std::cerr << std::endl;
#endif
return size;
}
}
#ifdef DEBUG_UDP_LAYER
std::cerr << "RestrictedUdpLayer::sendUdpPacket() Sending packet";
std::cerr << ", Port(" << outPort << ") in Okay range!";
std::cerr << std::endl;
#endif
// otherwise read normally;
return UdpLayer::sendUdpPacket(data, size, to);
}
#define STARTUP_PERIOD 60
TimedUdpLayer::TimedUdpLayer(UdpReceiver *udpr,
struct sockaddr_in &local)
:UdpLayer(udpr, local)
{
mStartTime = time(NULL) + STARTUP_PERIOD;
mActive = false;
return;
}
TimedUdpLayer::~TimedUdpLayer() { return; }
int TimedUdpLayer::receiveUdpPacket(void *data, int *size, struct sockaddr_in &from)
{
if (0 < UdpLayer::receiveUdpPacket(data, size, from))
{
if (!mActive)
{
if (time(NULL) < mStartTime)
{
#ifdef DEBUG_UDP_LAYER
#endif
std::cerr << "TimedUdpLayer::receiveUdpPacket() Dropping packet (Too Early)";
std::cerr << std::endl;
//std::cerr << printPkt(data, *size);
//std::cerr << std::endl;
*size = 0;
return -1;
}
mActive = true;
}
/* acceptable port */
return *size;
}
return -1;
}
int TimedUdpLayer::sendUdpPacket(const void *data, int size, const struct sockaddr_in &to)
{
if (!mActive)
{
if (time(NULL) < mStartTime)
{
/* drop */
#ifdef DEBUG_UDP_LAYER
#endif
std::cerr << "TimedUdpLayer::sendUdpPacket() Dropping packet (Too Early)";
std::cerr << std::endl;
return size;
}
/* else activate */
mActive = true;
}
// otherwise read normally;
return UdpLayer::sendUdpPacket(data, size, to);
}

View File

@ -1,188 +0,0 @@
/*******************************************************************************
* udp/udplayer.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2004-2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_UDP_LAYER_H
#define BITDHT_UDP_LAYER_H
#include "util/bdthreads.h"
#include "util/bdnet.h"
#include <iosfwd>
#include <list>
#include <deque>
/* careful - duplicate definitions */
//std::ostream &operator<<(std::ostream &out, const struct sockaddr_in &addr);
std::ostream &operator<<(std::ostream &out, struct sockaddr_in &addr);
bool operator==(const struct sockaddr_in &addr, const struct sockaddr_in &addr2);
bool operator<(const struct sockaddr_in &addr, const struct sockaddr_in &addr2);
std::string printPkt(void *d, int size);
std::string printPktOffset(unsigned int offset, void *d, unsigned int size);
/* UdpLayer ..... is the bottom layer which
* just sends and receives Udp packets.
*/
class UdpReceiver
{
public:
virtual ~UdpReceiver() {}
virtual int recvPkt(void *data, int size, struct sockaddr_in &from) = 0;
virtual int status(std::ostream &out) = 0;
};
class UdpPublisher
{
public:
virtual ~UdpPublisher() {}
virtual int sendPkt(const void *data, int size, const struct sockaddr_in &to, int ttl) = 0;
};
class UdpLayer: public bdThread
{
public:
UdpLayer(UdpReceiver *recv, struct sockaddr_in &local);
virtual ~UdpLayer() { return; }
int reset(struct sockaddr_in &local); /* calls join, close, openSocket */
void getDataTransferred(uint32_t &read, uint32_t &write);
int status(std::ostream &out);
/* setup connections */
int closeSocket();
int openSocket();
/* RsThread functions */
virtual void run(); /* called once the thread is started */
void recv_loop(); /* uses callback to UdpReceiver */
/* Higher Level Interface */
//int readPkt(void *data, int *size, struct sockaddr_in &from);
int sendPkt(const void *data, int size, const struct sockaddr_in &to, int ttl);
/* monitoring / updates */
int okay();
int tick();
/* data */
/* internals */
protected:
virtual int receiveUdpPacket(void *data, int *size, struct sockaddr_in &from);
virtual int sendUdpPacket(const void *data, int size, const struct sockaddr_in &to);
int setTTL(int t);
int getTTL();
/* low level */
private:
void clearDataTransferred();
UdpReceiver *recv;
struct sockaddr_in laddr; /* local addr */
uint32_t readBytes;
uint32_t writeBytes;
int errorState;
int sockfd;
int ttl;
bool stopThread;
bdMutex sockMtx;
};
/* For Testing - drops packets */
class LossyUdpLayer: public UdpLayer
{
public:
LossyUdpLayer(UdpReceiver *udpr, struct sockaddr_in &local, double frac);
virtual ~LossyUdpLayer();
protected:
virtual int receiveUdpPacket(void *data, int *size, struct sockaddr_in &from);
virtual int sendUdpPacket(const void *data, int size, const struct sockaddr_in &to);
double lossFraction;
};
class PortRange
{
public:
PortRange();
PortRange(uint16_t lp, uint16_t up);
bool inRange(uint16_t port);
uint16_t lport;
uint16_t uport;
};
/* For Testing - drops packets */
class RestrictedUdpLayer: public UdpLayer
{
public:
RestrictedUdpLayer(UdpReceiver *udpr, struct sockaddr_in &local);
virtual ~RestrictedUdpLayer();
void addRestrictedPortRange(int lp, int up);
protected:
virtual int receiveUdpPacket(void *data, int *size, struct sockaddr_in &from);
virtual int sendUdpPacket(const void *data, int size, const struct sockaddr_in &to);
std::list<PortRange> mLostPorts;
};
/* For Testing - drops packets all packets for initial minute (simulates TTL) */
class TimedUdpLayer: public UdpLayer
{
public:
TimedUdpLayer(UdpReceiver *udpr, struct sockaddr_in &local);
virtual ~TimedUdpLayer();
protected:
virtual int receiveUdpPacket(void *data, int *size, struct sockaddr_in &from);
virtual int sendUdpPacket(const void *data, int size, const struct sockaddr_in &to);
time_t mStartTime;
bool mActive;
};
#endif

View File

@ -1,181 +0,0 @@
/*******************************************************************************
* libbitdht/src/udp/udpproxylayer.h *
* *
* Copyright 2004 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_UDP_LAYER_H
#define BITDHT_UDP_LAYER_H
#include "util/bdthreads.h"
#include "util/bdnet.h"
#include <iosfwd>
#include <list>
#include <deque>
/* careful - duplicate definitions */
//std::ostream &operator<<(std::ostream &out, const struct sockaddr_in &addr);
std::ostream &operator<<(std::ostream &out, struct sockaddr_in &addr);
bool operator==(const struct sockaddr_in &addr, const struct sockaddr_in &addr2);
bool operator<(const struct sockaddr_in &addr, const struct sockaddr_in &addr2);
std::string printPkt(void *d, int size);
std::string printPktOffset(unsigned int offset, void *d, unsigned int size);
/* UdpLayer ..... is the bottom layer which
* just sends and receives Udp packets.
*/
class UdpReceiver
{
public:
virtual ~UdpReceiver() {}
virtual int recvPkt(void *data, int size, struct sockaddr_in &from) = 0;
virtual int status(std::ostream &out) = 0;
};
class UdpPublisher
{
public:
virtual ~UdpPublisher() {}
virtual int sendPkt(const void *data, int size, const struct sockaddr_in &to, int ttl) = 0;
};
class UdpLayer: public bdThread
{
public:
UdpLayer(UdpReceiver *recv, struct sockaddr_in &local);
virtual ~UdpLayer() { return; }
int reset(struct sockaddr_in &local); /* calls join, close, openSocket */
int status(std::ostream &out);
/* setup connections */
int closeSocket();
int openSocket();
/* RsThread functions */
virtual void run(); /* called once the thread is started */
void recv_loop(); /* uses callback to UdpReceiver */
/* Higher Level Interface */
//int readPkt(void *data, int *size, struct sockaddr_in &from);
int sendPkt(const void *data, int size, const struct sockaddr_in &to, int ttl);
/* monitoring / updates */
int okay();
int tick();
/* data */
/* internals */
protected:
virtual int receiveUdpPacket(void *data, int *size, struct sockaddr_in &from);
virtual int sendUdpPacket(const void *data, int size, const struct sockaddr_in &to);
int setTTL(int t);
int getTTL();
/* low level */
private:
UdpReceiver *recv;
struct sockaddr_in laddr; /* local addr */
int errorState;
int sockfd;
int ttl;
bool stopThread;
bdMutex sockMtx;
};
/* For Testing - drops packets */
class LossyUdpLayer: public UdpLayer
{
public:
LossyUdpLayer(UdpReceiver *udpr, struct sockaddr_in &local, double frac);
virtual ~LossyUdpLayer();
protected:
virtual int receiveUdpPacket(void *data, int *size, struct sockaddr_in &from);
virtual int sendUdpPacket(const void *data, int size, const struct sockaddr_in &to);
double lossFraction;
};
class PortRange
{
public:
PortRange();
PortRange(uint16_t lp, uint16_t up);
bool inRange(uint16_t port);
uint16_t lport;
uint16_t uport;
};
/* For Testing - drops packets */
class RestrictedUdpLayer: public UdpLayer
{
public:
RestrictedUdpLayer(UdpReceiver *udpr, struct sockaddr_in &local);
virtual ~RestrictedUdpLayer();
void addRestrictedPortRange(int lp, int up);
protected:
virtual int receiveUdpPacket(void *data, int *size, struct sockaddr_in &from);
virtual int sendUdpPacket(const void *data, int size, const struct sockaddr_in &to);
std::list<PortRange> mLostPorts;
};
/* For Testing - drops packets all packets for initial minute (simulates TTL) */
class TimedUdpLayer: public UdpLayer
{
public:
TimedUdpLayer(UdpReceiver *udpr, struct sockaddr_in &local);
virtual ~TimedUdpLayer();
protected:
virtual int receiveUdpPacket(void *data, int *size, struct sockaddr_in &from);
virtual int sendUdpPacket(const void *data, int size, const struct sockaddr_in &to);
time_t mStartTime;
bool mActive;
};
#endif

View File

@ -1,252 +0,0 @@
/*******************************************************************************
* udp/udpstack.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "udp/udpstack.h"
#include <iostream>
#include <iomanip>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
/***
* #define DEBUG_UDP_RECV 1
***/
//#define DEBUG_UDP_RECV 1
UdpStack::UdpStack(struct sockaddr_in &local)
:udpLayer(NULL), laddr(local)
{
openSocket();
return;
}
UdpStack::UdpStack(int testmode, struct sockaddr_in &local)
:udpLayer(NULL), laddr(local)
{
std::cerr << "UdpStack::UdpStack() Evoked in TestMode" << std::endl;
if (testmode == UDP_TEST_LOSSY_LAYER)
{
std::cerr << "UdpStack::UdpStack() Installing LossyUdpLayer" << std::endl;
udpLayer = new LossyUdpLayer(this, laddr, UDP_TEST_LOSSY_FRAC);
}
else if (testmode == UDP_TEST_RESTRICTED_LAYER)
{
std::cerr << "UdpStack::UdpStack() Installing RestrictedUdpLayer" << std::endl;
udpLayer = new RestrictedUdpLayer(this, laddr);
}
else if (testmode == UDP_TEST_TIMED_LAYER)
{
std::cerr << "UdpStack::UdpStack() Installing TimedUdpLayer" << std::endl;
udpLayer = new TimedUdpLayer(this, laddr);
}
else
{
std::cerr << "UdpStack::UdpStack() Installing Standard UdpLayer" << std::endl;
// standard layer
openSocket();
}
return;
}
UdpLayer *UdpStack::getUdpLayer() /* for testing only */
{
return udpLayer;
}
bool UdpStack::getLocalAddress(struct sockaddr_in &local)
{
local = laddr;
return true;
}
bool UdpStack::resetAddress(struct sockaddr_in &local)
{
#ifdef DEBUG_UDP_RECV
std::cerr << "UdpStack::resetAddress(" << local << ")";
std::cerr << std::endl;
#endif
laddr = local;
return udpLayer->reset(local);
}
/* higher level interface */
int UdpStack::recvPkt(void *data, int size, struct sockaddr_in &from)
{
/* print packet information */
#ifdef DEBUG_UDP_RECV
std::cerr << "UdpStack::recvPkt(" << size << ") from: " << from;
std::cerr << std::endl;
#endif
bdStackMutex stack(stackMtx); /********** LOCK MUTEX *********/
std::list<UdpReceiver *>::iterator it;
for(it = mReceivers.begin(); it != mReceivers.end(); it++)
{
// See if they want the packet.
if ((*it)->recvPkt(data, size, from))
{
#ifdef DEBUG_UDP_RECV
std::cerr << "UdpStack::recvPkt(" << size << ") from: " << from;
std::cerr << std::endl;
#endif
break;
}
}
return 1;
}
int UdpStack::sendPkt(const void *data, int size, const struct sockaddr_in &to, int ttl)
{
/* print packet information */
#ifdef DEBUG_UDP_RECV
std::cerr << "UdpStack::sendPkt(" << size << ") ttl: " << ttl;
std::cerr << " to: " << to;
std::cerr << std::endl;
#endif
/* send to udpLayer */
return udpLayer->sendPkt(data, size, to, ttl);
}
int UdpStack::status(std::ostream &out)
{
{
bdStackMutex stack(stackMtx); /********** LOCK MUTEX *********/
out << "UdpStack::status()" << std::endl;
out << "localaddr: " << laddr << std::endl;
out << "UdpStack::SubReceivers:" << std::endl;
std::list<UdpReceiver *>::iterator it;
int i = 0;
for(it = mReceivers.begin(); it != mReceivers.end(); it++, i++)
{
out << "\tReceiver " << i << " --------------------" << std::endl;
(*it)->status(out);
}
out << "--------------------" << std::endl;
out << std::endl;
}
udpLayer->status(out);
return 1;
}
/* setup connections */
int UdpStack::openSocket()
{
udpLayer = new UdpLayer(this, laddr);
return 1;
}
/* monitoring / updates */
int UdpStack::okay()
{
return udpLayer->okay();
}
int UdpStack::close()
{
/* TODO */
return 1;
}
/* add a TCPonUDP stream */
int UdpStack::addReceiver(UdpReceiver *recv)
{
bdStackMutex stack(stackMtx); /********** LOCK MUTEX *********/
/* check for duplicate */
std::list<UdpReceiver *>::iterator it;
it = std::find(mReceivers.begin(), mReceivers.end(), recv);
if (it == mReceivers.end())
{
mReceivers.push_back(recv);
return 1;
}
/* otherwise its already there! */
#ifdef DEBUG_UDP_RECV
std::cerr << "UdpStack::addReceiver() Recv already exists!" << std::endl;
std::cerr << "UdpStack::addReceiver() ERROR" << std::endl;
#endif
return 0;
}
int UdpStack::removeReceiver(UdpReceiver *recv)
{
bdStackMutex stack(stackMtx); /********** LOCK MUTEX *********/
/* check for duplicate */
std::list<UdpReceiver *>::iterator it;
it = std::find(mReceivers.begin(), mReceivers.end(), recv);
if (it != mReceivers.end())
{
mReceivers.erase(it);
return 1;
}
/* otherwise its not there! */
#ifdef DEBUG_UDP_RECV
std::cerr << "UdpStack::removeReceiver() Recv dont exist!" << std::endl;
std::cerr << "UdpStack::removeReceiver() ERROR" << std::endl;
#endif
return 0;
}
/*****************************************************************************************/
UdpSubReceiver::UdpSubReceiver(UdpPublisher *pub)
:mPublisher(pub)
{
return;
}
int UdpSubReceiver::sendPkt(const void *data, int size, const struct sockaddr_in &to, int ttl)
{
/* print packet information */
#ifdef DEBUG_UDP_RECV
std::cerr << "UdpSubReceiver::sendPkt(" << size << ") ttl: " << ttl;
std::cerr << " to: " << to;
std::cerr << std::endl;
#endif
/* send to udpLayer */
return mPublisher->sendPkt(data, size, to, ttl);
}

View File

@ -1,114 +0,0 @@
/*******************************************************************************
* udp/udpstack.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_UDP_STACK_RECEIVER_H
#define BITDHT_UDP_STACK_RECEIVER_H
#include "util/bdthreads.h"
#include "util/bdnet.h"
#include <iosfwd>
#include <list>
#include <deque>
#include <iosfwd>
#include <map>
#include "udp/udplayer.h"
/* UdpStackReceiver is a Generic Receiver of info from a UdpLayer class.
* it provides a UdpReceiver class, and accepts a stack of UdpReceivers,
* which will be iterated through (in-order) until someone accepts the packet.
*
* It is important to order these Receivers correctly!
*
* This infact becomes the holder of the UdpLayer, and all controls
* go through the StackReceiver.
*/
class UdpSubReceiver: public UdpReceiver
{
public:
UdpSubReceiver(UdpPublisher *pub);
/* calls mPublisher->sendPkt */
virtual int sendPkt(const void *data, int size, const struct sockaddr_in &to, int ttl);
/* callback for recved data (overloaded from UdpReceiver) */
//virtual int recvPkt(void *data, int size, struct sockaddr_in &from) = 0;
UdpPublisher *mPublisher;
};
#define UDP_TEST_LOSSY_LAYER 1
#define UDP_TEST_RESTRICTED_LAYER 2
#define UDP_TEST_TIMED_LAYER 3
#define UDP_TEST_LOSSY_FRAC (0.10)
class UdpStack: public UdpReceiver, public UdpPublisher
{
public:
UdpStack(struct sockaddr_in &local);
UdpStack(int testmode, struct sockaddr_in &local);
virtual ~UdpStack() { return; }
UdpLayer *getUdpLayer(); /* for testing only */
bool getLocalAddress(struct sockaddr_in &local);
bool resetAddress(struct sockaddr_in &local);
/* add in a receiver */
int addReceiver(UdpReceiver *recv);
int removeReceiver(UdpReceiver *recv);
/* Packet IO */
/* pass-through send packets */
virtual int sendPkt(const void *data, int size, const struct sockaddr_in &to, int ttl);
/* callback for recved data (overloaded from UdpReceiver) */
virtual int recvPkt(void *data, int size, struct sockaddr_in &from);
int status(std::ostream &out);
/* setup connections */
int openSocket();
/* monitoring / updates */
int okay();
// int tick();
int close();
private:
UdpLayer *udpLayer;
bdMutex stackMtx; /* for all class data (below) */
struct sockaddr_in laddr; /* local addr */
std::list<UdpReceiver *> mReceivers;
};
#endif

View File

@ -1,25 +0,0 @@
# RetroShare main qmake build script
#
# Copyright (C) 2004-2019, Retroshare Team <contact@retroshare.cc>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-FileCopyrightText: Retroshare Team <contact@retroshare.cc>
# SPDX-License-Identifier: LGPL-3.0-or-later
DEPENDPATH *= $$system_path($$clean_path($${PWD}/../../libbitdht/src))
INCLUDEPATH *= $$system_path($$clean_path($${PWD}/../../libbitdht/src))
LIBS *= -L$$system_path($$clean_path($${OUT_PWD}/../../libbitdht/src/lib/)) -lbitdht
!equals(TARGET, bitdht):PRE_TARGETDEPS *= $$system_path($$clean_path($${OUT_PWD}/../../libbitdht/src/lib/libbitdht.a))

View File

@ -1,402 +0,0 @@
/*******************************************************************************
* util/bdbloom.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "util/bdbloom.h"
#include "util/bdstring.h"
#include <stdlib.h>
#include <iomanip>
#if defined(_WIN32) || defined(__MINGW32__)
#include <malloc.h>
#endif
/* Bloom Filter implementation */
bloomFilter::bloomFilter(int m, int k)
{
mBits.resize(m);
mHashFns.resize(k);
mFilterBits = m;
mNoHashs = k;
mNoElements = 0;
int i;
for(i = 0; i < m; i++)
{
mBits[i] = 0;
}
for(i = 0; i < k; i++)
{
mHashFns[i] = NULL;
}
}
uint8_t convertCharToUint8(char ch1, char ch2)
{
uint8_t value1 = 0;
uint8_t value2 = 0;
/* do char1 */
if (ch1 >= '0' && ch1 <= '9')
value1 = (ch1 - '0');
else if (ch1 >= 'A' && ch1 <= 'F')
value1 = (ch1 - 'A' + 10);
else if (ch1 >= 'a' && ch1 <= 'f')
value1 = (ch1 - 'a' + 10);
/* do char2 */
if (ch2 >= '0' && ch2 <= '9')
value2 = (ch2 - '0');
else if (ch2 >= 'A' && ch2 <= 'F')
value2 = (ch2 - 'A' + 10);
else if (ch2 >= 'a' && ch2 <= 'f')
value2 = (ch2 - 'a' + 10);
uint8_t output = (value1 << 4) + value2;
return output;
}
#define BITS_PER_BYTE (8)
int bloomFilter::setFilterBits(const std::string &hex)
{
uint32_t bytes = (mFilterBits / BITS_PER_BYTE);
if (mFilterBits % BITS_PER_BYTE)
{
bytes++;
}
if (hex.size() < bytes * 2)
{
return 0;
}
// convert to binary array.
uint8_t *tmparray = (uint8_t *) malloc(bytes);
if(tmparray == NULL)
{
std::cerr << "(EE) Error. Cannot allocate memory for " << bytes << " bytes in " << __PRETTY_FUNCTION__ << std::endl;
return 0;
}
uint32_t i = 0;
for(i = 0; i < bytes; i++)
{
tmparray[i] = convertCharToUint8(hex[2 * i], hex[2 * i + 1]);
}
for(i = 0; i < mFilterBits; i++)
{
int byte = i / BITS_PER_BYTE;
int bit = i % BITS_PER_BYTE;
uint8_t value = (tmparray[byte] & (1 << bit));
if (value)
{
mBits[i] = 1;
}
else
{
mBits[i] = 0;
}
}
free(tmparray);
return 1;
}
std::string bloomFilter::getFilter()
{
/* extract filter as a hex string */
int bytes = (mFilterBits / BITS_PER_BYTE);
if (mFilterBits % BITS_PER_BYTE)
{
bytes++;
}
if (bytes==0)
{
std::cerr << "(EE) Error. Cannot allocate memory for 0 byte in " << __PRETTY_FUNCTION__ << std::endl;
return std::string();
}
// convert to binary array.
uint8_t *tmparray = (uint8_t *) malloc(bytes);
if(tmparray == NULL)
{
std::cerr << "(EE) Error. Cannot allocate memory for " << bytes << " bytes in " << __PRETTY_FUNCTION__ << std::endl;
return std::string();
}
int i,j;
for(i = 0; i < bytes; i++)
{
tmparray[i] = 0;
for(j = 0; j < BITS_PER_BYTE; j++)
{
int bit = i * BITS_PER_BYTE + j;
if (mBits[bit])
{
tmparray[i] |= (1 << j);
}
}
}
std::string out;
for(int i = 0; i < bytes; i++)
{
bd_sprintf_append(out, "%02lx", (uint32_t) (tmparray)[i]);
}
free(tmparray);
return out;
}
void bloomFilter::setBit(int bit)
{
mBits[bit] = 1;
}
bool bloomFilter::isBitSet(int bit)
{
return (mBits[bit] == 1);
}
uint32_t bloomFilter::filterBits()
{
return mFilterBits;
}
uint32_t bloomFilter::countBits()
{
int count = 0;
uint32_t i;
for(i = 0; i < mFilterBits; i++)
{
if (mBits[i])
{
count++;
}
}
return count;
}
void bloomFilter::printFilter(std::ostream &out)
{
out << "bloomFilter: m = " << mFilterBits;
out << " k = " << mNoHashs;
out << " n = " << mNoElements;
out << std::endl;
out << "BITS: ";
uint32_t i;
for(i = 0; i < mFilterBits; i++)
{
if ((i > 0) && (i % 32 == 0))
{
out << std::endl;
out << "BITS: ";
}
if (mBits[i])
{
out << "1";
}
else
{
out << "0";
}
}
out << std::endl;
out << "STR: " << getFilter();
out << std::endl;
}
void bloomFilter::setHashFunction(int idx, uint32_t (*hashfn)(const std::string &))
{
mHashFns[idx] = hashfn;
}
void bloomFilter::add(const std::string &hex)
{
uint32_t (*hashfn)(const std::string &);
uint32_t i;
for(i = 0; i < mNoHashs; i++)
{
hashfn = mHashFns[i];
int bit = hashfn(hex);
setBit(bit);
}
mNoElements++;
}
bool bloomFilter::test(const std::string &hex)
{
uint32_t (*hashfn)(const std::string &);
uint32_t i;
for(i = 0; i < mNoHashs; i++)
{
hashfn = mHashFns[i];
int bit = hashfn(hex);
if (!isBitSet(bit))
{
return false;
}
}
return true;
}
uint32_t getFirst10BitsAsNumber(const std::string &input)
{
if (input.size() < 8)
{
std::cerr << "getFirst10BitsAsNumber() ERROR Size too small!";
std::cerr << std::endl;
return 0;
}
uint8_t data[4];
data[0] = convertCharToUint8(input[0], input[1]);
data[1] = convertCharToUint8(input[2], input[3]);
data[2] = convertCharToUint8(input[4], input[5]);
data[3] = convertCharToUint8(input[6], input[7]);
uint32_t val = ((data[0] & 0xff) << 2) + ((data[1] & 0xc0) >> 6);
#ifdef DEBUG_BLOOM
std::cerr << "getFirst10BitsAsNumber() input: " << input;
std::cerr << std::endl;
std::cerr << "getFirst10BitsAsNumber() ";
std::cerr << " data[0]: " << std::hex << (uint32_t) data[0];
std::cerr << " data[1]: " << (uint32_t) data[1];
std::cerr << " data[2]: " << (uint32_t) data[2];
std::cerr << " data[3]: " << (uint32_t) data[3];
std::cerr << " val: " << std::dec << (uint32_t) val;
std::cerr << std::endl;
#endif
return val;
}
uint32_t getSecond10BitsAsNumber(const std::string &input)
{
if (input.size() < 8)
{
std::cerr << "getSecond10BitsAsNumber() ERROR Size too small!";
std::cerr << std::endl;
return 0;
}
uint8_t data[4];
data[0] = convertCharToUint8(input[0], input[1]);
data[1] = convertCharToUint8(input[2], input[3]);
data[2] = convertCharToUint8(input[4], input[5]);
data[3] = convertCharToUint8(input[6], input[7]);
uint32_t val = ((data[1] & 0x3f) << 4) + ((data[2] & 0xf0) >> 4);
#ifdef DEBUG_BLOOM
std::cerr << "getSecond10BitsAsNumber() input: " << input;
std::cerr << std::endl;
std::cerr << "getSecond10BitsAsNumber() ";
std::cerr << " data[0]: " << std::hex << (uint32_t) data[0];
std::cerr << " data[1]: " << (uint32_t) data[1];
std::cerr << " data[2]: " << (uint32_t) data[2];
std::cerr << " data[3]: " << (uint32_t) data[3];
std::cerr << " val: " << std::dec << (uint32_t) val;
std::cerr << std::endl;
#endif
return val;
}
uint32_t getMid10BitsAsNumber(const std::string &input)
{
if (input.size() < 8)
{
std::cerr << "getMid10BitsAsNumber() ERROR Size too small!";
std::cerr << std::endl;
return 0;
}
uint8_t data[4];
data[0] = convertCharToUint8(input[0], input[1]);
data[1] = convertCharToUint8(input[2], input[3]);
data[2] = convertCharToUint8(input[4], input[5]);
data[3] = convertCharToUint8(input[6], input[7]);
uint32_t val = ((data[0] & 0x07) << 7) + ((data[1] & 0x7f) >> 1);
#ifdef DEBUG_BLOOM
std::cerr << "getMid10BitsAsNumber() input: " << input;
std::cerr << std::endl;
std::cerr << "getMid10BitsAsNumber() ";
std::cerr << " data[0]: " << std::hex << (uint32_t) data[0];
std::cerr << " data[1]: " << (uint32_t) data[1];
std::cerr << " data[2]: " << (uint32_t) data[2];
std::cerr << " data[3]: " << (uint32_t) data[3];
std::cerr << " val: " << std::dec << (uint32_t) val;
std::cerr << std::endl;
#endif
return val;
}
#define BDFILTER_M 1024
#define BDFILTER_K 3
bdBloom::bdBloom()
:bloomFilter(BDFILTER_M, BDFILTER_K)
{
/* set the fns. */
setHashFunction(0, getFirst10BitsAsNumber);
setHashFunction(1, getSecond10BitsAsNumber);
setHashFunction(2, getMid10BitsAsNumber);
}

View File

@ -1,74 +0,0 @@
/*******************************************************************************
* util/bdbloom.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_BLOOM_H
#define BITDHT_BLOOM_H
#include <vector>
#include <string>
#include <iostream>
#include <inttypes.h>
class bloomFilter
{
public:
bloomFilter(int m, int k);
int setFilterBits(const std::string &hex);
std::string getFilter();
void printFilter(std::ostream &out);
bool test(const std::string &hex); // takes first m bits.
void add(const std::string &hex);
uint32_t countBits();
uint32_t filterBits();
protected:
void setHashFunction(int idx, uint32_t (*hashfn)(const std::string &));
private:
void setBit(int bit);
bool isBitSet(int bit);
std::vector<uint8_t> mBits;
std::vector<uint32_t (*)(const std::string &)> mHashFns;
uint32_t mFilterBits;
uint32_t mNoHashs;
uint32_t mNoElements;
};
/* our specific implementation */
class bdBloom: public bloomFilter
{
public:
bdBloom();
};
#endif

View File

@ -1,75 +0,0 @@
/*******************************************************************************
* util/bdfile.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include "bdfile.h"
namespace librs {
namespace util {
bool ConvertUtf8ToUtf16(const std::string& source, std::wstring& dest) ;
}
}
bool bdFile::renameFile(const std::string& from, const std::string& to)
{
int loops = 0;
#ifdef WIN32
std::wstring f;
librs::util::ConvertUtf8ToUtf16(from, f);
std::wstring t;
librs::util::ConvertUtf8ToUtf16(to, t);
while (!MoveFileEx(f.c_str(), t.c_str(), MOVEFILE_REPLACE_EXISTING))
#else
std::string f(from),t(to) ;
while (rename(from.c_str(), to.c_str()) < 0)
#endif
{
#ifdef WIN32
if (GetLastError() != ERROR_ACCESS_DENIED)
#else
if (errno != EACCES)
#endif
/* set errno? */
return false ;
#ifdef WIN32
Sleep(100000); /* us */
#else
usleep(100000); /* us */
#endif
if (loops >= 30)
return false ;
loops++;
}
return true ;
}

View File

@ -1,30 +0,0 @@
/*******************************************************************************
* util/bdfile.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2011 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#pragma once
#include <string>
class bdFile
{
public:
static bool renameFile(const std::string& from, const std::string& to) ;
} ;

View File

@ -1,363 +0,0 @@
/*******************************************************************************
* util/bdnet.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bdnet.h"
#include "bdstring.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
#if defined(_WIN32) || defined(__MINGW32__)
//#define BDNET_DEBUG
/* error handling */
int bdnet_int_errno;
int bdnet_errno()
{
return bdnet_int_errno;
}
int bdnet_init()
{
std::cerr << "bdnet_init()" << std::endl;
bdnet_int_errno = 0;
// Windows Networking Init.
WORD wVerReq = MAKEWORD(2,2);
WSADATA wsaData;
if (0 != WSAStartup(wVerReq, &wsaData))
{
std::cerr << "Failed to Startup Windows Networking";
std::cerr << std::endl;
}
else
{
std::cerr << "Started Windows Networking";
std::cerr << std::endl;
}
return 0;
}
/* check if we can modify the TTL on a UDP packet */
int bdnet_checkTTL(int fd)
{
std::cerr << "bdnet_checkTTL()" << std::endl;
int optlen = 4;
char optval[optlen];
int ret = getsockopt(fd, IPPROTO_IP, IP_TTL, optval, &optlen);
//int ret = getsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, optval, &optlen);
if (ret == SOCKET_ERROR)
{
ret = -1;
bdnet_int_errno = bdnet_w2u_errno(WSAGetLastError());
std::cerr << "bdnet_checkTTL() Failed!";
std::cerr << std::endl;
}
else
{
std::cerr << "bdnet_checkTTL() :";
std::cerr << (int) optval[0] << ":";
std::cerr << (int) optval[1] << ":";
std::cerr << (int) optval[2] << ":";
std::cerr << (int) optval[3] << ": RET: ";
std::cerr << ret << ":";
std::cerr << std::endl;
}
return ret;
}
int bdnet_close(int fd)
{
std::cerr << "bdnet_close()" << std::endl;
return closesocket(fd);
}
int bdnet_socket(int domain, int type, int protocol)
{
int osock = socket(domain, type, protocol);
std::cerr << "bdnet_socket()" << std::endl;
if ((unsigned) osock == INVALID_SOCKET)
{
// Invalidate socket Unix style.
osock = -1;
bdnet_int_errno = bdnet_w2u_errno(WSAGetLastError());
}
bdnet_checkTTL(osock);
return osock;
}
int bdnet_bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen)
{
std::cerr << "bdnet_bind()" << std::endl;
int ret = bind(sockfd,my_addr,addrlen);
if (ret != 0)
{
/* store unix-style error
*/
ret = -1;
bdnet_int_errno = bdnet_w2u_errno(WSAGetLastError());
}
return ret;
}
int bdnet_fcntl(int fd, int cmd, long arg)
{
int ret;
unsigned long int on = 1;
std::cerr << "bdnet_fcntl()" << std::endl;
/* can only do NONBLOCK at the moment */
if ((cmd != F_SETFL) || (arg != O_NONBLOCK))
{
std::cerr << "bdnet_fcntl() limited to fcntl(fd, F_SETFL, O_NONBLOCK)";
std::cerr << std::endl;
bdnet_int_errno = EOPNOTSUPP;
return -1;
}
ret = ioctlsocket(fd, FIONBIO, &on);
if (ret != 0)
{
/* store unix-style error
*/
ret = -1;
bdnet_int_errno = bdnet_w2u_errno(WSAGetLastError());
}
return ret;
}
int bdnet_setsockopt(int s, int level, int optname,
const void *optval, socklen_t optlen)
{
std::cerr << "bdnet_setsockopt() val:" << *((int *) optval) << std::endl;
std::cerr << "bdnet_setsockopt() len:" << optlen << std::endl;
if ((level != IPPROTO_IP) || (optname != IP_TTL))
{
std::cerr << "bdnet_setsockopt() limited to ";
std::cerr << "setsockopt(fd, IPPROTO_IP, IP_TTL, ....)";
std::cerr << std::endl;
bdnet_int_errno = EOPNOTSUPP;
return -1;
}
int ret = setsockopt(s, level, optname, (const char *) optval, optlen);
//int ret = setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (const char *) optval, optlen);
if (ret == SOCKET_ERROR)
{
ret = -1;
bdnet_int_errno = bdnet_w2u_errno(WSAGetLastError());
}
bdnet_checkTTL(s);
return ret;
}
ssize_t bdnet_recvfrom(int s, void *buf, size_t len, int flags,
struct sockaddr *from, socklen_t *fromlen)
{
#ifdef BDNET_DEBUG
std::cerr << "bdnet_recvfrom()" << std::endl;
#endif
int ret = recvfrom(s, (char *) buf, len, flags, from, fromlen);
if (ret == SOCKET_ERROR)
{
ret = -1;
bdnet_int_errno = bdnet_w2u_errno(WSAGetLastError());
}
return ret;
}
ssize_t bdnet_sendto(int s, const void *buf, size_t len, int flags,
const struct sockaddr *to, socklen_t tolen)
{
#ifdef BDNET_DEBUG
std::cerr << "bdnet_sendto()" << std::endl;
#endif
int ret = sendto(s, (const char *) buf, len, flags, to, tolen);
if (ret == SOCKET_ERROR)
{
ret = -1;
bdnet_int_errno = bdnet_w2u_errno(WSAGetLastError());
}
return ret;
}
int bdnet_w2u_errno(int err)
{
/* switch */
std::cerr << "tou_net_w2u_errno(" << err << ")" << std::endl;
switch(err)
{
case WSAEINPROGRESS:
return EINPROGRESS;
break;
case WSAEWOULDBLOCK:
return EINPROGRESS;
break;
case WSAENETUNREACH:
return ENETUNREACH;
break;
case WSAETIMEDOUT:
return ETIMEDOUT;
break;
case WSAEHOSTDOWN:
return EHOSTDOWN;
break;
case WSAECONNREFUSED:
return ECONNREFUSED;
break;
case WSAEADDRINUSE:
return EADDRINUSE;
break;
case WSAEUSERS:
return EUSERS;
break;
/* This one is returned for UDP recvfrom, when nothing there
* but not a real error... translate into EINPROGRESS
*/
case WSAECONNRESET:
std::cerr << "tou_net_w2u_errno(" << err << ")";
std::cerr << " = WSAECONNRESET ---> EINPROGRESS";
std::cerr << std::endl;
return EINPROGRESS;
break;
/***
*
case WSAECONNRESET:
return ECONNRESET;
break;
*
***/
case WSANOTINITIALISED:
std::cerr << "tou_net_w2u_errno(" << err << ") WSANOTINITIALISED. Fix Your Code!";
std::cerr << std::endl;
break;
default:
std::cerr << "tou_net_w2u_errno(" << err << ") Unknown";
std::cerr << std::endl;
break;
}
return ECONNREFUSED; /* sensible default? */
}
int bdnet_inet_aton(const char *name, struct in_addr *addr)
{
return (((*addr).s_addr = inet_addr(name)) != INADDR_NONE);
}
#ifndef __MINGW64_VERSION_MAJOR
int sleep(unsigned int sec)
{
Sleep(sec * 1000);
return 0;
}
#endif
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
#else // UNIX
/* Unix Version is easy -> just call the unix fn
*/
#include <unistd.h> /* for close definition */
/* the universal interface */
int bdnet_init() { return 0; }
int bdnet_errno() { return errno; }
/* check if we can modify the TTL on a UDP packet */
int bdnet_checkTTL(int /*fd*/) { return 1;}
int bdnet_inet_aton(const char *name, struct in_addr *addr)
{
return inet_aton(name, addr);
}
int bdnet_close(int fd) { return close(fd); }
int bdnet_socket(int domain, int type, int protocol)
{
return socket(domain, type, protocol);
}
int bdnet_bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen)
{
return bind(sockfd,my_addr,addrlen);
}
int bdnet_fcntl(int fd, int cmd, long arg)
{
return fcntl(fd, cmd, arg);
}
int bdnet_setsockopt(int s, int level, int optname,
const void *optval, socklen_t optlen)
{
return setsockopt(s, level, optname, optval, optlen);
}
ssize_t bdnet_recvfrom(int s, void *buf, size_t len, int flags,
struct sockaddr *from, socklen_t *fromlen)
{
return recvfrom(s, buf, len, flags, from, fromlen);
}
ssize_t bdnet_sendto(int s, const void *buf, size_t len, int flags,
const struct sockaddr *to, socklen_t tolen)
{
return sendto(s, buf, len, flags, to, tolen);
}
#endif
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
void bdsockaddr_clear(struct sockaddr_in *addr)
{
memset(addr, 0, sizeof(*addr));
}
/* thread-safe version of inet_ntoa */
std::string bdnet_inet_ntoa(struct in_addr in)
{
std::string str;
uint8_t *bytes = (uint8_t *) &(in.s_addr);
bd_sprintf(str, "%u.%u.%u.%u", (int) bytes[0], (int) bytes[1], (int) bytes[2], (int) bytes[3]);
return str;
}

View File

@ -1,174 +0,0 @@
/*******************************************************************************
* util/bdnet.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright 2010 by Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_UNIVERSAL_NETWORK_HEADER
#define BITDHT_UNIVERSAL_NETWORK_HEADER
#include <inttypes.h>
#include <string>
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
#if defined(_WIN32) || defined(__MINGW32__)
#include <ws2tcpip.h>
#include <stdio.h> /* for ssize_t */
typedef uint32_t in_addr_t;
#else // UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>
#endif
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
/* C Interface */
#ifdef __cplusplus
extern "C" {
#endif
/*******
* This defines a (unix-like) universal networking layer
* that should function on both windows and unix. (C - interface)
*
* This is of course only a subset of the full interface.
* functions required are:
*
* int bdnet_close(int fd);
* int bdnet_socket(int domain, int type, int protocol);
* int bdnet_bind(int sockfd, const struct sockaddr *my_addr,
* socklen_t addrlen);
* int bdnet_fcntl(int fd, int cmd, long arg);
* int bdnet_setsockopt(int s, int level, int optname,
* const void *optval, socklen_t optlen);
* ssize_t bdnet_recvfrom(int s, void *buf, size_t len, int flags,
* struct sockaddr *from, socklen_t *fromlen);
* ssize_t bdnet_sendto(int s, const void *buf, size_t len, int flags,
* const struct sockaddr *to, socklen_t tolen);
*
* There are some non-standard ones as well:
* int bdnet_errno(); for internal networking errors
* int bdnet_init(); required for windows
* int bdnet_checkTTL(); a check if we can modify the ttl
*/
/* the universal interface */
int bdnet_errno(); /* for internal networking errors */
int bdnet_init(); /* required for windows */
int bdnet_close(int fd);
int bdnet_socket(int domain, int type, int protocol);
int bdnet_bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen);
int bdnet_fcntl(int fd, int cmd, long arg);
int bdnet_setsockopt(int s, int level, int optname,
const void *optval, socklen_t optlen);
ssize_t bdnet_recvfrom(int s, void *buf, size_t len, int flags,
struct sockaddr *from, socklen_t *fromlen);
ssize_t bdnet_sendto(int s, const void *buf, size_t len, int flags,
const struct sockaddr *to, socklen_t tolen);
/* address filling */
int bdnet_inet_aton(const char *name, struct in_addr *addr);
/* check if we can modify the TTL on a UDP packet */
int bdnet_checkTTL(int fd);
void bdsockaddr_clear(struct sockaddr_in *addr);
/* Extra stuff to declare for windows error handling (mimics unix errno)
*/
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
#if defined(_WIN32) || defined(__MINGW32__)
// Some Network functions that are missing from windows.
//in_addr_t inet_netof(struct in_addr addr);
//in_addr_t inet_network(char *inet_name);
//int inet_aton(const char *name, struct in_addr *addr);
// definitions for fcntl (NON_BLOCK) (random?)
#define F_SETFL 0x1010
#define O_NONBLOCK 0x0100
// definitions for setsockopt (TTL) (random?)
//#define IPPROTO_IP 0x0011
//#define IP_TTL 0x0110
/* define the Unix Error Codes that we use...
* NB. we should make the same, but not necessary
*/
#define EAGAIN 11
#define EUSERS 87
#define EHOSTDOWN 112
#ifndef __MINGW64_VERSION_MAJOR
#define EWOULDBLOCK EAGAIN
#define ENOTSOCK 88
#define EOPNOTSUPP 95
#define EADDRINUSE 98
#define EADDRNOTAVAIL 99
#define ENETDOWN 100
#define ENETUNREACH 101
#define ECONNRESET 104
#define ETIMEDOUT 10060 // value from pthread.h
#define ECONNREFUSED 111
#define EHOSTUNREACH 113
#define EALREADY 114
#define EINPROGRESS 115
#endif
int bdnet_w2u_errno(int error);
/* also put the sleep commands in here (where else to go)
* ms uses millisecs.
* void Sleep(int ms);
*/
#ifndef __MINGW64_VERSION_MAJOR
int sleep(unsigned int sec);
#endif
#endif // END of WINDOWS defines.
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
#ifdef __cplusplus
} /* C Interface */
#endif
/* thread-safe version of inet_ntoa */
std::string bdnet_inet_ntoa(struct in_addr in);
#endif /* BITDHT_UNIVERSAL_NETWORK_HEADER */

View File

@ -1,120 +0,0 @@
/*******************************************************************************
* util/bdrandom.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright (C) 2010 Cyril Soler <csoler@users.sourceforge.net> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <time.h>
#include "util/bdrandom.h"
uint32_t bdRandom::index = 0 ;
std::vector<uint32_t> bdRandom::MT(bdRandom::N,0u) ;
bdMutex bdRandom::rndMtx ;
#if (defined(_WIN32) || defined(__MINGW32__)) && !defined(WIN_PTHREADS_H)
static bool auto_seed = bdRandom::seed( (time(NULL) + ((uint32_t) pthread_self().p)*0x1293fe)^0x18e34a12 ) ;
#else
#ifdef __APPLE__
static bool auto_seed = bdRandom::seed( (time(NULL) + pthread_mach_thread_np(pthread_self())*0x1293fe + (getpid()^0x113ef76b))^0x18e34a12 ) ;
#elif defined(__FreeBSD__) || (__HAIKU__)
// since this is completely insecure anyway, just kludge for now
static bool auto_seed = bdRandom::seed(time(NULL));
#elif defined(__OpenBSD__)
static bool auto_seed = bdRandom::seed(arc4random());
#else
static bool auto_seed = bdRandom::seed( (time(NULL) + pthread_self()*0x1293fe + (getpid()^0x113ef76b))^0x18e34a12 ) ;
#endif
#endif
bool bdRandom::seed(uint32_t s)
{
bdStackMutex mtx(rndMtx) ;
MT.resize(N,0) ; // because MT might not be already resized
uint32_t j ;
MT[0]= s & 0xffffffffUL;
for (j=1; j<N; j++)
MT[j] = (1812433253UL * (MT[j-1] ^ (MT[j-1] >> 30)) + j) & 0xffffffffUL ;
return true ;
}
void bdRandom::locked_next_state()
{
for(uint32_t i=0;i<N;++i)
{
uint32_t y = ((MT[i]) & UMASK) | ((MT[(i+1)%(int)N]) & LMASK) ;
MT[i] = MT[(i + M) % (int)N] ^ (y >> 1) ;
if((y & 1) == 1)
MT[i] = MT[i] ^ 0x9908b0df ;
}
index = 0 ;
}
uint32_t bdRandom::random_u32()
{
uint32_t y;
{
bdStackMutex mtx(rndMtx) ;
y = MT[index++] ;
if(index == N)
locked_next_state();
}
// Tempering
y ^= (y >> 11);
y ^= (y << 7 ) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
uint64_t bdRandom::random_u64()
{
return ((uint64_t)random_u32() << 32ul) + random_u32() ;
}
float bdRandom::random_f32()
{
return random_u32() / (float)(~(uint32_t)0) ;
}
double bdRandom::random_f64()
{
return random_u64() / (double)(~(uint64_t)0) ;
}
std::string bdRandom::random_alphaNumericString(uint32_t len)
{
std::string s = "" ;
for(uint32_t i=0;i<len;++i)
s += (char)( (random_u32()%94) + 33) ;
return s ;
}

View File

@ -1,72 +0,0 @@
/*******************************************************************************
* util/bdrandom.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright (C) 2010 Cyril Soler <csoler@users.sourceforge.net> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_UTILS_BDRANDOM_H
#define BITDHT_UTILS_BDRANDOM_H
/* This Source Code is basically a direct copy of libretroshare's RsRandom.
* the function names have just been renamed. drbob
*/
// bdRandom contains a random number generator that is
// - thread safe
// - system independant
// - fast
// - NOT CRYPTOGRAPHICALLY SAFE
// - DO NOT USE FOR ANYTHING REQUIRING STRONG UNPREDICTABLE RANDOMNESS
//
// The implementation is adapted from the Mersenne Twister page of Wikipedia.
//
// http://en.wikipedia.org/wiki/Mersenne_twister
// FIXME(ben): MT is not cryptographically safe.
#include <vector>
#include "util/bdthreads.h"
class bdRandom
{
public:
static uint32_t random_u32() ;
static uint64_t random_u64() ;
static float random_f32() ;
static double random_f64() ;
static bool seed(uint32_t s) ;
static std::string random_alphaNumericString(uint32_t length) ;
private:
static bdMutex rndMtx ;
static const uint32_t N = 624;
static const uint32_t M = 397;
static const uint32_t MATRIX_A = 0x9908b0dfUL;
static const uint32_t UMASK = 0x80000000UL;
static const uint32_t LMASK = 0x7fffffffUL;
static void locked_next_state() ;
static uint32_t index ;
static std::vector<uint32_t> MT ;
};
#endif

View File

@ -1,97 +0,0 @@
/*******************************************************************************
* util/bdstring.h *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright (C) 2010 Retroshare Team <retroshare.project@gmail.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bdstring.h"
#ifdef _WIN32
#include <windows.h>
#include <malloc.h>
#else
#include <stdarg.h>
#include <stdlib.h>
#endif
#include <stdio.h>
#ifdef _WIN32
// asprintf() and vasprintf() are missing in Win32
static int vasprintf(char **sptr, const char *fmt, va_list argv)
{
int wanted = __mingw_vsnprintf(*sptr = NULL, 0, fmt, argv);
if ((wanted > 0) && ((*sptr = (char*) malloc(wanted + 1)) != NULL)) {
return __mingw_vsprintf(*sptr, fmt, argv);
}
return wanted;
}
//static int asprintf(char **sptr, const char *fmt, ...)
//{
// int retval;
// va_list argv;
// va_start( argv, fmt );
// retval = vasprintf(sptr, fmt, argv);
// va_end(argv);
// return retval;
//}
#endif
int bd_sprintf(std::string &str, const char *fmt, ...)
{
char *buffer = NULL;
va_list ap;
va_start(ap, fmt);
int retval = vasprintf(&buffer, fmt, ap);
va_end(ap);
if (retval >= 0) {
if (buffer) {
str = buffer;
free(buffer);
} else {
str.clear();
}
} else {
str.clear();
}
return retval;
}
int bd_sprintf_append(std::string &str, const char *fmt, ...)
{
va_list ap;
char *buffer = NULL;
va_start(ap, fmt);
int retval = vasprintf(&buffer, fmt, ap);
va_end(ap);
if (retval >= 0) {
if (buffer) {
str.append(buffer);
free(buffer);
}
}
return retval;
}

View File

@ -1,42 +0,0 @@
/*******************************************************************************
* util/bdstring.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright (C) 2010 Retroshare Team <retroshare.project@gmail.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_UTILS_BDSTRING_H
#define BITDHT_UTILS_BDSTRING_H
#ifdef WIN32
// for proper handling of %ll
#define bd_snprintf __mingw_snprintf
#define bd_fprintf __mingw_fprintf
#else
#define bd_snprintf snprintf
#define bd_fprintf fprintf
#endif
#ifdef __cplusplus
// These definitions are only available for C++ Modules.
#include <string>
int bd_sprintf(std::string &str, const char *fmt, ...);
int bd_sprintf_append(std::string &str, const char *fmt, ...);
#endif
#endif

View File

@ -1,167 +0,0 @@
/*******************************************************************************
* util/bdthread.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright (C) 2004-2010 Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "bdthreads.h"
#include <unistd.h> /* for usleep() */
/*******
* #define DEBUG_THREADS 1
*******/
//#define DEBUG_THREADS 1
#ifdef DEBUG_THREADS
#include <iostream>
#endif
extern "C" void* bdthread_init(void* p)
{
#ifdef DEBUG_THREADS
std::cerr << "bdthread_init()";
std::cerr << std::endl;
#endif
bdThread *thread = (bdThread *) p;
if (!thread)
{
#ifdef DEBUG_THREADS
std::cerr << "bdthread_init() Error Invalid thread pointer.";
std::cerr << std::endl;
#endif
return 0;
}
thread -> run();
return 0;
}
pthread_t createThread(bdThread &thread)
{
pthread_t tid;
void *data = (void *) (&thread);
#ifdef DEBUG_THREADS
std::cerr << "createThread() creating a bdThread";
std::cerr << std::endl;
#endif
thread.mMutex.lock();
{
pthread_create(&tid, 0, &bdthread_init, data);
thread.mTid = tid;
}
#ifdef DEBUG_THREADS
std::cerr << "createThread() created Thread.mTid: ";
#if defined(_WIN32) || defined(__MINGW32__)
std::cerr << "WIN32: Cannot print mTid ";
#else
std::cerr << thread.mTid;
#endif
std::cerr << std::endl;
#endif
thread.mMutex.unlock();
return tid;
}
bdThread::bdThread()
{
#ifdef DEBUG_THREADS
std::cerr << "bdThread::bdThread()";
std::cerr << std::endl;
#endif
#if defined(_WIN32) || defined(__MINGW32__)
memset (&mTid, 0, sizeof(mTid));
#else
mTid = 0;
#endif
}
void bdThread::join() /* waits for the the mTid thread to stop */
{
#ifdef DEBUG_THREADS
std::cerr << "bdThread::join() Called! Waiting for Thread.mTid: ";
#if defined(_WIN32) || defined(__MINGW32__)
std::cerr << "WIN32: Cannot print mTid ";
#else
std::cerr << mTid;
#endif
std::cerr << std::endl;
#endif
mMutex.lock();
{
#if defined(_WIN32) || defined(__MINGW32__) || defined(__APPLE__)
/* Its a struct in Windows compile and the member .p ist checked in the pthreads library */
#else
if(mTid > 0)
#endif
pthread_join(mTid, NULL);
#ifdef DEBUG_THREADS
std::cerr << "bdThread::join() Joined Thread.mTid: ";
#if defined(_WIN32) || defined(__MINGW32__)
std::cerr << "WIN32: Cannot print mTid ";
#else
std::cerr << mTid;
#endif
std::cerr << std::endl;
std::cerr << "bdThread::join() Setting mTid = 0";
std::cerr << std::endl;
#endif
#if defined(_WIN32) || defined(__MINGW32__)
memset (&mTid, 0, sizeof(mTid));
#else
mTid = 0;
#endif
}
mMutex.unlock();
}
void bdThread::stop()
{
#ifdef DEBUG_THREADS
std::cerr << "bdThread::stop() Called!";
std::cerr << std::endl;
#endif
pthread_exit(NULL);
}

View File

@ -1,97 +0,0 @@
/*******************************************************************************
* util/bdthread.cc *
* *
* BitDHT: An Flexible DHT library. *
* *
* Copyright (C) 2004-2010 Robert Fernie <bitdht@lunamutt.com> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef BITDHT_THREADS_H
#define BITDHT_THREADS_H
#include <iostream>
#include <pthread.h>
#include <inttypes.h>
/* Thread Wrappers */
class bdMutex
{
public:
bdMutex(bool recursive = false)
{
/* remove unused parameter warnings */
(void) recursive;
#if 0 // TESTING WITHOUT RECURSIVE
if(recursive)
{
pthread_mutexattr_t att ;
pthread_mutexattr_init(&att) ;
pthread_mutexattr_settype(&att,PTHREAD_MUTEX_RECURSIVE) ;
if( pthread_mutex_init(&realMutex, &att))
std::cerr << "ERROR: Could not initialize mutex !" << std::endl ;
}
else
#endif
if( pthread_mutex_init(&realMutex, NULL))
std::cerr << "ERROR: Could not initialize mutex !" << std::endl ;
}
~bdMutex() { pthread_mutex_destroy(&realMutex); }
void lock() { pthread_mutex_lock(&realMutex); }
void unlock() { pthread_mutex_unlock(&realMutex); }
bool trylock() { return (0 == pthread_mutex_trylock(&realMutex)); }
private:
pthread_mutex_t realMutex;
};
class bdStackMutex
{
public:
bdStackMutex(bdMutex &mtx): mMtx(mtx) { mMtx.lock(); }
~bdStackMutex() { mMtx.unlock(); }
private:
bdMutex &mMtx;
};
class bdThread;
/* to create a thread! */
pthread_t createThread(bdThread &thread);
class bdThread
{
public:
bdThread();
virtual ~bdThread() { return; }
virtual void start() { createThread(*this); }
virtual void run() = 0; /* called once the thread is started */
virtual void join(); /* waits for the mTid thread to stop */
virtual void stop(); /* calls pthread_exit() */
pthread_t mTid;
bdMutex mMutex;
};
#endif

1
libretroshare Submodule

@ -0,0 +1 @@
Subproject commit 8044b19bb1e51a8446164813fe826b612c0b1e7a

View File

@ -1,6 +0,0 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# These are explicitly windows files and should use crlf
*.bat text eol=crlf

View File

@ -1,8 +0,0 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build
# Ignore Gradle local options
local.properties

View File

@ -1,457 +0,0 @@
# RetroShare decentralized communication platform
#
# Copyright (C) 2021 Gioacchino Mazzurco <gio@eigenlab.org>
# Copyright (C) 2021 Asociación Civil Altermundi <info@altermundi.net>
#
# SPDX-License-Identifier: CC0-1.0
cmake_minimum_required (VERSION 3.18.0)
project(retroshare)
include(CMakeDependentOption)
set(FETCHCONTENT_QUIET OFF)
include(FetchContent)
# sqlcipher
option(
RS_SQLCIPHER
"SQLCipher encryption for GXS database"
ON )
# rs_gxs_send_all
option(
RS_GXS_SEND_ALL
"GXS distribute all available messages on request, indipendently from \
local sync timer"
ON )
# bitdht
option(
RS_BITDHT
"Use bitdht (BitTorrent DHT own implementation) to look for online peers"
ON )
# use_dht_stunner
cmake_dependent_option(
RS_BITDHT_STUNNER
"Use bitdht (BitTorrent DHT own implementation) for NAT type discovery and \
attempt the STUN (Session Traversal Utilities for NAT)"
ON
"RS_BITDHT"
OFF )
# use_dht_stunner_ext_ip
cmake_dependent_option(
RS_BITDHT_STUNNER_EXT_IP
"Use bitdht (BitTorrent DHT own implementation) stunner to figure out our \
external IP. As this purely relying on random DHT peers that answer our \
request, it can easily be abused. Therefore, it is turned off by default."
OFF
"RS_BITDHT_STUNNER"
OFF )
# rs_jsonapi
option(
RS_JSON_API
"Use restbed to expose libretroshare as JSON API via HTTP"
OFF )
# rs_deep_forums_index
option(
RS_FORUM_DEEP_INDEX
"Xapian based full text index and search of GXS forums"
OFF )
# rs_broadcast_discovery
option(
RS_BRODCAST_DISCOVERY
"Local area network peer discovery via udp-discovery-cpp"
ON )
# rs_dh_init_check
option(
RS_DH_PRIME_INIT_CHECK
"Check Diffie Hellman prime at each startup. This is not necessary and on \
all Android mobile phones tested this take at least one minute at startup \
which is untolerable for most phone users."
ON )
option(
RS_MINIUPNPC
"Forward ports in NAT router via miniupnpc"
ON )
cmake_dependent_option(
RS_LIBUPNP
"Forward ports in NAT router via libupnp (unstable)"
OFF
"NOT RS_MINIUPNPC"
OFF )
option(
RS_LIBRETROSHARE_STATIC
"Build RetroShare static library"
ON )
cmake_dependent_option(
RS_LIBRETROSHARE_SHARED
"Build RetroShare shared library"
OFF
"NOT RS_LIBRETROSHARE_STATIC"
OFF )
# rs_deprecatedwarning
option(
RS_WARN_DEPRECATED
"Print warning about RetroShare deprecated components usage during build"
ON )
# rs_cppwarning
option(
RS_WARN_LESS
"Silence a few at the moment very common warnings about RetroShare \
components during build"
OFF )
# rs_v07_changes
option(
RS_V07_BREAKING_CHANGES
"Enable retro-compatibility breaking changes planned for RetroShare 0.7.0"
OFF )
set(
RS_DATA_DIR
"${CMAKE_INSTALL_PREFIX}/share/retroshare"
CACHE STRING
"Path where to install RetroShare system wide data" )
option(
RS_EXPORT_JNI_ONLOAD
"Export libretroshare JNI_OnLoad. See src/rs_android/rsjni.cpp for details"
ON )
################################################################################
find_package(Git REQUIRED)
#function(check_submodule sPath)
# if(NOT EXISTS "${sPath}/.git" )
# message("Initializing submodule ${sPath}")
# execute_process(
# COMMAND "${GIT_EXECUTABLE}" submodule update --init
# WORKING_DIRECTORY "${sPath}"
# COMMAND_ECHO STDERR
# COMMAND_ERROR_IS_FATAL ANY)
# endif()
#endfunction()
################################################################################
include(src/CMakeLists.txt)
list(TRANSFORM RS_SOURCES PREPEND src/)
list(TRANSFORM RS_PUBLIC_HEADERS PREPEND src/)
if(RS_LIBRETROSHARE_STATIC)
add_library(${PROJECT_NAME} STATIC ${RS_SOURCES})
endif(RS_LIBRETROSHARE_STATIC)
if(RS_LIBRETROSHARE_SHARED)
add_library(${PROJECT_NAME} SHARED ${RS_SOURCES})
## Ensure statically linked libraries such as openpgpsdk are compiled with
## PIC Which is needed for shared library
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif(RS_LIBRETROSHARE_SHARED)
target_include_directories(
${PROJECT_NAME}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src )
install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
# TODO: install public headers
find_package(OpenSSL REQUIRED)
target_include_directories(${PROJECT_NAME} PRIVATE ${OPENSSL_INCLUDE_DIR})
target_link_libraries(${PROJECT_NAME} PRIVATE OpenSSL::SSL OpenSSL::Crypto)
################################################################################
set(OPENPGPSDK_DEVEL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../openpgpsdk/")
if(EXISTS "${OPENPGPSDK_DEVEL_DIR}/.git" )
message(
CHECK_PASS
"openpgpsdk submodule found at ${OPENPGPSDK_DEVEL_DIR} using it" )
add_subdirectory(${OPENPGPSDK_DEVEL_DIR} ${CMAKE_BINARY_DIR}/openpgpsdk)
else()
FetchContent_Declare(
openpgpsdk
GIT_REPOSITORY "https://gitlab.com/RetroShare/openpgpsdk.git"
GIT_TAG "origin/master"
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
TIMEOUT 10
)
FetchContent_MakeAvailable(openpgpsdk)
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE openpgpsdk)
################################################################################
if(RS_BITDHT)
set(BITDHT_DEVEL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../libbitdht/")
if(EXISTS "${BITDHT_DEVEL_DIR}/.git" )
message(
CHECK_PASS
"BitDHT submodule found at ${BITDHT_DEVEL_DIR} using it" )
add_subdirectory(${BITDHT_DEVEL_DIR} ${CMAKE_BINARY_DIR}/bitdht)
set(RS_BITDHT_DIR "${BITDHT_DEVEL_DIR}")
else()
FetchContent_Declare(
bitdht
GIT_REPOSITORY "https://gitlab.com/RetroShare/bitdht.git"
GIT_TAG "origin/master"
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
TIMEOUT 10
)
FetchContent_MakeAvailable(bitdht)
set(RS_BITDHT_DIR "${bitdht_SOURCE_DIR}")
endif()
add_compile_definitions(RS_USE_BITDHT)
target_link_libraries(${PROJECT_NAME} PRIVATE bitdht)
if(RS_BITDHT_STUNNER)
add_compile_definitions(RS_USE_DHT_STUNNER)
if(RS_BITDHT_STUNNER_EXT_IP)
# TODO: Refactor this define to use proper naming
add_compile_definitions(ALLOW_DHT_STUNNER)
endif(RS_BITDHT_STUNNER_EXT_IP)
endif(RS_BITDHT_STUNNER)
endif(RS_BITDHT)
################################################################################
if(RS_JSON_API)
find_package(Doxygen REQUIRED)
find_package(Python3 REQUIRED)
set(
JSON_API_GENERATOR_WORK_DIR
"${CMAKE_BINARY_DIR}/jsonapi-generator.workdir/" )
set(
JSON_API_GENERATOR_DOXYFILE
"${JSON_API_GENERATOR_WORK_DIR}/jsonapi-generator-doxygen.conf" )
set(
JSONAPI_GENERATOR_OUTPUT_DIR
"${JSON_API_GENERATOR_WORK_DIR}/src/" )
set(
JSONAPI_GENERATOR_SOURCE_DIR
"${CMAKE_CURRENT_SOURCE_DIR}/src/jsonapi/" )
set(
JSONAPI_GENERATOR_EXECUTABLE
"${JSONAPI_GENERATOR_SOURCE_DIR}/jsonapi-generator.py" )
file(
COPY "src/jsonapi/jsonapi-generator-doxygen.conf"
DESTINATION "${JSON_API_GENERATOR_WORK_DIR}" )
file(
APPEND
"${JSON_API_GENERATOR_DOXYFILE}"
"OUTPUT_DIRECTORY=${JSONAPI_GENERATOR_OUTPUT_DIR}\n"
"INPUT=${CMAKE_CURRENT_SOURCE_DIR}" )
add_custom_command(
OUTPUT
"${JSONAPI_GENERATOR_OUTPUT_DIR}/jsonapi-includes.inl"
"${JSONAPI_GENERATOR_OUTPUT_DIR}/jsonapi-wrappers.inl"
COMMAND ${DOXYGEN_EXECUTABLE} ${JSON_API_GENERATOR_DOXYFILE}
COMMAND
${Python3_EXECUTABLE} ${JSONAPI_GENERATOR_EXECUTABLE}
${JSONAPI_GENERATOR_SOURCE_DIR} ${JSONAPI_GENERATOR_OUTPUT_DIR}
MAIN_DEPENDENCY "${JSONAPI_GENERATOR_EXECUTABLE}"
DEPENDS ${JSON_API_GENERATOR_DOXYFILE} ${RS_PUBLIC_HEADERS} )
target_sources(
${PROJECT_NAME} PRIVATE
"${JSONAPI_GENERATOR_OUTPUT_DIR}/jsonapi-includes.inl"
"${JSONAPI_GENERATOR_OUTPUT_DIR}/jsonapi-wrappers.inl" )
include_directories(${JSONAPI_GENERATOR_OUTPUT_DIR})
set(BUILD_TESTS OFF CACHE BOOL "Do not build restbed tests")
set(BUILD_SSL OFF CACHE BOOL "Do not build restbed SSL support")
FetchContent_Declare(
restbed
GIT_REPOSITORY "https://github.com/Corvusoft/restbed.git"
GIT_TAG "4.8"
GIT_SUBMODULES dependency/asio dependency/catch
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
TIMEOUT 10
)
FetchContent_MakeAvailable(restbed)
target_link_libraries(${PROJECT_NAME} PRIVATE restbed)
## TODO: work around target_include_directories should be added upstream
include_directories(${restbed_SOURCE_DIR}/source/)
add_compile_definitions(RS_JSONAPI)
endif(RS_JSON_API)
################################################################################
if(RS_FORUM_DEEP_INDEX)
find_package(Xapian REQUIRED)
target_link_libraries(${PROJECT_NAME} PRIVATE ${XAPIAN_LIBRARIES})
add_compile_definitions(RS_DEEP_FORUMS_INDEX)
endif(RS_FORUM_DEEP_INDEX)
################################################################################
## TODO: Check if https://github.com/rbock/sqlpp11 or
## https://github.com/rbock/sqlpp17 may improve GXS code
if(RS_SQLCIPHER)
find_library(RS_SQL_LIB "sqlcipher" REQUIRED)
find_path(
RS_SQL_LIB_INCLUDE "sqlcipher/sqlite3.h"
PATH_SUFFIXES "include" "includes"
REQUIRED )
target_include_directories(
${PROJECT_NAME}
PRIVATE "${RS_SQL_LIB_INCLUDE}/sqlcipher" )
target_link_libraries(${PROJECT_NAME} PRIVATE ${RS_SQL_LIB})
else()
add_compile_definitions(NO_SQLCIPHER)
find_package(SQLite3 REQUIRED)
target_link_libraries(${PROJECT_NAME} PRIVATE SQLite::SQLite3)
endif()
add_compile_definitions(
SQLITE_HAS_CODEC
RS_ENABLE_GXS
GXS_ENABLE_SYNC_MSGS
RS_USE_GXS_DISTANT_SYNC
RS_GXS_TRANS
V07_NON_BACKWARD_COMPATIBLE_CHANGE_001
V07_NON_BACKWARD_COMPATIBLE_CHANGE_002
V07_NON_BACKWARD_COMPATIBLE_CHANGE_003 )
if(RS_V07_BREAKING_CHANGES)
add_compile_definitions(
V07_NON_BACKWARD_COMPATIBLE_CHANGE_004
V07_NON_BACKWARD_COMPATIBLE_CHANGE_UNNAMED )
endif()
if(RS_DH_PRIME_INIT_CHECK)
add_compile_definitions(RS_DISABLE_DIFFIE_HELLMAN_INIT_CHECK)
endif(RS_DH_PRIME_INIT_CHECK)
if(RS_MINIUPNPC)
add_compile_definitions(RS_USE_LIBMINIUPNPC)
endif(RS_MINIUPNPC)
if(RS_LIBUPNP)
message(FATAL_ERROR "UPnP support via libupnp is currently not supported")
#add_compile_definitions(RS_USE_LIBUPNP)
endif(RS_LIBUPNP)
if(RS_GXS_SEND_ALL)
add_compile_definitions(RS_GXS_SEND_ALL)
endif(RS_GXS_SEND_ALL)
if(RS_BRODCAST_DISCOVERY)
## TODO: upstream option to disable tests building
set(BUILD_EXAMPLE OFF CACHE BOOL "Do not build udp-discovery-cpp examples")
set(BUILD_TOOL OFF CACHE BOOL "Do not build udp-discovery-tool application")
FetchContent_Declare(
udp-discovery-cpp
GIT_REPOSITORY "https://github.com/truvorskameikin/udp-discovery-cpp.git"
GIT_TAG "origin/master"
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
TIMEOUT 10
)
FetchContent_MakeAvailable(udp-discovery-cpp)
target_link_libraries(${PROJECT_NAME} PRIVATE udp-discovery)
## TODO: Temporary work around target_include_directories should be added
## upstream
include_directories(${udp-discovery-cpp_SOURCE_DIR})
endif(RS_BRODCAST_DISCOVERY)
if(NOT RS_WARN_DEPRECATED)
add_compile_definitions(RS_NO_WARN_DEPRECATED)
target_compile_options(
${PROJECT_NAME} PRIVATE
-Wno-deprecated -Wno-deprecated-declarations )
endif(NOT RS_WARN_DEPRECATED)
if(RS_WARN_LESS)
add_compile_definitions(RS_NO_WARN_CPP)
target_compile_options(
${PROJECT_NAME} PRIVATE
-Wno-cpp -Wno-inconsistent-missing-override )
endif(RS_WARN_LESS)
################################################################################
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
add_compile_definitions(RS_DATA_DIR="${RS_DATA_DIR}")
endif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
################################################################################
if(RS_EXPORT_JNI_ONLOAD)
add_compile_definitions(RS_LIBRETROSHARE_EXPORT_JNI_ONLOAD)
endif(RS_EXPORT_JNI_ONLOAD)
################################################################################
#if(CMAKE_SYSTEM_NAME STREQUAL "Android")
if(RS_ANDROID)
FetchContent_Declare(
jni-hpp
GIT_REPOSITORY "https://gitlab.com/RetroShare/jni-hpp.git"
GIT_TAG "origin/master"
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
TIMEOUT 10
)
FetchContent_MakeAvailable(jni-hpp)
include_directories(${jni-hpp_SOURCE_DIR}/include)
if(RS_BITDHT)
set(RS_ANDROID_ASSETS_DIR "${CMAKE_BINARY_DIR}/android-assets")
set(RS_ANDROID_VALUES_DIR "${RS_ANDROID_ASSETS_DIR}/values")
file(MAKE_DIRECTORY "${RS_ANDROID_VALUES_DIR}")
file(
COPY "${RS_BITDHT_DIR}/src/bitdht/bdboot.txt"
DESTINATION "${RS_ANDROID_VALUES_DIR}" )
set(
ANDROID_ASSETS_DIRECTORIES
"${RS_ANDROID_ASSETS_DIR};${ANDROID_ASSETS_DIRECTORIES}" )
endif(RS_BITDHT)
endif(RS_ANDROID)
#endif(CMAKE_SYSTEM_NAME STREQUAL "Android")
################################################################################
## Useful to debug CMake
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

View File

@ -1,226 +0,0 @@
/*
* libretroshare Android AAR library gradle builder
*
* Copyright (C) 2022 Gioacchino Mazzurco <gio@eigenlab.org>
* Copyright (C) 2022 Asociación Civil Altermundi <info@altermundi.net>
*
* SPDX-License-Identifier: CC0-1.0
*/
buildscript
{
repositories
{
// The order in which you list these repositories matter.
google()
mavenCentral()
}
dependencies
{
classpath 'com.android.tools.build:gradle:7.1.+'
}
}
allprojects
{
repositories
{
// The order in which you list these repositories matter.
google()
mavenCentral()
}
}
ext.buildLibretroshareNativeLib =
{
pApiLevel, /* Android API level */
pAbi, /* Arch name as seen in AAR native libraries directories */
pNdkPath, /* Android NDK path */
pReuseToolchain = true /* If true reuse previously built toochain */ ->
/* Convert pAbi into corresponding prepare toolchain ANDROID_NDK_ARCH */
def toolchainArch = "unsupported"
def libcxxsharedTriple = "unsupported"
switch(pAbi)
{
case "armeabi-v7a":
toolchainArch = "arm";
libcxxsharedTriple = "arm-linux-androideabi";
break;
case "arm64-v8a":
toolchainArch = "arm64";
libcxxsharedTriple = "aarch64-linux-android";
break;
default:
throw new GradleException(
"buildLibretroshareNativeLib unsupported pAbi: $pAbi" );
break;
}
def toolchainsWorkdir = "${buildDir}/native_toolchains/"
mkdir toolchainsWorkdir
def currToolchainPath = "$toolchainsWorkdir/$pApiLevel-$toolchainArch/"
// Todo: use proper way to resolve the script path
def toolChainScriptPath = "${projectDir}/../build_scripts/Android/prepare-toolchain-clang.sh"
if(!pReuseToolchain || !file(currToolchainPath).exists())
{
exec
{
workingDir toolchainsWorkdir
environment "ANDROID_NDK_PATH", pNdkPath
environment "NATIVE_LIBS_TOOLCHAIN_PATH", currToolchainPath
environment "ANDROID_PLATFORM_VER", pApiLevel
environment "ANDROID_NDK_ARCH", toolchainArch
commandLine toolChainScriptPath /*, 'build_libretroshare'*/
}
}
else
{/*
exec
{
workingDir toolchainsWorkdir
environment "ANDROID_NDK_PATH", pNdkPath
environment "NATIVE_LIBS_TOOLCHAIN_PATH", currToolchainPath
environment "ANDROID_PLATFORM_VER", pApiLevel
environment "ANDROID_NDK_ARCH", toolchainArch
commandLine toolChainScriptPath, 'build_libretroshare'
}*/
}
def nativeLibsDir = "${buildDir}/native_libs-$pApiLevel/"
mkdir nativeLibsDir
def currAbiLibDir = "${nativeLibsDir}/$pAbi/"
mkdir currAbiLibDir
copy
{
from "${currToolchainPath}/sysroot/usr/lib/libretroshare.so"
into currAbiLibDir
}
copy
{
from "${currToolchainPath}/sysroot/usr/lib/${libcxxsharedTriple}/libc++_shared.so"
into currAbiLibDir
}
}
apply plugin: 'com.android.library'
apply plugin: 'maven-publish'
android
{
// see https://stackoverflow.com/questions/27301867/what-is-compilesdkversion
compileSdkVersion 21
sourceSets
{
main
{
java.srcDirs = [ 'src/rs_android/' ]
manifest.srcFile 'src/rs_android/AndroidManifest.xml'
assets.srcDirs = [ "${buildDir}/libretroshare-build/android-assets/" ]
jniLibs.srcDirs = [ "${buildDir}/native_libs-16" ]
}
minApi16
{
jniLibs.srcDirs = [ "${buildDir}/native_libs-16" ]
}
minApi21
{
jniLibs.srcDirs = [ "${buildDir}/native_libs-21" ]
}
minApi24
{
jniLibs.srcDirs = [ "${buildDir}/native_libs-24" ]
}
}
lintOptions
{
disable 'LongLogTag'
}
flavorDimensions 'api'
def currNdk = android.getNdkDirectory().getAbsolutePath()
productFlavors
{
minApi16
{
minSdkVersion '16'
targetSdkVersion '16'
def currApi = minSdkVersion.mApiLevel
versionNameSuffix "-API_${currApi}"
buildLibretroshareNativeLib(currApi, "armeabi-v7a", currNdk)
}
minApi21
{
minSdkVersion '21'
targetSdkVersion '21'
def currApi = minSdkVersion.mApiLevel
versionNameSuffix "-API_${currApi}"
buildLibretroshareNativeLib(currApi, "arm64-v8a", currNdk)
buildLibretroshareNativeLib(currApi, "armeabi-v7a", currNdk)
}
minApi24
{
minSdkVersion '24'
targetSdkVersion '28'
def currApi = minSdkVersion.mApiLevel
versionNameSuffix "-API_${currApi}"
buildLibretroshareNativeLib(currApi, "arm64-v8a", currNdk)
buildLibretroshareNativeLib(currApi, "armeabi-v7a", currNdk)
}
}
publishing
{
multipleVariants
{
allVariants()
}
}
}
afterEvaluate
{
publishing
{
// see https://developer.android.com/reference/tools/gradle-api/7.1/com/android/build/api/dsl/LibraryPublishing
publications
{
android.libraryVariants.each
{
variant ->
publishing.publications.create(variant.name, MavenPublication)
{
from components.findByName(variant.name)
groupId = 'org.retroshare.service'
// -${variant.flavorName}
artifactId "${rootProject.name}-${variant.name}"
version "0.6.6"
artifacts = [ "${buildDir}/outputs/aar/${rootProject.name}-${variant.flavorName}-${variant.buildType.name}.aar" ]
}
}
}
}
}

Binary file not shown.

View File

@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
libretroshare/gradlew vendored
View File

@ -1,185 +0,0 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MSYS* | MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

Some files were not shown because too many files have changed in this diff Show More