-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
1453 lines (1164 loc) · 38.2 KB
/
main.cpp
File metadata and controls
1453 lines (1164 loc) · 38.2 KB
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include <errno.h>
#include <cstdlib>
#include <cstdio>
#include <csignal>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include "server.h"
#include "exttask.h"
#if THIS_TARGET == NetBSD_Target
#include <sys/resource.h>
#include <util.h>
#endif
// Local types...
// Local prototypes...
static int errorConditions();
static ipaddr_t ipAddress(trunknode_t&, ipaddr_t, bool);
static bool getResources();
static bool isPacketSizeValid(size_t, uint16_t, size_t, ipaddr_t);
static int normalConditions();
static void releaseResources();
static void sigHup(int);
static void sigInt(int);
static int waitingForNodeTable();
// Global data...
bool dumpIncoming = false;
int64_t statTimeBase = now();
int sClient = -1;
uint16_t acnetPort = ACNET_PORT;
TaskPoolMap taskPoolMap;
// Local variables...
static int sClientTcp = -1;
static nodename_t tcpNodeName;
static bool defaultNodeFallback = true;
#ifndef NO_REPORT
static bool sendReport = false;
#endif
bool termSignal = false;
static bool termApp = false;
static int (*nodeTableConstraints)() = waitingForNodeTable;
static int64_t currTime = 0;
struct CmdLineArgs {
trunknode_t myNode;
bool standAlone;
bool alternate;
bool tcpClients;
uint16_t altPort;
std::set<taskhandle_t> taskReject;
CmdLineArgs() :
standAlone(false), alternate(false), tcpClients(false)
{
}
bool proc(int argc, char **argv)
{
for (int ii = 1; ii < argc; ++ii) {
char const* curPtr = argv[ii];
if (*curPtr == '-') {
bool done = false;
++curPtr;
while (!done)
switch (*curPtr++) {
case '\0':
done = true;
break;
case 'n':
if (!*curPtr) {
if (ii < argc - 1 && argv[ii + 1][0] != '-')
curPtr = argv[++ii];
else {
printf("missing trunk/node argument to '-n' option\n\n");
return false;
}
}
if (!getTrunkNode(&curPtr, myNode, '\0')) {
printf("Bad trunk/node value\n\n");
return false;
}
break;
case 'H':
if (!*curPtr) {
if (ii < argc - 1 && argv[ii + 1][0] != '-')
curPtr = argv[++ii];
else {
printf("missing name argument to '-H' option\n\n");
return false;
}
}
setMyHostName(nodename_t(ator(curPtr)));
done = true;
break;
case 's':
standAlone = true;
break;
case 'a':
alternate = true;
if (!*curPtr) {
if (ii < argc - 1 && isdigit(argv[ii + 1][0]))
curPtr = argv[++ii];
else {
printf("missing port argument to '-a' option\n\n");
return false;
}
}
if (!getAltPort(&curPtr)) {
printf("Bad port value\n");
return false;
}
done = true;
break;
case 't':
tcpClients = true;
if (!*curPtr) {
if (ii < argc - 1 && argv[ii + 1][0] != '-')
curPtr = argv[++ii];
else {
printf("missing name argument to '-t' option\n\n");
return false;
}
}
tcpNodeName = nodename_t(ator(curPtr));
done = true;
break;
case 'r':
if (!*curPtr) {
if (ii < argc - 1 && argv[ii + 1][0] != '-')
curPtr = argv[++ii];
else {
printf("missing task name list to '-r' option\n\n");
return false;
}
}
getTaskRejectList(curPtr);
done = true;
break;
case 'f':
defaultNodeFallback = false;
syslog(LOG_NOTICE, "default node fallback is off");
break;
case 'h':
case '?':
return false;
default:
printf("Unknown option '-%c'\n\n", curPtr[-1]);
return false;
}
} else {
printf("unknown argument -- '%s'\n\n", curPtr);
return false;
}
}
return true;
}
void showUsage()
{
printf("Usage: acnetd [-h] [-s -nTRUNKNODE]\n"
" -h display help\n"
" -s stand-alone mode -- don't try to download\n"
" ACNET node tables\n"
" -t name allow TCP client connections on host name\n"
" -r list comma seperated list of task handles to reject on TCP connections\n"
" -H name sets the ACNET host name of this node\n"
" -n TRUNKNODE sets the current trunk and node to the\n"
" specified four hex digits\n"
" -f turn off default node fallback\n"
" -a port use alternate port\n");
}
void getTaskRejectList(std::string s)
{
std::string name;
std::istringstream is(s);
while (getline(is, s, ',')) {
taskReject.insert(taskhandle_t(ator(s.c_str())));
syslog(LOG_NOTICE, "rejecting requests to task '%s'", s.c_str());
}
}
bool getAltPort(char const** const buf)
{
unsigned long v = strtol(*buf, NULL, 0);
if (v != 0 && v != ACNET_CLIENT_PORT && v <= 65535) {
altPort = (uint16_t) v;
return true;
}
return false;
}
bool getTrunkNode(char const** const buf, trunknode_t& node, char endCh)
{
uint16_t _node = 0;
while (true) {
char c = tolower(**buf);
if (isdigit(c))
_node = _node * 16 + (c - '0');
else if (c >= 'a' && c <= 'f')
_node = _node * 16 + (10 + (c - 'a'));
else if (c == endCh) {
node = trunknode_t(_node);
return true;
} else
return false;
(*buf)++;
}
}
bool getTrunkNodeAddrPair(char const* buf, trunknode_t& node,
uint32_t& addr)
{
if (getTrunkNode(&buf, node, ':') && !node.isBlank())
if (*buf == ':')
if ((addr = ipAddr(++buf)) != 0)
return true;
return false;
}
} cmdLineArgs;
bool rejectTask(taskhandle_t const task)
{
return cmdLineArgs.taskReject.find(task) != cmdLineArgs.taskReject.end();
}
void dumpIncomingAcnetPackets(bool const status)
{
dumpIncoming = status;
syslog(LOG_NOTICE, "Dumping incoming ACNET packets: %s", status ? "ON" : "OFF");
}
int64_t currentTimeMillis()
{
struct timeval now;
gettimeofday(&now, 0);
return now.tv_sec * 1000LL + now.tv_usec / 1000LL;
}
int64_t now()
{
if (!currTime)
currTime = currentTimeMillis();
return currTime;
}
static void getCurrentTime()
{
currTime = currentTimeMillis();
}
// This function tries to get all the resources needed for the ACNET
// protocol. This means, of course, the datagram socket sitting at port
// ACNET_PORT or the user specified port. But it also includes the
// local datagram socket used to communicate with local clients.
static bool getResources()
{
// Initialize the random number generator. We use random numbers to
// select a bank of IDs for requests and for replies.
srandom(time(0));
// Open the network socket(s).
if (networkInit(acnetPort)) {
#if THIS_TARGET == Darwin_Target
#define PLATFORM_INADDR INADDR_ANY
#else
#define PLATFORM_INADDR INADDR_LOOPBACK
#endif
if (-1 != (sClient = allocSocket(PLATFORM_INADDR, ACNET_CLIENT_PORT, 128 * 1024, 1024 * 1024))) {
setMyIp();
if (cmdLineArgs.tcpClients) {
if (-1 != (sClientTcp = allocClientTcpSocket(INADDR_ANY, ACNET_CLIENT_PORT, 128 * 1024, 128 * 1024)))
syslog(LOG_NOTICE, "TCP client interface enabled");
else
syslog(LOG_ERR, "unable to allocate client TCP socket -- %m");
}
return true;
}
networkTerm();
}
return false;
}
void cancelReqToNode(trunknode_t const tn)
{
auto ii = taskPoolMap.begin();
while (ii != taskPoolMap.end())
(*ii++).second->reqPool.cancelReqToNode(tn);
}
void endRpyToNode(trunknode_t const tn)
{
auto ii = taskPoolMap.begin();
while (ii != taskPoolMap.end())
(*ii++).second->rpyPool.endRpyToNode(tn);
}
static void handleAcnetUsm(TaskPool *taskPool, AcnetHeader& hdr)
{
// We have a regular USM. We look up the destination task and, if it
// is listening, deliver the packet to it.
auto ii = taskPool->tasks(hdr.svrTaskName());
while (ii.first != ii.second) {
TaskInfo * const task = ii.first->second;
if (task->acceptsUsm())
if (task->sendDataToClient(&hdr))
++task->stats.usmRcv;
++ii.first;
}
++taskPool->stats.usmRcv;
}
static void handleAcnetCancel(TaskPool *taskPool, AcnetHeader& hdr)
{
// We have a CANCEL packet. Look for the corresponding Reply structure.
RpyInfo const* rpy;
while (0 != (rpy = taskPool->rpyPool.rpyInfo(hdr.client(), hdr.msgId()))) {
// Since we just found this msg id then the rpy info should have the
// same value. If not, then it's a bug in acnetd
assert(hdr.msgId() == rpy->reqId());
// Check if the header matches our knowledge of the request
if (hdr.svrTaskName() != rpy->taskName()) {
char buf1[16], buf2[16];
syslog(LOG_ERR, "mismatched CANCEL task name (%s != %s) "
"received from node 0x%04x",
hdr.svrTaskName().str(buf1),
rpy->taskName().str(buf2),
hdr.client().raw());
return;
}
if (hdr.client() != rpy->remNode()) {
syslog(LOG_ERR, "mismatched CANCEL client/remote nodes "
"(0x%04x != 0x%04x) received from node 0x%04x",
hdr.client().raw(), rpy->remNode().raw(),
hdr.client().raw());
return;
}
if (hdr.clntTaskId() != rpy->taskId()) {
syslog(LOG_ERR, "mismatched CANCEL task id (%d != %d) "
"received from node 0x%04x",
hdr.clntTaskId().raw(), rpy->taskId().raw(), hdr.client().raw());
return;
}
assert(rpy->task().acceptsRequests());
#ifdef DEBUG
syslog(LOG_NOTICE, "CANCEL REQUEST: reqid:0x%04x rpyid:0x%04x", rpy->reqId().raw(), rpy->id().raw());
#endif
// NOTICE: Our data passing protocol between acnetd and local
// clients dictates that all packets passed through the data
// socket must be an ACNET packet. The ACNET packets don't have
// a field for Reply IDs. We assume all CANCELs have a 0 ACNET
// status, so we stuff the Reply ID into the status field. The
// client library knows to pull the Reply ID from the status when
// cleaning up its tables, but report 0 to the application.
TaskInfo& task = rpy->task();
if (!rpy->beenAcked())
task.decrementPendingRequests();
hdr.setStatus(rpy->id());
taskPool->rpyPool.endRpyId(rpy->id());
if (task.sendDataToClient(&hdr)) {
++task.stats.usmRcv;
++taskPool->stats.usmRcv;
} else
taskPool->removeTask(&task);
}
}
static void handleAcnetRequest(TaskPool *taskPool, AcnetHeader& hdr)
{
sockaddr_in const* const in = getAddr(hdr.server());
bool const isMulticast = in && IN_MULTICAST(htonl(in->sin_addr.s_addr));
auto ii = taskPool->tasks(hdr.svrTaskName());
// If the request is a multicast request, then we don't want to send back
// a ACNET_NOTASK because other multicast recipients may have the
// properly named task and will respond. Our ACNET_NOTASK would
// prematurely close the request.
//
// If 'sendError' is true, then we don't have any listeners. We look to
// see if the target node is a multicast node. If so, 'sendError' gets
// cleared and we won't send the ACNET_NOTASK.
if (ii.first == ii.second) {
if (!isMulticast)
sendErrorToNetwork(hdr, ACNET_NOTASK);
return;
}
TaskInfo *deadTask = 0;
bool sendError = true;
++taskPool->stats.reqRcv;
while (ii.first != ii.second) {
status_t result = ACNET_SUCCESS;
TaskInfo * const task = ii.first->second;
++(ii.first);
// We test to see if the task is still alive. If a client gets
// disconnected abruptly, acnetd will still think it's alive until
// any communications is attempted. If this call fails, we remove the
// task, which will clean up all the resources bound to the task.
if (task->stillAlive()) {
sendError = false;
// Even if the task is alive, it may not be a listening task.
if (task->acceptsRequests()) {
#ifdef DEBUG
syslog(LOG_NOTICE, "NEW REQUEST: id = 0x%04x", hdr.msgId().raw());
#endif
// Keep track of how many pending requests a task has
// and print a message to the log if it's been too slow
//
task->testPendingRequestsAndIncrement();
try {
// At this point, we believe we have a valid ACNET
// request. Allocate a Reply structure so the client
// can reply.
RpyInfo const* const rpy = taskPool->rpyPool.alloc(task, hdr.msgId(), hdr.clntTaskId(),
hdr.svrTaskName(), hdr.server(),
hdr.client(), hdr.flags());
// Send the packet to the client. If the
// communications fails, we deallocate the reply.
// NOTICE: See the NOTICE section above (in handling
// CANCELs) for the reason we stuff the reply ID in
// the status field.
hdr.setStatus(rpy->id());
if (task->sendDataToClient(&hdr)) {
++task->stats.reqRcv;
continue;
}
result = ACNET_BUSY;
taskPool->rpyPool.endRpyId(rpy->id(), ACNET_DISCONNECTED);
}
catch (...) {
result = ACNET_NOREMMEM;
}
task->decrementPendingRequests();
} else
result = ACNET_NCR;
if (!isMulticast)
sendErrorToNetwork(hdr, result);
} else
// Since the associated client isn't responding, we'll assume
// it's dead and free up the resources assigned to it. This only
// allows us to remote one dead task per call to this function,
// but that's alright -- others will get cleaned up in future
// calls to the function.
deadTask = task;
}
// If there are no tasks with the requested handle, return an error to
// the sender.
if (sendError && !isMulticast)
sendErrorToNetwork(hdr, ACNET_NOTASK);
// Did we find a dead task? If so, free up its associated resources.
if (deadTask) {
taskPool->removeTask(deadTask);
}
}
// The following function has some sanity checks to determine whether a
// client should receive the packet and whether the ACNET protocol was
// violated, requiring a CANCEL to be sent. This all became more complicated
// when we added ACNET_PEND statuses which keep the connection open, but
// aren't sent up to the client.
//
// I encoded the conditions in a Karnaugh map to try to document and simplify
// the boolean expressions. This function's sanity checks are based upon the
// following tables. There are 4 "inputs" to the logic:
//
// A <- The Request expects multiple replies
// B <- The Request was multicasted
// C <- The incoming packet is EMR (End of Multiple Reply)
// D <- The incoming packet has ACNET_PEND status
//
// The first table calculates whether the request should be cleared up in our
// local tables.
//
// !A!B !A B A B A!B
// !C!D 1 1 0 0
// !C D 0 0 0 0
// C D 0 0 0 0
// C!D 1 1 0 1
//
// Which yields A!BC!D + !A!D
// (A!BC + !A)!D
// (!BC + !A)!D
//
// The second table calculates whether a CANCEL needs to be sent to the
// remote node. This is also the condition in which we need to fix the header
// to the client because we asked for a single reply and the client sent one
// of multiple replies.
//
// !A!B !A B A B A!B
// !C!D 1 1 0 0
// !C D 0 0 0 0
// C D 0 0 0 0
// C!D 0 1 0 0
//
// Which yields !A!C!D + !AB!D
// !A!D(!C + B)
//
// The third table determines whether we need to adjust the header because
// we sent a multicasted request for multiple request and this response has
// the EMR set. The only way to stop a multicast request for multiple replies
// is to multicast a CANCEL.
//
// !A!B !A B A B A!B
// !C!D 0 0 0 0
// !C D 0 0 0 0
// C D 0 0 1 0
// C!D 0 0 1 0
//
// Which yields ABC
//
// The fourth table calculates whether the packet should be sent to the client.
//
// !A!B !A B A B A!B
// !C!D 1 1 1 1
// !C D 0 0 0 0
// C D 0 0 0 0
// C!D 1 1 1 1
//
// Which yields !D
static void handleAcnetReply(TaskPool *taskPool, AcnetHeader& hdr)
{
reqid_t const msgId = hdr.msgId();
// Look up the request structure. If we don't have that request active,
// return a CANCEL so the remote system can clean up their tables.
ReqInfo* const req = taskPool->reqPool.entry(msgId);
if (req && (hdr.server() == req->remNode() || req->multicasted()) &&
hdr.svrTaskName() == req->taskName() && hdr.clntTaskId() == req->task().id()) {
// Check every 5 seconds to see if the task that's receiving replies
// is still alive. We throttle it because the call is too expensive
// to do on every reply with pid-based contexts.
if (req->task().stillAlive(5000)) {
// Update some bookkeeping; increment packet counters and reset the
// time-out.
++req->task().stats.rpyRcv;
++taskPool->stats.rpyRcv;
req->bumpPktStats();
taskPool->reqPool.update(req);
// If it's not a PEND message, we process it and send it to the
// client. (All the expressions calculated above have a common !D
// component. This if-statement tests the !D component for all of the
// expressions.)
if (hdr.status() != ACNET_PEND) {
bool const A = req->wantsMultReplies();
bool const B = req->multicasted();
bool const C = hdr.isEMR();
if (A && C) {
// The request is multicasted for multiple replies. We set
// the mult bit and clear out an ENDMULT status since the
// link needs to stay open until cancelled.
if (B) {
hdr.setFlags(hdr.flags() | ACNET_FLG_MLT);
if (hdr.status() == ACNET_ENDMULT)
hdr.setStatus(ACNET_SUCCESS);
}
// If the request was not multicasted. We update the header
// to reflect the correct value.
else {
hdr.setFlags(hdr.flags() & ~ACNET_FLG_MLT);
if (hdr.status() == ACNET_SUCCESS)
hdr.setStatus(ACNET_ENDMULT);
}
}
// Send the packet to the client. If we can't talk to the client,
// clean up the request resources. If it's a multiple reply or a
// multicasted request, send a cancel, as well.
if (req->task().sendDataToClient(&hdr)) {
if (!A || (!B && C))
taskPool->reqPool.cancelReqId(msgId, !A && (!C || B));
} else {
syslog(LOG_WARNING, "Trouble communicating with %s, shutting "
"down request 0x%04x", req->task().handle().str(),
msgId.raw());
taskPool->reqPool.cancelReqId(msgId, A || B);
}
}
} else
// Remove the dead task and clean up it's active requests
taskPool->removeTask(&req->task());
} else {
AcnetHeader const hdr2(ACNET_FLG_CAN, ACNET_SUCCESS, hdr.server(),
hdr.client(), hdr.svrTaskName(),
hdr.clntTaskId(), msgId, sizeof(AcnetHeader));
(void) sendDataToNetwork(hdr2, 0, 0);
if (dumpIncoming)
syslog(LOG_WARNING, "Sent CANCEL to 0x%04x for bad req id 0x%04x "
"from task 0x%08x", hdr.server().raw(),
msgId.raw(), hdr.svrTaskName().raw());
}
}
// Looks up the IP address of the specified ACNET node and returns it or 0,
// if the node cannot be found. If the node can't be found and we don't have
// a valid IP table, then we temporarily insert the entry into our table (it
// will get overridden when NODES updates us.)
static ipaddr_t ipAddress(trunknode_t& tn, ipaddr_t const defAddress, bool tempAdd)
{
if (tn.isBlank()) {
if (defAddress != myIp())
addrLookup(defAddress, tn);
return defAddress;
} else {
sockaddr_in const* const in = getAddr(tn);
if (in)
return ipaddr_t(ntohl(in->sin_addr.s_addr));
else if (!lastNodeTableDownloadTime() && !cmdLineArgs.standAlone && tempAdd) {
updateAddr(tn, nodename_t(-1), defAddress);
syslog(LOG_WARNING, "Temporarily adding %s for node 0x%02x%02x",
defAddress.str().c_str(), tn.trunk().raw(), tn.node().raw());
return defAddress;
} else
return ipaddr_t();
}
}
static void handleNodeTableDownloadRequest(AcnetHeader& hdr)
{
TaskPool *taskPool = new TaskPool(hdr.server(), nodename_t());
if (taskPool) {
handleAcnetRequest(taskPool, hdr);
delete taskPool;
} else
syslog(LOG_ERR, "unable to allocate TaskPool for node table download");
}
static TaskPool* getTaskPool(trunknode_t node)
{
nodename_t name;
if (nodeLookup(node, name)) {
auto ii = taskPoolMap.find(name);
if (ii == taskPoolMap.end()) {
if (isThisMachine(node)) {
TaskPool* taskPool = new TaskPool(node, name);
if (taskPool) {
taskPoolMap.insert(TaskPoolMap::value_type(name, taskPool));
syslog(LOG_NOTICE, "created TaskPool for node %s(0x%02x%02x)", name.str(), node.trunk().raw(), node.node().raw());
return taskPool;
} else
syslog(LOG_ERR, "unable to allocate TaskPool for node %s", name.str());
}
} else
return (*ii).second;
}
return 0;
}
static TaskPool* getTaskPool(nodename_t name)
{
// Blank names mean the configured node for this host
if (name.isBlank())
return getTaskPool(myNode());
auto ii = taskPoolMap.find(name);
if (ii == taskPoolMap.end()) {
trunknode_t node;
if (nameLookup(name, node))
return getTaskPool(node);
} else
return (*ii).second;
return 0;
}
static void process_packet(bool mcast, AcnetHeader& hdr,
void (*f)(TaskPool*, AcnetHeader&)) {
if (mcast) {
auto ii = taskPoolMap.begin();
while (ii != taskPoolMap.end())
f((*ii++).second, hdr);
} else {
TaskPool* taskPool = getTaskPool(hdr.server());
if (taskPool && (taskPool->taskExists(hdr.svrTaskName()) || !defaultNodeFallback))
f(taskPool, hdr);
else if ((taskPool = getTaskPool(myNode())))
f(taskPool, hdr);
}
}
void handleAcnetPacket(AcnetHeader& hdr, ipaddr_t const ip)
{
uint16_t const flags = hdr.flags();
uint16_t pktType = (flags & (0xf800 | ACNET_FLG_TYPE | ACNET_FLG_CAN | ACNET_FLG_MLT));
// Dump the contents of the packet to the logger.
if (dumpIncoming) {
dumpPacket("Incoming", hdr, hdr.msg(), hdr.msgLen());
syslog(LOG_WARNING, "Incoming from %s", ip.str().c_str());
}
trunknode_t ctn = hdr.client();
ipaddr_t const inClient = ipAddress(ctn, ip, pktType == ACNET_FLG_REQ);
if (!inClient.isValid()) {
if (dumpIncoming)
syslog(LOG_WARNING, "Dropping packet from %s -- bad client node 0x%02x%02x",
ip.str().c_str(), ctn.trunk().raw(), ctn.node().raw());
return;
}
// The client node cannot be a multicast node. We also don't allow
// packets from multicast IP addresses.
if (inClient.isMulticast() || ip.isMulticast()) {
if (dumpIncoming)
syslog(LOG_WARNING, "Dropping packet from multicast node 0x%02x%02x (ip = %s)",
ctn.trunk().raw(), ctn.node().raw(), ip.str().c_str());
return;
}
hdr.setClient(ctn);
trunknode_t stn = hdr.server();
ipaddr_t const inServer = ipAddress(stn, myIp(), pktType == ACNET_FLG_REQ);
if (!inServer.isValid()) {
if (dumpIncoming)
syslog(LOG_WARNING, "Dropping packet from %s -- bad server node 0x%02x%02x",
ip.str().c_str(), ctn.trunk().raw(), ctn.node().raw());
return;
}
bool mcast = inServer.isMulticast();
TaskPool *taskPool = 0;
switch (pktType) {
case ACNET_FLG_USM:
process_packet(mcast, hdr, handleAcnetUsm);
break;
case ACNET_FLG_REQ:
case ACNET_FLG_REQ | ACNET_FLG_MLT:
if (!lastNodeTableDownloadTime())
handleNodeTableDownloadRequest(hdr);
else
process_packet(mcast, hdr, handleAcnetRequest);
break;
case ACNET_FLG_CAN:
if (mcast) {
auto ii = taskPoolMap.begin();
while (ii != taskPoolMap.end())
handleAcnetCancel((*ii++).second, hdr);
} else if ((taskPool = getTaskPool(hdr.server())) && taskPool->rpyPool.rpyInfo(hdr.client(), hdr.msgId()))
handleAcnetCancel(taskPool, hdr);
else if (defaultNodeFallback && hdr.server() != myNode() && (taskPool = getTaskPool(myNode()))) {
#ifdef DEBUG
syslog(LOG_NOTICE, "Passing cancel for %04x to the default node %04x", hdr.server().raw(), myNode().raw());
#endif
handleAcnetCancel(taskPool, hdr);
}
break;
case ACNET_FLG_RPY:
case ACNET_FLG_RPY | ACNET_FLG_MLT:
taskPool = getTaskPool(hdr.client());
if (taskPool)
handleAcnetReply(taskPool, hdr);
break;
default:
if (dumpIncoming)
syslog(LOG_WARNING, "Invalid 'flags' field in ACNET header (from %s) -- 0x%04x",
ip.str().c_str(), flags);
break;
}
}
// This function breaks the packet up (if necessary), and routes the data to
// the packet handler
static void handleNetworkDatagram(uint8_t const* const buf, ssize_t const len, ipaddr_t const ip)
{
// If the packet is an odd length, log it and drop it.
if (len & 1) {
if (dumpIncoming)
syslog(LOG_WARNING, "Odd-sized ACNET packet received from %s", ip.str().c_str());
return;
}
size_t offset = 0;
// We loop through (possibly) multiple acnet packets. To do this, we need
// to have at least one AcnetHeader's worth of data. If the remaining
// data size is less, then we're done.
while (len - offset >= sizeof(AcnetHeader)) {
AcnetHeader& hdr = *const_cast<AcnetHeader*>(reinterpret_cast<AcnetHeader const*>(buf + offset));
uint16_t const pktSize = hdr.msgLen();
// If this packet indicates more data than what is here, we log a
// message and ignore it.
if (!isPacketSizeValid(offset, pktSize, len, ip))
return;
handleAcnetPacket(hdr, ip);
offset += (pktSize + 1) & ~1;
}
}
static void sendClientError(sockaddr_in const& in, status_t err)
{
Ack ack;
ack.setStatus(err);
(void) sendto(sClient, &ack, sizeof(ack), 0, (sockaddr*) &in, sizeof(in));
}
static bool handleClientCommand()
{
static char buf[64 * 1024];
sockaddr_in in;
socklen_t in_len = sizeof(in);
ssize_t recvLen;
// Make sure we were able to successfully read from the socket. If we
// couldn't, we're in a bad state and need to report the problem (over
// and over and over, probably.)
if ((recvLen = recvfrom(sClient, buf, sizeof(buf), 0, reinterpret_cast<sockaddr*>(&in), &in_len)) > 0) {
// Make sure the packet is at least the size of a minimum packet. If
// it is at least the size of the CommandHeader base class, then we
// can look at the typecode. (TP-1)
if ((size_t) recvLen >= sizeof(CommandHeader)) {
CommandHeader* const cmdHdr = reinterpret_cast<CommandHeader*>(buf);
// Check for adding a node to the node table since it doesn't
// require a TaskPool
if (CommandList::cmdAddNode == cmdHdr->cmd()) {
Ack ack;
AddNodeCommand const* const cmd = static_cast<AddNodeCommand const*>(cmdHdr);
trunknode_t const node = cmd->addr();
nodename_t const name = cmd->nodeName();
ipaddr_t const addr = cmd->ipAddr();
if (myHostName() == name)
setMyIp(addr);
if (node.isBlank() && name.isBlank() && addr.value() == 0) {
if (!lastNodeTableDownloadTime())
generateKillerMessages();
setLastNodeTableDownloadTime();
} else
updateAddr(node, name, addr);
(void) sendto(sClient, &ack, sizeof(ack), 0, (sockaddr*) &in, in_len);
} else {
// All commands at this point need a valid TaskPool
TaskPool* const taskPool = getTaskPool(cmdHdr->virtualNodeName());
if (!taskPool)
sendClientError(in, ACNET_NO_NODE);
else if (CommandList::cmdConnect == cmdHdr->cmd() || CommandList::cmdConnectExt == cmdHdr->cmd()
|| CommandList::cmdTcpConnectExt == cmdHdr->cmd()) {
// Make sure the packet size is correct. (TP-3)
if ((size_t) recvLen < sizeof(ConnectCommand))
sendClientError(in, ACNET_INVARG);
else
taskPool->handleConnect(in, static_cast<ConnectCommand const*>(cmdHdr), recvLen);
} else if (CommandList::cmdNameLookup == cmdHdr->cmd()) {
// Name Lookup commands don't require a valid connection
// either. Make sure the packet size is correct.
if ((size_t) recvLen != sizeof(NameLookupCommand))
sendClientError(in, ACNET_INVARG);
else {
AckNameLookup ack;
trunknode_t addr;
NameLookupCommand const* const cmd = static_cast<NameLookupCommand const*>(cmdHdr);