]> git.localhorst.tv Git - blank.git/blob - src/net/net.cpp
3f4bf7453eab78a0ac79b7f045026ec10114a8f0
[blank.git] / src / net / net.cpp
1 #include "Client.hpp"
2 #include "ClientConnection.hpp"
3 #include "Connection.hpp"
4 #include "ConnectionHandler.hpp"
5 #include "io.hpp"
6 #include "Packet.hpp"
7 #include "Server.hpp"
8
9 #include "../app/init.hpp"
10 #include "../model/CompositeModel.hpp"
11 #include "../world/Entity.hpp"
12 #include "../world/EntityState.hpp"
13 #include "../world/World.hpp"
14
15 #include <cstring>
16 #include <iostream>
17 #include <glm/gtx/io.hpp>
18
19 using namespace std;
20
21
22 namespace blank {
23
24 constexpr size_t Packet::Ping::MAX_LEN;
25 constexpr size_t Packet::Login::MAX_LEN;
26 constexpr size_t Packet::Join::MAX_LEN;
27 constexpr size_t Packet::Part::MAX_LEN;
28 constexpr size_t Packet::PlayerUpdate::MAX_LEN;
29 constexpr size_t Packet::SpawnEntity::MAX_LEN;
30 constexpr size_t Packet::DespawnEntity::MAX_LEN;
31 constexpr size_t Packet::EntityUpdate::MAX_LEN;
32 constexpr size_t Packet::PlayerCorrection::MAX_LEN;
33
34 namespace {
35
36 UDPsocket client_bind(Uint16 port) {
37         UDPsocket sock = SDLNet_UDP_Open(port);
38         if (!sock) {
39                 throw NetError("SDLNet_UDP_Open");
40         }
41         return sock;
42 }
43
44 IPaddress client_resolve(const char *host, Uint16 port) {
45         IPaddress addr;
46         if (SDLNet_ResolveHost(&addr, host, port) != 0) {
47                 throw NetError("SDLNet_ResolveHost");
48         }
49         return addr;
50 }
51
52 }
53
54 Client::Client(const Config &conf)
55 : conn(client_resolve(conf.host.c_str(), conf.port))
56 , client_sock(client_bind(0))
57 , client_pack{ -1, nullptr, 0 } {
58         client_pack.data = new Uint8[sizeof(Packet)];
59         client_pack.maxlen = sizeof(Packet);
60         // establish connection
61         SendPing();
62 }
63
64 Client::~Client() {
65         delete[] client_pack.data;
66         SDLNet_UDP_Close(client_sock);
67 }
68
69
70 void Client::Handle() {
71         int result = SDLNet_UDP_Recv(client_sock, &client_pack);
72         while (result > 0) {
73                 HandlePacket(client_pack);
74                 result = SDLNet_UDP_Recv(client_sock, &client_pack);
75         }
76         if (result == -1) {
77                 // a boo boo happened
78                 throw NetError("SDLNet_UDP_Recv");
79         }
80 }
81
82 void Client::HandlePacket(const UDPpacket &udp_pack) {
83         if (!conn.Matches(udp_pack.address)) {
84                 // packet came from somewhere else, drop
85                 return;
86         }
87         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
88         if (pack.header.tag != Packet::TAG) {
89                 // mistagged packet, drop
90                 return;
91         }
92
93         conn.Received(udp_pack);
94 }
95
96 void Client::Update(int dt) {
97         conn.Update(dt);
98         if (conn.ShouldPing()) {
99                 SendPing();
100         }
101 }
102
103 uint16_t Client::SendPing() {
104         return conn.SendPing(client_pack, client_sock);
105 }
106
107 uint16_t Client::SendLogin(const string &name) {
108         auto pack = Packet::Make<Packet::Login>(client_pack);
109         pack.WritePlayerName(name);
110         return conn.Send(client_pack, client_sock);
111 }
112
113 uint16_t Client::SendPlayerUpdate(const Entity &player) {
114         auto pack = Packet::Make<Packet::PlayerUpdate>(client_pack);
115         pack.WritePlayer(player);
116         return conn.Send(client_pack, client_sock);
117 }
118
119 uint16_t Client::SendPart() {
120         Packet::Make<Packet::Part>(client_pack);
121         return conn.Send(client_pack, client_sock);
122 }
123
124
125 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
126 : server(server)
127 , conn(addr)
128 , player(nullptr)
129 , spawns()
130 , confirm_wait(0)
131 , player_update_pack(0)
132 , player_update_timer(1500) {
133         conn.SetHandler(this);
134 }
135
136 ClientConnection::~ClientConnection() {
137         DetachPlayer();
138 }
139
140 void ClientConnection::Update(int dt) {
141         conn.Update(dt);
142         if (Disconnected()) {
143                 return;
144         }
145         if (HasPlayer()) {
146                 // sync entities
147                 auto global_iter = server.GetWorld().Entities().begin();
148                 auto global_end = server.GetWorld().Entities().end();
149                 auto local_iter = spawns.begin();
150                 auto local_end = spawns.end();
151
152                 while (global_iter != global_end && local_iter != local_end) {
153                         if (global_iter->ID() == local_iter->entity->ID()) {
154                                 // they're the same
155                                 if (CanDespawn(*global_iter)) {
156                                         SendDespawn(*local_iter);
157                                 } else {
158                                         // update
159                                         SendUpdate(*local_iter);
160                                 }
161                                 ++global_iter;
162                                 ++local_iter;
163                         } else if (global_iter->ID() < local_iter->entity->ID()) {
164                                 // global entity was inserted
165                                 if (CanSpawn(*global_iter)) {
166                                         auto spawned = spawns.emplace(local_iter, *global_iter);
167                                         SendSpawn(*spawned);
168                                 }
169                                 ++global_iter;
170                         } else {
171                                 // global entity was removed
172                                 SendDespawn(*local_iter);
173                                 ++local_iter;
174                         }
175                 }
176
177                 // leftover spawns
178                 while (global_iter != global_end) {
179                         if (CanSpawn(*global_iter)) {
180                                 spawns.emplace_back(*global_iter);
181                                 SendSpawn(spawns.back());
182                         }
183                         ++global_iter;
184                 }
185
186                 // leftover despawns
187                 while (local_iter != local_end) {
188                         SendDespawn(*local_iter);
189                         ++local_iter;
190                 }
191
192                 CheckPlayerFix();
193         }
194         if (conn.ShouldPing()) {
195                 conn.SendPing(server.GetPacket(), server.GetSocket());
196         }
197 }
198
199 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
200 : entity(&e)
201 , spawn_pack(-1)
202 , despawn_pack(-1) {
203         entity->Ref();
204 }
205
206 ClientConnection::SpawnStatus::~SpawnStatus() {
207         entity->UnRef();
208 }
209
210 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
211         return
212                 &e != player &&
213                 !e.Dead() &&
214                 manhattan_radius(e.ChunkCoords() - Player().ChunkCoords()) < 7;
215 }
216
217 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
218         return
219                 e.Dead() ||
220                 manhattan_radius(e.ChunkCoords() - Player().ChunkCoords()) > 7;
221 }
222
223 void ClientConnection::SendSpawn(SpawnStatus &status) {
224         // don't double spawn
225         if (status.spawn_pack != -1) return;
226
227         auto pack = Packet::Make<Packet::SpawnEntity>(server.GetPacket());
228         pack.WriteEntity(*status.entity);
229         status.spawn_pack = conn.Send(server.GetPacket(), server.GetSocket());
230         ++confirm_wait;
231 }
232
233 void ClientConnection::SendDespawn(SpawnStatus &status) {
234         // don't double despawn
235         if (status.despawn_pack != -1) return;
236
237         auto pack = Packet::Make<Packet::DespawnEntity>(server.GetPacket());
238         pack.WriteEntityID(status.entity->ID());
239         status.despawn_pack = conn.Send(server.GetPacket(), server.GetSocket());
240         ++confirm_wait;
241 }
242
243 void ClientConnection::SendUpdate(SpawnStatus &status) {
244         // don't send updates while spawn not ack'd or despawn sent
245         if (status.spawn_pack != -1 || status.despawn_pack != -1) return;
246
247         // TODO: pack entity updates
248         auto pack = Packet::Make<Packet::EntityUpdate>(server.GetPacket());
249         pack.WriteEntityCount(1);
250         pack.WriteEntity(*status.entity, 0);
251         server.GetPacket().len = Packet::EntityUpdate::GetSize(1);
252         conn.Send(server.GetPacket(), server.GetSocket());
253 }
254
255 void ClientConnection::CheckPlayerFix() {
256         // check always succeeds for now ;)
257         auto pack = Packet::Make<Packet::PlayerCorrection>(server.GetPacket());
258         pack.WritePacketSeq(player_update_pack);
259         pack.WritePlayer(Player());
260         conn.Send(server.GetPacket(), server.GetSocket());
261 }
262
263 void ClientConnection::AttachPlayer(Entity &new_player) {
264         DetachPlayer();
265         player = &new_player;
266         player->Ref();
267         cout << "player \"" << player->Name() << "\" joined" << endl;
268 }
269
270 void ClientConnection::DetachPlayer() {
271         if (!player) return;
272         player->Kill();
273         player->UnRef();
274         cout << "player \"" << player->Name() << "\" left" << endl;
275         player = nullptr;
276 }
277
278 void ClientConnection::OnPacketReceived(uint16_t seq) {
279         if (!confirm_wait) return;
280         for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
281                 if (seq == iter->spawn_pack) {
282                         iter->spawn_pack = -1;
283                         --confirm_wait;
284                         return;
285                 }
286                 if (seq == iter->despawn_pack) {
287                         spawns.erase(iter);
288                         --confirm_wait;
289                         return;
290                 }
291         }
292 }
293
294 void ClientConnection::OnPacketLost(uint16_t seq) {
295         if (!confirm_wait) return;
296         for (SpawnStatus &status : spawns) {
297                 if (seq == status.spawn_pack) {
298                         status.spawn_pack = -1;
299                         --confirm_wait;
300                         SendSpawn(status);
301                         return;
302                 }
303                 if (seq == status.despawn_pack) {
304                         status.despawn_pack = -1;
305                         --confirm_wait;
306                         SendDespawn(status);
307                         return;
308                 }
309         }
310 }
311
312 void ClientConnection::On(const Packet::Login &pack) {
313         string name;
314         pack.ReadPlayerName(name);
315
316         Entity *new_player = server.GetWorld().AddPlayer(name).entity;
317
318         if (new_player) {
319                 // success!
320                 AttachPlayer(*new_player);
321                 cout << "accepted login from player \"" << name << '"' << endl;
322                 auto response = Packet::Make<Packet::Join>(server.GetPacket());
323                 response.WritePlayer(*new_player);
324                 response.WriteWorldName(server.GetWorld().Name());
325                 conn.Send(server.GetPacket(), server.GetSocket());
326                 // set up update tracking
327                 player_update_pack = pack.Seq();
328                 player_update_timer.Reset();
329                 player_update_timer.Start();
330         } else {
331                 // aw no :(
332                 cout << "rejected login from player \"" << name << '"' << endl;
333                 Packet::Make<Packet::Part>(server.GetPacket());
334                 conn.Send(server.GetPacket(), server.GetSocket());
335                 conn.Close();
336         }
337 }
338
339 void ClientConnection::On(const Packet::Part &) {
340         conn.Close();
341 }
342
343 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
344         if (!HasPlayer()) return;
345         int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
346         bool overdue = player_update_timer.HitOnce();
347         player_update_timer.Reset();
348         if (pack_diff > 0 || overdue) {
349                 player_update_pack = pack.Seq();
350                 // TODO: do client input validation here
351                 pack.ReadPlayerState(Player().GetState());
352         }
353 }
354
355
356 Connection::Connection(const IPaddress &addr)
357 : handler(nullptr)
358 , addr(addr)
359 , send_timer(500)
360 , recv_timer(10000)
361 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
362 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
363 , closed(false) {
364         send_timer.Start();
365         recv_timer.Start();
366 }
367
368 bool Connection::Matches(const IPaddress &remote) const noexcept {
369         return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
370 }
371
372 void Connection::FlagSend() noexcept {
373         send_timer.Reset();
374 }
375
376 void Connection::FlagRecv() noexcept {
377         recv_timer.Reset();
378 }
379
380 bool Connection::ShouldPing() const noexcept {
381         return !closed && send_timer.HitOnce();
382 }
383
384 bool Connection::TimedOut() const noexcept {
385         return recv_timer.HitOnce();
386 }
387
388 void Connection::Update(int dt) {
389         send_timer.Update(dt);
390         recv_timer.Update(dt);
391         if (TimedOut()) {
392                 Close();
393                 if (HasHandler()) {
394                         Handler().OnTimeout();
395                 }
396         }
397 }
398
399
400 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
401         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
402         pack.header.ctrl = ctrl_out;
403         uint16_t seq = ctrl_out.seq++;
404
405         udp_pack.address = addr;
406         if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
407                 throw NetError("SDLNet_UDP_Send");
408         }
409
410         FlagSend();
411         return seq;
412 }
413
414 void Connection::Received(const UDPpacket &udp_pack) {
415         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
416
417         // ack to the remote
418         int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
419         if (diff > 0) {
420                 if (diff >= 32) {
421                         ctrl_out.hist = 0;
422                 } else {
423                         ctrl_out.hist <<= diff;
424                         ctrl_out.hist |= 1 << (diff - 1);
425                 }
426         } else if (diff < 0 && diff >= -32) {
427                 ctrl_out.hist |= 1 << (-diff - 1);
428         }
429         ctrl_out.ack = pack.header.ctrl.seq;
430         FlagRecv();
431
432         if (!HasHandler()) {
433                 return;
434         }
435
436         Packet::TControl ctrl_new = pack.header.ctrl;
437         Handler().Handle(udp_pack);
438
439         if (diff > 0) {
440                 // if the packet holds more recent information
441                 // check if remote failed to ack one of our packets
442                 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
443                 // should always be true, but you never know…
444                 if (diff > 0) {
445                         for (int i = 0; i < diff; ++i) {
446                                 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
447                                         Handler().OnPacketLost(ctrl_in.ack - 32 + i);
448                                 }
449                         }
450                 }
451                 // check for newly ack'd packets
452                 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); ++s) {
453                         if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
454                                 Handler().OnPacketReceived(s);
455                         }
456                 }
457                 ctrl_in = ctrl_new;
458         }
459 }
460
461 bool Packet::TControl::Acks(uint16_t s) const noexcept {
462         int16_t diff = int16_t(ack) - int16_t(s);
463         if (diff == 0) return true;
464         if (diff < 0 || diff > 32) return false;
465         return (hist & (1 << (diff - 1))) != 0;
466 }
467
468 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
469         Packet::Make<Packet::Ping>(udp_pack);
470         return Send(udp_pack, sock);
471 }
472
473
474 ostream &operator <<(ostream &out, const IPaddress &addr) {
475         const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
476         out << int(host[0])
477                 << '.' << int(host[1])
478                 << '.' << int(host[2])
479                 << '.' << int(host[3]);
480         if (addr.port) {
481                 out << ':' << SDLNet_Read16(&addr.port);
482         }
483         return out;
484 }
485
486
487 const char *Packet::Type2String(uint8_t t) noexcept {
488         switch (t) {
489                 case Ping::TYPE:
490                         return "Ping";
491                 case Login::TYPE:
492                         return "Login";
493                 case Join::TYPE:
494                         return "Join";
495                 case Part::TYPE:
496                         return "Part";
497                 case PlayerUpdate::TYPE:
498                         return "PlayerUpdate";
499                 case SpawnEntity::TYPE:
500                         return "SpawnEntity";
501                 case DespawnEntity::TYPE:
502                         return "DespawnEntity";
503                 case EntityUpdate::TYPE:
504                         return "EntityUpdate";
505                 case PlayerCorrection::TYPE:
506                         return "PlayerCorrection";
507                 default:
508                         return "Unknown";
509         }
510 }
511
512 template<class T>
513 void Packet::Payload::Write(const T &src, size_t off) noexcept {
514         if ((length - off) < sizeof(T)) {
515                 // dismiss out of bounds write
516                 return;
517         }
518         *reinterpret_cast<T *>(&data[off]) = src;
519 }
520
521 template<class T>
522 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
523         if ((length - off) < sizeof(T)) {
524                 // dismiss out of bounds read
525                 return;
526         }
527         dst = *reinterpret_cast<T *>(&data[off]);
528 }
529
530 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
531         uint8_t *dst = &data[off];
532         size_t len = min(maxlen, length - off);
533         if (src.size() < len) {
534                 memset(dst, '\0', len);
535                 memcpy(dst, src.c_str(), src.size());
536         } else {
537                 memcpy(dst, src.c_str(), len);
538         }
539 }
540
541 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
542         size_t len = min(maxlen, length - off);
543         dst.clear();
544         dst.reserve(len);
545         for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
546                 dst.push_back(data[off + i]);
547         }
548 }
549
550
551 void Packet::Login::WritePlayerName(const string &name) noexcept {
552         WriteString(name, 0, 32);
553 }
554
555 void Packet::Login::ReadPlayerName(string &name) const noexcept {
556         ReadString(name, 0, 32);
557 }
558
559 void Packet::Join::WritePlayer(const Entity &player) noexcept {
560         Write(player.ID(), 0);
561         Write(player.GetState(), 4);
562 }
563
564 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
565         Read(id, 0);
566 }
567
568 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
569         Read(state, 4);
570 }
571
572 void Packet::Join::WriteWorldName(const string &name) noexcept {
573         WriteString(name, 68, 32);
574 }
575
576 void Packet::Join::ReadWorldName(string &name) const noexcept {
577         ReadString(name, 68, 32);
578 }
579
580 void Packet::PlayerUpdate::WritePlayer(const Entity &player) noexcept {
581         Write(player.GetState(), 0);
582 }
583
584 void Packet::PlayerUpdate::ReadPlayerState(EntityState &state) const noexcept {
585         Read(state, 0);
586 }
587
588 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
589         Write(e.ID(), 0);
590         if (e.GetModel()) {
591                 Write(e.GetModel().GetModel().ID(), 4);
592         } else {
593                 Write(uint32_t(0), 4);
594         }
595         Write(e.GetState(), 8);
596         Write(e.Bounds(), 72);
597         uint32_t flags = 0;
598         if (e.WorldCollidable()) {
599                 flags |= 1;
600         }
601         Write(flags, 96);
602         WriteString(e.Name(), 100, 32);
603 }
604
605 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
606         Read(id, 0);
607 }
608
609 void Packet::SpawnEntity::ReadSkeletonID(uint32_t &id) const noexcept {
610         Read(id, 4);
611 }
612
613 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
614         EntityState state;
615         AABB bounds;
616         uint32_t flags = 0;
617         string name;
618
619         Read(state, 8);
620         Read(bounds, 72);
621         Read(flags, 96);
622         ReadString(name, 100, 32);
623
624         e.SetState(state);
625         e.Bounds(bounds);
626         e.WorldCollidable(flags & 1);
627         e.Name(name);
628 }
629
630 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
631         Write(id, 0);
632 }
633
634 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
635         Read(id, 0);
636 }
637
638 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
639         Write(count, 0);
640 }
641
642 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
643         Read(count, 0);
644 }
645
646 void Packet::EntityUpdate::WriteEntity(const Entity &entity, uint32_t num) noexcept {
647         uint32_t off = 4 + (num * 64);
648
649         Write(entity.ID(), off);
650         Write(entity.GetState(), off + 4);
651 }
652
653 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
654         Read(id, 4 + (num * 64));
655 }
656
657 void Packet::EntityUpdate::ReadEntityState(EntityState &state, uint32_t num) const noexcept {
658         uint32_t off = 4 + (num * 64);
659         Read(state, off + 4);
660 }
661
662 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
663         Write(s, 0);
664 }
665
666 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
667         Read(s, 0);
668 }
669
670 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
671         Write(player.GetState(), 2);
672 }
673
674 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
675         Read(state, 2);
676 }
677
678
679 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
680         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
681         switch (pack.Type()) {
682                 case Packet::Ping::TYPE:
683                         On(Packet::As<Packet::Ping>(udp_pack));
684                         break;
685                 case Packet::Login::TYPE:
686                         On(Packet::As<Packet::Login>(udp_pack));
687                         break;
688                 case Packet::Join::TYPE:
689                         On(Packet::As<Packet::Join>(udp_pack));
690                         break;
691                 case Packet::Part::TYPE:
692                         On(Packet::As<Packet::Part>(udp_pack));
693                         break;
694                 case Packet::PlayerUpdate::TYPE:
695                         On(Packet::As<Packet::PlayerUpdate>(udp_pack));
696                         break;
697                 case Packet::SpawnEntity::TYPE:
698                         On(Packet::As<Packet::SpawnEntity>(udp_pack));
699                         break;
700                 case Packet::DespawnEntity::TYPE:
701                         On(Packet::As<Packet::DespawnEntity>(udp_pack));
702                         break;
703                 case Packet::EntityUpdate::TYPE:
704                         On(Packet::As<Packet::EntityUpdate>(udp_pack));
705                         break;
706                 case Packet::PlayerCorrection::TYPE:
707                         On(Packet::As<Packet::PlayerCorrection>(udp_pack));
708                         break;
709                 default:
710                         // drop unknown or unhandled packets
711                         break;
712         }
713 }
714
715
716 Server::Server(const Config &conf, World &world)
717 : serv_sock(nullptr)
718 , serv_pack{ -1, nullptr, 0 }
719 , clients()
720 , world(world) {
721         serv_sock = SDLNet_UDP_Open(conf.port);
722         if (!serv_sock) {
723                 throw NetError("SDLNet_UDP_Open");
724         }
725
726         serv_pack.data = new Uint8[sizeof(Packet)];
727         serv_pack.maxlen = sizeof(Packet);
728 }
729
730 Server::~Server() {
731         delete[] serv_pack.data;
732         SDLNet_UDP_Close(serv_sock);
733 }
734
735
736 void Server::Handle() {
737         int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
738         while (result > 0) {
739                 HandlePacket(serv_pack);
740                 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
741         }
742         if (result == -1) {
743                 // a boo boo happened
744                 throw NetError("SDLNet_UDP_Recv");
745         }
746 }
747
748 void Server::HandlePacket(const UDPpacket &udp_pack) {
749         if (udp_pack.len < int(sizeof(Packet::Header))) {
750                 // packet too small, drop
751                 return;
752         }
753         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
754         if (pack.header.tag != Packet::TAG) {
755                 // mistagged packet, drop
756                 return;
757         }
758
759         ClientConnection &client = GetClient(udp_pack.address);
760         client.GetConnection().Received(udp_pack);
761 }
762
763 ClientConnection &Server::GetClient(const IPaddress &addr) {
764         for (ClientConnection &client : clients) {
765                 if (client.Matches(addr)) {
766                         return client;
767                 }
768         }
769         clients.emplace_back(*this, addr);
770         return clients.back();
771 }
772
773 void Server::Update(int dt) {
774         for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
775                 client->Update(dt);
776                 if (client->Disconnected()) {
777                         client = clients.erase(client);
778                 } else {
779                         ++client;
780                 }
781         }
782 }
783
784 }