]> git.localhorst.tv Git - blank.git/blob - src/net/net.cpp
er, didn't mean to kill all communication ^^
[blank.git] / src / net / net.cpp
1 #include "Connection.hpp"
2 #include "ConnectionHandler.hpp"
3 #include "io.hpp"
4 #include "Packet.hpp"
5
6 #include "../app/init.hpp"
7 #include "../model/CompositeModel.hpp"
8 #include "../world/Entity.hpp"
9 #include "../world/EntityState.hpp"
10
11 #include <cstring>
12
13 using namespace std;
14
15
16 namespace blank {
17
18 constexpr size_t Packet::Ping::MAX_LEN;
19 constexpr size_t Packet::Login::MAX_LEN;
20 constexpr size_t Packet::Join::MAX_LEN;
21 constexpr size_t Packet::Part::MAX_LEN;
22 constexpr size_t Packet::PlayerUpdate::MAX_LEN;
23 constexpr size_t Packet::SpawnEntity::MAX_LEN;
24 constexpr size_t Packet::DespawnEntity::MAX_LEN;
25 constexpr size_t Packet::EntityUpdate::MAX_LEN;
26 constexpr size_t Packet::PlayerCorrection::MAX_LEN;
27 constexpr size_t Packet::ChunkBegin::MAX_LEN;
28 constexpr size_t Packet::ChunkData::MAX_LEN;
29
30 Connection::Connection(const IPaddress &addr)
31 : handler(nullptr)
32 , addr(addr)
33 , send_timer(500)
34 , recv_timer(10000)
35 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
36 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
37 , closed(false) {
38         send_timer.Start();
39         recv_timer.Start();
40 }
41
42 bool Connection::Matches(const IPaddress &remote) const noexcept {
43         return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
44 }
45
46 void Connection::FlagSend() noexcept {
47         send_timer.Reset();
48 }
49
50 void Connection::FlagRecv() noexcept {
51         recv_timer.Reset();
52 }
53
54 bool Connection::ShouldPing() const noexcept {
55         return !closed && send_timer.HitOnce();
56 }
57
58 bool Connection::TimedOut() const noexcept {
59         return recv_timer.HitOnce();
60 }
61
62 void Connection::Update(int dt) {
63         send_timer.Update(dt);
64         recv_timer.Update(dt);
65         if (TimedOut()) {
66                 Close();
67                 if (HasHandler()) {
68                         Handler().OnTimeout();
69                 }
70         }
71 }
72
73
74 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
75         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
76         pack.header.ctrl = ctrl_out;
77         uint16_t seq = ctrl_out.seq++;
78
79         udp_pack.address = addr;
80         if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
81                 throw NetError("SDLNet_UDP_Send");
82         }
83
84         FlagSend();
85         return seq;
86 }
87
88 void Connection::Received(const UDPpacket &udp_pack) {
89         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
90
91         // ack to the remote
92         int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
93         if (diff > 0) {
94                 if (diff >= 32) {
95                         ctrl_out.hist = 0;
96                 } else {
97                         ctrl_out.hist <<= diff;
98                         ctrl_out.hist |= 1 << (diff - 1);
99                 }
100         } else if (diff < 0 && diff >= -32) {
101                 ctrl_out.hist |= 1 << (-diff - 1);
102         }
103         ctrl_out.ack = pack.header.ctrl.seq;
104         FlagRecv();
105
106         if (!HasHandler()) {
107                 return;
108         }
109
110         Packet::TControl ctrl_new = pack.header.ctrl;
111         Handler().Handle(udp_pack);
112
113         if (diff > 0) {
114                 // if the packet holds more recent information
115                 // check if remote failed to ack one of our packets
116                 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
117                 // should always be true, but you never know…
118                 if (diff > 0) {
119                         for (int i = 0; i < diff; ++i) {
120                                 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
121                                         Handler().OnPacketLost(ctrl_in.ack - 32 + i);
122                                 }
123                         }
124                 }
125                 // check for newly ack'd packets
126                 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
127                         if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
128                                 Handler().OnPacketReceived(s);
129                         }
130                 }
131                 ctrl_in = ctrl_new;
132         }
133 }
134
135 bool Packet::TControl::Acks(uint16_t s) const noexcept {
136         int16_t diff = int16_t(ack) - int16_t(s);
137         if (diff == 0) return true;
138         if (diff < 0 || diff > 32) return false;
139         return (hist & (1 << (diff - 1))) != 0;
140 }
141
142 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
143         Packet::Make<Packet::Ping>(udp_pack);
144         return Send(udp_pack, sock);
145 }
146
147
148 ostream &operator <<(ostream &out, const IPaddress &addr) {
149         const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
150         out << int(host[0])
151                 << '.' << int(host[1])
152                 << '.' << int(host[2])
153                 << '.' << int(host[3]);
154         if (addr.port) {
155                 out << ':' << SDLNet_Read16(&addr.port);
156         }
157         return out;
158 }
159
160
161 const char *Packet::Type2String(uint8_t t) noexcept {
162         switch (t) {
163                 case Ping::TYPE:
164                         return "Ping";
165                 case Login::TYPE:
166                         return "Login";
167                 case Join::TYPE:
168                         return "Join";
169                 case Part::TYPE:
170                         return "Part";
171                 case PlayerUpdate::TYPE:
172                         return "PlayerUpdate";
173                 case SpawnEntity::TYPE:
174                         return "SpawnEntity";
175                 case DespawnEntity::TYPE:
176                         return "DespawnEntity";
177                 case EntityUpdate::TYPE:
178                         return "EntityUpdate";
179                 case PlayerCorrection::TYPE:
180                         return "PlayerCorrection";
181                 case ChunkBegin::TYPE:
182                         return "ChunkBegin";
183                 case ChunkData::TYPE:
184                         return "ChunkData";
185                 default:
186                         return "Unknown";
187         }
188 }
189
190 template<class T>
191 void Packet::Payload::Write(const T &src, size_t off) noexcept {
192         if ((length - off) < sizeof(T)) {
193                 // dismiss out of bounds write
194                 return;
195         }
196         *reinterpret_cast<T *>(&data[off]) = src;
197 }
198
199 template<class T>
200 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
201         if ((length - off) < sizeof(T)) {
202                 // dismiss out of bounds read
203                 return;
204         }
205         dst = *reinterpret_cast<T *>(&data[off]);
206 }
207
208 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
209         uint8_t *dst = &data[off];
210         size_t len = min(maxlen, length - off);
211         if (src.size() < len) {
212                 memset(dst, '\0', len);
213                 memcpy(dst, src.c_str(), src.size());
214         } else {
215                 memcpy(dst, src.c_str(), len);
216         }
217 }
218
219 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
220         size_t len = min(maxlen, length - off);
221         dst.clear();
222         dst.reserve(len);
223         for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
224                 dst.push_back(data[off + i]);
225         }
226 }
227
228
229 void Packet::Login::WritePlayerName(const string &name) noexcept {
230         WriteString(name, 0, 32);
231 }
232
233 void Packet::Login::ReadPlayerName(string &name) const noexcept {
234         ReadString(name, 0, 32);
235 }
236
237 void Packet::Join::WritePlayer(const Entity &player) noexcept {
238         Write(player.ID(), 0);
239         Write(player.GetState(), 4);
240 }
241
242 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
243         Read(id, 0);
244 }
245
246 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
247         Read(state, 4);
248 }
249
250 void Packet::Join::WriteWorldName(const string &name) noexcept {
251         WriteString(name, 68, 32);
252 }
253
254 void Packet::Join::ReadWorldName(string &name) const noexcept {
255         ReadString(name, 68, 32);
256 }
257
258 void Packet::PlayerUpdate::WritePlayer(const Entity &player) noexcept {
259         Write(player.GetState(), 0);
260 }
261
262 void Packet::PlayerUpdate::ReadPlayerState(EntityState &state) const noexcept {
263         Read(state, 0);
264 }
265
266 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
267         Write(e.ID(), 0);
268         if (e.GetModel()) {
269                 Write(e.GetModel().GetModel().ID(), 4);
270         } else {
271                 Write(uint32_t(0), 4);
272         }
273         Write(e.GetState(), 8);
274         Write(e.Bounds(), 72);
275         uint32_t flags = 0;
276         if (e.WorldCollidable()) {
277                 flags |= 1;
278         }
279         Write(flags, 96);
280         WriteString(e.Name(), 100, 32);
281 }
282
283 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
284         Read(id, 0);
285 }
286
287 void Packet::SpawnEntity::ReadSkeletonID(uint32_t &id) const noexcept {
288         Read(id, 4);
289 }
290
291 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
292         EntityState state;
293         AABB bounds;
294         uint32_t flags = 0;
295         string name;
296
297         Read(state, 8);
298         Read(bounds, 72);
299         Read(flags, 96);
300         ReadString(name, 100, 32);
301
302         e.SetState(state);
303         e.Bounds(bounds);
304         e.WorldCollidable(flags & 1);
305         e.Name(name);
306 }
307
308 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
309         Write(id, 0);
310 }
311
312 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
313         Read(id, 0);
314 }
315
316 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
317         Write(count, 0);
318 }
319
320 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
321         Read(count, 0);
322 }
323
324 void Packet::EntityUpdate::WriteEntity(const Entity &entity, uint32_t num) noexcept {
325         uint32_t off = 4 + (num * 64);
326
327         Write(entity.ID(), off);
328         Write(entity.GetState(), off + 4);
329 }
330
331 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
332         Read(id, 4 + (num * 64));
333 }
334
335 void Packet::EntityUpdate::ReadEntityState(EntityState &state, uint32_t num) const noexcept {
336         uint32_t off = 4 + (num * 64);
337         Read(state, off + 4);
338 }
339
340 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
341         Write(s, 0);
342 }
343
344 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
345         Read(s, 0);
346 }
347
348 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
349         Write(player.GetState(), 2);
350 }
351
352 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
353         Read(state, 2);
354 }
355
356 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
357         Write(id, 0);
358 }
359
360 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
361         Read(id, 0);
362 }
363
364 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
365         Write(f, 4);
366 }
367
368 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
369         Read(f, 4);
370 }
371
372 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
373         Write(pos, 8);
374 }
375
376 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
377         Read(pos, 8);
378 }
379
380 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
381         Write(s, 20);
382 }
383
384 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
385         Read(s, 20);
386 }
387
388 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
389         Write(id, 0);
390 }
391
392 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
393         Read(id, 0);
394 }
395
396 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
397         Write(o, 4);
398 }
399
400 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
401         Read(o, 4);
402 }
403
404 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
405         Write(s, 8);
406 }
407
408 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
409         Read(s, 8);
410 }
411
412 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
413         size_t len = min(length - 12, l);
414         memcpy(&data[12], d, len);
415 }
416
417 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
418         size_t len = min(length - 12, l);
419         memcpy(d, &data[12], len);
420 }
421
422
423 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
424         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
425         switch (pack.Type()) {
426                 case Packet::Ping::TYPE:
427                         On(Packet::As<Packet::Ping>(udp_pack));
428                         break;
429                 case Packet::Login::TYPE:
430                         On(Packet::As<Packet::Login>(udp_pack));
431                         break;
432                 case Packet::Join::TYPE:
433                         On(Packet::As<Packet::Join>(udp_pack));
434                         break;
435                 case Packet::Part::TYPE:
436                         On(Packet::As<Packet::Part>(udp_pack));
437                         break;
438                 case Packet::PlayerUpdate::TYPE:
439                         On(Packet::As<Packet::PlayerUpdate>(udp_pack));
440                         break;
441                 case Packet::SpawnEntity::TYPE:
442                         On(Packet::As<Packet::SpawnEntity>(udp_pack));
443                         break;
444                 case Packet::DespawnEntity::TYPE:
445                         On(Packet::As<Packet::DespawnEntity>(udp_pack));
446                         break;
447                 case Packet::EntityUpdate::TYPE:
448                         On(Packet::As<Packet::EntityUpdate>(udp_pack));
449                         break;
450                 case Packet::PlayerCorrection::TYPE:
451                         On(Packet::As<Packet::PlayerCorrection>(udp_pack));
452                         break;
453                 case Packet::ChunkBegin::TYPE:
454                         On(Packet::As<Packet::ChunkBegin>(udp_pack));
455                         break;
456                 case Packet::ChunkData::TYPE:
457                         On(Packet::As<Packet::ChunkData>(udp_pack));
458                         break;
459                 default:
460                         // drop unknown or unhandled packets
461                         break;
462         }
463 }
464
465 }