Debian Codegraph @

src/cdogs/net_client.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4
5 Copyright (c) 2014-2016, 2019, 2021, 2024 Cong Xu
6 All rights reserved.
7
8 Redistribution and use in source and binary forms, with or without
9 modification, are permitted provided that the following conditions are met:
10
11 Redistributions of source code must retain the above copyright notice, this
12 list of conditions and the following disclaimer.
13 Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the documentation
15 and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 POSSIBILITY OF SUCH DAMAGE.
28 */
29 #include "net_client.h"
30
31 #include <errno.h>
32 #include <string.h>
33
34 #include "proto/nanopb/pb_decode.h"
35 #include "actors.h"
36 #include "campaigns.h"
37 #include "game_events.h"
38 #include "gamedata.h"
39 #include "log.h"
40 #include "net_server.h"
41 #include "player.h"
42 #include "utils.h"
43
44
45 NetClient gNetClient;
46
47
48 #define CONNECTION_WAIT_MS 5000
49 #define FIND_CONNECTION_WAIT_SECONDS 1
50 #define TIMEOUT_MS 5000
51
52
53 void NetClientInit(NetClient *n, const uint16_t port)
54 {
55 memset(n, 0, sizeof *n);
56 n->ClientId = -1; // -1 is unset
57 n->scanner = ENET_SOCKET_NULL;
58 n->port = port;
59 n->client = enet_host_create(NULL, 1, 2,
60 57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,
61 14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);
62 if (n->client == NULL)
63 {
64 LOG(LM_NET, LL_ERROR, "cannot create ENet client host");
65 }
66 CArrayInit(&n->ScannedAddrs, sizeof(ScanInfo));
67 CArrayInit(&n->scannedAddrBuf, sizeof(ScanInfo));
68 }
69 void NetClientTerminate(NetClient *n)
70 {
71 NetClientDisconnect(n);
72 n->peer = NULL;
73 enet_host_destroy(n->client);
74 n->client = NULL;
75 if (n->scanner != ENET_SOCKET_NULL)
76 {
77 if (enet_socket_shutdown(n->scanner, ENET_SOCKET_SHUTDOWN_READ_WRITE) != 0)
78 {
79 LOG(LM_NET, LL_ERROR,
80 "Failed to shutdown listen socket: %s", strerror(errno));
81 }
82 enet_socket_destroy(n->scanner);
83 n->scanner = ENET_SOCKET_NULL;
84 }
85 CArrayTerminate(&n->ScannedAddrs);
86 CArrayTerminate(&n->scannedAddrBuf);
87 }
88
89 static bool TryScanHost(NetClient *n, const enet_uint32 host);
90 void NetClientFindLANServers(NetClient *n)
91 {
92 // If we've already begun scanning, wait for that to finish
93 if (n->ScanTicks > 0)
94 {
95 return;
96 }
97
98 // Replace the scanned addresses with the buffer
99 CArray temp = n->ScannedAddrs;
100 n->ScannedAddrs = n->scannedAddrBuf;
101 n->scannedAddrBuf = temp;
102 CArrayClear(&n->scannedAddrBuf);
103
104 // Scan for servers on LAN using broadcast host
105 if (!TryScanHost(n, ENET_HOST_BROADCAST))
106 {
107 return;
108 }
109
110 n->ScanTicks = FIND_CONNECTION_WAIT_SECONDS * FPS_FRAMELIMIT;
111 }
112 static bool TryScanHost(NetClient *n, const enet_uint32 host)
113 {
114 // Create scanner socket if it has not been created yet
115 if (n->scanner == ENET_SOCKET_NULL)
116 {
117 n->scanner = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM);
118 if (n->scanner == ENET_SOCKET_NULL)
119 {
120 LOG(LM_NET, LL_ERROR, "Failed to create socket");
121 goto bail;
122 }
123 if (enet_socket_set_option(n->scanner, ENET_SOCKOPT_BROADCAST, 1) != 0)
124 {
125 LOG(LM_NET, LL_ERROR, "Failed to enable broadcast socket");
126 goto bail;
127 }
128 }
129
130 // Send the scanning message
131 ENetAddress addr;
132 addr.host = host;
133 addr.port = n->port;
134 // Send a dummy payload
135 char data = 42;
136 ENetBuffer sendbuf;
137 sendbuf.data = &data;
138 sendbuf.dataLength = 1;
139 if (enet_socket_send(n->scanner, &addr, &sendbuf, 1) !=
140 (int)sendbuf.dataLength)
141 {
142 LOG(LM_NET, LL_ERROR, "Failed to scan for server");
143 goto bail;
144 }
145
146 return true;
147
148 bail:
149 enet_socket_destroy(n->scanner);
150 n->scanner = ENET_SOCKET_NULL;
151 return false;
152 }
153
154 bool NetClientTryConnect(NetClient *n, const ENetAddress addr)
155 {
156 NetClientDisconnect(n);
157
158 char buf[256];
159 enet_address_get_host_ip(&addr, buf, sizeof buf);
160 LOG(LM_NET, LL_INFO, "Connecting client to %s:%u...", buf, addr.port);
161
162 /* Initiate the connection, allocating the two channels 0 and 1. */
163 n->peer = enet_host_connect(n->client, &addr, 2, 0);
164 if (n->peer == NULL)
165 {
166 LOG(LM_NET, LL_WARN, "No server connection found");
167 goto bail;
168 }
169
170 /* Wait milliseconds for the connection attempt to succeed. */
171 ENetEvent event;
172 if (enet_host_service(n->client, &event, CONNECTION_WAIT_MS) > 0 &&
173 event.type == ENET_EVENT_TYPE_CONNECT)
174 {
175 fprintf(stderr, "Connected.\n");
176 }
177 else
178 {
179 /* Either the 5 seconds are up or a disconnect event was */
180 /* received. Reset the peer in the event the 5 seconds */
181 /* had run out without any significant event. */
182 LOG(LM_NET, LL_WARN, "connection failed");
183 goto bail;
184 }
185
186 // Set disconnect timeout ms
187 enet_peer_timeout(n->peer, 0, 0, TIMEOUT_MS);
188
189 // Tell the server that this is a proper connection request
190 NetClientSendMsg(n, GAME_EVENT_CLIENT_CONNECT, NULL);
191
192 return NetClientIsConnected(n);
193
194 bail:
195 NetClientDisconnect(n);
196 return false;
197 }
198
199 static bool TryRecvScanForServerPort(
200 NetClient *n, const int timeoutMs,
201 NServerInfo *outInfo, ENetAddress *outAddr);
202 bool NetClientTryScanAndConnect(NetClient *n, const enet_uint32 host)
203 {
204 if (!TryScanHost(n, host))
205 {
206 return false;
207 }
208
209 // Wait for the scan to return
210 NServerInfo sinfo;
211 ENetAddress addr;
212 if (!TryRecvScanForServerPort(n, CONNECTION_WAIT_MS, &sinfo, &addr))
213 {
214 return false;
215 }
216
217 // Connect to address
218 return NetClientTryConnect(n, addr);
219 }
220 static bool TryRecvScanForServerPort(
221 NetClient *n, const int timeoutMs,
222 NServerInfo *outInfo, ENetAddress *outAddr)
223 {
224 CASSERT(n->scanner != ENET_SOCKET_NULL,
225 "cannot recv scans without scanner");
226 // Check for the reply, which will give us the server address
227 ENetSocketSet set;
228 ENET_SOCKETSET_EMPTY(set);
229 ENET_SOCKETSET_ADD(set, n->scanner);
230 if (enet_socketset_select(n->scanner, &set, NULL, timeoutMs) <= 0)
231 {
232 return false;
233 }
234
235 // Receive the reply
236 uint8_t buf[1024];
237 ENetBuffer recvbuf;
238 recvbuf.data = buf;
239 recvbuf.dataLength = sizeof buf;
240 const int recvlen = enet_socket_receive(n->scanner, outAddr, &recvbuf, 1);
241 if (recvlen <= 0)
242 {
243 return false;
244 }
245 pb_istream_t stream = pb_istream_from_buffer(buf, recvlen);
246 if (!pb_decode(&stream, NServerInfo_fields, outInfo))
247 {
248 LOG(LM_NET, LL_ERROR, "Failed to decode scan reply");
249 return false;
250 }
251 // Check the protocol version, if it doesn't match we can't connect
252 if (outInfo->ProtocolVersion != NET_PROTOCOL_VERSION)
253 {
254 LOG(LM_NET, LL_DEBUG, "Protocol mismatch; %d (theirs) != %d",
255 outInfo->ProtocolVersion, NET_PROTOCOL_VERSION);
256 return false;
257 }
258 outAddr->port = (enet_uint16)outInfo->ENetPort;
259 char ipbuf[256];
260 enet_address_get_host_ip(outAddr, ipbuf, sizeof ipbuf);
261 LOG(LM_NET, LL_DEBUG, "Found server at %s:%u", ipbuf, outInfo->ENetPort);
262 return true;
263 }
264
265 void NetClientDisconnect(NetClient *n)
266 {
267 if (n->peer)
268 {
269 LOG(LM_NET, LL_INFO, "disconnecting peer");
270 enet_peer_disconnect_now(n->peer, 0);
271 n->peer = NULL;
272 }
273 // Reset IDs so that when we start a server, we use our own IDs
274 n->ClientId = -1;
275 n->FirstPlayerUID = 0;
276 n->Ready = false;
277 // Also reset the scanned address buffer
278 CArrayClear(&n->ScannedAddrs);
279 CArrayClear(&n->scannedAddrBuf);
280 }
281
282 static void OnReceive(NetClient *n, ENetEvent event);
283 static void Scanning(NetClient *n);
284 void NetClientPoll(NetClient *n)
285 {
286 // Check to see if LAN servers have been scanned
287 Scanning(n);
288
289 if (!n->client || !n->peer)
290 {
291 return;
292 }
293
294 // Service the connection
295 int check;
296 do
297 {
298 ENetEvent event;
299 check = enet_host_service(n->client, &event, 0);
300 if (check < 0)
301 {
302 LOG(LM_NET, LL_ERROR, "connection error(%d)", check);
303 NetClientTerminate(n);
304 NetClientInit(n, n->port);
305 return;
306 }
307 else if (check > 0)
308 {
309 switch (event.type)
310 {
311 case ENET_EVENT_TYPE_RECEIVE:
312 OnReceive(n, event);
313 break;
314 case ENET_EVENT_TYPE_DISCONNECT:
315 LOG(LM_NET, LL_INFO, "disconnected");
316 NetClientDisconnect(n);
317 return;
318 default:
319 LOG(LM_NET, LL_ERROR, "Unexpected event type(%d)", (int)event.type);
320 break;
321 }
322 }
323 } while (check > 0);
324 }
325 static void Scanning(NetClient *n)
326 {
327 // If it's been too long, stop scanning
328 if (n->ScanTicks <= 0)
329 {
330 return;
331 }
332 n->ScanTicks--;
333
334 // Check to see if we have received the scan reply
335 ScanInfo sinfo;
336 while (TryRecvScanForServerPort(n, 0, &sinfo.ServerInfo, &sinfo.Addr))
337 {
338 // Check if we've seen this scan before
339 // This can happen occasionally, especially if the network is flaky
340 bool found = false;
341 CA_FOREACH(const ScanInfo, si, n->scannedAddrBuf)
342 if (si->Addr.host == sinfo.Addr.host &&
343 si->Addr.port == sinfo.Addr.port)
344 {
345 found = true;
346 break;
347 }
348 CA_FOREACH_END()
349 if (found)
350 {
351 continue;
352 }
353
354 // Save them into our buffer
355 // Calculate latency based on ticks
356 sinfo.LatencyMS =
357 (FIND_CONNECTION_WAIT_SECONDS * FPS_FRAMELIMIT - n->ScanTicks) *
358 1000 / FPS_FRAMELIMIT;
359 CArrayPushBack(&n->scannedAddrBuf, &sinfo);
360 // Also add them to the main collection, so we can find servers quickly
361 found = false;
362 CA_FOREACH(const ScanInfo, si, n->ScannedAddrs)
363 if (si->Addr.host == sinfo.Addr.host &&
364 si->Addr.port == sinfo.Addr.port)
365 {
366 found = true;
367 break;
368 }
369 CA_FOREACH_END()
370 if (!found)
371 {
372 CArrayPushBack(&n->ScannedAddrs, &sinfo);
373 }
374 }
375 }
376 static void OnReceive(NetClient *n, ENetEvent event)
377 {
378 const GameEventType msg = (GameEventType)*(uint32_t *)event.packet->data;
379 LOG(LM_NET, LL_TRACE, "recv msg(%u)", msg);
380 const GameEventEntry gee = GameEventGetEntry(msg);
381 if (gee.Enqueue)
382 {
383 if (gee.GameStart && !gMission.HasStarted)
384 {
385 LOG(LM_NET, LL_TRACE, "ignore game start gameEvent(%d)",
386 (int)gee.Type);
387 }
388 else
389 {
390 // Game event message; decode and add to event queue
391 LOG(LM_NET, LL_TRACE, "recv gameEvent(%d)", (int)gee.Type);
392 GameEvent e = GameEventNew(gee.Type);
393 if (gee.Fields != NULL)
394 {
395 NetDecode(event.packet, &e.u, gee.Fields);
396 }
397
398 // For actor events, check if UID is not for local player
399 // TODO: repeated code (see game_events.c)
400 int actorUID = -1;
401 bool actorIsLocal = false;
402 switch (gee.Type)
403 {
404 case GAME_EVENT_ACTOR_ADD:
405 // Note: ignore checking this event
406 break;
407 case GAME_EVENT_ACTOR_MOVE: actorUID = e.u.ActorMove.UID; break;
408 case GAME_EVENT_ACTOR_STATE: actorUID = e.u.ActorState.UID; break;
409 case GAME_EVENT_ACTOR_DIR: actorUID = e.u.ActorDir.UID; break;
410 case GAME_EVENT_ACTOR_SLIDE: actorUID = e.u.ActorSlide.UID; break;
411 case GAME_EVENT_ACTOR_SWITCH_GUN: actorUID = e.u.ActorSwitchGun.UID; break;
412 case GAME_EVENT_ACTOR_PICKUP_ALL: actorUID = e.u.ActorPickupAll.UID; break;
413 case GAME_EVENT_ACTOR_USE_AMMO: actorUID = e.u.UseAmmo.UID; break;
414 case GAME_EVENT_ACTOR_MELEE: actorUID = e.u.Melee.UID; break;
415 case GAME_EVENT_ACTOR_PILOT: actorUID = e.u.Pilot.UID;
416 break;
417 case GAME_EVENT_GUN_FIRE:
418 if (e.u.GunFire.IsGun)
419 {
420 actorUID = e.u.GunFire.ActorUID;
421 }
422 break;
423 case GAME_EVENT_GUN_RELOAD:
424 actorIsLocal = PlayerIsLocal(e.u.GunReload.PlayerUID);
425 break;
426 case GAME_EVENT_GUN_STATE: actorUID = e.u.GunState.ActorUID; break;
427 default: break;
428 }
429 if (actorUID >= 0)
430 {
431 actorIsLocal = ActorIsLocalPlayer(actorUID);
432 }
433 if (actorIsLocal)
434 {
435 LOG(LM_NET, LL_TRACE, "game event is for local player, ignoring");
436 }
437 else
438 {
439 GameEventsEnqueue(&gGameEvents, e);
440 }
441 }
442 }
443 else
444 {
445 switch (gee.Type)
446 {
447 case GAME_EVENT_CLIENT_ID:
448 {
449 CASSERT(
450 n->ClientId == -1,
451 "unexpected client ID message, already set");
452 NClientId cid;
453 NetDecode(event.packet, &cid, NClientId_fields);
454 LOG(LM_NET, LL_DEBUG, "recv clientId(%u) uid(%u)",
455 cid.Id, cid.FirstPlayerUID);
456 n->ClientId = (int)cid.Id;
457 n->FirstPlayerUID = (int)cid.FirstPlayerUID;
458 }
459 break;
460 case GAME_EVENT_CAMPAIGN_DEF:
461 if (gCampaign.IsLoaded)
462 {
463 LOG(LM_NET, LL_INFO, "WARNING: unexpected campaign def msg received");
464 }
465 else
466 {
467 LOG(LM_NET, LL_DEBUG, "NetClient: received campaign def, loading...");
468 NCampaignDef def;
469 NetDecode(event.packet, &def, NCampaignDef_fields);
470 gCampaign.Entry.Mode = (GameMode)def.GameMode;
471 // Normalise the path
472 char buf[CDOGS_PATH_MAX];
473 GetDataFilePath(buf, def.Path);
474 CampaignEntry entry;
475 if (CampaignEntryTryLoad(&entry, buf, GAME_MODE_NORMAL) &&
476 CampaignLoad(&gCampaign, &entry))
477 {
478 gCampaign.IsClient = true;
479 gCampaign.MissionIndex = def.Mission;
480 }
481 else
482 {
483 LOG(LM_NET, LL_ERROR, "failed to load campaign def %s",
484 def.Path);
485 gCampaign.IsError = true;
486 }
487 }
488 break;
489 case GAME_EVENT_NET_GAME_START:
490 LOG(LM_NET, LL_DEBUG, "recv game start ready(%s)",
491 n->Ready ? "yes" : "no");
492 // Don't ready-up unless we're ready
493 if (n->Ready)
494 {
495 gMission.HasStarted = true;
496 }
497 break;
498 default:
499 CASSERT(false, "unexpected message type");
500 break;
501 }
502 }
503 enet_packet_destroy(event.packet);
504 }
505
506 void NetClientFlush(NetClient *n)
507 {
508 if (n->client == NULL) return;
509 enet_host_flush(n->client);
510 }
511
512 void NetClientSendMsg(NetClient *n, const GameEventType e, const void *data)
513 {
514 if (!NetClientIsConnected(n))
515 {
516 return;
517 }
518
519 LOG(LM_NET, LL_TRACE, "NetClient: send msg type %d", (int)e);
520 enet_peer_send(n->peer, 0, NetEncode(e, data));
521 }
522
523 bool NetClientIsConnected(const NetClient *n)
524 {
525 return n->client && n->peer;
526 }