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-2008 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
[] = {
282 // Try to unpack the file, might be an archive
284 if (UnpackArchive(path
, ipfilter_files
).second
!= EFT_Text
) {
286 CFormat(_("Failed to load ipfilter.dat file '%s', unknown format encountered.")) % file
);
291 int discardedCount
= 0;
294 if (readFile
.Open(path
, CTextFile::read
)) {
295 // Function pointer-type of the parse-functions we can use
296 typedef bool (CIPFilterTask::*ParseFunc
)(const wxString
&);
298 ParseFunc func
= NULL
;
300 while (!readFile
.Eof()) {
301 wxString line
= readFile
.GetNextLine();
303 /* See CIPFilter::Reload()
306 } else */ if (func
&& (*this.*func
)(line
)) {
308 } else if (ProcessPeerGuardianLine(line
)) {
309 func
= &CIPFilterTask::ProcessPeerGuardianLine
;
311 } else if (ProcessAntiP2PLine(line
)) {
312 func
= &CIPFilterTask::ProcessAntiP2PLine
;
315 // Comments and empty lines are ignored
316 line
= line
.Strip(wxString::both
);
318 if (!line
.IsEmpty() && !line
.StartsWith(wxT("#"))) {
320 AddDebugLogLineM(false, logIPFilter
, wxT(
321 "Invalid line found while reading ipfilter file: ") + line
);
326 AddLogLineM(true, CFormat(_(
327 "Failed to load ipfilter.dat file '%s', could not open file.")) % file
);
332 ( CFormat(wxPLURAL("Loaded %u IP-range from '%s'.", "Loaded %u IP-ranges from '%s'.", filtercount
)) % filtercount
% file
)
334 ( CFormat(wxPLURAL("%u malformed line was discarded.", "%u malformed lines were discarded.", discardedCount
)) % discardedCount
)
341 wxEvtHandler
* m_owner
;
342 CIPFilter::IPMap m_result
;
346 ////////////////////////////////////////////////////////////
350 BEGIN_EVENT_TABLE(CIPFilter
, wxEvtHandler
)
351 EVT_MULE_IPFILTER_LOADED(CIPFilter::OnIPFilterEvent
)
357 * This function creates a text-file containing the specified text,
358 * but only if the file does not already exist.
360 void CreateDummyFile(const wxString
& filename
, const wxString
& text
)
362 // Create template files
363 if (!wxFileExists(filename
)) {
366 if (file
.Open(filename
, CTextFile::write
)) {
367 file
.WriteLine(text
);
373 CIPFilter::CIPFilter()
375 // Setup dummy files for the curious user.
376 const wxString normalDat
= theApp
->ConfigDir
+ wxT("ipfilter.dat");
377 const wxString normalMsg
= wxString()
378 << wxT("# This file is used by aMule to store ipfilter lists downloaded\n")
379 << wxT("# through the auto-update functionality. Do not save ipfilter-\n")
380 << wxT("# ranges here that should not be overwritten by aMule.\n");
382 CreateDummyFile(normalDat
, normalMsg
);
384 const wxString staticDat
= theApp
->ConfigDir
+ wxT("ipfilter_static.dat");
385 const wxString staticMsg
= wxString()
386 << wxT("# This file is used to store ipfilter-ranges that should\n")
387 << wxT("# not be overwritten by aMule. If you wish to keep a custom\n")
388 << wxT("# set of ipfilter-ranges that take precedence over ipfilter-\n")
389 << wxT("# ranges aquired through the auto-update functionality, then\n")
390 << wxT("# place them in this file. aMule will not change this file.");
392 CreateDummyFile(staticDat
, staticMsg
);
398 void CIPFilter::Reload()
400 // We keep the current filter till the new one has been loaded.
401 //CThreadScheduler::AddTask(new CIPFilterTask(this));
403 // This procedure cannot be run as a task,
404 // wxArchiveFSHandler::FindFirst() will eventually call wxExecute(),
405 // and this can only be done from the main task.
407 // This way, We call the Entry() routine manually and comment out the
408 // calls to TestDestroy().
409 CIPFilterTask
ipf_task(this);
414 uint32
CIPFilter::BanCount() const
416 wxMutexLocker
lock(m_mutex
);
418 return m_iplist
.size();
422 bool CIPFilter::IsFiltered(uint32 IPTest
, bool isServer
)
424 if ((thePrefs::IsFilteringClients() && !isServer
) || (thePrefs::IsFilteringServers() && isServer
)) {
425 wxMutexLocker
lock(m_mutex
);
427 // The IP needs to be in host order
428 IPMap::iterator it
= m_iplist
.find_range(wxUINT32_SWAP_ALWAYS(IPTest
));
430 if (it
!= m_iplist
.end()) {
431 if (it
->AccessLevel
< thePrefs::GetIPFilterLevel()) {
433 AddDebugLogLineM(false, logIPFilter
, wxString(wxT("Filtered IP (AccLvl: ")) << (long)it
->AccessLevel
<< wxT("): ")
434 << Uint32toStringIP(IPTest
) << wxT(" (") << it
->Description
+ wxT(")"));
438 theStats::AddFilteredServer();
440 theStats::AddFilteredClient();
451 void CIPFilter::Update(const wxString
& strURL
)
453 if (!strURL
.IsEmpty()) {
454 wxString filename
= theApp
->ConfigDir
+ wxT("ipfilter.download");
455 CHTTPDownloadThread
*downloader
= new CHTTPDownloadThread(strURL
, filename
, HTTP_IPFilter
);
457 downloader
->Create();
463 void CIPFilter::DownloadFinished(uint32 result
)
466 // download succeeded. proceed with ipfilter loading
467 wxString newDat
= theApp
->ConfigDir
+ wxT("ipfilter.download");
468 wxString oldDat
= theApp
->ConfigDir
+ wxT("ipfilter.dat");
470 if (wxFileExists(oldDat
)) {
471 if (!wxRemoveFile(oldDat
)) {
472 AddDebugLogLineM(true, logIPFilter
,
473 wxT("Failed to remove ipfilter.dat file, aborting update."));
478 if (!wxRenameFile(newDat
, oldDat
)) {
479 AddDebugLogLineM(true, logIPFilter
,
480 wxT("Failed to rename new ipfilter.dat file, aborting update."));
484 // Reload both ipfilter files
487 AddDebugLogLineM(true, logIPFilter
,
488 wxT("Failed to download the ipfilter from ") + thePrefs::IPFilterURL());
493 void CIPFilter::OnIPFilterEvent(CIPFilterEvent
& evt
)
496 wxMutexLocker
lock(m_mutex
);
497 std::swap(m_iplist
, evt
.m_result
);
500 if (thePrefs::IsFilteringClients()) {
501 theApp
->clientlist
->FilterQueues();
503 if (thePrefs::IsFilteringServers()) {
504 theApp
->serverlist
->FilterServers();
508 // File_checked_for_headers