1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3#include "config.h"
4#include "network.h"
5
6#include <base/dbg.h>
7#include <base/log.h>
8#include <base/mem.h>
9#include <base/secure.h>
10#include <base/str.h>
11#include <base/time.h>
12
13bool CNetConnection::IsPeerAddress(const NETADDR &Addr) const
14{
15 // While connecting, the peer address is not determined yet, so any of the
16 // addresses that the connection was initiated to is accepted.
17 if(m_State != EState::CONNECT)
18 {
19 return m_PeerAddr == Addr;
20 }
21 for(int i = 0; i < m_NumConnectAddrs; i++)
22 {
23 if(m_aConnectAddrs[i] == Addr)
24 {
25 return true;
26 }
27 }
28 return false;
29}
30
31void CNetConnection::SetPeerAddr(const NETADDR *pAddr)
32{
33 m_PeerAddr = *pAddr;
34 net_addr_str(addr: pAddr, string: m_aPeerAddrStr.data(), max_length: m_aPeerAddrStr.size(), add_port: true);
35 net_addr_str(addr: pAddr, string: m_aPeerAddrStrNoPort.data(), max_length: m_aPeerAddrStrNoPort.size(), add_port: false);
36}
37
38void CNetConnection::ClearPeerAddr()
39{
40 mem_zero(block: &m_PeerAddr, size: sizeof(m_PeerAddr));
41 m_aPeerAddrStr[0] = '\0';
42 m_aPeerAddrStrNoPort[0] = '\0';
43}
44
45void CNetConnection::ResetStats()
46{
47 m_Stats = {};
48 ClearPeerAddr();
49 m_LastUpdateTime = 0;
50}
51
52void CNetConnection::Reset()
53{
54 m_Sequence = 0;
55 m_Ack = 0;
56 m_PeerAck = 0;
57 m_RemoteClosed = 0;
58
59 m_TimeoutProtected = false;
60 m_TimeoutSituation = false;
61
62 m_State = EState::OFFLINE;
63 m_Token = -1;
64 m_SecurityToken = NET_SECURITY_TOKEN_UNKNOWN;
65 m_Sixup = false;
66
67 m_LastSendTime = 0;
68 m_LastRecvTime = 0;
69 m_LastResendTime = 0;
70 m_ResendRequested = false;
71
72 mem_zero(block: &m_aConnectAddrs, size: sizeof(m_aConnectAddrs));
73 m_NumConnectAddrs = 0;
74 m_UnknownSeq = false;
75
76 m_Buffer.Init();
77
78 mem_zero(block: &m_Construct, size: sizeof(m_Construct));
79}
80
81const char *CNetConnection::ErrorString()
82{
83 return m_aErrorString;
84}
85
86void CNetConnection::SetError(const char *pString)
87{
88 str_copy(dst&: m_aErrorString, src: pString);
89}
90
91void CNetConnection::Init(NETSOCKET Socket, bool BlockCloseMsg)
92{
93 Reset();
94 ResetStats();
95
96 m_Socket = Socket;
97 m_BlockCloseMsg = BlockCloseMsg;
98 m_aErrorString[0] = '\0';
99}
100
101void CNetConnection::AckChunks(int Ack)
102{
103 while(true)
104 {
105 CNetChunkResend *pResend = m_Buffer.First();
106 if(!pResend)
107 break;
108
109 if(CNetBase::IsSeqInBackroom(Seq: pResend->m_Sequence, Ack))
110 m_Buffer.PopFirst();
111 else
112 break;
113 }
114}
115
116void CNetConnection::SignalResend()
117{
118 m_Construct.m_Flags |= NET_PACKETFLAG_RESEND;
119}
120
121int CNetConnection::Flush()
122{
123 // Only flush the connection if there is at least one chunk to flush,
124 // or if a resend should be signaled.
125 const int NumChunks = m_Construct.m_NumChunks;
126 if(!NumChunks && (m_Construct.m_Flags & NET_PACKETFLAG_RESEND) == 0)
127 {
128 return 0;
129 }
130
131 // send of the packets
132 m_Construct.m_Ack = m_Ack;
133 CNetBase::SendPacket(Socket: m_Socket, pAddr: &m_PeerAddr, pPacket: &m_Construct, SecurityToken: m_SecurityToken, Sixup: m_Sixup);
134
135 // update send times
136 m_LastSendTime = time_get();
137
138 // clear construct so we can start building a new package
139 mem_zero(block: &m_Construct, size: sizeof(m_Construct));
140 return NumChunks;
141}
142
143int CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence)
144{
145 if(m_State == EState::OFFLINE || m_State == EState::ERROR)
146 return -1;
147
148 unsigned char *pChunkData;
149
150 // check if we have space for it, if not, flush the connection
151 if(m_Construct.m_DataSize + DataSize + NET_MAX_CHUNKHEADERSIZE > (int)sizeof(m_Construct.m_aChunkData) - (int)sizeof(SECURITY_TOKEN) ||
152 m_Construct.m_NumChunks == NET_MAX_PACKET_CHUNKS)
153 {
154 Flush();
155 }
156
157 // pack all the data
158 CNetChunkHeader Header;
159 Header.m_Flags = Flags;
160 Header.m_Size = DataSize;
161 Header.m_Sequence = Sequence;
162 pChunkData = &m_Construct.m_aChunkData[m_Construct.m_DataSize];
163 pChunkData = Header.Pack(pData: pChunkData, Split: m_Sixup ? 6 : 4);
164 mem_copy(dest: pChunkData, source: pData, size: DataSize);
165 pChunkData += DataSize;
166
167 //
168 m_Construct.m_NumChunks++;
169 m_Construct.m_DataSize = (int)(pChunkData - m_Construct.m_aChunkData);
170
171 // set packet flags as well
172
173 if(Flags & NET_CHUNKFLAG_VITAL && !(Flags & NET_CHUNKFLAG_RESEND))
174 {
175 // save packet if we need to resend
176 CNetChunkResend *pResend = m_Buffer.Allocate(Size: sizeof(CNetChunkResend) + DataSize);
177 if(pResend)
178 {
179 pResend->m_Sequence = Sequence;
180 pResend->m_Flags = Flags;
181 pResend->m_DataSize = DataSize;
182 pResend->m_pData = (unsigned char *)(pResend + 1);
183 pResend->m_FirstSendTime = time_get();
184 pResend->m_LastSendTime = pResend->m_FirstSendTime;
185 mem_copy(dest: pResend->m_pData, source: pData, size: DataSize);
186 }
187 else
188 {
189 // out of buffer, don't save the packet and hope nobody will ask for resend
190 return -1;
191 }
192 }
193
194 return 0;
195}
196
197int CNetConnection::QueueChunk(int Flags, int DataSize, const void *pData)
198{
199 if(Flags & NET_CHUNKFLAG_VITAL)
200 m_Sequence = (m_Sequence + 1) % NET_MAX_SEQUENCE;
201 return QueueChunkEx(Flags, DataSize, pData, Sequence: m_Sequence);
202}
203
204void CNetConnection::SendConnect()
205{
206 // send the connect message
207 m_LastSendTime = time_get();
208 for(int i = 0; i < m_NumConnectAddrs; i++)
209 {
210 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &m_aConnectAddrs[i], Ack: m_Ack, ControlMsg: NET_CTRLMSG_CONNECT, pExtra: SECURITY_TOKEN_MAGIC, ExtraSize: sizeof(SECURITY_TOKEN_MAGIC), SecurityToken: m_SecurityToken, Sixup: m_Sixup);
211 }
212}
213
214void CNetConnection::SendControl(int ControlMsg, const void *pExtra, int ExtraSize)
215{
216 // send the control message
217 m_LastSendTime = time_get();
218 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &m_PeerAddr, Ack: m_Ack, ControlMsg, pExtra, ExtraSize, SecurityToken: m_SecurityToken, Sixup: m_Sixup);
219}
220
221void CNetConnection::ResendChunk(CNetChunkResend *pResend)
222{
223 QueueChunkEx(Flags: pResend->m_Flags | NET_CHUNKFLAG_RESEND, DataSize: pResend->m_DataSize, pData: pResend->m_pData, Sequence: pResend->m_Sequence);
224 pResend->m_LastSendTime = time_get();
225}
226
227void CNetConnection::Resend()
228{
229 for(CNetChunkResend *pResend = m_Buffer.First(); pResend; pResend = m_Buffer.Next(pCurrent: pResend))
230 ResendChunk(pResend);
231}
232
233void CNetConnection::AnswerResendRequest(int64_t Now)
234{
235 // requests that arrive within the interval are answered together by the next one
236 if(!m_ResendRequested)
237 return;
238 if(g_Config.m_ConnResendRequestsPerSecond != 0 &&
239 Now - m_LastResendTime < time_freq() / g_Config.m_ConnResendRequestsPerSecond)
240 return;
241
242 m_ResendRequested = false;
243 m_LastResendTime = Now;
244 Resend();
245}
246
247int CNetConnection::Connect(const NETADDR *pAddr, int NumAddrs)
248{
249 if(State() != EState::OFFLINE)
250 return -1;
251
252 // init connection
253 Reset();
254 ClearPeerAddr();
255
256 for(int i = 0; i < NumAddrs; i++)
257 {
258 m_aConnectAddrs[i] = pAddr[i];
259 }
260 m_NumConnectAddrs = NumAddrs;
261 m_aErrorString[0] = '\0';
262 m_State = EState::CONNECT;
263 SendConnect();
264 return 0;
265}
266
267void CNetConnection::SendControlWithToken7(int ControlMsg, SECURITY_TOKEN ResponseToken)
268{
269 m_LastSendTime = time_get();
270
271 CNetBase::SendControlMsgWithToken7(Socket: m_Socket, pAddr: &m_PeerAddr, Token: ResponseToken, Ack: 0, ControlMsg, MyToken: m_Token, Extended: true);
272}
273
274int CNetConnection::Connect7(const NETADDR *pAddr, int NumAddrs)
275{
276 if(State() != EState::OFFLINE)
277 return -1;
278
279 // init connection
280 Reset();
281 for(int i = 0; i < NumAddrs; i++)
282 {
283 m_aConnectAddrs[i] = pAddr[i];
284 }
285 m_LastRecvTime = time_get();
286 m_NumConnectAddrs = NumAddrs;
287 SetPeerAddr(pAddr);
288 SetToken7(GenerateToken7(pPeerAddr: pAddr));
289 m_aErrorString[0] = '\0';
290 m_State = EState::WANT_TOKEN;
291 SendControlWithToken7(ControlMsg: protocol7::NET_CTRLMSG_TOKEN, ResponseToken: NET_TOKEN_NONE);
292 m_Sixup = true;
293 return 0;
294}
295
296void CNetConnection::SetToken7(TOKEN Token)
297{
298 if(State() != EState::OFFLINE)
299 return;
300
301 m_Token = Token;
302}
303
304TOKEN CNetConnection::GenerateToken7(const NETADDR *pPeerAddr)
305{
306 TOKEN Token;
307 secure_random_fill(bytes: &Token, length: sizeof(Token));
308 return Token;
309}
310
311void CNetConnection::Disconnect(const char *pReason)
312{
313 if(State() == EState::OFFLINE)
314 return;
315
316 if(m_RemoteClosed == 0)
317 {
318 if(!m_TimeoutSituation)
319 {
320 if(pReason)
321 SendControl(ControlMsg: NET_CTRLMSG_CLOSE, pExtra: pReason, ExtraSize: str_length(str: pReason) + 1);
322 else
323 SendControl(ControlMsg: NET_CTRLMSG_CLOSE, pExtra: nullptr, ExtraSize: 0);
324 }
325
326 if(pReason != m_aErrorString)
327 {
328 m_aErrorString[0] = 0;
329 if(pReason)
330 str_copy(dst&: m_aErrorString, src: pReason);
331 }
332 }
333
334 Reset();
335}
336
337void CNetConnection::DirectInit(const NETADDR &Addr, SECURITY_TOKEN SecurityToken, SECURITY_TOKEN Token, bool Sixup)
338{
339 Reset();
340
341 m_State = EState::ONLINE;
342
343 SetPeerAddr(&Addr);
344 m_aErrorString[0] = '\0';
345
346 int64_t Now = time_get();
347 m_LastSendTime = Now;
348 m_LastRecvTime = Now;
349 m_LastUpdateTime = Now;
350
351 m_SecurityToken = SecurityToken;
352 m_Token = Token;
353 m_Sixup = Sixup;
354}
355
356int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr, SECURITY_TOKEN SecurityToken, SECURITY_TOKEN ResponseToken)
357{
358 dbg_assert(State() != EState::OFFLINE, "can't feed packets to offline connection");
359 // Disregard packets from the wrong address.
360 if(!IsPeerAddress(Addr: *pAddr))
361 {
362 return 0;
363 }
364
365 if(!m_Sixup && m_SecurityToken != NET_SECURITY_TOKEN_UNKNOWN && m_SecurityToken != NET_SECURITY_TOKEN_UNSUPPORTED)
366 {
367 // supposed to have a valid token in this packet, check it
368 if(pPacket->m_DataSize < (int)sizeof(m_SecurityToken))
369 return 0;
370 pPacket->m_DataSize -= sizeof(m_SecurityToken);
371 if(m_SecurityToken != ToSecurityToken(pData: &pPacket->m_aChunkData[pPacket->m_DataSize]))
372 {
373 if(g_Config.m_Debug)
374 dbg_msg(sys: "security", fmt: "token mismatch, expected %d got %d", m_SecurityToken, ToSecurityToken(pData: &pPacket->m_aChunkData[pPacket->m_DataSize]));
375 return 0;
376 }
377 }
378
379 if(m_Sixup && SecurityToken != m_Token)
380 return 0;
381
382 // check if actual ack value is valid(own sequence..latest peer ack)
383 if(m_Sequence >= m_PeerAck)
384 {
385 if(pPacket->m_Ack < m_PeerAck || pPacket->m_Ack > m_Sequence)
386 return 0;
387 }
388 else
389 {
390 if(pPacket->m_Ack < m_PeerAck && pPacket->m_Ack > m_Sequence)
391 return 0;
392 }
393 m_PeerAck = pPacket->m_Ack;
394
395 int64_t Now = time_get();
396
397 if(pPacket->m_Flags & NET_PACKETFLAG_RESEND)
398 m_ResendRequested = true;
399 AnswerResendRequest(Now);
400
401 //
402 if(pPacket->m_Flags & NET_PACKETFLAG_CONTROL)
403 {
404 int CtrlMsg = pPacket->m_aChunkData[0];
405
406 if(CtrlMsg == NET_CTRLMSG_CLOSE)
407 {
408 m_State = EState::ERROR;
409 m_RemoteClosed = 1;
410
411 char aStr[256] = {0};
412 if(pPacket->m_DataSize > 1)
413 {
414 // make sure to sanitize the error string from the other party
415 str_copy(dst: aStr, src: (char *)&pPacket->m_aChunkData[1], dst_size: std::min(a: (size_t)pPacket->m_DataSize, b: sizeof(aStr)));
416 str_sanitize_cc(str: aStr);
417 if(!str_utf8_check(str: aStr))
418 {
419 str_copy(dst&: aStr, src: "(Invalid error message)");
420 }
421 }
422
423 if(!m_BlockCloseMsg)
424 {
425 // set the error string
426 SetError(aStr);
427 }
428
429 if(g_Config.m_Debug)
430 dbg_msg(sys: "conn", fmt: "closed reason='%s'", aStr);
431 return 0;
432 }
433 else
434 {
435 if(m_Sixup && CtrlMsg == protocol7::NET_CTRLMSG_TOKEN)
436 {
437 if(State() == EState::WANT_TOKEN)
438 {
439 m_LastRecvTime = Now;
440 m_State = EState::CONNECT;
441 m_SecurityToken = ResponseToken;
442 SendControlWithToken7(ControlMsg: NET_CTRLMSG_CONNECT, ResponseToken: m_SecurityToken);
443 if(g_Config.m_Debug)
444 {
445 log_debug("connection", "got token, replying, token=%x mytoken=%x", m_SecurityToken, m_Token);
446 }
447 }
448 else if(g_Config.m_Debug)
449 {
450 log_debug("connection", "got token, token=%x", ResponseToken);
451 }
452 }
453 else
454 {
455 if(State() == EState::CONNECT)
456 {
457 // connection made
458 if(CtrlMsg == NET_CTRLMSG_CONNECTACCEPT)
459 {
460 SetPeerAddr(pAddr);
461 if(m_SecurityToken == NET_SECURITY_TOKEN_UNKNOWN && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(m_SecurityToken)) && !mem_comp(a: &pPacket->m_aChunkData[1], b: SECURITY_TOKEN_MAGIC, size: sizeof(SECURITY_TOKEN_MAGIC)))
462 {
463 m_SecurityToken = ToSecurityToken(pData: &pPacket->m_aChunkData[1 + sizeof(SECURITY_TOKEN_MAGIC)]);
464 if(g_Config.m_Debug)
465 dbg_msg(sys: "security", fmt: "got token %d", m_SecurityToken);
466 }
467 else if(!IsSixup())
468 {
469 m_SecurityToken = NET_SECURITY_TOKEN_UNSUPPORTED;
470 if(g_Config.m_Debug)
471 dbg_msg(sys: "security", fmt: "token not supported by server");
472 }
473 if(!IsSixup())
474 SendControl(ControlMsg: NET_CTRLMSG_ACCEPT, pExtra: nullptr, ExtraSize: 0);
475 m_LastRecvTime = Now;
476 m_State = EState::ONLINE;
477 if(g_Config.m_Debug)
478 dbg_msg(sys: "connection", fmt: "got connect+accept, sending accept. connection online");
479 }
480 }
481 }
482 }
483 }
484 else
485 {
486 if(State() == EState::PENDING)
487 {
488 m_LastRecvTime = Now;
489 m_State = EState::ONLINE;
490 if(g_Config.m_Debug)
491 dbg_msg(sys: "connection", fmt: "connecting online");
492 }
493 }
494
495 if(State() == EState::ONLINE)
496 {
497 m_LastRecvTime = Now;
498 AckChunks(Ack: pPacket->m_Ack);
499 }
500
501 return 1;
502}
503
504int CNetConnection::Update()
505{
506 int64_t Now = time_get();
507
508 if(State() == EState::ERROR && m_TimeoutSituation && (Now - m_LastRecvTime) > time_freq() * g_Config.m_ConnTimeoutProtection)
509 {
510 m_TimeoutSituation = false;
511 SetError("Timeout Protection over");
512 }
513
514 if(State() == EState::OFFLINE || State() == EState::ERROR)
515 return 0;
516
517 m_TimeoutSituation = false;
518
519 AnswerResendRequest(Now);
520
521 // check for timeout
522 if(State() != EState::CONNECT &&
523 (Now - m_LastRecvTime) > time_freq() * g_Config.m_ConnTimeout)
524 {
525 m_State = EState::ERROR;
526 SetError("Timeout");
527 m_TimeoutSituation = true;
528 }
529
530 // fix resends
531 if(m_Buffer.First())
532 {
533 CNetChunkResend *pResend = m_Buffer.First();
534
535 // check if we have some really old stuff laying around and abort if not acked
536 if(Now - pResend->m_FirstSendTime > time_freq() * g_Config.m_ConnTimeout)
537 {
538 m_State = EState::ERROR;
539 char aBuf[128];
540 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Too weak connection (not acked for %d seconds)", g_Config.m_ConnTimeout);
541 SetError(aBuf);
542 m_TimeoutSituation = true;
543 }
544 else
545 {
546 // resend packet if we haven't got it acked in 1 second
547 if(Now - pResend->m_LastSendTime > time_freq())
548 ResendChunk(pResend);
549 }
550 }
551
552 // send keep alives if nothing has happened for 250ms
553 if(State() == EState::ONLINE)
554 {
555 if(time_get() - m_LastSendTime > time_freq() / 2) // flush connection after 500ms if needed
556 {
557 int NumFlushedChunks = Flush();
558 if(NumFlushedChunks && g_Config.m_Debug)
559 dbg_msg(sys: "connection", fmt: "flushed connection due to timeout. %d chunks.", NumFlushedChunks);
560 }
561
562 if(time_get() - m_LastSendTime > time_freq())
563 SendControl(ControlMsg: NET_CTRLMSG_KEEPALIVE, pExtra: nullptr, ExtraSize: 0);
564 }
565 else if(State() == EState::CONNECT)
566 {
567 if(time_get() - m_LastSendTime > time_freq() / 2) // send a new connect every 500ms
568 SendConnect();
569 }
570 else if(State() == EState::PENDING)
571 {
572 if(time_get() - m_LastSendTime > time_freq() / 2) // send a new connect/accept every 500ms
573 SendControl(ControlMsg: NET_CTRLMSG_CONNECTACCEPT, pExtra: SECURITY_TOKEN_MAGIC, ExtraSize: sizeof(SECURITY_TOKEN_MAGIC));
574 }
575
576 return 0;
577}
578
579void CNetConnection::ResumeConnection(const NETADDR *pAddr, int Sequence, int Ack, SECURITY_TOKEN SecurityToken, CStaticRingBuffer<CNetChunkResend, NET_CONN_BUFFERSIZE> *pResendBuffer, bool Sixup)
580{
581 int64_t Now = time_get();
582
583 m_Sequence = Sequence;
584 m_Ack = Ack;
585 m_RemoteClosed = 0;
586
587 m_State = EState::ONLINE;
588 SetPeerAddr(pAddr);
589 m_aErrorString[0] = '\0';
590 m_LastSendTime = Now;
591 m_LastRecvTime = Now;
592 m_LastUpdateTime = Now;
593 m_SecurityToken = SecurityToken;
594 m_Sixup = Sixup;
595
596 // copy resend buffer
597 m_Buffer.Init();
598 while(pResendBuffer->First())
599 {
600 CNetChunkResend *pFirst = pResendBuffer->First();
601
602 CNetChunkResend *pResend = m_Buffer.Allocate(Size: sizeof(CNetChunkResend) + pFirst->m_DataSize);
603 mem_copy(dest: pResend, source: pFirst, size: sizeof(CNetChunkResend) + pFirst->m_DataSize);
604 pResend->m_pData = (unsigned char *)(pResend + 1);
605
606 pResendBuffer->PopFirst();
607 }
608}
609