fixed a new bison warning in Ubuntu 13.4
[amule.git] / src / MuleUDPSocket.cpp
blob64fb1e91e5235571ffb4428770d9af660d2a3215
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, 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->IsOk()) {
78 AddDebugLogLineC(logMuleUDP, wxT("Failed to create valid ") + m_name);
79 DestroySocket();
80 } else {
81 AddLogLineN(wxString(wxT("Created ")) << m_name << wxT(" at port ") << m_addr.Service());
86 void CMuleUDPSocket::DestroySocket()
88 if (m_socket) {
89 AddDebugLogLineN(logMuleUDP, wxT("Shutting down ") + m_name);
90 m_socket->SetNotify(0);
91 m_socket->Notify(false);
92 m_socket->Close();
93 m_socket->Destroy();
94 m_socket = NULL;
99 void CMuleUDPSocket::Open()
101 wxMutexLocker lock(m_mutex);
103 CreateSocket();
107 void CMuleUDPSocket::Close()
109 wxMutexLocker lock(m_mutex);
111 DestroySocket();
115 void CMuleUDPSocket::OnSend(int errorCode)
117 if (errorCode) {
118 return;
122 wxMutexLocker lock(m_mutex);
123 m_busy = false;
124 if (m_queue.empty()) {
125 return;
129 theApp->uploadBandwidthThrottler->QueueForSendingControlPacket(this);
133 void CMuleUDPSocket::OnReceive(int errorCode)
135 AddDebugLogLineN(logMuleUDP, CFormat(wxT("Got UDP callback for read: Error %i Socket state %i"))
136 % errorCode % Ok());
138 char buffer[UDP_BUFFER_SIZE];
139 amuleIPV4Address addr;
140 unsigned length = 0;
141 bool error = false;
142 int lastError = 0;
145 wxMutexLocker lock(m_mutex);
147 if (errorCode || (m_socket == NULL) || !m_socket->IsOk()) {
148 DestroySocket();
149 CreateSocket();
151 return;
155 length = m_socket->RecvFrom(addr, buffer, UDP_BUFFER_SIZE);
156 lastError = m_socket->LastError();
157 error = lastError != 0;
160 const uint32 ip = StringIPtoUint32(addr.IPAddress());
161 const uint16 port = addr.Service();
162 if (error) {
163 OnReceiveError(lastError, ip, port);
164 } else if (length < 2) {
165 // 2 bytes (protocol and opcode) is the smallets possible packet.
166 AddDebugLogLineN(logMuleUDP, m_name + wxT(": Invalid Packet received"));
167 } else if (!ip) {
168 // wxFAIL;
169 AddLogLineNS(wxT("Unknown ip receiving a UDP packet! Ignoring: '") + addr.IPAddress() + wxT("'"));
170 } else if (!port) {
171 // wxFAIL;
172 AddLogLineNS(wxT("Unknown port receiving a UDP packet! Ignoring"));
173 } else if (theApp->clientlist->IsBannedClient(ip)) {
174 AddDebugLogLineN(logMuleUDP, m_name + wxT(": Dropped packet from banned IP ") + addr.IPAddress());
175 } else {
176 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet received ("))
177 << addr.IPAddress() << wxT(":") << port << wxT("): ")
178 << length << wxT("b"));
179 OnPacketReceived(ip, port, (byte*)buffer, length);
184 void CMuleUDPSocket::OnReceiveError(int DEBUG_ONLY(errorCode), uint32 WXUNUSED(ip), uint16 WXUNUSED(port))
186 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Error while reading: ")) << errorCode);
190 void CMuleUDPSocket::OnDisconnected(int WXUNUSED(errorCode))
192 /* Due to bugs in wxWidgets, UDP sockets will sometimes
193 * be closed. This is caused by the fact that wx treats
194 * zero-length datagrams as EOF, which is only the case
195 * when dealing with streaming sockets.
197 * This has been reported as patch #1885472:
198 * http://sourceforge.net/tracker/index.php?func=detail&aid=1885472&group_id=9863&atid=309863
200 AddDebugLogLineC(logMuleUDP, m_name + wxT("Socket died, recreating."));
201 DestroySocket();
202 CreateSocket();
206 void CMuleUDPSocket::SendPacket(CPacket* packet, uint32 IP, uint16 port, bool bEncrypt, const uint8* pachTargetClientHashORKadID, bool bKad, uint32 nReceiverVerifyKey)
208 wxCHECK_RET(packet, wxT("Invalid packet."));
209 /*wxCHECK_RET(port, wxT("Invalid port."));
210 wxCHECK_RET(IP, wxT("Invalid IP."));
213 if (!port || !IP) {
214 return;
217 if (!Ok()) {
218 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet discarded, socket not Ok ("))
219 << Uint32_16toStringIP_Port(IP, port) << wxT("): ") << packet->GetPacketSize() << wxT("b"));
220 delete packet;
222 return;
225 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet queued ("))
226 << Uint32_16toStringIP_Port(IP, port) << wxT("): ") << packet->GetPacketSize() << wxT("b"));
228 UDPPack newpending;
229 newpending.IP = IP;
230 newpending.port = port;
231 newpending.packet = packet;
232 newpending.time = GetTickCount();
233 newpending.bEncrypt = bEncrypt && (pachTargetClientHashORKadID != NULL || (bKad && nReceiverVerifyKey != 0))
234 && thePrefs::IsClientCryptLayerSupported();
235 newpending.bKad = bKad;
236 newpending.nReceiverVerifyKey = nReceiverVerifyKey;
237 if (newpending.bEncrypt && pachTargetClientHashORKadID != NULL) {
238 md4cpy(newpending.pachTargetClientHashORKadID, pachTargetClientHashORKadID);
239 } else {
240 md4clr(newpending.pachTargetClientHashORKadID);
244 wxMutexLocker lock(m_mutex);
245 m_queue.push_back(newpending);
248 theApp->uploadBandwidthThrottler->QueueForSendingControlPacket(this);
252 bool CMuleUDPSocket::Ok()
254 wxMutexLocker lock(m_mutex);
256 return m_socket && m_socket->IsOk();
260 SocketSentBytes CMuleUDPSocket::SendControlData(uint32 maxNumberOfBytesToSend, uint32 WXUNUSED(minFragSize))
262 wxMutexLocker lock(m_mutex);
263 uint32 sentBytes = 0;
264 while (!m_queue.empty() && !m_busy && (sentBytes < maxNumberOfBytesToSend)) {
265 UDPPack item = m_queue.front();
266 CPacket* packet = item.packet;
267 if (GetTickCount() - item.time < UDPMAXQUEUETIME) {
268 uint32_t len = packet->GetPacketSize() + 2;
269 uint8_t *sendbuffer = new uint8_t [len];
270 memcpy(sendbuffer, packet->GetUDPHeader(), 2);
271 memcpy(sendbuffer + 2, packet->GetDataBuffer(), packet->GetPacketSize());
273 if (item.bEncrypt && (theApp->GetPublicIP() > 0 || item.bKad)) {
274 len = CEncryptedDatagramSocket::EncryptSendClient(&sendbuffer, len, item.pachTargetClientHashORKadID, item.bKad, item.nReceiverVerifyKey, (item.bKad ? Kademlia::CPrefs::GetUDPVerifyKey(item.IP) : 0));
277 if (SendTo(sendbuffer, len, item.IP, item.port)) {
278 sentBytes += len;
279 m_queue.pop_front();
280 delete packet;
281 delete [] sendbuffer;
282 } else {
283 // TODO: Needs better error handling, see SentTo
284 delete [] sendbuffer;
285 break;
287 } else {
288 m_queue.pop_front();
289 delete packet;
292 if (!m_busy && !m_queue.empty()) {
293 theApp->uploadBandwidthThrottler->QueueForSendingControlPacket(this);
295 SocketSentBytes returnVal = { true, 0, sentBytes };
297 return returnVal;
301 bool CMuleUDPSocket::SendTo(uint8_t *buffer, uint32_t length, uint32_t ip, uint16_t port)
303 // Just pretend that we sent the packet in order to avoid infinite loops.
304 if (!(m_socket && m_socket->IsOk())) {
305 return true;
308 amuleIPV4Address addr;
309 addr.Hostname(ip);
310 addr.Service(port);
312 // We better clear this flag here, status might have been changed
313 // between the U.B.T. addition and the real sending happening later
314 m_busy = false;
315 bool sent = false;
316 m_socket->SendTo(addr, buffer, length);
317 if (m_socket->BlocksWrite()) {
318 // Socket is busy and can't send this data right now,
319 // so we just return not sent and set the wouldblock
320 // flag so it gets resent when socket is ready.
321 m_busy = true;
322 } else if (uint32 error = m_socket->LastError()) {
323 // An error which we can't handle happended, so we drop
324 // the packet rather than risk entering an infinite loop.
325 AddLogLineN((wxT("WARNING! ") + m_name + wxT(": Packet to "))
326 << Uint32_16toStringIP_Port(ip, port)
327 << wxT(" discarded due to error (") << error << wxT(") while sending."));
328 sent = true;
329 } else {
330 AddDebugLogLineN(logMuleUDP, (m_name + wxT(": Packet sent ("))
331 << Uint32_16toStringIP_Port(ip, port) << wxT("): ")
332 << length << wxT("b"));
333 sent = true;
336 return sent;
339 // File_checked_for_headers