Merge pull request #507 from mr-alice/v0.6-FileLists

V0.6 file lists
This commit is contained in:
csoler 2016-09-24 14:13:38 +02:00 committed by GitHub
commit 91c9ed2569
29 changed files with 742 additions and 435 deletions

136
src/LICENSE.md Normal file
View File

@ -0,0 +1,136 @@
# GNU LIBRARY GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1991 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the library GPL. It is
numbered 2 because it goes with version 2 of the ordinary GPL.]
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.
This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it.
For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights.
Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library.
Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license.
The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such.
Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better.
However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries.
The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library.
Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one.
## TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.
(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library.
In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.
Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange.
If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:
a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.
7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
### NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
# END OF TERMS AND CONDITIONS

View File

@ -1,44 +0,0 @@
CPPFLAGS += -g -Wall -D BE_DEBUG -lpthread
LDFLAGS += -g -Wall -D BE_DEBUG -lpthread
CFLAGS += -g -Wall -D BE_DEBUG
CC = g++
LIB = -lpthread
CPPLIB = -lpthread
EXEC = bdmsgs_test bdmetric_test bdquery_test bdspace_test bdspace_test2 bdnode_test bdnode_test2 bdstore_test
EXEC += bdnode_multitest1 bdmidids_test
EXEC += udpbitdht_nettest bencode_test
EXEC += bdmgr_multitest
#EXEC += bdudp_test
all: $(EXEC)
OBJ = bencode.o bdmsgs.o bdobj.o
OBJ += bdpeer.o bdquery.o bdnode.o bdstore.o bdhash.o
OBJ += bdmanager.o bdstddht.o
# udp base objs
OBJ += bdthreads.o udplayer.o udpstack.o
OBJ += udpbitdht.o
bdmsgs_test: $(OBJ) bdmsgs_test.o
bdmetric_test: $(OBJ) bdmetric_test.o
bdquery_test: $(OBJ) bdquery_test.o
bdspace_test: $(OBJ) bdspace_test.o
bdspace_test2: $(OBJ) bdspace_test2.o
bdnode_test: $(OBJ) bdnode_test.o
bdnode_test2: $(OBJ) bdnode_test2.o
bdmidids_test: $(OBJ) bdmidids_test.o
bdnode_multitest1: $(OBJ) bdnode_multitest1.o
bdmgr_multitest: $(OBJ) bdmgr_multitest.o
bdstore_test: $(OBJ) bdstore_test.o
bdudp_test: $(OBJ) bdudp_test.o
udpbitdht_nettest: $(OBJ) udpbitdht_nettest.o
bencode_test: $(OBJ) bencode_test.o
clean:
rm -f *.o core $(EXEC)
.PHONY: all clean

View File

@ -524,7 +524,7 @@ int bdConnectManager::requestConnection_proxy(struct sockaddr_in *laddr, bdNodeI
std::cerr << std::endl;
#endif
//connreq.mGoodProxies.push_back(it->second);
mPub->send_query(&(it->second), target);
mPub->send_query(&(it->second), target, true);
}
}

View File

@ -151,12 +151,11 @@ class bdConnection
class bdProxyId
{
public:
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) { return; }
bdProxyId() :srcType(BD_PI_SRC_UNKNOWN), errcode(0) { return; }
std::string proxySrcType() const;
@ -168,7 +167,13 @@ class bdProxyId
class bdConnectionRequest
{
public:
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);

View File

@ -26,8 +26,11 @@
#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>
@ -35,39 +38,110 @@
/**
* #define DEBUG_FILTER 1
**/
#define BDFILTER_ENTRY_DROP_PERIOD (7 * 24 * 3600)
#define BDFILTER_ENTRY_DROP_PERIOD (6 * 3600)
bdFilter::bdFilter(const bdNodeId *ownId, std::list<bdFilteredPeer> &startList,
uint32_t filterFlags, bdDhtFunctions *fns)
bdFilter::bdFilter(const std::string &fname, const bdNodeId *ownid, uint32_t filterFlags, bdDhtFunctions *fns, bdNodeManager *manager)
{
/* */
mOwnId = *ownId;
mFns = fns;
mOwnId = *ownid;
mFns = fns;
mFilename = fname ;
std::list<bdFilteredPeer>::iterator it;
loadBannedIpFile() ;
for(it = startList.begin(); it != startList.end(); it++)
{
mFiltered.push_back(*it);
}
mFilterFlags = filterFlags;
mFilterFlags = filterFlags;
mNodeManager = manager;
}
bool bdFilter::filtered(std::list<bdFilteredPeer> &answer)
void bdFilter::writeBannedIpFile()
{
answer = mFiltered;
return (answer.size() > 0);
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::list<bdFilteredPeer>::iterator it;
std::map<uint32_t,bdFilteredPeer>::iterator it;
for(it = mFiltered.begin(); it != mFiltered.end(); it++)
{
answer.push_back(it->mAddr);
answer.push_back(it->second.mAddr);
}
return (answer.size() > 0);
}
@ -85,7 +159,8 @@ int bdFilter::checkPeer(const bdId *id, uint32_t mode)
if (add)
{
bool isNew = addPeerToFilter(id, flags);
bool isNew = addPeerToFilter(id->addr, flags);
if (isNew)
{
return 1;
@ -95,54 +170,75 @@ int bdFilter::checkPeer(const bdId *id, uint32_t mode)
return 0;
}
int bdFilter::addPeerToFilter(const bdId *id, uint32_t flags)
int bdFilter::addPeerToFilter(const struct sockaddr_in& addr, uint32_t flags)
{
std::list<bdFilteredPeer>::iterator it;
bool found = false;
for(it = mFiltered.begin(); it != mFiltered.end(); it++)
std::map<uint32_t,bdFilteredPeer>::iterator it = mFiltered.find(addr.sin_addr.s_addr) ;
if(it != mFiltered.end())
{
if (id->addr.sin_addr.s_addr == it->mAddr.sin_addr.s_addr)
{
found = true;
it->mLastSeen = time(NULL);
it->mFilterFlags |= flags;
break;
}
}
it->second.mLastSeen = time(NULL);
it->second.mFilterFlags |= flags;
}
else
{
time_t now = time(NULL);
bdFilteredPeer fp;
if (!found)
{
time_t now = time(NULL);
bdFilteredPeer fp;
fp.mAddr = addr;
fp.mAddr.sin_port = 0;
fp.mFilterFlags = flags;
fp.mFilterTS = now;
fp.mLastSeen = now;
fp.mAddr = id->addr;
fp.mAddr.sin_port = 0;
fp.mFilterFlags = flags;
fp.mFilterTS = now;
fp.mLastSeen = now;
uint32_t saddr = addr.sin_addr.s_addr;
mFiltered.push_back(fp);
mFiltered[saddr] = fp;
uint32_t saddr = id->addr.sin_addr.s_addr;
mIpsBanned.insert(saddr);
std::cerr << "Adding New Banned Ip Address: " << bdnet_inet_ntoa(addr.sin_addr);
std::cerr << std::endl;
}
writeBannedIpFile() ;
std::cerr << "Adding New Banned Ip Address: " << bdnet_inet_ntoa(id->addr.sin_addr);
std::cerr << std::endl;
return true;
}
return false;
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)
{
std::set<uint32_t>::const_iterator it = mIpsBanned.find(addr->sin_addr.s_addr);
if (it == mIpsBanned.end())
{
return 1; // Address is Okay!
// 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;
@ -184,55 +280,41 @@ bool bdFilter::isOwnIdWithoutBitDhtFlags(const bdId *id, uint32_t peerFlags)
bool bdFilter::cleanupFilter()
{
#ifdef DEBUG_FILTER
std::cerr << "bdFilter::cleanupFilter() Current BanList" << std::endl;
struct in_addr inaddr;
std::set<uint32_t>::iterator sit;
for(sit = mIpsBanned.begin(); sit != mIpsBanned.end(); sit++)
{
inaddr.s_addr = *sit;
std::cerr << "\tBanned: " << inet_ntoa(inaddr) << std::endl;
}
#endif
mIpsBanned.clear();
#ifdef DEBUG_FILTER
std::cerr << "Filter List:" << std::endl;
std::cerr << "bdFilter: Checking current filter List:" << std::endl;
#endif
time_t now = time(NULL);
time_t dropTime = now - BDFILTER_ENTRY_DROP_PERIOD;
std::list<bdFilteredPeer>::iterator it;
for(it = mFiltered.begin(); it != mFiltered.end();)
{
for(std::map<uint32_t,bdFilteredPeer>::iterator it = mFiltered.begin(); it != mFiltered.end();)
{
#ifdef DEBUG_FILTER
std::cerr << "\t" << inet_ntoa(it->mAddr.sin_addr);
std::cerr << " Flags: " << it->mFilterFlags;
std::cerr << " FilterTS: " << now - it->mFilterTS;
std::cerr << " LastSeen: " << now - it->mLastSeen;
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->mLastSeen < dropTime)
{
/* remove from filter */
if (it->second.mLastSeen < dropTime)
{
/* remove from filter */
#ifdef DEBUG_FILTER
std::cerr << " OLD DROPPING" << std::endl;
std::cerr << " OLD DROPPING" << std::endl;
#endif
it = mFiltered.erase(it);
}
else
{
#ifdef DEBUG_FILTER
std::cerr << " OK" << std::endl;
#endif
uint32_t saddr = it->mAddr.sin_addr.s_addr;
mIpsBanned.insert(saddr);
std::map<uint32_t,bdFilteredPeer>::iterator tmp(it) ;
++tmp ;
it++;
}
}
mFiltered.erase(it);
it = tmp ;
}
else
{
#ifdef DEBUG_FILTER
std::cerr << " OK" << std::endl;
#endif
it++;
}
}
return true;
}

View File

@ -40,31 +40,38 @@
class bdFilteredPeer
{
public:
struct sockaddr_in mAddr;
uint32_t mFilterFlags; /* reasons why we are filtering */
time_t mFilterTS;
time_t mLastSeen;
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 bdNodeId *ownid, std::list<bdFilteredPeer> &initialFilters,
uint32_t filterFlags, bdDhtFunctions *fns);
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 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 bdId *id, uint32_t flags);
int addPeerToFilter(const struct sockaddr_in &addr, uint32_t flags);
bool cleanupFilter();
private:
void loadBannedIpFile() ;
void writeBannedIpFile() ;
private:
bool isOwnIdWithoutBitDhtFlags(const bdId *id, uint32_t peerFlags);
@ -72,11 +79,12 @@ bool isOwnIdWithoutBitDhtFlags(const bdId *id, uint32_t peerFlags);
bdNodeId mOwnId;
uint32_t mFilterFlags;
std::list<bdFilteredPeer> mFiltered;
std::map<uint32_t,bdFilteredPeer> mFiltered;
bdDhtFunctions *mFns;
std::string mFilename ;
// = addr.sin_addr.s_addr (uint32_t) stored in network order.
std::set<uint32_t> mIpsBanned;
// have access to the manager for isBanned callback
bdNodeManager* mNodeManager;
};

