Fix the equality operator
[amule.git] / src / MuleUDPSocket.cpp
bloba666c9303214a5662779035b546109c511a2f02b
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2005-2011 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.
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"
43 #include "Preferences.h"
46 CMuleUDPSocket::CMuleUDPSocket(const wxString& name, int id, const amuleIPV4Address& address, const CProxyData* ProxyData)
48 m_busy(false),
49 m_name(name),
50 m_id(id),
51 m_addr(address),
52 m_proxy(ProxyData),
53 m_socket(NULL)
58 CMuleUDPSocket::~CMuleUDPSocket()
60 theApp->uploadBandwidthThrottler->RemoveFromAllQueues(this);
62 wxMutexLocker lock(m_mutex);
63 DestroySocket();
67 void CMuleUDPSocket::CreateSocket()
69 wxCHECK_RET(!m_socket, wxT("Socket already opened."));
71 m_socket = new CEncryptedDatagramSocket(m_addr, MULE_SOCKET_NOWAIT, m_proxy);
72 m_socket->SetClientData(this);
73 #ifndef ASIO_SOCKETS
74 m_socket->SetEventHandler(*theApp, m_id);
75 m_socket->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_OUTPUT_FLAG | wxSOCKET_LOST_FLAG);
76 #endif
77 m_socket->Notify(true);
79 if (!m_socket->IsOk()) {
80 AddDebugLogLineC(logMuleUDP, wxT("Failed to create valid ") + m_name);
81 DestroySocket();
82 } else {
83 AddLogLineN(wxString(wxT("Created ")) << m_name << wxT(" at port ") << m_addr.Service());
88 void CMuleUDPSocket::DestroySocket()
90 if (m_socket) {
91 AddDebugLogLineN(logMuleUDP, wxT("Shutting down ") + m_name);
92 #ifndef ASIO_SOCKETS
93 m_socket->SetNotify(0);
94 m_socket->Notify(false);
95 #endif
96 m_socket->Close();
97 m_socket->Destroy();
98 m_socket = NULL;
103 void CMuleUDPSocket::Open()
105 wxMutexLocker lock(m_mutex);
107 CreateSocket();
111 void CMuleUDPSocket::Close()
113 wxMutexLocker lock(m_mutex);
115 DestroySocket();
119 void CMuleUDPSocket::OnSend(int errorCode)
121 if (errorCode) {
122 return;
126 wxMutexLocker lock(m_mutex);
127 m_busy = false;
128 if (m_queue.empty()) {
129 return;
133 theApp->uploadBandwidthThrottler->QueueForSendingControlPacket(this);
137 void CMuleUDPSocket::OnReceive(int errorCode)
139 AddDebugLogLineN(logMuleUDP, CFormat(wxT("Got UDP callback for read: Error %i Socket state %i"))
140 % errorCode % Ok());
142 char buffer[UDP_BUFFER_SIZE];
143 amuleIPV4Address addr;
144 unsigned length = 0;
145 bool error = false;
146 int lastError = 0;
149 wxMutexLocker lock(m_mutex);
151 if (errorCode || (m_socket == NULL) || !m_socket->IsOk()) {
152 DestroySocket();
153 CreateSocket();
155 return;
159 length = m_socket->RecvFrom(addr, buffer, UDP_BUFFER_SIZE);
160 lastError = m_socket->LastError();
161 error = lastError != 0;
164 const uint32 ip = StringIPtoUint32(addr.IPAddress());
165 const uint16 port = addr.Service();
166 if (error) {
167 OnReceiveError(lastError, ip, port);
168 } else if (length < 2) {
169 // 2 bytes (protocol and opcode) is the smallets possible packet.
170 AddDebugLogLineN(logMuleUDP, m_name + wxT(": Invalid Packet received"));
171 } else if (!ip) {
172 // wxFAIL;
173 AddLogLineNS(wxT("Unknown ip receiving a UDP packet! Ignoring: '") + addr.IPAddress() + wxT("'"));
174 } else if (!port) {
175 // wxFAIL;
176 AddLogLineNS(wxT("Unknown port receiving a UDP packet! Ignoring"));
177 } else if (theApp->clientlist->IsBannedClient(ip)) {
178 AddDebugLogLineN(logMuleUDP, m_name + wxT(": Dropped packet from banned IP ") + addr.IPAddress());
179 } else {
180 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet received ("))
181 << addr.IPAddress() << wxT(":") << port << wxT("): ")
182 << length << wxT("b"));
183 OnPacketReceived(ip, port, (byte*)buffer, length);
188 void CMuleUDPSocket::OnReceiveError(int DEBUG_ONLY(errorCode), uint32 WXUNUSED(ip), uint16 WXUNUSED(port))
190 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Error while reading: ")) << errorCode);
194 void CMuleUDPSocket::OnDisconnected(int WXUNUSED(errorCode))
196 /* Due to bugs in wxWidgets, UDP sockets will sometimes
197 * be closed. This is caused by the fact that wx treats
198 * zero-length datagrams as EOF, which is only the case
199 * when dealing with streaming sockets.
201 * This has been reported as patch #1885472:
202 * http://sourceforge.net/tracker/index.php?func=detail&aid=1885472&group_id=9863&atid=309863
204 AddDebugLogLineC(logMuleUDP, m_name + wxT("Socket died, recreating."));
205 DestroySocket();
206 CreateSocket();
210 void CMuleUDPSocket::SendPacket(CPacket* packet, uint32 IP, uint16 port, bool bEncrypt, const uint8* pachTargetClientHashORKadID, bool bKad, uint32 nReceiverVerifyKey)
212 wxCHECK_RET(packet, wxT("Invalid packet."));
213 /*wxCHECK_RET(port, wxT("Invalid port."));
214 wxCHECK_RET(IP, wxT("Invalid IP."));
217 if (!port || !IP) {
218 return;
221 if (!Ok()) {
222 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet discarded, socket not Ok ("))
223 << Uint32_16toStringIP_Port(IP, port) << wxT("): ") << packet->GetPacketSize() << wxT("b"));
224 delete packet;
226 return;
229 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet queued ("))
230 << Uint32_16toStringIP_Port(IP, port) << wxT("): ") << packet->GetPacketSize() << wxT("b"));
232 UDPPack newpending;
233 newpending.IP = IP;
234 newpending.port = port;
235 newpending.packet = packet;
236 newpending.time = GetTickCount();
237 newpending.bEncrypt = bEncrypt && (pachTargetClientHashORKadID != NULL || (bKad && nReceiverVerifyKey != 0))
238 && thePrefs::IsClientCryptLayerSupported();
239 newpending.bKad = bKad;
240 newpending.nReceiverVerifyKey = nReceiverVerifyKey;
241 if (newpending.bEncrypt && pachTargetClientHashORKadID != NULL) {
242 md4cpy(newpending.pachTargetClientHashORKadID, pachTargetClientHashORKadID);
243 } else {
244 md4clr(newpending.pachTargetClientHashORKadID);
248 wxMutexLocker lock(m_mutex);
249 m_queue.push_back(newpending);
252 theApp->uploadBandwidthThrottler->QueueForSendingControlPacket(this);
256 bool CMuleUDPSocket::Ok()
258 wxMutexLocker lock(m_mutex);
260 return m_socket && m_socket->IsOk();
264 SocketSentBytes CMuleUDPSocket::SendControlData(uint32 maxNumberOfBytesToSend, uint32 WXUNUSED(minFragSize))
266 wxMutexLocker lock(m_mutex);
267 uint32 sentBytes = 0;
268 while (!m_queue.empty() && !m_busy && (sentBytes < maxNumberOfBytesToSend)) {
269 UDPPack item = m_queue.front();
270 CPacket* packet = item.packet;
271 if (GetTickCount() - item.time < UDPMAXQUEUETIME) {
272 uint32_t len = packet->GetPacketSize() + 2;
273 uint8_t *sendbuffer = new uint8_t [len];
274 memcpy(sendbuffer, packet->GetUDPHeader(), 2);
275 memcpy(sendbuffer + 2, packet->GetDataBuffer(), packet->GetPacketSize());
277 if (item.bEncrypt && (theApp->GetPublicIP() > 0 || item.bKad)) {
278 len = CEncryptedDatagramSocket::EncryptSendClient(&sendbuffer, len, item.pachTargetClientHashORKadID, item.bKad, item.nReceiverVerifyKey, (item.bKad ? Kademlia::CPrefs::GetUDPVerifyKey(item.IP) : 0));
281 if (SendTo(sendbuffer, len, item.IP, item.port)) {
282 sentBytes += len;
283 m_queue.pop_front();
284 delete packet;
285 delete [] sendbuffer;
286 } else {
287 // TODO: Needs better error handling, see SentTo
288 delete [] sendbuffer;
289 break;
291 } else {
292 m_queue.pop_front();
293 delete packet;
296 if (!m_busy && !m_queue.empty()) {
297 theApp->uploadBandwidthThrottler->QueueForSendingControlPacket(this);
299 SocketSentBytes returnVal = { true, 0, sentBytes };
301 return returnVal;
305 bool CMuleUDPSocket::SendTo(uint8_t *buffer, uint32_t length, uint32_t ip, uint16_t port)
307 // Just pretend that we sent the packet in order to avoid infinite loops.
308 if (!(m_socket && m_socket->IsOk())) {
309 return true;
312 amuleIPV4Address addr;
313 addr.Hostname(ip);
314 addr.Service(port);
316 // We better clear this flag here, status might have been changed
317 // between the U.B.T. addition and the real sending happening later
318 m_busy = false;
319 bool sent = false;
320 m_socket->SendTo(addr, buffer, length);
321 if (m_socket->BlocksWrite()) {
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 if (uint32 error = m_socket->LastError()) {
327 // An error which we can't handle happended, so we drop
328 // the packet rather than risk entering an infinite loop.
329 AddLogLineN((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;
333 } else {
334 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet sent ("))
335 << Uint32_16toStringIP_Port(ip, port) << wxT("): ")
336 << length << wxT("b"));
337 sent = true;
340 return sent;
343 // File_checked_for_headers