summaryrefslogtreecommitdiffhomepage
path: root/NetEx/NetLink.cpp
blob: 10e817af56d6cd035102a68c221ac4ffd2f93239 (plain)
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
/*  Starshatter: The Open Source Project
    Copyright (c) 2021-2022, Starshatter: The Open Source Project Contributors
    Copyright (c) 2011-2012, Starshatter OpenSource Distribution Contributors
    Copyright (c) 1997-2006, Destroyer Studios LLC.

     AUTHOR:       John DiCamillo


     OVERVIEW
     ========
     Network (IP) Socket Wrapper Implementation
*/

#include "NetLink.h"
#include "NetGram.h"
#include "NetMsg.h"
#include "NetPeer.h"
#include "NetLayer.h"

// +-------------------------------------------------------------------+

DWORD WINAPI NetLinkProc(LPVOID link);

const DWORD UDP_HEADER_SIZE = 34;

// +-------------------------------------------------------------------+
// client-side ctor
NetLink::NetLink()
    : hnet(0), shutdown(false), traffic_time(50), resend_time(300),
      packets_sent(0), packets_recv(0), bytes_sent(0), bytes_recv(0), retries(0), drops(0), lag(100)
{
    ZeroMemory(lag_samples, sizeof(lag_samples));
    lag_index = 0;

    DWORD thread_id = 0;
    hnet = CreateThread(0, 4096, NetLinkProc, (LPVOID) this, 0, &thread_id);
}

// server-side ctor
NetLink::NetLink(NetAddr& a)
    : addr(a), hnet(0), shutdown(false), traffic_time(50), resend_time(300),
      packets_sent(0), packets_recv(0), bytes_sent(0), bytes_recv(0), retries(0), drops(0), lag(100)
{
    ZeroMemory(lag_samples, sizeof(lag_samples));
    lag_index = 0;

    sock.bind(addr);
    DWORD thread_id = 0;
    hnet = CreateThread(0, 4096, NetLinkProc, (LPVOID) this, 0, &thread_id);
}

NetLink::~NetLink()
{
    if (!shutdown) {
        shutdown = true;
    }

    if (hnet) {
        WaitForSingleObject(hnet, 2000);
        CloseHandle(hnet);
    }

    send_list.destroy();    // packets waiting to be ack'ed must be destroyed
    recv_list.clear();      // received messages are owned by the peers
    peer_list.destroy();    // but the net link owns the peers!
}

// +--------------------------------------------------------------------+

static DWORD base_netid = 1000;

DWORD
NetLink::AddPeer(const char* a, WORD p)
{
    return AddPeer(NetAddr(a, p));
}

DWORD
NetLink::AddPeer(DWORD a, WORD p)
{
    return AddPeer(NetAddr(a, p));
}

DWORD
NetLink::AddPeer(const NetAddr& a)
{
    if (!a.IPAddr())
        return 0;

    NetPeer* peer = FindPeer(a);
    const std::lock_guard<std::mutex> lock(sync);

    if (!peer) {
        peer = new NetPeer(a, base_netid++);
        if (peer)
            peer_list.append(peer);
    }

    if (peer)
        return peer->NetID();

    return 0;
}

// +--------------------------------------------------------------------+

bool
NetLink::SendMessage(DWORD nid, void* d, int l, BYTE f)
{
    return SendMessage(new NetMsg(nid, d, l, f));
}

bool
NetLink::SendMessage(DWORD nid, BYTE type, const char* text, int len, BYTE f)
{
    return SendMessage(new NetMsg(nid, type, text, len, f));
}

bool
NetLink::SendMessage(NetMsg* msg)
{
    if (msg) {
        if (msg->Type() != NetMsg::INVALID  &&
             msg->Type() <  NetMsg::RESERVED &&
             msg->NetID()) {

            NetPeer* p = FindPeer(msg->NetID());
            if (p)
                return p->SendMessage(msg);
        }

        delete msg;
    }

    return false;
}

// +--------------------------------------------------------------------+

NetMsg*
NetLink::GetMessage(DWORD netid)
{
    NetMsg* msg = 0;

    // receive from specific host:
    if (netid) {
        NetPeer* p = FindPeer(netid);
        if (p) {
            msg = p->GetMessage();

            sync.lock();
            recv_list.remove(msg);
            sync.unlock();
        }
    }

    return msg;
}

// +--------------------------------------------------------------------+

NetMsg*
NetLink::GetMessage()
{
    NetMsg* msg = 0;

    // get first available packet:

    // Double-checked locking:
    if (recv_list.size()) {
        sync.lock();
        if (recv_list.size()) {
            msg = recv_list.removeIndex(0);
        }
        sync.unlock();

        if (msg && msg->NetID()) {
            NetPeer* p = FindPeer(msg->NetID());
            if (p) {
                p->GetMessage();  // remove message from peer's list
                                  // don't do this inside of sync block -
                                  // it might cause a deadlock
            }
        }
    }

    return msg;
}

// +--------------------------------------------------------------------+

void
NetLink::Shutdown()
{
    shutdown = true;
}

// +--------------------------------------------------------------------+

DWORD WINAPI NetLinkProc(LPVOID link)
{
    NetLink* netlink = (NetLink*) link;

    if (netlink)
        return netlink->DoSendRecv();

    return (DWORD) E_POINTER;
}

DWORD
NetLink::DoSendRecv()
{
    while (!shutdown) {
        ReadPackets();
        SendPackets();

        // discard reeeeally old peers:
        sync.lock();

        ListIter<NetPeer> iter = peer_list;
        while (!shutdown && ++iter) {
            NetPeer* peer = iter.value();

            if ((NetLayer::GetUTC() - peer->LastReceiveTime()) > 300)
                delete iter.removeItem();
        }

        sync.unlock();
        Sleep(traffic_time);
    }

    return 0;
}

