2 // This file is part of the aMule Project.
4 // Copyright (C) 2005-2008 aMule Team ( admin@amule.org / http://www.amule.org )
6 // Any parts of this program derived from the xMule, lMule or eMule project,
7 // or contributed by third-party developers are copyrighted by their
10 // This program is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 2 of the License, or
13 // (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
28 #include "MuleUDPSocket.h" // Interface declarations
30 #include <protocol/ed2k/Constants.h>
32 #include "Logger.h" // Needed for AddDebugLogLineM
33 #include "amule.h" // Needed for theApp
34 #include "GetTickCount.h" // Needed for GetTickCount()
35 #include "Packet.h" // Needed for CPacket
36 #include <common/StringFunctions.h> // Needed for unicode2char
37 #include "Proxy.h" // Needed for CDatagramSocketProxy
38 #include "Logger.h" // Needed for AddDebugLogLineM
39 #include "UploadBandwidthThrottler.h"
40 #include "EncryptedDatagramSocket.h"
41 #include "OtherFunctions.h"
42 #include "kademlia/kademlia/Prefs.h"
43 #include "ClientList.h"
46 CMuleUDPSocket::CMuleUDPSocket(const wxString
& name
, int id
, const amuleIPV4Address
& address
, const CProxyData
* ProxyData
)
58 CMuleUDPSocket::~CMuleUDPSocket()
60 theApp
->uploadBandwidthThrottler
->RemoveFromAllQueues(this);
62 wxMutexLocker
lock(m_mutex
);
67 void CMuleUDPSocket::CreateSocket()
69 wxCHECK_RET(!m_socket
, wxT("Socket already opened."));
71 m_socket
= new CEncryptedDatagramSocket(m_addr
, wxSOCKET_NOWAIT
, m_proxy
);
72 m_socket
->SetClientData(this);
73 m_socket
->SetEventHandler(*theApp
, m_id
);
74 m_socket
->SetNotify(wxSOCKET_INPUT_FLAG
| wxSOCKET_OUTPUT_FLAG
| wxSOCKET_LOST_FLAG
);
75 m_socket
->Notify(true);
77 if (!m_socket
->Ok()) {
78 AddDebugLogLineM(true, logMuleUDP
, wxT("Failed to create valid ") + m_name
);
81 AddLogLineM(false, wxString(wxT("Created ")) << m_name
<< wxT(" at port ") << m_addr
.Service());
86 void CMuleUDPSocket::DestroySocket()
89 AddDebugLogLineM(false, logMuleUDP
, wxT("Shutting down ") + m_name
);
90 m_socket
->SetNotify(0);
91 m_socket
->Notify(false);
99 void CMuleUDPSocket::Open()
101 wxMutexLocker
lock(m_mutex
);
107 void CMuleUDPSocket::Close()
109 wxMutexLocker
lock(m_mutex
);
115 void CMuleUDPSocket::OnSend(int errorCode
)
122 wxMutexLocker
lock(m_mutex
);
124 if (m_queue
.empty()) {
129 theApp
->uploadBandwidthThrottler
->QueueForSendingControlPacket(this);
133 const unsigned UDP_BUFFER_SIZE
= 16384;
136 void CMuleUDPSocket::OnReceive(int errorCode
)
138 AddDebugLogLineM(false, logMuleUDP
, wxString::Format(
139 wxT("Got UDP callback for read: Error %i Socket state %i"),
140 errorCode
, Ok() ? 1 : 0));
142 char buffer
[UDP_BUFFER_SIZE
];
149 wxMutexLocker
lock(m_mutex
);
151 if (errorCode
|| (m_socket
== NULL
) || !m_socket
->Ok()) {
159 length
= m_socket
->RecvFrom(addr
, buffer
, UDP_BUFFER_SIZE
).LastCount();
160 error
= m_socket
->Error();
161 lastError
= m_socket
->LastError();
164 const uint32 ip
= StringIPtoUint32(addr
.IPAddress());
165 const uint16 port
= addr
.Service();
167 OnReceiveError(lastError
, ip
, port
);
168 } else if (length
< 2) {
169 // 2 bytes (protocol and opcode) is the smallets possible packet.
170 AddDebugLogLineM(false, logMuleUDP
, m_name
+ wxT(": Invalid Packet received"));
173 printf("Unknown ip receiving on UDP packet! Ignoring: '%s'\n",
174 (const char*)unicode2char(addr
.IPAddress()));
177 printf("Unknown port receiving an UDP packet! Ignoring\n");
178 } else if (theApp
->clientlist
->IsBannedClient(ip
)) {
179 AddDebugLogLineM(false, logMuleUDP
, m_name
+ wxT(": Dropped packet from banned IP ") + addr
.IPAddress());
181 AddDebugLogLineM(false, logMuleUDP
, (m_name
+ wxT(": Packet received ("))
182 << addr
.IPAddress() << wxT(":") << port
<< wxT("): ")
183 << length
<< wxT("b"));
184 OnPacketReceived(ip
, port
, (byte
*)buffer
, length
);
189 void CMuleUDPSocket::OnReceiveError(int errorCode
, uint32
WXUNUSED(ip
), uint16
WXUNUSED(port
))
191 AddDebugLogLineM(false, logMuleUDP
, (m_name
+ wxT(": Error while reading: ")) << errorCode
);
195 void CMuleUDPSocket::OnDisconnected(int WXUNUSED(errorCode
))
197 /* Due to bugs in wxWidgets, UDP sockets will sometimes
198 * be closed. This is caused by the fact that wx treats
199 * zero-length datagrams as EOF, which is only the case
200 * when dealing with streaming sockets.
202 * This has been reported as patch #1885472:
203 * http://sourceforge.net/tracker/index.php?func=detail&aid=1885472&group_id=9863&atid=309863
205 AddDebugLogLineM(true, logMuleUDP
, m_name
+ wxT("Socket died, recreating."));
211 void CMuleUDPSocket::SendPacket(CPacket
* packet
, uint32 IP
, uint16 port
, bool bEncrypt
, const uint8
* pachTargetClientHashORKadID
, bool bKad
, uint32 nReceiverVerifyKey
)
213 wxCHECK_RET(packet
, wxT("Invalid packet."));
214 /*wxCHECK_RET(port, wxT("Invalid port."));
215 wxCHECK_RET(IP, wxT("Invalid IP."));
223 AddDebugLogLineM(false, logMuleUDP
, (m_name
+ wxT(": Packet discarded (socket not Ok): "))
224 << Uint32toStringIP(IP
) << wxT(":") << port
<< wxT(" ") << packet
->GetPacketSize()
231 AddDebugLogLineM(false, logMuleUDP
, (m_name
+ wxT(": Packet queued: "))
232 << Uint32toStringIP(IP
) << wxT(":") << port
<< wxT(" ")
233 << packet
->GetPacketSize() << wxT("b"));
237 newpending
.port
= port
;
238 newpending
.packet
= packet
;
239 newpending
.time
= GetTickCount();
240 newpending
.bEncrypt
= bEncrypt
&& (pachTargetClientHashORKadID
!= NULL
|| (bKad
&& nReceiverVerifyKey
!= 0));
241 newpending
.bKad
= bKad
;
242 newpending
.nReceiverVerifyKey
= nReceiverVerifyKey
;
243 if (newpending
.bEncrypt
&& pachTargetClientHashORKadID
!= NULL
) {
244 md4cpy(newpending
.pachTargetClientHashORKadID
, pachTargetClientHashORKadID
);
246 md4clr(newpending
.pachTargetClientHashORKadID
);
250 wxMutexLocker
lock(m_mutex
);
251 m_queue
.push_back(newpending
);
254 theApp
->uploadBandwidthThrottler
->QueueForSendingControlPacket(this);
258 bool CMuleUDPSocket::Ok()
260 wxMutexLocker
lock(m_mutex
);
262 return m_socket
&& m_socket
->Ok();
266 SocketSentBytes
CMuleUDPSocket::SendControlData(uint32 maxNumberOfBytesToSend
, uint32
WXUNUSED(minFragSize
))
268 wxMutexLocker
lock(m_mutex
);
269 uint32 sentBytes
= 0;
270 while (!m_queue
.empty() && !m_busy
&& (sentBytes
< maxNumberOfBytesToSend
)) {
271 UDPPack item
= m_queue
.front();
272 CPacket
* packet
= item
.packet
;
273 if (GetTickCount() - item
.time
< UDPMAXQUEUETIME
) {
274 uint32_t len
= packet
->GetPacketSize() + 2;
275 uint8_t *sendbuffer
= new uint8_t [len
];
276 memcpy(sendbuffer
, packet
->GetUDPHeader(), 2);
277 memcpy(sendbuffer
+ 2, packet
->GetDataBuffer(), packet
->GetPacketSize());
279 if (item
.bEncrypt
&& (theApp
->GetPublicIP() > 0 || item
.bKad
)) {
280 len
= CEncryptedDatagramSocket::EncryptSendClient(&sendbuffer
, len
, item
.pachTargetClientHashORKadID
, item
.bKad
, item
.nReceiverVerifyKey
, (item
.bKad
? Kademlia::CPrefs::GetUDPVerifyKey(item
.IP
) : 0));
283 if (SendTo(sendbuffer
, len
, item
.IP
, item
.port
)) {
287 delete [] sendbuffer
;
289 // TODO: Needs better error handling, see SentTo
290 delete [] sendbuffer
;
298 if (!m_busy
&& !m_queue
.empty()) {
299 theApp
->uploadBandwidthThrottler
->QueueForSendingControlPacket(this);
301 SocketSentBytes returnVal
= { true, 0, sentBytes
};
307 bool CMuleUDPSocket::SendTo(uint8_t *buffer
, uint32_t length
, uint32_t ip
, uint16_t port
)
309 // Just pretend that we sent the packet in order to avoid infinite loops.
310 if (!(m_socket
&& m_socket
->Ok())) {
314 amuleIPV4Address addr
;
318 // We better clear this flag here, status might have been changed
319 // between the U.B.T. addition and the real sending happening later
322 m_socket
->SendTo(addr
, buffer
, length
);
323 if (m_socket
->Error()) {
324 wxSocketError error
= m_socket
->LastError();
326 if (error
== wxSOCKET_WOULDBLOCK
) {
327 // Socket is busy and can't send this data right now,
328 // so we just return not sent and set the wouldblock
329 // flag so it gets resent when socket is ready.
332 // An error which we can't handle happended, so we drop
333 // the packet rather than risk entering an infinite loop.
334 printf("WARNING! %s discarded packet due to errors (%i) while sending.\n",
335 (const char*)unicode2char(m_name
), error
);
339 AddDebugLogLineM(false, logMuleUDP
, (m_name
+ wxT(": Packet sent to "))
340 << ip
<< wxT(":") << port
<< wxT(": ")
341 << length
<< wxT("b"));
348 // File_checked_for_headers