-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_main.cpp
584 lines (413 loc) · 11.3 KB
/
net_main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
NET_MAIN.CPP v0.12
Network main functionality module.
*/
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include "main.h"
#include "net.h"
/*=============================================================================
* GLOBALS
*/
connectionC net_connections[NET_MAX_CONNECTIONS];
connectionC *net_connections_end = net_connections + sizeof(net_connections)/sizeof(connectionC);
static int listen_fd;
/*=============================================================================
* CONNECTED
* Just tells if the connection with server (ie: net_connections[0]) is up.
*/
int netConnected()
{
return (listen_fd == -1) && (net_connections->socket_fast != -1);
}
/*=============================================================================
* SLEEP
* Not really a network function, but very useful when making cross connections
* between client/server/daemon.
*/
int netSleep(int msec)
{
unsigned long t;
struct timeval s;
gettimeofday(&s, NULL);
t = s.tv_sec * 1000*1000 + s.tv_usec + msec * 1000;
do gettimeofday(&s, NULL);
while(t > s.tv_sec * 1000*1000 + s.tv_usec);
}
/*=============================================================================
* ERR and ERRB
* Generic error output function.
*/
int netErr(char *fe)
{
pe("%s: %s.\n", fe, strerror(errno));
return -1;
}
int netErrB(char *fe, char *bfe)
{
pe("%s (%s): %s.\n", fe, bfe, strerror(errno));
return -1;
}
/*=============================================================================
* CLEAR
* Cleans a connectionC structure.
*/
int netClear(connectionC *c)
{
memset(c, 0, sizeof(connectionC));
c->fast_p = c->fast_bf;
c->socket_safe = -1;
c->socket_fast = -1;
}
/*=============================================================================
* FREE
* Frees a connection structure resources.
*/
int netFree(connectionC *c)
{
if(c->name) free(c->name);
if(c->socket_safe > 0) close(c->socket_safe);
if(c->socket_fast > 0) close(c->socket_fast);
}
/*=============================================================================
* CLOSE
*/
int netClose(connectionC *c)
{
netFree(c);
netClear(c);
}
/*=============================================================================
* INIT
* Cleans up everything, prepares for a new network session.
*/
int netInit()
{
connectionC *c;
for(c = net_connections; c < net_connections_end; c++) netClear(c);
listen_fd = -1;
}
/*=============================================================================
* RESET
* Closes and cleans a network session.
* Can be called at any time both to shut all connections and to prepare for a
* new network session.
*/
void netReset()
{
connectionC *c;
for(c = net_connections; c < net_connections_end; c++) netFree(c);
if(listen_fd != -1) close(listen_fd);
netInit();
}
/*=============================================================================
* CONNECTION LOST
*/
int netConnectionLost(connectionC *c)
{
pe("connection with %s (%s) lost.\n", c->name, c->addr);
netClose(c);
return -1;
}
/*=============================================================================
* WAIT SOCKET
* Waits for readable data to come from a socket within 2".
*/
int netWaitSocket(int sk)
{
struct timeval tm;
fd_set fds[1];
int e;
// wait up to 2" for the listen_fd to show off //
tm.tv_sec = 2;
tm.tv_usec = 0;
FD_ZERO(fds);
FD_SET(sk, fds);
e = select(sk + 1, fds, NULL, NULL, &tm);
if(e == -1)
{
netErr("select");
return -1;
}
// if something arrived is all ok... //
if(FD_ISSET(sk, fds)) return 0;
// if not, we timed out! //
errno = ETIMEDOUT;
netErr("netWaitSocket");
return -1;
}
/*=============================================================================
* RESOLVE
* Attempts to resolve a IP address.
*/
char *netResolve(char *name)
{
char fe[] = "netResolve: ";
struct hostent *host;
struct in_addr *addr;
host = gethostbyname(name);
if(host == NULL)
{
// hstrerror is obsolete... shall I remove it? //
pe("%s%s.\n", fe, hstrerror(h_errno));
return NULL;
}
addr = (struct in_addr *)host->h_addr_list[0];
return inet_ntoa(*addr);
}
/*=============================================================================
* CREATE AND BIND SOCKET
*/
int netCreateAndBindSocket(int socket_type, int port)
{
char fe[] = "netCreateAndBindSocket: ";
struct sockaddr_in addr;
int socket_fd;
int yes; // needed by setsockopt() //
int e;
// create a socket //
socket_fd = socket(AF_INET, socket_type, 0);
if(socket_fd == -1)
{
netErrB(fe, "socket");
return -1;
}
yes = 1;
e = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
// setsockopt failing should not be a critical error //
if(e == -1) pe("%ssetsockopt failed: %s.\n", fe, strerror(errno));
// bind socket //
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);
memset(&(addr.sin_zero), 0, 8);
e = bind(socket_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr));
if(e == -1)
{
close(socket_fd);
netErrB(fe, "bind");
return -1;
}
return socket_fd;
}
/*=============================================================================
* CREATE AND CONNECT SOCKET
*/
int netCreateAndConnectSocket(int socket_type, char *ipstr, int port)
{
char fe[] = "netCreateAndConnectSocket: ";
struct sockaddr_in addr;
int socket_fd;
int e;
// prepare struct sockaddr, check ipstr //
if(!inet_aton(ipstr, &addr.sin_addr))
{
pe("%sinvalid ip address: %s.\n", fe, ipstr);
return -1;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
memset(&(addr.sin_zero), 0, 8);
// create a socket
socket_fd = socket(AF_INET, socket_type, 0);
if(socket_fd == -1)
{
netErrB(fe, "socket");
return -1;
}
// connect socket
for(int t = 0; t < 20; t++)
{
e = connect(socket_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr));
if(e != -1) break;
netSleep(100);
}
if(e == -1)
{
close(socket_fd);
netErrB(fe, "connect");
return -1;
}
return socket_fd;
}
/*=============================================================================
* CONNECT
* Creates a full connection with a server.
*/
int netConnect(char *name)
{
char introbf[200];
connectionC *c;
char *ip;
int fd, e;
// prepare for a new connection
netReset();
ip = netResolve(name);
if(ip == NULL) goto ERROR;
// initial connection attempt
pf("connecting to %s...\n", name);
fd = net_safeConnect(ip);
if(fd == -1) goto ERROR;
// init the connection struct
c = net_connections;
c->socket_safe = fd;
c->name = (char*)malloc(strlen(name) + 1);
strcpy(c->name, name);
strcpy(c->addr, ip);
// send intro string
net_introClientWrite(introbf);
e = net_safeSend(c, (unsigned char*)introbf, strlen(introbf)+1);
if(e == -1) goto ERROR;
// wait for server intro //
if(netWaitSocket(c->socket_safe)) goto ERROR;
// read server intro //
e = net_safeRecv(c, (unsigned char*)introbf, sizeof(introbf));
if(e == -1) goto ERROR;
c->fast_bf[50] = '\0'; // ensure termination //
if(net_introServerRead(introbf))
{
pe("netConnect: bad intro from sv, aborting\n");
goto ERROR;
}
// ok, establish fast connection //
pf("establishing main connection...\n");
e = net_fastConnect(c); // net_fastConnect() will also initialize c->socket_fast //
if(e == -1) goto ERROR;
// OK! //
pf("connected with server %s (%s).\n", c->name, c->addr);
return 0;
ERROR:
netReset();
return -1;
}
/*=============================================================================
* ACCEPT NEW CONNECTION
* Establishes an incoming connection.
*/
int netAcceptNewConnection(int lfd, connectionC *c)
{
char introbf[200];
char *n;
int fd, e;
// if c == NULL, connection must be discarded //
if(!c) return close(net_safeAccept(lfd, 0));
// accept incoming connection, and store address in c->addr //
fd = net_safeAccept(lfd, c->addr);
if(fd == -1) return -1;
// safe connection established //
c->socket_safe = fd;
pf("incoming connection from %s.\n", c->addr);
// wait for client introduction //
if(netWaitSocket(c->socket_safe)) goto ERROR;
// read client intro //
e = net_safeRecv(c, (unsigned char*)introbf, sizeof(introbf));
if(e == -1) goto ERROR;
// check intro //
n = net_introClientRead(introbf);
if(n == NULL)
{
pe("netAccept...: bad intro from client, refused\n");
goto ERROR;
}
c->name = n;
// send introduction: GameString, PlayerID, game args //
net_introServerWrite(introbf, c - net_connections);
e = net_safeSend(c, (unsigned char*)introbf, strlen(introbf)+1);
if(e == -1) goto ERROR;
// ok, establish fast connection //
e = net_fastAccept(c); // net_fastAccept() will also set c->socket_fast //
if(e == -1) goto ERROR;
// OK! //
pf("%s connected.\n", c->name);
*c->fast_p++ = 0; // add some empty data, just to make server consider the new one! //
return 0;
ERROR:
netClose(c);
return -1;
}
/*=============================================================================
* LISTEN
* Initializes server stuff.
*/
int netListen()
{
netReset();
listen_fd = net_safeListen();
if(listen_fd == -1) goto ERROR;
pf("waiting for incoming connections.\n");
// anything else? //
return 0;
ERROR:
netReset();
return -1;
}
/*=============================================================================
* LOOP
* Main network loop, for both client and server.
* Polls network for incoming connections and data.
* Returns -1 when the network goes down.
*/
int netLoop()
{
connectionC *c;
struct timeval tm;
fd_set fds[1];
int max, e;
// initialize file-descriptor set, to use with select() //
FD_ZERO(fds);
max = listen_fd; // for client listen_fd is -1! //
if(listen_fd != -1) FD_SET(listen_fd, fds);
for(c = net_connections; c < net_connections_end; c++) if(c->socket_safe != -1)
{
FD_SET(c->socket_safe, fds);
FD_SET(c->socket_fast, fds);
if(c->socket_safe > max) max = c->socket_safe;
if(c->socket_fast > max) max = c->socket_fast;
}
// set no timeout //
tm.tv_sec = 0;
tm.tv_usec = 0;
// select()! //
e = select(max + 1, fds, NULL, NULL, &tm);
if(e == -1) // unlikely to happen, but who knows? //
{
netErr("select");
return -1;
}
// recv incoming data //
// mantaining loop if() as i suppose that FD_ISSET may not be fast //
for(c = net_connections; c < net_connections_end; c++) if(c->socket_safe != -1)
{
//debug if(listen_fd == -1) pf("server socket: %d\n", c->socket_fast), exit(0);
if(FD_ISSET(c->socket_fast, fds)) net_fastRecv(c);
if(c->socket_fast != -1)
if(FD_ISSET(c->socket_safe, fds)) net_packRecv(c);
}
// check listen socket //
if(listen_fd != -1 && FD_ISSET(listen_fd, fds))
{
// search for an empty connection struct //
for(c = net_connections; c < net_connections_end && c->name; c++);
if(c >= net_connections_end) c = 0; // no connection available, drop request //
netAcceptNewConnection(listen_fd, c);
}
// all done //
if(max == -1) netReset();
return max;
}
/*=============================================================================
* Initializer
*/
class netInitC { public:
netInitC() { netInit(); }
} static netInitializer;
//EOF =========================================================================