Improve speed of category tab title updates
[amule.git] / src / MuleUDPSocket.cpp
blob7ddc1944f5f6c1a82106793cb484288d5cb35925
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2005-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 //
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
8 // respective authors.
9 //
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.
19 //
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
25 #include <wx/wx.h>
26 #include <algorithm>
28 #include "MuleUDPSocket.h" // Interface declarations
30 #include <protocol/ed2k/Constants.h>
32 #include "amule.h" // Needed for theApp
33 #include "GetTickCount.h" // Needed for GetTickCount()
34 #include "Packet.h" // Needed for CPacket
35 #include <common/StringFunctions.h> // Needed for unicode2char
36 #include "Proxy.h" // Needed for CDatagramSocketProxy
37 #include "Logger.h" // Needed for AddDebugLogLine{C,N}
38 #include "UploadBandwidthThrottler.h"
39 #include "EncryptedDatagramSocket.h"
40 #include "OtherFunctions.h"
41 #include "kademlia/kademlia/Prefs.h"
42 #include "ClientList.h"
45 CMuleUDPSocket::CMuleUDPSocket(const wxString& name, int id, const amuleIPV4Address& address, const CProxyData* ProxyData)
47 m_busy(false),
48 m_name(name),
49 m_id(id),
50 m_addr(address),
51 m_proxy(ProxyData),
52 m_socket(NULL)
57 CMuleUDPSocket::~CMuleUDPSocket()
59 theApp->uploadBandwidthThrottler->RemoveFromAllQueues(this);
61 wxMutexLocker lock(m_mutex);
62 DestroySocket();
66 void CMuleUDPSocket::CreateSocket()
68 wxCHECK_RET(!m_socket, wxT("Socket already opened."));
70 m_socket = new CEncryptedDatagramSocket(m_addr, wxSOCKET_NOWAIT, m_proxy);
71 m_socket->SetClientData(this);
72 m_socket->SetEventHandler(*theApp, m_id);
73 m_socket->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_OUTPUT_FLAG | wxSOCKET_LOST_FLAG);
74 m_socket->Notify(true);
76 if (!m_socket->Ok()) {
77 AddDebugLogLineC(logMuleUDP, wxT("Failed to create valid ") + m_name);
78 DestroySocket();
79 } else {
80 AddLogLineN(wxString(wxT("Created ")) << m_name << wxT(" at port ") << m_addr.Service());
85 void CMuleUDPSocket::DestroySocket()
87 if (m_socket) {
88 AddDebugLogLineN(logMuleUDP, wxT("Shutting down ") + m_name);
89 m_socket->SetNotify(0);
90 m_socket->Notify(false);
91 m_socket->Close();
92 m_socket->Destroy();
93 m_socket = NULL;
98 void CMuleUDPSocket::Open()
100 wxMutexLocker lock(m_mutex);
102 CreateSocket();
106 void CMuleUDPSocket::Close()
108 wxMutexLocker lock(m_mutex);
110 DestroySocket();
114 void CMuleUDPSocket::OnSend(int errorCode)
116 if (errorCode) {
117 return;
121 wxMutexLocker lock(m_mutex);
122 m_busy = false;
123 if (m_queue.empty()) {
124 return;
128 theApp->uploadBandwidthThrottler->QueueForSendingControlPacket(this);
132 const unsigned UDP_BUFFER_SIZE = 16384;
135 void CMuleUDPSocket::OnReceive(int errorCode)
137 AddDebugLogLineN(logMuleUDP, CFormat(wxT("Got UDP callback for read: Error %i Socket state %i"))
138 % errorCode % Ok());
140 char buffer[UDP_BUFFER_SIZE];
141 wxIPV4address addr;
142 unsigned length = 0;
143 bool error = false;
144 int lastError = 0;
147 wxMutexLocker lock(m_mutex);
149 if (errorCode || (m_socket == NULL) || !m_socket->Ok()) {
150 DestroySocket();
151 CreateSocket();
153 return;
157 length = m_socket->RecvFrom(addr, buffer, UDP_BUFFER_SIZE).LastCount();
158 error = m_socket->Error();
159 lastError = m_socket->LastError();
162 const uint32 ip = StringIPtoUint32(addr.IPAddress());
163 const uint16 port = addr.Service();
164 if (error) {
165 OnReceiveError(lastError, ip, port);
166 } else if (length < 2) {
167 // 2 bytes (protocol and opcode) is the smallets possible packet.
168 AddDebugLogLineN(logMuleUDP, m_name + wxT(": Invalid Packet received"));
169 } else if (!ip) {
170 // wxFAIL;
171 AddLogLineNS(wxT("Unknown ip receiving a UDP packet! Ignoring: '") + addr.IPAddress() + wxT("'"));
172 } else if (!port) {
173 // wxFAIL;
174 AddLogLineNS(wxT("Unknown port receiving a UDP packet! Ignoring"));
175 } else if (theApp->clientlist->IsBannedClient(ip)) {
176 AddDebugLogLineN(logMuleUDP, m_name + wxT(": Dropped packet from banned IP ") + addr.IPAddress());
177 } else {
178 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet received ("))
179 << addr.IPAddress() << wxT(":") << port << wxT("): ")
180 << length << wxT("b"));
181 OnPacketReceived(ip, port, (byte*)buffer, length);
186 void CMuleUDPSocket::OnReceiveError(int errorCode, uint32 WXUNUSED(ip), uint16 WXUNUSED(port))
188 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Error while reading: ")) << errorCode);
192 void CMuleUDPSocket::OnDisconnected(int WXUNUSED(errorCode))
194 /* Due to bugs in wxWidgets, UDP sockets will sometimes
195 * be closed. This is caused by the fact that wx treats
196 * zero-length datagrams as EOF, which is only the case
197 * when dealing with streaming sockets.
199 * This has been reported as patch #1885472:
200 * http://sourceforge.net/tracker/index.php?func=detail&aid=1885472&group_id=9863&atid=309863
202 AddDebugLogLineC(logMuleUDP, m_name + wxT("Socket died, recreating."));
203 DestroySocket();
204 CreateSocket();
208 void CMuleUDPSocket::SendPacket(CPacket* packet, uint32 IP, uint16 port, bool bEncrypt, const uint8* pachTargetClientHashORKadID, bool bKad, uint32 nReceiverVerifyKey)
210 wxCHECK_RET(packet, wxT("Invalid packet."));
211 /*wxCHECK_RET(port, wxT("Invalid port."));
212 wxCHECK_RET(IP, wxT("Invalid IP."));
215 if (!port || !IP) {
216 return;
219 if (!Ok()) {
220 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet discarded, socket not Ok ("))
221 << Uint32_16toStringIP_Port(IP, port) << wxT("): ") << packet->GetPacketSize() << wxT("b"));
222 delete packet;
224 return;
227 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet queued ("))
228 << Uint32_16toStringIP_Port(IP, port) << wxT("): ") << packet->GetPacketSize() << wxT("b"));
230 UDPPack newpending;
231 newpending.IP = IP;
232 newpending.port = port;
233 newpending.packet = packet;
234 newpending.time = GetTickCount();
235 newpending.bEncrypt = bEncrypt && (pachTargetClientHashORKadID != NULL || (bKad && nReceiverVerifyKey != 0));
236 newpending.bKad = bKad;
237 newpending.nReceiverVerifyKey = nReceiverVerifyKey;
238 if (newpending.bEncrypt && pachTargetClientHashORKadID != NULL) {
239 md4cpy(newpending.pachTargetClientHashORKadID, pachTargetClientHashORKadID);
240 } else {
241 md4clr(newpending.pachTargetClientHashORKadID);
245 wxMutexLocker lock(m_mutex);
246 m_queue.push_back(newpending);
249 theApp->uploadBandwidthThrottler->QueueForSendingControlPacket(this);
253 bool CMuleUDPSocket::Ok()
255 wxMutexLocker lock(m_mutex);
257 return m_socket && m_socket->Ok();
261 SocketSentBytes CMuleUDPSocket::SendControlData(uint32 maxNumberOfBytesToSend, uint32 WXUNUSED(minFragSize))
263 wxMutexLocker lock(m_mutex);
264 uint32 sentBytes = 0;
265 while (!m_queue.empty() && !m_busy && (sentBytes < maxNumberOfBytesToSend)) {
266 UDPPack item = m_queue.front();
267 CPacket* packet = item.packet;
268 if (GetTickCount() - item.time < UDPMAXQUEUETIME) {
269 uint32_t len = packet->GetPacketSize() + 2;
270 uint8_t *sendbuffer = new uint8_t [len];
271 memcpy(sendbuffer, packet->GetUDPHeader(), 2);
272 memcpy(sendbuffer + 2, packet->GetDataBuffer(), packet->GetPacketSize());
274 if (item.bEncrypt && (theApp->GetPublicIP() > 0 || item.bKad)) {
275 len = CEncryptedDatagramSocket::EncryptSendClient(&sendbuffer, len, item.pachTargetClientHashORKadID, item.bKad, item.nReceiverVerifyKey, (item.bKad ? Kademlia::CPrefs::GetUDPVerifyKey(item.IP) : 0));
278 if (SendTo(sendbuffer, len, item.IP, item.port)) {
279 sentBytes += len;
280 m_queue.pop_front();
281 delete packet;
282 delete [] sendbuffer;
283 } else {
284 // TODO: Needs better error handling, see SentTo
285 delete [] sendbuffer;
286 break;
288 } else {
289 m_queue.pop_front();
290 delete packet;
293 if (!m_busy && !m_queue.empty()) {
294 theApp->uploadBandwidthThrottler->QueueForSendingControlPacket(this);
296 SocketSentBytes returnVal = { true, 0, sentBytes };
298 return returnVal;
302 bool CMuleUDPSocket::SendTo(uint8_t *buffer, uint32_t length, uint32_t ip, uint16_t port)
304 // Just pretend that we sent the packet in order to avoid infinite loops.
305 if (!(m_socket && m_socket->Ok())) {
306 return true;
309 amuleIPV4Address addr;
310 addr.Hostname(ip);
311 addr.Service(port);
313 // We better clear this flag here, status might have been changed
314 // between the U.B.T. addition and the real sending happening later
315 m_busy = false;
316 bool sent = false;
317 m_socket->SendTo(addr, buffer, length);
318 if (m_socket->Error()) {
319 wxSocketError error = m_socket->LastError();
321 if (error == wxSOCKET_WOULDBLOCK) {
322 // Socket is busy and can't send this data right now,
323 // so we just return not sent and set the wouldblock
324 // flag so it gets resent when socket is ready.
325 m_busy = true;
326 } else {
327 // An error which we can't handle happended, so we drop
328 // the packet rather than risk entering an infinite loop.
329 AddLogLineNS((wxT("WARNING! ") + m_name + wxT(": Packet to "))
330 << Uint32_16toStringIP_Port(ip, port)
331 << wxT(" discarded due to error (") << error << wxT(") while sending."));
332 sent = true;
334 } else {
335 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet sent ("))
336 << Uint32_16toStringIP_Port(ip, port) << wxT("): ")
337 << length << wxT("b"));
338 sent = true;
341 return sent;
344 // File_checked_for_headers