void
NetLink::ReadPackets()
{
    while (!shutdown && sock.select(NetSock::SELECT_READ) > 0) {
        NetGram* gram = RecvNetGram();

        if (gram && gram->IsReliable()) {
            if (gram->IsAck()) {
                ProcessAck(gram);
                delete gram;
            }
            else {
                AckNetGram(gram);
                QueueNetGram(gram);
            }
        }
        else {
            QueueNetGram(gram);
        }
    }
}

void
NetLink::SendPackets()
{
    if (shutdown)
        return;

    if (sock.select(NetSock::SELECT_WRITE) > 0) {
        DoRetries();
    }

    const std::lock_guard<std::mutex> lock(sync);

    ListIter<NetPeer> iter = peer_list;
    while (!shutdown && ++iter) {
        NetPeer* p = iter.value();
        NetGram* g = 0;

        do {
            if (sock.select(NetSock::SELECT_WRITE) > 0) {
                g = p->ComposeGram();
                if (g) {
                    SendNetGram(g);
                }
            }
            else {
                g = 0;
            }
        }
        while (!shutdown && g);
    }
}

// +--------------------------------------------------------------------+

void
NetLink::SendNetGram(NetGram* gram)
{
    if (gram) {
        if (gram->IsReliable()) {
            send_list.append(gram);
        }

        int err = sock.sendto(gram->Body(), gram->Address());

        if (err < 0) {
            err = NetLayer::GetLastError();
        }
        else {
            packets_sent += 1;
            bytes_sent   += gram->Size() + UDP_HEADER_SIZE;
        }

        if (!gram->IsReliable())
            delete gram;
    }
}

NetGram*
NetLink::RecvNetGram()
{
    NetAddr from;
    Text msg = sock.recvfrom(&from);

    packets_recv += 1;
    bytes_recv   += msg.length() + UDP_HEADER_SIZE;

    return new NetGram(from, msg);
}

// +--------------------------------------------------------------------+

void
NetLink::AckNetGram(NetGram* gram)
{
    if (gram) {
        NetGram ack = gram->Ack();

        int err = sock.sendto(ack.Body(), gram->Address());
        if (err < 0)
            err = NetLayer::GetLastError();
    }
    else {
        Print("NetLink::AckNetGram( NULL!!! )\n");
    }
}

void
NetLink::ProcessAck(NetGram* gram)
{
    if (!shutdown && send_list.size()) {
        sync.lock();

        // remove the ack flag:
        gram->ClearAck();

        // find a matching outgoing packet:
        int sent = send_list.index(gram);
        if (sent >= 0) {
            NetGram* orig = send_list.removeIndex(sent);
            DWORD    time = NetLayer::GetTime();
            DWORD    msec = time - orig->SendTime();
            double   dlag = 0.75 * lag + 0.25 * msec;

            if (lag_index >= 10) lag_index = 0;
            lag_samples[lag_index++] = msec;

            sync.unlock();
            NetPeer* peer = FindPeer(orig->Address());
            sync.lock();
            if (peer)
                peer->SetLastReceiveTime(NetLayer::GetUTC());

            delete orig;

            lag = (DWORD) dlag;

            if (lag > 100)
                resend_time = 3 * lag;
            else
                resend_time = 300;
        }
        sync.unlock();
    }
}

void
NetLink::QueueNetGram(NetGram* gram)
{
    if (!shutdown) {
        DWORD    sequence = 0;
        NetPeer* peer     = FindPeer(gram->Address());
        const std::lock_guard<std::mutex> lock(sync);

        if (peer) {
            sequence = peer->Sequence();
        }
        else {
            peer = new NetPeer(gram->Address(), base_netid++);
            if (peer)
                peer_list.append(peer);
        }

        if (!gram->IsReliable()) {
            if (gram->Sequence() < sequence) {  // discard, too old
                delete gram;
                return;
            }
        }

        // sort this gram into the recv list(s) based on sequence:
        if (peer) {
            peer->ReceiveGram(gram, &recv_list);
        }
    }
}

// +--------------------------------------------------------------------+

void
NetLink::DoRetries()
{
    if (!shutdown) {
        const std::lock_guard<std::mutex> lock(sync);

        if (send_list.size()) {
            int time = (int) NetLayer::GetTime();

            ListIter<NetGram> iter = send_list;
            while (!shutdown && ++iter) {
                NetGram* gram = iter.value();

                // still trying ?
                if (gram->Retries() > 0) {
                    DWORD last_send = gram->SendTime();
                    DWORD delta     = time - last_send;

                    if (delta > resend_time) {
                        gram->Retry();
                        sock.sendto(gram->Body(), gram->Address());
                        retries++;
                    }
                }

                // oh, give it up:
                else {
                    iter.removeItem();
                    delete gram;
                    drops++;
                }
            }
        }
    }
}

// +--------------------------------------------------------------------+

NetPeer*
NetLink::FindPeer(DWORD netid)
{
    const std::lock_guard<std::mutex> lock(sync);
    NetPeer* peer = 0;

    ListIter<NetPeer> iter = peer_list;
    while (++iter && !peer) {
        NetPeer* p = iter.value();

        if (p->NetID() == netid)
            peer = p;
    }

    return peer;
}

NetPeer*
NetLink::FindPeer(const NetAddr& a)
{
    const std::lock_guard<std::mutex> lock(sync);
    NetPeer* peer = 0;

    ListIter<NetPeer> iter = peer_list;
    while (++iter && !peer) {
        NetPeer* p = iter.value();

        if (p->Address() == a)
            peer = p;
    }

    return peer;
}