2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002 Merkur ( devs@emule-project.net / http://www.emule-project.net )
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include <wx/stdpaths.h> // Needed for GetDataDir
28 #include "IPFilter.h" // Interface declarations.
29 #include "Preferences.h" // Needed for thePrefs
30 #include "amule.h" // Needed for theApp
31 #include "Statistics.h" // Needed for theStats
32 #include "HTTPDownload.h" // Needed for CHTTPDownloadThread
33 #include "Logger.h" // Needed for AddDebugLogLineM
34 #include <common/Format.h> // Needed for CFormat
35 #include <common/StringFunctions.h> // Needed for CSimpleTokenizer
36 #include <common/FileFunctions.h> // Needed for UnpackArchive
37 #include <common/TextFile.h> // Needed for CTextFile
38 #include "ThreadScheduler.h" // Needed for CThreadScheduler and CThreadTask
39 #include "ClientList.h" // Needed for CClientList
40 #include "ServerList.h" // Needed for CServerList
43 ////////////////////////////////////////////////////////////
46 BEGIN_DECLARE_EVENT_TYPES()
47 DECLARE_EVENT_TYPE(MULE_EVT_IPFILTER_LOADED
, -1)
48 END_DECLARE_EVENT_TYPES()
50 DEFINE_EVENT_TYPE(MULE_EVT_IPFILTER_LOADED
)
53 class CIPFilterEvent
: public wxEvent
56 CIPFilterEvent(CIPFilter::IPMap
& result
)
57 : wxEvent(-1, MULE_EVT_IPFILTER_LOADED
)
59 // Avoid needles copying
60 std::swap(result
, m_result
);
63 /** @see wxEvent::Clone */
64 virtual wxEvent
* Clone() const {
65 return new CIPFilterEvent(*this);
68 CIPFilter::IPMap m_result
;
72 typedef void (wxEvtHandler::*MuleIPFilterEventFunction
)(CIPFilterEvent
&);
74 //! Event-handler for completed hashings of new shared files and partfiles.
75 #define EVT_MULE_IPFILTER_LOADED(func) \
76 DECLARE_EVENT_TABLE_ENTRY(MULE_EVT_IPFILTER_LOADED, -1, -1, \
77 (wxObjectEventFunction) (wxEventFunction) \
78 wxStaticCastEvent(MuleIPFilterEventFunction, &func), (wxObject*) NULL),
81 ////////////////////////////////////////////////////////////
82 // Thread task for loading the ipfilter.dat files.
85 * This task loads the two ipfilter.dat files, a task that
86 * can take quite a while on a slow system with a large dat-
89 class CIPFilterTask
: public CThreadTask
92 CIPFilterTask(wxEvtHandler
* owner
)
93 : CThreadTask(wxT("Load IPFilter"), wxEmptyString
, ETP_Critical
),
99 wxStandardPathsBase
&spb(wxStandardPaths::Get());
101 wxString
dataDir(spb
.GetPluginsDir());
102 #elif defined(__WXMAC__)
103 wxString
dataDir(spb
.GetDataDir());
105 wxString
dataDir(spb
.GetDataDir().BeforeLast(wxT('/')) + wxT("/amule"));
107 wxString
systemwideFile(JoinPaths(dataDir
,wxT("ipfilter.dat")));
109 AddLogLineM(false, _("Loading IP-filters 'ipfilter.dat' and 'ipfilter_static.dat'."));
110 if ( !LoadFromFile(theApp
->ConfigDir
+ wxT("ipfilter.dat")) &&
111 thePrefs::UseIPFilterSystem() ) {
112 LoadFromFile(systemwideFile
);
116 LoadFromFile(theApp
->ConfigDir
+ wxT("ipfilter_static.dat"));
118 CIPFilterEvent
evt(m_result
);
119 wxPostEvent(m_owner
, evt
);
127 * @param IPstart The start of the IP-range.
128 * @param IPend The end of the IP-range, must be less than or equal to IPstart.
129 * @param AccessLevel The AccessLevel of this range.
130 * @param Description The assosiated description of this range.
131 * @return true if the range was added, false if it was discarded.
133 * This function inserts the specified range into the IPMap. Invalid
134 * ranges where the AccessLevel is not within the range 0..255, or
135 * where IPEnd < IPstart not inserted.
137 bool AddIPRange(uint32 IPStart
, uint32 IPEnd
, uint16 AccessLevel
, const wxString
& Description
)
139 if (AccessLevel
< 256) {
140 if (IPStart
<= IPEnd
) {
141 CIPFilter::rangeObject item
;
142 item
.AccessLevel
= AccessLevel
;
144 item
.Description
= Description
;
147 m_result
.insert(IPStart
, IPEnd
, item
);
160 * @param str A string representation of an IP-range in the format "<ip>-<ip>".
161 * @param ipA The target of the first IP in the range.
162 * @param ipB The target of the second IP in the range.
163 * @return True if the parsing succeded, false otherwise (results will be invalid).
165 * The IPs returned by this function are in host order, not network order.
167 bool m_inet_atoh(const wxString
&str
, uint32
& ipA
, uint32
& ipB
)
169 wxString first
= str
.BeforeFirst(wxT('-'));
170 wxString second
= str
.Mid(first
.Len() + 1);
172 bool result
= StringIPtoUint32(first
, ipA
) && StringIPtoUint32(second
, ipB
);
174 // StringIPtoUint32 saves the ip in anti-host order, but in order
175 // to be able to make relational comparisons, we need to convert
176 // it back to host-order.
177 ipA
= wxUINT32_SWAP_ALWAYS(ipA
);
178 ipB
= wxUINT32_SWAP_ALWAYS(ipB
);
185 * Helper-function for processing the PeerGuardian format.
187 * @return True if the line was valid, false otherwise.
189 * This function will correctly parse files that follow the folllowing
190 * format for specifying IP-ranges (whitespace is optional):
191 * <IPStart> - <IPEnd> , <AccessLevel> , <Description>
193 bool ProcessPeerGuardianLine(const wxString
& sLine
)
195 CSimpleTokenizer
tkz(sLine
, wxT(','));
197 wxString first
= tkz
.next();
198 wxString second
= tkz
.next();
199 wxString third
= tkz
.remaining().Strip(wxString::both
);
201 // If there were less than two tokens, fail
202 if (tkz
.tokenCount() != 2) {
206 // Convert string IP's to host order IP numbers
210 // This will also fail if the line is commented out
211 if (!m_inet_atoh(first
, IPStart
, IPEnd
)) {
215 // Second token is Access Level, default is 0.
216 unsigned long AccessLevel
= 0;
217 if (!second
.Strip(wxString::both
).ToULong(&AccessLevel
) || AccessLevel
>= 255) {
222 return AddIPRange(IPStart
, IPEnd
, AccessLevel
, third
);
227 * Helper-function for processing the AntiP2P format.
229 * @return True if the line was valid, false otherwise.
231 * This function will correctly parse files that follow the folllowing
232 * format for specifying IP-ranges (whitespace is optional):
233 * <Description> : <IPStart> - <IPEnd>
235 bool ProcessAntiP2PLine(const wxString
& sLine
)
237 // remove spaces from the left and right.
238 const wxString line
= sLine
.Strip(wxString::leading
);
240 // Extract description (first) and IP-range (second) form the line
241 int pos
= line
.Find(wxT(':'), true);
246 wxString Description
= line
.Left(pos
).Strip(wxString::trailing
);
247 wxString IPRange
= line
.Right(line
.Len() - pos
- 1);
249 // Convert string IP's to host order IP numbers
253 if (!m_inet_atoh(IPRange
,IPStart
, IPEnd
)) {
258 return AddIPRange(IPStart
, IPEnd
, 0, Description
);
263 * Loads a IP-list from the specified file, can be text or zip.
265 * @return True if the file was loaded, false otherwise.
267 int LoadFromFile(const wxString
& file
)
269 const CPath path
= CPath(file
);
271 if (!path
.FileExists() /* || TestDestroy() (see CIPFilter::Reload()) */) {
275 const wxChar
* ipfilter_files
[] = {
281 // Try to unpack the file, might be an archive
282 if (UnpackArchive(path
, ipfilter_files
).second
!= EFT_Text
) {
284 CFormat(_("Failed to load ipfilter.dat file '%s', unknown format encountered.")) % file
);
289 int discardedCount
= 0;
292 if (readFile
.Open(path
, CTextFile::read
)) {
293 // Function pointer-type of the parse-functions we can use
294 typedef bool (CIPFilterTask::*ParseFunc
)(const wxString
&);
296 ParseFunc func
= NULL
;
298 while (!readFile
.Eof()) {
299 wxString line
= readFile
.GetNextLine();
301 /* See CIPFilter::Reload()
304 } else */ if (func
&& (*this.*func
)(line
)) {
306 } else if (ProcessPeerGuardianLine(line
)) {
307 func
= &CIPFilterTask::ProcessPeerGuardianLine
;
309 } else if (ProcessAntiP2PLine(line
)) {
310 func
= &CIPFilterTask::ProcessAntiP2PLine
;
313 // Comments and empty lines are ignored
314 line
= line
.Strip(wxString::both
);
316 if (!line
.IsEmpty() && !line
.StartsWith(wxT("#"))) {
318 AddDebugLogLineM(false, logIPFilter
, wxT(
319 "Invalid line found while reading ipfilter file: ") + line
);
324 AddLogLineM(true, CFormat(_(
325 "Failed to load ipfilter.dat file '%s', could not open file.")) % file
);
330 ( CFormat(wxPLURAL("Loaded %u IP-range from '%s'.", "Loaded %u IP-ranges from '%s'.", filtercount
)) % filtercount
% file
)
332 ( CFormat(wxPLURAL("%u malformed line was discarded.", "%u malformed lines were discarded.", discardedCount
)) % discardedCount
)
339 wxEvtHandler
* m_owner
;
340 CIPFilter::IPMap m_result
;
344 ////////////////////////////////////////////////////////////
348 BEGIN_EVENT_TABLE(CIPFilter
, wxEvtHandler
)
349 EVT_MULE_IPFILTER_LOADED(CIPFilter::OnIPFilterEvent
)
355 * This function creates a text-file containing the specified text,
356 * but only if the file does not already exist.
358 void CreateDummyFile(const wxString
& filename
, const wxString
& text
)
360 // Create template files
361 if (!wxFileExists(filename
)) {
364 if (file
.Open(filename
, CTextFile::write
)) {
365 file
.WriteLine(text
);
371 CIPFilter::CIPFilter()
373 // Setup dummy files for the curious user.
374 const wxString normalDat
= theApp
->ConfigDir
+ wxT("ipfilter.dat");
375 const wxString normalMsg
= wxString()
376 << wxT("# This file is used by aMule to store ipfilter lists downloaded\n")
377 << wxT("# through the auto-update functionality. Do not save ipfilter-\n")
378 << wxT("# ranges here that should not be overwritten by aMule.\n");
380 CreateDummyFile(normalDat
, normalMsg
);
382 const wxString staticDat
= theApp
->ConfigDir
+ wxT("ipfilter_static.dat");
383 const wxString staticMsg
= wxString()
384 << wxT("# This file is used to store ipfilter-ranges that should\n")
385 << wxT("# not be overwritten by aMule. If you wish to keep a custom\n")
386 << wxT("# set of ipfilter-ranges that take precedence over ipfilter-\n")
387 << wxT("# ranges aquired through the auto-update functionality, then\n")
388 << wxT("# place them in this file. aMule will not change this file.");
390 CreateDummyFile(staticDat
, staticMsg
);
396 void CIPFilter::Reload()
398 // We keep the current filter till the new one has been loaded.
399 //CThreadScheduler::AddTask(new CIPFilterTask(this));
401 // This procedure cannot be run as a task,
402 // wxArchiveFSHandler::FindFirst() will eventually call wxExecute(),
403 // and this can only be done from the main task.
405 // This way, We call the Entry() routine manually and comment out the
406 // calls to TestDestroy().
407 CIPFilterTask
ipf_task(this);
412 uint32
CIPFilter::BanCount() const
414 wxMutexLocker
lock(m_mutex
);
416 return m_iplist
.size();
420 bool CIPFilter::IsFiltered(uint32 IPTest
, bool isServer
)
422 if ((thePrefs::IsFilteringClients() && !isServer
) || (thePrefs::IsFilteringServers() && isServer
)) {
423 wxMutexLocker
lock(m_mutex
);
425 // The IP needs to be in host order
426 IPMap::iterator it
= m_iplist
.find_range(wxUINT32_SWAP_ALWAYS(IPTest
));
428 if (it
!= m_iplist
.end()) {
429 if (it
->AccessLevel
< thePrefs::GetIPFilterLevel()) {
431 AddDebugLogLineM(false, logIPFilter
, wxString(wxT("Filtered IP (AccLvl: ")) << (long)it
->AccessLevel
<< wxT("): ")
432 << Uint32toStringIP(IPTest
) << wxT(" (") << it
->Description
+ wxT(")"));
436 theStats::AddFilteredServer();
438 theStats::AddFilteredClient();
449 void CIPFilter::Update(const wxString
& strURL
)
451 if (!strURL
.IsEmpty()) {
452 wxString filename
= theApp
->ConfigDir
+ wxT("ipfilter.download");
453 CHTTPDownloadThread
*downloader
= new CHTTPDownloadThread(strURL
, filename
, HTTP_IPFilter
);
455 downloader
->Create();
461 void CIPFilter::DownloadFinished(uint32 result
)
464 // download succeeded. proceed with ipfilter loading
465 wxString newDat
= theApp
->ConfigDir
+ wxT("ipfilter.download");
466 wxString oldDat
= theApp
->ConfigDir
+ wxT("ipfilter.dat");
468 if (wxFileExists(oldDat
)) {
469 if (!wxRemoveFile(oldDat
)) {
470 AddDebugLogLineM(true, logIPFilter
,
471 wxT("Failed to remove ipfilter.dat file, aborting update."));
476 if (!wxRenameFile(newDat
, oldDat
)) {
477 AddDebugLogLineM(true, logIPFilter
,
478 wxT("Failed to rename new ipfilter.dat file, aborting update."));
482 // Reload both ipfilter files
485 AddDebugLogLineM(true, logIPFilter
,
486 wxT("Failed to download the ipfilter from ") + thePrefs::IPFilterURL());
491 void CIPFilter::OnIPFilterEvent(CIPFilterEvent
& evt
)
494 wxMutexLocker
lock(m_mutex
);
495 std::swap(m_iplist
, evt
.m_result
);
498 if (thePrefs::IsFilteringClients()) {
499 theApp
->clientlist
->FilterQueues();
501 if (thePrefs::IsFilteringServers()) {
502 theApp
->serverlist
->FilterServers();
506 // File_checked_for_headers