View File

@ -337,20 +337,25 @@ class BitDhtCallback
public:
// ~BitDhtCallback();
// dummy cos not needed for standard dht behaviour;
virtual int dhtNodeCallback(const bdId * /*id*/, uint32_t /*peerflags*/) { return 0; }
// 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;
// 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; } */
// 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;
// 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;}
};

View File

@ -68,12 +68,15 @@
#define QUERY_UPDATE_PERIOD 8 // under refresh period - so it'll happen at the MAX_REFRESH_PERIOD
bdNodeManager::bdNodeManager(bdNodeId *id, std::string dhtVersion, std::string bootfile, bdDhtFunctions *fns)
:bdNode(id, dhtVersion, bootfile, fns)
bdNodeManager::bdNodeManager(bdNodeId *id, std::string dhtVersion, std::string bootfile, const std::string& filterfile,bdDhtFunctions *fns)
:bdNode(id, dhtVersion, bootfile, filterfile, fns, this)
{
mMode = BITDHT_MGR_STATE_OFF;
mFns = fns;
mModeTS = 0 ;
mStartTS = 0;
mSearchingDone = false;
mSearchTS = 0;
mNetworkSize = 0;
mBdNetworkSize = 0;
@ -394,7 +397,7 @@ void bdNodeManager::iteration()
std::cerr << std::endl;
#endif
mFilterPeers->cleanupFilter();
mFilterPeers.cleanupFilter();
#ifdef DEBUG_MGR
@ -526,15 +529,19 @@ int bdNodeManager::QueryRandomLocalNet()
}
/* do standard find_peer message */
mQueryMgr->addWorthyPeerSource(&id); /* Tell BitDHT that we really want to ping their peers */
send_query(&id, &targetNodeId);
send_query(&id, &targetNodeId, true);
#ifdef DEBUG_MGR
std::cerr << "bdNodeManager::QueryRandomLocalNet() Querying : ";
mFns->bdPrintId(std::cerr, &id);
std::cerr << " searching for : ";
mFns->bdPrintNodeId(std::cerr, &targetNodeId);
bdMetric dist;
mFns->bdDistance(&targetNodeId, &(mOwnId), &dist);
int bucket = mFns->bdBucketDistance(&dist);
std::cerr << " in Bucket: " << bucket;
std::cerr << std::endl;
#endif
@ -584,9 +591,11 @@ void bdNodeManager::SearchForLocalNet()
{
if (it->second.mQFlags & BITDHT_QFLAGS_INTERNAL)
{
std::cerr << "bdNodeManager::SearchForLocalNet() Existing Internal Search: ";
#ifdef DEBUG_MGR
std::cerr << "bdNodeManager::SearchForLocalNet() Existing Internal Search: ";
mFns->bdPrintNodeId(std::cerr, &(it->first));
std::cerr << std::endl;
std::cerr << std::endl;
#endif
numSearchQueries++;
}
@ -1170,10 +1179,9 @@ void bdNodeManager::doPeerCallback(const bdId *id, uint32_t status)
void bdNodeManager::doValueCallback(const bdNodeId *id, std::string key, uint32_t status)
{
#ifdef DEBUG_MGR
std::cerr << "bdNodeManager::doValueCallback()";
std::cerr << std::endl;
#ifdef DEBUG_MGR
#endif
/* search list */
std::list<BitDhtCallback *>::iterator it;
@ -1187,10 +1195,9 @@ void bdNodeManager::doValueCallback(const bdNodeId *id, std::string key, uint32_
void bdNodeManager::doInfoCallback(const bdId *id, uint32_t type, uint32_t flags, std::string info)
{
#ifdef DEBUG_MGR
std::cerr << "bdNodeManager::doInfoCallback()";
std::cerr << std::endl;
#ifdef DEBUG_MGR
#endif
/* search list */
std::list<BitDhtCallback *>::iterator it;
@ -1201,6 +1208,28 @@ void bdNodeManager::doInfoCallback(const bdId *id, uint32_t type, uint32_t flags
return;
}
void bdNodeManager::doIsBannedCallback(const sockaddr_in *addr, bool *isAvailable, bool *isBanned)
{
#ifdef DEBUG_MGR
std::cerr << "bdNodeManager::doIsBannedCallback()";
std::cerr << std::endl;
#endif
/* search list */
std::list<BitDhtCallback *>::iterator it;
*isBanned = false;
*isAvailable = false;
for(it = mCallbacks.begin(); it != mCallbacks.end(); it++)
{
// set isBanned to true as soon as one callback answers with true
bool banned;
if((*it)->dhtIsBannedCallback(addr, &banned))
{
*isBanned = *isBanned || banned;
*isAvailable = true;
}
}
}
#define BITDHT_IDENTITY_STRING_V1 "d1:"
#define BITDHT_IDENTITY_SIZE_V1 3

View File

@ -96,7 +96,7 @@ class bdQueryPeer
class bdNodeManager: public bdNode, public BitDhtInterface
{
public:
bdNodeManager(bdNodeId *id, std::string dhtVersion, std::string bootfile, bdDhtFunctions *fns);
bdNodeManager(bdNodeId *id, std::string dhtVersion, std::string bootfile, const std::string &filterfile, bdDhtFunctions *fns);
void iteration();
@ -152,7 +152,11 @@ 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);
private:
// 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);

View File

@ -52,7 +52,7 @@ bencoded = d1:ad2:id20:abcdefghij0123456789e1:q4:ping1:t2:aa1:y1:qe
****/
int bitdht_create_ping_msg(bdToken *tid, bdNodeId *id, char *msg, int avail)
int bitdht_create_ping_msg(bdToken *tid, bdNodeId *id, bdToken *vid, char *msg, int avail)
{
#ifdef DEBUG_MSGS
fprintf(stderr, "bitdht_create_ping_msg()\n");
@ -74,6 +74,13 @@ int bitdht_create_ping_msg(bdToken *tid, bdNodeId *id, char *msg, int avail)
be_add_keypair(dict, "t", tidnode);
be_add_keypair(dict, "y", qynode);
if (vid)
{
be_node *vnode = be_create_str_wlen((char *) vid->data, vid->len);
be_add_keypair(dict, "v", vnode);
}
#ifdef DEBUG_MSG_DUMP
/* dump answer */
be_dump(dict);
@ -135,7 +142,7 @@ bencoded = d1:ad2:id20:abcdefghij01234567896:target20:mnopqrstuvwxyz123456e1:q9:
*/
int bitdht_find_node_msg(bdToken *tid, bdNodeId *id, bdNodeId *target,
int bitdht_find_node_msg(bdToken *tid, bdNodeId *id, bdNodeId *target, bool localoption,
char *msg, int avail)
{
#ifdef DEBUG_MSGS
@ -160,6 +167,12 @@ int bitdht_find_node_msg(bdToken *tid, bdNodeId *id, bdNodeId *target,
be_add_keypair(dict, "y", yqrnode);
be_add_keypair(dict, "q", findnode);
if (localoption)
{
be_node *optionnode = be_create_str("l");
be_add_keypair(dict, "o", optionnode);
}
#ifdef DEBUG_MSG_DUMP
/* dump answer */
be_dump(dict);

View File

@ -73,9 +73,9 @@
#define BITDHT_VID_UT 2
int bitdht_create_ping_msg(bdToken *tid, bdNodeId *id, char *msg, int avail);
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, 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,

View File

@ -70,12 +70,14 @@
#define HISTORY_PERIOD 60
bdNode::bdNode(bdNodeId *ownId, std::string dhtVersion, std::string bootfile, bdDhtFunctions *fns)
:mNodeSpace(ownId, fns), mQueryMgr(NULL), mConnMgr(NULL),
mFilterPeers(NULL), mOwnId(*ownId), mDhtVersion(dhtVersion), mStore(bootfile, fns), mFns(fns),
mFriendList(ownId), mHistory(HISTORY_PERIOD)
bdNode::bdNode(bdNodeId *ownId, std::string dhtVersion, const std::string& bootfile, const std::string& filterfile, bdDhtFunctions *fns, bdNodeManager *manager)
:mNodeSpace(ownId, fns),
mFilterPeers(filterfile,ownId, BITDHT_FILTER_REASON_OWNID, fns, manager),
mQueryMgr(NULL),
mConnMgr(NULL),
mOwnId(*ownId), mDhtVersion(dhtVersion), mStore(bootfile, fns), mFns(fns),
mFriendList(ownId), mHistory(HISTORY_PERIOD)
{
init(); /* (uses this pointers) stuff it - do it here! */
}
@ -84,9 +86,6 @@ void bdNode::init()
mQueryMgr = new bdQueryManager(&mNodeSpace, mFns, this);
mConnMgr = new bdConnectManager(&mOwnId, &mNodeSpace, mQueryMgr, mFns, this);
std::list<bdFilteredPeer> emptyList;
mFilterPeers = new bdFilter(&mOwnId, emptyList, BITDHT_FILTER_REASON_OWNID, mFns);
//setNodeOptions(BITDHT_OPTIONS_MAINTAIN_UNSTABLE_PORT);
setNodeOptions(0);
@ -94,7 +93,16 @@ void bdNode::init()
setNodeDhtMode(BITDHT_MODE_TRAFFIC_DEFAULT);
}
bool bdNode::getFilteredPeers(std::list<bdFilteredPeer>& peers)
{
mFilterPeers.getFilteredPeers(peers) ;
return true ;
}
//
//void bdNode::loadFilteredPeers(const std::list<bdFilteredPeer>& peers)
//{
// mFilterPeers.loadFilteredPeers(peers) ;
//}
/* Unfortunately I've ended up with 2 calls down through the heirarchy...
* not ideal - must clean this up one day.
*/
@ -249,7 +257,12 @@ void bdNode::shutdownNode()
/* Crappy initial store... use bdspace as answer */
void bdNode::updateStore()
{
mStore.writeStore();
mStore.writeStore();
}
bool bdNode::addressBanned(const sockaddr_in& raddr)
{
return !mFilterPeers.addrOkay(const_cast<sockaddr_in*>(&raddr)) ;
}
void bdNode::printState()
@ -442,13 +455,13 @@ void bdNode::send_ping(bdId *id)
}
void bdNode::send_query(bdId *id, bdNodeId *targetNodeId)
void bdNode::send_query(bdId *id, bdNodeId *targetNodeId, bool localnet)
{
/* push out query */
bdToken transId;
genNewTransId(&transId);
msgout_find_node(id, &transId, targetNodeId);
msgout_find_node(id, &transId, targetNodeId, localnet);
#ifdef DEBUG_NODE_MSGS
std::cerr << "bdNode::send_query() Find Node Req for : ";
@ -481,12 +494,14 @@ void bdNode::checkPotentialPeer(bdId *id, bdId *src)
/* Check BadPeer Filters for Potential Peers too */
/* first check the filters */
if (!mFilterPeers->addrOkay(&(id->addr)))
if (!mFilterPeers.addrOkay(&(id->addr)))
{
#ifdef DEBUG_NODE_MSGS
std::cerr << "bdNode::checkPotentialPeer(";
mFns->bdPrintId(std::cerr, id);
std::cerr << ") BAD ADDRESS!!!! SHOULD DISCARD POTENTIAL PEER";
std::cerr << std::endl;
#endif
return;
}
@ -509,10 +524,10 @@ void bdNode::checkPotentialPeer(bdId *id, bdId *src)
// Stores in queue for later callback and desemination around the network.
mBadPeerQueue.queuePeer(id, 0);
mFilterPeers->addPeerToFilter(id, 0);
mFilterPeers.addPeerToFilter(id->addr, 0);
std::list<struct sockaddr_in> filteredIPs;
mFilterPeers->filteredIPs(filteredIPs);
mFilterPeers.filteredIPs(filteredIPs);
mStore.filterIpList(filteredIPs);
return;
@ -542,8 +557,6 @@ void bdNode::addPotentialPeer(bdId *id, bdId * /*src*/)
mPotentialPeers.push_back(*id);
}
// virtual so manager can do callback.
// peer flags defined in bdiface.h
void bdNode::addPeer(const bdId *id, uint32_t peerflags)
@ -556,7 +569,7 @@ void bdNode::addPeer(const bdId *id, uint32_t peerflags)
#endif
/* first check the filters */
if (mFilterPeers->checkPeer(id, peerflags))
if (mFilterPeers.checkPeer(id, peerflags))
{
std::cerr << "bdNode::addPeer(";
mFns->bdPrintId(std::cerr, id);
@ -565,7 +578,7 @@ void bdNode::addPeer(const bdId *id, uint32_t peerflags)
std::cerr << std::endl;
std::list<struct sockaddr_in> filteredIPs;
mFilterPeers->filteredIPs(filteredIPs);
mFilterPeers.filteredIPs(filteredIPs);
mStore.filterIpList(filteredIPs);
mBadPeerQueue.queuePeer(id, peerflags);
@ -597,10 +610,10 @@ void bdNode::addPeer(const bdId *id, uint32_t peerflags)
// Stores in queue for later callback and desemination around the network.
mBadPeerQueue.queuePeer(id, peerflags);
mFilterPeers->addPeerToFilter(id, peerflags);
mFilterPeers.addPeerToFilter(id->addr, peerflags);
std::list<struct sockaddr_in> filteredIPs;
mFilterPeers->filteredIPs(filteredIPs);
mFilterPeers.filteredIPs(filteredIPs);
mStore.filterIpList(filteredIPs);
// DO WE EXPLICITLY NEED TO DO THIS, OR WILL THEY JUST BE DROPPED?
@ -681,6 +694,7 @@ void bdNode::processRemoteQuery()
switch(query.mQueryType)
{
case BD_QUERY_NEIGHBOURS:
case BD_QUERY_LOCALNET:
{
/* search bdSpace for neighbours */
@ -688,17 +702,26 @@ void bdNode::processRemoteQuery()
std::multimap<bdMetric, bdId> nearest;
std::multimap<bdMetric, bdId>::iterator it;
if (mRelayMode == BITDHT_RELAYS_SERVER)
if (query.mQueryType == BD_QUERY_LOCALNET)
{
std::list<bdId> excludeList;
mNodeSpace.find_nearest_nodes_with_flags(&(query.mQuery),
BITDHT_QUERY_NEIGHBOUR_PEERS,
excludeList, nearest, BITDHT_PEER_STATUS_DHT_RELAY_SERVER);
excludeList, nearest, BITDHT_PEER_STATUS_DHT_APPL);
}
else
{
mNodeSpace.find_nearest_nodes(&(query.mQuery), BITDHT_QUERY_NEIGHBOUR_PEERS, nearest);
if (mRelayMode == BITDHT_RELAYS_SERVER)
{
std::list<bdId> excludeList;
mNodeSpace.find_nearest_nodes_with_flags(&(query.mQuery),
BITDHT_QUERY_NEIGHBOUR_PEERS,
excludeList, nearest, BITDHT_PEER_STATUS_DHT_RELAY_SERVER);
}
else
{
mNodeSpace.find_nearest_nodes(&(query.mQuery), BITDHT_QUERY_NEIGHBOUR_PEERS, nearest);
}
}
for(it = nearest.begin(); it != nearest.end(); it++)
@ -756,9 +779,9 @@ void bdNode::processRemoteQuery()
std::cerr << "bdNode::processRemoteQuery() Query Too Old: Discarding: ";
}
#endif
#ifdef DEBUG_NODE_MSGS
mFns->bdPrintId(std::cerr, &(query.mId));
std::cerr << std::endl;
#ifdef DEBUG_NODE_MSGS
#endif
}
@ -816,7 +839,7 @@ int bdNode::outgoingMsg(struct sockaddr_in *addr, char *msg, int *len)
void bdNode::incomingMsg(struct sockaddr_in *addr, char *msg, int len)
{
/* check against the filter */
if (mFilterPeers->addrOkay(addr))
if (mFilterPeers.addrOkay(addr))
{
bdNodeNetMsg *bdmsg = new bdNodeNetMsg(msg, len, addr);
mIncomingMsgs.push_back(bdmsg);
@ -852,11 +875,21 @@ void bdNode::msgout_ping(bdId *id, bdToken *transId)
bdId dupId(*id);
registerOutgoingMsg(&dupId, transId, BITDHT_MSG_TYPE_PING, NULL);
/* generate message, send to udp */
bdToken vid;
uint32_t vlen = BITDHT_TOKEN_MAX_LEN;
if (mDhtVersion.size() < vlen)
{
vlen = mDhtVersion.size();
}
memcpy(vid.data, mDhtVersion.c_str(), vlen);
vid.len = vlen;
/* create string */
char msg[10240];
int avail = 10240;
int blen = bitdht_create_ping_msg(transId, &(mOwnId), msg, avail-1);
int blen = bitdht_create_ping_msg(transId, &(mOwnId), &vid, msg, avail-1);
sendPkt(msg, blen, id->addr);
mAccount.incCounter(BDACCOUNT_MSG_PING, true);
@ -899,7 +932,7 @@ void bdNode::msgout_pong(bdId *id, bdToken *transId)
}
void bdNode::msgout_find_node(bdId *id, bdToken *transId, bdNodeId *query)
void bdNode::msgout_find_node(bdId *id, bdToken *transId, bdNodeId *query, bool localnet)
{
#ifdef DEBUG_NODE_MSGOUT
std::cerr << "bdNode::msgout_find_node() TransId: ";
@ -918,7 +951,7 @@ void bdNode::msgout_find_node(bdId *id, bdToken *transId, bdNodeId *query)
char msg[10240];
int avail = 10240;
int blen = bitdht_find_node_msg(transId, &(mOwnId), query, msg, avail-1);
int blen = bitdht_find_node_msg(transId, &(mOwnId), query, localnet, msg, avail-1);
sendPkt(msg, blen, id->addr);
@ -1113,7 +1146,7 @@ void bdNode::sendPkt(char *msg, int len, struct sockaddr_in addr)
// len, inet_ntoa(addr.sin_addr), htons(addr.sin_port));
/* filter outgoing packets */
if (mFilterPeers->addrOkay(&addr))
if (mFilterPeers.addrOkay(&addr))
{
bdNodeNetMsg *bdmsg = new bdNodeNetMsg(msg, len, &addr);
//bdmsg->print(std::cerr);
@ -1253,7 +1286,7 @@ void bdNode::recvPkt(char *msg, int len, struct sockaddr_in addr)
/************************ handle version (optional:pong) **************/
be_node *be_version = NULL;
bdToken versionId;
if (beType == BITDHT_MSG_TYPE_PONG)
if ((beType == BITDHT_MSG_TYPE_PONG) || (beType == BITDHT_MSG_TYPE_PING))
{
be_version = beMsgGetDictNode(node, "v");
if (!be_version)
@ -1270,6 +1303,18 @@ void bdNode::recvPkt(char *msg, int len, struct sockaddr_in addr)
beMsgGetToken(be_version, versionId);
}
/************************ handle options (optional:bitdht extension) **************/
be_node *be_options = beMsgGetDictNode(node, "o");
bool localnet = false;
if (be_options)
{
#ifdef DEBUG_NODE_PARSE
std::cerr << "bdNode::recvPkt() Found Options Node, localnet";
std::cerr << std::endl;
#endif
localnet = true;
}
/*********** handle target (query) or info_hash (get_hash) ************/
bdNodeId target_info_hash;
be_node *be_target = NULL;
@ -1285,6 +1330,7 @@ void bdNode::recvPkt(char *msg, int len, struct sockaddr_in addr)
be_free(node);
return;
}
}
else if ((beType == BITDHT_MSG_TYPE_GET_HASH) ||
(beType == BITDHT_MSG_TYPE_POST_HASH))
@ -1540,7 +1586,14 @@ void bdNode::recvPkt(char *msg, int len, struct sockaddr_in addr)
mFns->bdPrintId(std::cerr, &srcId);
std::cerr << std::endl;
#endif
msgin_ping(&srcId, &transId);
if (be_version)
{
msgin_ping(&srcId, &transId, &versionId);
}
else
{
msgin_ping(&srcId, &transId, NULL);
}
break;
}
case BITDHT_MSG_TYPE_PONG: /* r: id, transId */
@ -1570,7 +1623,7 @@ void bdNode::recvPkt(char *msg, int len, struct sockaddr_in addr)
mFns->bdPrintNodeId(std::cerr, &target_info_hash);
std::cerr << std::endl;
#endif
msgin_find_node(&srcId, &transId, &target_info_hash);
msgin_find_node(&srcId, &transId, &target_info_hash, localnet);
break;
}
case BITDHT_MSG_TYPE_REPLY_NODE: /* r: id, transId, nodes */
@ -1669,7 +1722,7 @@ void bdNode::recvPkt(char *msg, int len, struct sockaddr_in addr)
* Response: pong(id, token)
*/
void bdNode::msgin_ping(bdId *id, bdToken *transId)
void bdNode::msgin_ping(bdId *id, bdToken *transId, bdToken *versionId)
{
#ifdef DEBUG_NODE_MSGIN
std::cerr << "bdNode::msgin_ping() TransId: ";
@ -1683,6 +1736,7 @@ void bdNode::msgin_ping(bdId *id, bdToken *transId)
/* peer is alive */
uint32_t peerflags = BITDHT_PEER_STATUS_RECV_PING; /* no id typically, so cant get version */
peerflags |= parseVersion(versionId);
addPeer(id, peerflags);
/* reply */
@ -1707,8 +1761,16 @@ void bdNode::msgin_pong(bdId *id, bdToken *transId, bdToken *versionId)
(void) transId;
#endif
mAccount.incCounter(BDACCOUNT_MSG_PONG, false);
uint32_t peerflags = BITDHT_PEER_STATUS_RECV_PONG;
peerflags |= parseVersion(versionId);
mAccount.incCounter(BDACCOUNT_MSG_PONG, false);
addPeer(id, peerflags);
}
uint32_t bdNode::parseVersion(bdToken *versionId)
{
/* recv pong, and peer is alive. add to DHT */
//uint32_t vId = 0; // TODO XXX convertBdVersionToVID(versionId);
@ -1722,7 +1784,7 @@ void bdNode::msgin_pong(bdId *id, bdToken *transId, bdToken *versionId)
{
#ifdef DEBUG_NODE_MSGIN
std::cerr << "bdNode::msgin_pong() Peer Version: ";
std::cerr << "bdNode::parseVersion() Peer Version: ";
for(int i = 0; i < versionId->len; i++)
{
std::cerr << versionId->data[i];
@ -1771,7 +1833,7 @@ void bdNode::msgin_pong(bdId *id, bdToken *transId, bdToken *versionId)
{
sameDhtVersion = false;
#ifdef DEBUG_NODE_MSGIN
std::cerr << "bdNode::msgin_pong() STRANGE Peer Version: ";
std::cerr << "bdNode::parseVersion() STRANGE Peer Version: ";
for(uint32_t i = 0; i < versionId->len; i++)
{
std::cerr << versionId->data[i];
@ -1802,12 +1864,11 @@ void bdNode::msgin_pong(bdId *id, bdToken *transId, bdToken *versionId)
{
#ifdef DEBUG_NODE_MSGIN
std::cerr << "bdNode::msgin_pong() No Version";
std::cerr << "bdNode::parseVersion() No Version";
std::cerr << std::endl;
#endif
}
uint32_t peerflags = BITDHT_PEER_STATUS_RECV_PONG; /* should have id too */
if (sameDhtEngine)
{
@ -1825,13 +1886,14 @@ void bdNode::msgin_pong(bdId *id, bdToken *transId, bdToken *versionId)
{
peerflags |= BITDHT_PEER_STATUS_DHT_APPL_VERSION;
}
addPeer(id, peerflags);
return peerflags;
}
/* Input: id, token, queryId */
void bdNode::msgin_find_node(bdId *id, bdToken *transId, bdNodeId *query)
void bdNode::msgin_find_node(bdId *id, bdToken *transId, bdNodeId *query, bool localnet)
{
#ifdef DEBUG_NODE_MSGIN
std::cerr << "bdNode::msgin_find_node() TransId: ";
@ -1847,7 +1909,12 @@ void bdNode::msgin_find_node(bdId *id, bdToken *transId, bdNodeId *query)
/* store query... */
queueQuery(id, query, transId, BD_QUERY_NEIGHBOURS);
uint32_t query_type = BD_QUERY_NEIGHBOURS;
if (localnet)
{
query_type = BD_QUERY_LOCALNET;
}
queueQuery(id, query, transId, query_type);
uint32_t peerflags = 0; /* no id, and no help! */
@ -2334,6 +2401,13 @@ bdNodeNetMsg::bdNodeNetMsg(char *msg, int len, struct sockaddr_in *in_addr)
:data(NULL), mSize(len), addr(*in_addr)
{
data = (char *) malloc(len);
if(data == NULL)
{
std::cerr << "(EE) " << __PRETTY_FUNCTION__ << ": ERROR. cannot allocate memory for " << len << " bytes." << std::endl;
return ;
}
memcpy(data, msg, len);
//print(std::cerr);
}

View File

@ -33,6 +33,7 @@
#include "bitdht/bdobj.h"
#include "bitdht/bdhash.h"
#include "bitdht/bdhistory.h"
#include "bitdht/bdfilter.h"
#include "bitdht/bdconnection.h"
#include "bitdht/bdaccount.h"
@ -43,7 +44,8 @@ class bdFilter;
#define BD_QUERY_NEIGHBOURS 1
#define BD_QUERY_HASH 2
#define BD_QUERY_LOCALNET 2
#define BD_QUERY_HASH 3
/**********************************
* Running a node....
@ -82,6 +84,9 @@ output -> call back to Udp().
*********/
class bdFilteredPeer ;
class bdNodeManager;
class bdNodeNetMsg
{
@ -102,7 +107,7 @@ 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) = 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;
@ -117,8 +122,8 @@ class bdNode: public bdNodePublisher
{
public:
bdNode(bdNodeId *id, std::string dhtVersion, std::string bootfile,
bdDhtFunctions *fns);
bdNode(bdNodeId *id, std::string dhtVersion, const std::string& bootfile, const std::string& filterfile,
bdDhtFunctions *fns, bdNodeManager* manager);
void init(); /* sets up the self referential classes (mQueryMgr & mConnMgr) */
@ -144,9 +149,13 @@ class bdNode: public bdNodePublisher
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); /* 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);
@ -162,8 +171,9 @@ void incomingMsg(struct sockaddr_in *addr, char *msg, int len);
void dropRelayServers();
void pingRelayServers();
// Below is internal Management of incoming / outgoing messages.
private:
// Below is internal Management of incoming / outgoing messages.
private:
/* internal interaction with network */
void sendPkt(char *msg, int len, struct sockaddr_in addr);
@ -173,7 +183,7 @@ 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);
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);
@ -188,10 +198,11 @@ void recvPkt(char *msg, int len, struct sockaddr_in addr);
/* input functions (once mesg is parsed) */
void msgin_ping(bdId *id, bdToken *token);
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);
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);
@ -233,10 +244,10 @@ void recvPkt(char *msg, int len, struct sockaddr_in addr);
protected:
bdSpace mNodeSpace;
bdFilter mFilterPeers;
bdQueryManager *mQueryMgr;
bdConnectManager *mConnMgr;
bdFilter *mFilterPeers;
bdNodeId mOwnId;
bdId mLikelyOwnId; // Try to workout own id address.

View File

@ -336,14 +336,16 @@ int bdSpace::find_node(const bdNodeId *id, int number, std::list<bdId> &matchIds
mFns->bdDistance(id, &(mOwnId), &dist);
int buckno = mFns->bdBucketDistance(&dist);
std::cerr << "bdSpace::find_node(NodeId:";
#ifdef DEBUG_BD_SPACE
std::cerr << "bdSpace::find_node(NodeId:";
mFns->bdPrintNodeId(std::cerr, id);
std::cerr << ")";
std::cerr << " Number: " << number;
std::cerr << " Bucket #: " << buckno;
std::cerr << std::endl;
#ifdef DEBUG_BD_SPACE
#else
(void)number;
#endif
bdBucket &buck = buckets[buckno];
@ -352,10 +354,12 @@ int bdSpace::find_node(const bdNodeId *id, int number, std::list<bdId> &matchIds
int matchCount = 0;
for(eit = buck.entries.begin(); eit != buck.entries.end(); eit++)
{
std::cerr << "bdSpace::find_node() Checking Against Peer: ";
#ifdef DEBUG_BD_SPACE
std::cerr << "bdSpace::find_node() Checking Against Peer: ";
mFns->bdPrintId(std::cerr, &(eit->mPeerId));
std::cerr << " withFlags: " << eit->mPeerFlags;
std::cerr << std::endl;
std::cerr << std::endl;
#endif
if ((!with_flags) || ((with_flags & eit->mPeerFlags) == with_flags))
{
@ -364,10 +368,12 @@ int bdSpace::find_node(const bdNodeId *id, int number, std::list<bdId> &matchIds
matchIds.push_back(eit->mPeerId);
matchCount++;
std::cerr << "bdSpace::find_node() Found Matching Peer: ";
#ifdef DEBUG_BD_SPACE
std::cerr << "bdSpace::find_node() Found Matching Peer: ";
mFns->bdPrintId(std::cerr, &(eit->mPeerId));
std::cerr << " withFlags: " << eit->mPeerFlags;
std::cerr << std::endl;
std::cerr << std::endl;
#endif
}
}
else
@ -377,17 +383,19 @@ int bdSpace::find_node(const bdNodeId *id, int number, std::list<bdId> &matchIds
//matchIds.push_back(eit->mPeerId);
//matchCount++;
std::cerr << "bdSpace::find_node() Found (WITHOUT FLAGS) Matching Peer: ";
#ifdef DEBUG_BD_SPACE
std::cerr << "bdSpace::find_node() Found (WITHOUT FLAGS) Matching Peer: ";
mFns->bdPrintId(std::cerr, &(eit->mPeerId));
std::cerr << " withFlags: " << eit->mPeerFlags;
std::cerr << std::endl;
std::cerr << std::endl;
#endif
}
}
}
std::cerr << "bdSpace::find_node() Found " << matchCount << " Matching Peers";
std::cerr << std::endl << std::endl;
#ifdef DEBUG_BD_SPACE
std::cerr << "bdSpace::find_node() Found " << matchCount << " Matching Peers";
std::cerr << std::endl << std::endl;
#endif
return matchCount;
@ -451,18 +459,22 @@ int bdSpace::clean_node_flags(uint32_t flags)
{
if (flags & eit->mPeerFlags)
{
std::cerr << "bdSpace::clean_node_flags() Found Match: ";
#ifdef DEBUG_BD_SPACE
std::cerr << "bdSpace::clean_node_flags() Found Match: ";
mFns->bdPrintId(std::cerr, &(eit->mPeerId));
std::cerr << " withFlags: " << eit->mPeerFlags;
std::cerr << std::endl;
std::cerr << std::endl;
#endif
count++;
eit->mPeerFlags &= ~flags;
}
}
}
std::cerr << "bdSpace::clean_node_flags() Cleaned " << count << " Matching Peers";
std::cerr << std::endl;
#ifdef DEBUG_BD_SPACE
std::cerr << "bdSpace::clean_node_flags() Cleaned " << count << " Matching Peers";
std::cerr << std::endl;
#endif
return count;
}

View File

@ -119,7 +119,7 @@ int bdQueryManager::iterateQueries(int maxQueries)
std::cerr << ")";
std::cerr << std::endl;
#endif
mPub->send_query(&id, &targetNodeId);
mPub->send_query(&id, &targetNodeId, false);
sentQueries++;
}
i++;

View File

@ -33,24 +33,24 @@
class bdStore
{
public:
public:
bdStore(std::string file, bdDhtFunctions *fns);
bdStore(std::string file, bdDhtFunctions *fns);
int reloadFromStore(); /* for restarts */
int filterIpList(const std::list<struct sockaddr_in> &filteredIPs);
int clear();
int reloadFromStore(); /* for restarts */
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();
int getPeer(bdPeer *peer);
void addStore(bdPeer *peer);
void writeStore(std::string file);
void writeStore();
private:
std::string mStoreFile;
std::list<bdPeer> store;
int mIndex;
bdDhtFunctions *mFns;
protected:
std::string mStoreFile;
std::list<bdPeer> store;
int mIndex;
bdDhtFunctions *mFns;
};

View File

@ -111,6 +111,15 @@ static char *_be_decode_str(const char **data, long long *data_len)
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);
@ -496,11 +505,19 @@ be_node *be_create_str(const char *str)
{
/* must */
be_node *n = be_alloc(BE_STR);
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);
@ -516,10 +533,18 @@ be_node *be_create_str_wlen(const char *str, int len) /* not including \0 */
{
/* must */
be_node *n = be_alloc(BE_STR);
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);
@ -550,7 +575,8 @@ int be_add_keypair(be_node *dict, const char *str, be_node *node)
}
// get to end of dict.
for(i = 0; dict->val.d[i].val; i++);
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);
@ -561,6 +587,13 @@ int be_add_keypair(be_node *dict, const char *str, be_node *node)
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);
@ -590,7 +623,8 @@ int be_add_list(be_node *list, be_node *node)
}
// get to end of dict.
for(i = 0; list->val.l[i]; i++);
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));

View File

@ -1,16 +0,0 @@
CXXFLAGS = -Wall -g -I..
#CXXFLAGS += -arch i386 # OSX
LIBS = -L../lib -lbitdht -lpthread
EXEC : bssdht
EGOBJ = bdhandler.o bssdht.o bootstrap_fn.o
bssdht: $(EGOBJ)
$(CXX) $(CXXFLAGS) -o bssdht $(EGOBJ) $(LIBS)

View File

@ -1,7 +1,11 @@
!include("../../retroshare.pri"): error("Could not include file ../../retroshare.pri")
TEMPLATE = lib
CONFIG += staticlib
CONFIG -= qt
TARGET = bitdht
DESTDIR = lib
QMAKE_CXXFLAGS *= -Wall -DBE_DEBUG
profiling {
@ -25,8 +29,7 @@ debug {
################################# Linux ##########################################
linux-* {
DESTDIR = lib
QMAKE_CC = g++
QMAKE_CC = $${QMAKE_CXX}
}
linux-g++ {
@ -37,11 +40,17 @@ 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
}
#################### Cross compilation for windows under Linux ####################
win32-x-g++ {
OBJECTS_DIR = temp/win32xgcc/obj
DESTDIR = lib.win32xgcc
# These have been replaced by _WIN32 && __MINGW32__
# DEFINES *= WINDOWS_SYS WIN32 WIN_CROSS_UBUNTU
QMAKE_CXXFLAGS *= -Wmissing-include-dirs
@ -55,13 +64,12 @@ win32-x-g++ {
################################# Windows ##########################################
win32 {
QMAKE_CC = g++
QMAKE_CC = $${QMAKE_CXX}
OBJECTS_DIR = temp/obj
MOC_DIR = temp/moc
DEFINES *= STATICLIB WIN32_LEAN_AND_MEAN _USE_32BIT_TIME_T
# These have been replaced by _WIN32 && __MINGW32__
#DEFINES *= WINDOWS_SYS WIN32 STATICLIB MINGW
DESTDIR = lib
# Switch on extra warnings
QMAKE_CFLAGS += -Wextra
@ -81,29 +89,32 @@ win32 {
################################# MacOSX ##########################################
mac {
QMAKE_CC = g++
QMAKE_CC = $${QMAKE_CXX}
OBJECTS_DIR = temp/obj
MOC_DIR = temp/moc
DESTDIR = lib
}
################################# FreeBSD ##########################################
freebsd-* {
DESTDIR = lib
}
################################# OpenBSD ##########################################
openbsd-* {
}
################################# Haiku ##########################################
haiku-* {
DESTDIR = lib
}
################################### COMMON stuff ##################################
################################### COMMON stuff ##################################
#DEPENDPATH += . \
INCLUDEPATH += . \
DEPENDPATH += .
INCLUDEPATH += .
HEADERS += \
bitdht/bdiface.h \
@ -159,5 +170,3 @@ SOURCES += \
bitdht/bdquerymgr.cc \
util/bdbloom.cc \
bitdht/bdfriendlist.cc \

View File

@ -1,4 +1,4 @@
set QTDIR=C:\Qt\4.8.5
set QTDIR=C:\Qt\4.8.6
set MINGW=C:\MinGW
set PATH=%QTDIR%\bin;%MINGW%\bin;%PATH%

View File

@ -1,91 +0,0 @@
LIB_TOP_DIR = ..
TEST_TOP_DIR = $(LIB_TOP_DIR)/tests
##### Define any flags that are needed for this section #######
###############################################################
###############################################################
include $(TEST_TOP_DIR)/scripts/config.mk
###############################################################
# Generic Test Harnesses.
TESTOBJ = bdmetric_test.o bdmsgs_test.o bdnode_test.o bdspace_test.o
TESTOBJ += bdmgr_multitest.o bdquery_test.o bdstore_test.o
TESTOBJ += bdmidids_test.o bdspace_test2.o udpbitdht_nettest.o
TESTOBJ += bdbloom_test.o bdbloom_makefilter.o
#TESTOBJ += bencode_test.o bdudp_test.o
#TESTOBJ = bdnode_test.o bdnode_multitest1.o bdnode_test2.o
TESTS = bdmetric_test bdmsgs_test bdspace_test
TESTS += bdmgr_multitest bdquery_test bdstore_test
TESTS += bdmidids_test bdspace_test2 udpbitdht_nettest
TESTS += bdbloom_test
#TESTS += bencode_test bdudp_test
#Tests to Fix.
#TESTS = bdnode_test bdnode_multitest1 bdnode_test2
MANUAL_TESTS =
all: tests $(MANUAL_TESTS)
bdmsgs_test: bdmsgs_test.o
$(CC) $(CFLAGS) -o bdmsgs_test bdmsgs_test.o $(LIBS)
bdmetric_test: bdmetric_test.o
$(CC) $(CFLAGS) -o bdmetric_test bdmetric_test.o $(LIBS)
bdquery_test: bdquery_test.o
$(CC) $(CFLAGS) -o bdquery_test bdquery_test.o $(LIBS)
bdspace_test: bdspace_test.o
$(CC) $(CFLAGS) -o bdspace_test bdspace_test.o $(LIBS)
bdspace_test2: bdspace_test2.o
$(CC) $(CFLAGS) -o bdspace_test2 bdspace_test2.o $(LIBS)
bdnode_test: bdnode_test.o
$(CC) $(CFLAGS) -o bdnode_test bdnode_test.o $(LIBS)
bdnode_test2: bdnode_test2.o
$(CC) $(CFLAGS) -o bdnode_test2 bdnode_test2.o $(LIBS)
bdmidids_test: bdmidids_test.o
$(CC) $(CFLAGS) -o bdmidids_test bdmidids_test.o $(LIBS)
bdnode_multitest1: bdnode_multitest1.o
$(CC) $(CFLAGS) -o bdnode_multitest1 bdnode_multitest1.o $(LIBS)
bdmgr_multitest: bdmgr_multitest.o
$(CC) $(CFLAGS) -o bdmgr_multitest bdmgr_multitest.o $(LIBS)
bdstore_test: bdstore_test.o
$(CC) $(CFLAGS) -o bdstore_test bdstore_test.o $(LIBS)
bdudp_test: bdudp_test.o
$(CC) $(CFLAGS) -o bdudp_test bdudp_test.o $(LIBS)
udpbitdht_nettest: udpbitdht_nettest.o
$(CC) $(CFLAGS) -o udpbitdht_nettest udpbitdht_nettest.o $(LIBS)
bencode_test: bencode_test.o
$(CC) $(CFLAGS) -o bencode_test bencode_test.o $(LIBS)
bdbloom_test: bdbloom_test.o
$(CC) $(CFLAGS) -o bdbloom_test bdbloom_test.o $(LIBS)
bdbloom_makefilter: bdbloom_makefilter.o
$(CC) $(CFLAGS) -o bdbloom_makefilter bdbloom_makefilter.o $(LIBS)
clobber: remove_extra_files
remove_extra_files:
-$(RM) $(MANUAL_TESTS)
###############################################################
include $(TEST_TOP_DIR)/scripts/rules.mk
###############################################################

View File

@ -57,7 +57,7 @@
/*************************************/
UdpBitDht::UdpBitDht(UdpPublisher *pub, bdNodeId *id, std::string appVersion, std::string bootstrapfile, bdDhtFunctions *fns)
UdpBitDht::UdpBitDht(UdpPublisher *pub, bdNodeId *id, std::string appVersion, std::string bootstrapfile, const std::string& filteredipfile, bdDhtFunctions *fns)
:UdpSubReceiver(pub), dhtMtx(true), mFns(fns)
{
std::string usedVersion;
@ -76,7 +76,7 @@ UdpBitDht::UdpBitDht(UdpPublisher *pub, bdNodeId *id, std::string appVersion, st
/* setup nodeManager */
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
mBitDhtManager = new bdNodeManager(id, usedVersion, bootstrapfile, fns);
mBitDhtManager = new bdNodeManager(id, usedVersion, bootstrapfile, filteredipfile, fns);
}
@ -209,7 +209,17 @@ int UdpBitDht::getDhtQueryStatus(const bdNodeId *id, bdQuerySummary &query)
{
bdStackMutex stack(dhtMtx); /********** MUTEX LOCKED *************/
return mBitDhtManager->getDhtQueryStatus(id, query);
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) ;
}

View File

@ -50,7 +50,7 @@ class UdpBitDht: public UdpSubReceiver, public bdThread, public BitDhtInterface
{
public:
UdpBitDht(UdpPublisher *pub, bdNodeId *id, std::string dhtVersion, std::string bootstrapfile, bdDhtFunctions *fns);
UdpBitDht(UdpPublisher *pub, bdNodeId *id, std::string dhtVersion, std::string bootstrapfile, const std::string& filteredipfile,bdDhtFunctions *fns);
virtual ~UdpBitDht();
@ -87,6 +87,9 @@ 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();
@ -109,9 +112,8 @@ virtual int status(std::ostream &out);
virtual void run();
/**** do whats to be done ***/
int tick();
private:
int tick();
private:
void clearDataTransferred();

View File

@ -32,6 +32,9 @@
#include <string.h>
#include <stdlib.h>
#include <time.h>
#ifndef WIN32
#include <sys/select.h>
#endif
/***
* #define UDP_ENABLE_BROADCAST 1
@ -63,7 +66,11 @@ class udpPacket
:raddr(*addr), len(dlen)
{
data = malloc(len);
memcpy(data, dta, len);
if(data != NULL)
memcpy(data, dta, len);
else
std::cerr << "(EE) error in memory allocation in " << __PRETTY_FUNCTION__ << std::endl;
}
~udpPacket()
@ -236,71 +243,67 @@ void UdpLayer::run()
/* higher level interface */
void UdpLayer::recv_loop()
{
int maxsize = 16000;
size_t maxsize = 16000;
void *inbuf = malloc(maxsize);
int status;
struct timeval timeout;
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)
{
fd_set rset;
for(;;)
for(;;)
{
/* check if we need to stop */
bool toStop = false;
{
bdStackMutex stack(sockMtx); /********** LOCK MUTEX *********/
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_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 */
}
else if (status < 0)
{
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
std::cerr << "UdpLayer::recv_loop() Error: " << bdnet_errno() << std::endl;
else if (status < 0) std::cerr << "UdpLayer::recv_loop() Error: "
<< bdnet_errno() << std::endl;
#endif
}
};
};
int nsize = maxsize;
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;
std::cerr << printPkt(inbuf, nsize);
std::cerr << "UdpLayer::readPkt() from : " << from << std::endl
<< printPkt(inbuf, nsize);
#endif
// send to reciever.
recv -> recvPkt(inbuf, nsize, from);
recv->recvPkt(inbuf, nsize, from); // pass to reciever.
}
else
{
#ifdef DEBUG_UDP_LAYER
std::cerr << "UdpLayer::readPkt() not ready" << from;
std::cerr << std::endl;
else std::cerr << "UdpLayer::readPkt() not ready" << from << std::endl;
#endif
}
}
free(inbuf) ;
return;
}

View File

@ -87,8 +87,10 @@ bool UdpStack::getLocalAddress(struct sockaddr_in &local)
bool UdpStack::resetAddress(struct sockaddr_in &local)
{
std::cerr << "UdpStack::resetAddress(" << local << ")";
#ifdef DEBUG_UDP_RECV
std::cerr << "UdpStack::resetAddress(" << local << ")";
std::cerr << std::endl;
#endif
laddr = local;
return udpLayer->reset(local);

View File

@ -100,6 +100,13 @@ int bloomFilter::setFilterBits(const std::string &hex)
// 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++)
@ -139,6 +146,13 @@ std::string bloomFilter::getFilter()
// 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++)

View File

@ -17,7 +17,7 @@ bool bdFile::renameFile(const std::string& from, const std::string& to)
{
int loops = 0;
#ifdef WINDOWS_SYS
#ifdef WIN32
std::wstring f;
librs::util::ConvertUtf8ToUtf16(from, f);
std::wstring t;

View File

@ -34,6 +34,7 @@
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
#if defined(_WIN32) || defined(__MINGW32__)
//#define BDNET_DEBUG
/* error handling */
int bdnet_int_errno;
@ -188,7 +189,9 @@ int bdnet_setsockopt(int s, int level, int optname,
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)
{
@ -201,7 +204,9 @@ ssize_t bdnet_recvfrom(int s, void *buf, size_t len, int flags,
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)
{

View File

@ -13,7 +13,7 @@ static bool auto_seed = bdRandom::seed( (time(NULL) + ((uint32_t) pthread_self()
#else
#ifdef __APPLE__
static bool auto_seed = bdRandom::seed( (time(NULL) + pthread_mach_thread_np(pthread_self())*0x1293fe + (getpid()^0x113ef76b))^0x18e34a12 ) ;
#elif defined(__FreeBSD__)
#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__)