forked from vrpn/vrpn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vrpn_Connection.C
6589 lines (5630 loc) · 211 KB
/
vrpn_Connection.C
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
// Must be done before stdio.h to avoid conflict for SEEK_SET, at least for
// MPICH2 on
// the Windows platform.. Note that this means we cannot include it in
// vrpn_Connection.h,
// because user code often includes stdio.h before and VRPN includes.
#ifdef VRPN_USE_MPI
#include <mpi.h>
#endif
#include <stddef.h> // for size_t
#include <stdio.h> // for fprintf, stderr, NULL, etc
#include <string.h> // for strlen, strcpy, memcpy, etc
#ifndef _WIN32_WCE
#include <signal.h> // for kill, signal, SIGKILL, etc
#ifdef sgi
#include <ctype.h>
#else
#include <cctype> // for isalnum
#endif
#endif
// malloc.h is deprecated; all the functionality *should*
// be in stdlib.h
#include <stdlib.h> // for exit, atoi, getenv, system
#include "vrpn_Connection.h"
#include <string>
#ifdef VRPN_USE_WINSOCK_SOCKETS
// A socket in Windows can not be closed like it can in unix-land
#define vrpn_closeSocket closesocket
// Socket errors don't set errno in Windows; they use their own
// custom error reporting methods.
#define vrpn_socket_error WSAGetLastError()
static std::string WSA_number_to_string(int err)
{
LPTSTR s = NULL;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&s, 0, NULL);
std::string ret = s;
LocalFree(s);
return ret;
}
#define vrpn_socket_error_to_chars(x) (WSA_number_to_string(x)).c_str()
#define vrpn_EINTR WSAEINTR
#else
#include <errno.h> // for errno, EINTR
#define vrpn_closeSocket close
#define vrpn_socket_error errno
#define vrpn_socket_error_to_chars(x) strerror(x)
#define vrpn_EINTR EINTR
#include <arpa/inet.h> // for inet_addr
#include <netinet/in.h> // for sockaddr_in, ntohl, in_addr, etc
#include <sys/socket.h> // for getsockname, send, AF_INET, etc
#include <unistd.h> // for close, read, fork, etc
#ifdef _AIX
#define _USE_IRS
#endif
#include <netdb.h> // for hostent, gethostbyname, etc
#endif
#ifdef sparc
#include <arpa/inet.h> // for inet_addr
#define INADDR_NONE -1
#endif
#ifdef sgi
#include <bstring.h>
#endif
#ifdef hpux
#include <arpa/nameser.h>
#include <resolv.h> // for herror() - but it isn't there?
#endif
#ifndef VRPN_USE_WINSOCK_SOCKETS
#include <sys/wait.h> // for wait, wait3, WNOHANG
#ifndef __CYGWIN__
#include <netinet/tcp.h> // for TCP_NODELAY
#endif /* __CYGWIN__ */
#endif /* VRPN_USE_WINSOCK_SOCKETS */
// cast fourth argument to setsockopt()
#ifdef VRPN_USE_WINSOCK_SOCKETS
#define SOCK_CAST (char *)
#else
#ifdef sparc
#define SOCK_CAST (const char *)
#else
#define SOCK_CAST
#endif
#endif
#if defined(_AIX) || defined(__APPLE__) || defined(ANDROID) || defined(__linux)
#define GSN_CAST (socklen_t *)
#else
#if defined(FreeBSD)
#define GSN_CAST (unsigned int *)
#else
#define GSN_CAST
#endif
#endif
// NOT SUPPORTED ON SPARC_SOLARIS
// gethostname() doesn't seem to want to link out of stdlib
#ifdef sparc
extern "C" {
int gethostname(char *, int);
}
#endif
#include "vrpn_FileConnection.h" // for vrpn_File_Connection
#include "vrpn_Log.h" // for vrpn_Log
struct timeval;
//#define VERBOSE
//#define VERBOSE2
//#define VERBOSE3
// On Win32, this constant is defined as ~0 (sockets are unsigned ints)
#ifndef VRPN_USE_WINSOCK_SOCKETS
#define INVALID_SOCKET -1
#endif
// Don't tell us about FD_SET() "conditional expression is constant"
#ifdef _WIN32
#pragma warning(disable : 4127)
#endif
// Syntax of vrpn_MAGIC:
//
// o The minor version number must follow the last period ('.') and be the
// only significant thing following the last period in the vrpn_MAGIC string.
//
// o Minor versions should interoperate. So, when establishing a connection,
// vrpn_MAGIC is checked through the last period. If everything up to, and
// including, the last period matches, a connection will be made.
//
// o If everything up to the last period matches, then a second check is
// preformed on everything after the last period (the minor version number).
// If the minor version numbers differ, a connection is still made, but a
// warning is printed to stderr. There is currently no way to suppress this
// warning message if the minor versions differ between the server and the
// client..
//
// o The version checking described above is performed by the function
// check_vrpn_cookie, found in this file. check_vrpn_cookie returns a
// different value for each of these three cases.
// -[juliano 2000/08]
//
// [juliano 2000/08] Suggestion:
//
// We have the situation today that vrpn5 can read stream files that were
// produced by vrpn-4.x. However, the way the library is written, vrpn
// doesn't know this. Further, it is difficult to change this quickly,
// because vrpn_check_cookie doesn't know if it's being called for a network
// or a file connection. The purpose of this comment is to suggest a
// solution.
//
// Our temporary solution is to change the cookie, rebulid the library, and
// relink into our app. Then, our app can read stream files produced by
// vrpn4.x.
//
// Vrpn currently knows that live network connections between vrpn-4.x and
// vrpn-5.x apps are not possible. But, ideally, it should also know that
// it's ok for a vrpn-5.x app to read a vrpn-4.x streamfile. Unfortunately,
// coding this is difficult in the current framework.
//
// I suggest that check_vrpn_cookie should not be a global function, but
// should instead be a protected member function of vrpn_Connection. The
// default implementation would do what is currently done by the global
// check_vrpn_cookie. However, vrpn_FileConnection would override it and
// perform a more permissive check.
//
// This strategy would scale in the future when we move to vrpn-6.x and
// higher. It would also be useful if we ever realize after a release that
// VRPN-major.minor is actually network incompatible (but not streamfile
// incompatible) with VRPN-major.(minor-1). Then, the vrpn_check_cookie
// implementation in VRPN-major.(minor-1) could test for this incompatibility
// and print an appropriate diagnostic. Similar solution exists if release
// n+1 is file-compatible but later found to be network-incompatible with
// release n.
//
// Again, in our current framework, we cannot distinguish between
// file-compatible and network-compatible. In the future, we may also have
// shared-memory-access-compatible as well as other types of connection. The
// proposed strategy handles both partial major version compatibility as well
// as accidental partial minor version incompatibility.
//
const char *vrpn_MAGIC = (const char *)"vrpn: ver. 07.34";
const char *vrpn_FILE_MAGIC = (const char *)"vrpn: ver. 04.00";
const int vrpn_MAGICLEN = 16; // Must be a multiple of vrpn_ALIGN bytes!
const char *vrpn_got_first_connection = "VRPN_Connection_Got_First_Connection";
const char *vrpn_got_connection = "VRPN_Connection_Got_Connection";
const char *vrpn_dropped_connection = "VRPN_Connection_Dropped_Connection";
const char *vrpn_dropped_last_connection =
"VRPN_Connection_Dropped_Last_Connection";
const char *vrpn_CONTROL = "VRPN Control";
//**********************************************************************
//** This section has been pulled from the "SDI" library and had its
//** functions renamed to vrpn_ from sdi_. This removes our dependence
//** on libsdi.a for VRPN.
#ifdef sparc
// On capefear and swift, getdtablesize() isn't declared in unistd.h
// even though the man page says it should be. Similarly, wait3()
// isn't declared in sys/{wait,time,resource}.h.
extern "C" {
extern int getdtablesize(void);
pid_t wait3(int *statusp, int options, struct rusage *rusage);
}
#endif
/* On HP's, this defines how many possible open file descriptors can be
* open at once. This is what is returned by the getdtablesize() function
* on other architectures. */
#ifdef hpux
#define getdtablesize() MAXFUPLIM
#endif
#ifdef __hpux
#define getdtablesize() MAXFUPLIM
#endif
/* The version of rsh in /usr/local/bin is the AFS version that passes tokens
* to the remote machine. This will allow remote execution of anything you
* can execute locally. This is the default location from which to get rsh.
* If the VRPN_RSH environment variable is set, that will be used as the full
* path instead. */
#ifdef linux
#define RSH (char *) "/usr/local/bin/ssh"
#else
#define RSH (char *) "/usr/local/bin/rsh"
#endif
/* How long to wait for a UDP packet to cause a callback connection,
* and how many times to retry. */
#define UDP_CALL_TIMEOUT (2)
#define UDP_CALL_RETRIES (5)
/* How long to wait for the server to connect, and how many times to wait
* this long. The death of the child is checked for between each of the
* waits, in order to allow faster exit if the child quits before calling
* back. */
#define SERVCOUNT (20)
#define SERVWAIT (120 / SERVCOUNT)
// From vrpn_CONNECTION_MAX_SENDERS and vrpn_CONNECTION_MAX_TYPES
// in vrpn_Connection.h.
#define vrpn_CONNECTION_MAX_XLATION_TABLE_SIZE 2000
/*
Major refactoring 18-20 April 2000 T. Hudson
Broke two classes (vrpn_Connection, vrpn_OneConnection) into five:
vrpn_TranslationTable
vrpn_TypeDispatcher
vrpn_Log
vrpn_Endpoint
vrpn_Connection
Each Connection manages one Endpoint per Connection that it is
communicating with. Each Endpoint has a Log, and at a future date
some Connections may have their own logs. Each Endpoint has two
TranslationTables to map remote senders and types to their local
identifiers; these tables are also used by Logs. The entire system
shares a single TypeDispatcher to track local types, senders, and callbacks.
This decomposition let me get rid of the circular references between
Connection and Endpoint and between Endpoint and Log. It lets us
have logs attached to both Endpoints and Connections. It better
isolates and identifies some of the functionality we're using.
I've always thought the central component of VRPN is the TypeDispatcher,
which I've also seen in the (late '80s) commercial database middleware
I've hacked the internals of. There isn't an example of it in the
Gang-Of-4 "Design Patterns" book, but I'm doing a small Patterns literature
search to try to find it.
This module's interface still only contains Connection and Endpoint.
The only reason Endpoint is visible is so that it can be used by
vrpn_FileConnection; unfortunately, it isn't easy to factor it out
of there. I'd suggest moving Connection and FileConnection into their
own directory; we can then extract all the classes out of this
file into their own C files.
TypeDispatcher could certainly use a better name.
*/
/**
* @class vrpn_TranslationTable
* Handles translation of type and sender names between local and
* network peer equivalents.
* Used by Endpoints, Logs, and diagnostic code.
*/
struct cRemoteMapping {
char *name;
vrpn_int32 remote_id;
vrpn_int32 local_id;
};
class vrpn_TranslationTable {
public:
vrpn_TranslationTable(void);
~vrpn_TranslationTable(void);
// ACCESSORS
vrpn_int32 numEntries(void) const;
vrpn_int32 mapToLocalID(vrpn_int32 remote_id) const;
// MANIPULATORS
void clear(void);
///< Deletes every entry in the table.
vrpn_int32 addRemoteEntry(cName name, vrpn_int32 remote_id,
vrpn_int32 local_id);
///< Adds a name and local ID to the table, returning its
///< remote ID. This exposes an UGLY hack in the VRPN internals -
///< that ID is implicitly carried as the index into this array,
///< and there isn't much in the way of checking (?).
vrpn_bool addLocalID(const char *name, vrpn_int32 local_id);
///< Adds a local ID to a name that was already in the table;
///< returns TRUE on success, FALSE if not found.
private:
vrpn_int32 d_numEntries;
cRemoteMapping d_entry[vrpn_CONNECTION_MAX_XLATION_TABLE_SIZE];
};
vrpn_TranslationTable::vrpn_TranslationTable(void)
: d_numEntries(0)
{
int i;
for (i = 0; i < vrpn_CONNECTION_MAX_XLATION_TABLE_SIZE; i++) {
d_entry[i].name = NULL;
d_entry[i].remote_id = -1;
d_entry[i].local_id = -1;
}
}
vrpn_TranslationTable::~vrpn_TranslationTable(void) { clear(); }
vrpn_int32 vrpn_TranslationTable::numEntries(void) const
{
return d_numEntries;
}
vrpn_int32 vrpn_TranslationTable::mapToLocalID(vrpn_int32 remote_id) const
{
if ((remote_id < 0) || (remote_id > d_numEntries)) {
#ifdef VERBOSE2
// This isn't an error!? It happens regularly!?
fprintf(stderr, "vrpn_TranslationTable::mapToLocalID: "
"Remote ID %d is illegal!\n",
remote_id);
#endif
return -1;
}
#ifdef VERBOSE
fprintf(stderr, "Remote ID %d maps to local ID %d (%s).\n", remote_id,
d_entry[remote_id].local_id, d_entry[remote_id].name);
#endif
return d_entry[remote_id].local_id;
}
vrpn_int32 vrpn_TranslationTable::addRemoteEntry(cName name,
vrpn_int32 remote_id,
vrpn_int32 local_id)
{
vrpn_int32 useEntry;
useEntry = remote_id;
if (useEntry >= vrpn_CONNECTION_MAX_XLATION_TABLE_SIZE) {
fprintf(stderr, "vrpn_TranslationTable::addRemoteEntry: "
"Too many entries in table (%d).\n",
d_numEntries);
return -1;
}
// We do not check to see if this entry is already filled in. Such
// a check caused problems with vrpn_Control when reading from log files.
// Also, it will cause problems with multi-logging, where the connection
// may be requested to send all of its IDs again for a log file is opeened
// at a time other than connection set-up.
if (!d_entry[useEntry].name) {
d_entry[useEntry].name = new cName;
if (!d_entry[useEntry].name) {
fprintf(stderr, "vrpn_TranslationTable::addRemoteEntry: "
"Out of memory.\n");
return -1;
}
}
memcpy(d_entry[useEntry].name, name, sizeof(cName));
d_entry[useEntry].remote_id = remote_id;
d_entry[useEntry].local_id = local_id;
#ifdef VERBOSE
fprintf(stderr, "Set up remote ID %d named %s with local equivalent %d.\n",
remote_id, name, local_id);
#endif
if (d_numEntries <= useEntry) {
d_numEntries = useEntry + 1;
}
return useEntry;
}
vrpn_bool vrpn_TranslationTable::addLocalID(const char *name,
vrpn_int32 local_id)
{
int i;
for (i = 0; i < d_numEntries; i++) {
if (d_entry[i].name && !strcmp(d_entry[i].name, name)) {
d_entry[i].local_id = local_id;
return VRPN_TRUE;
}
}
return VRPN_FALSE;
}
void vrpn_TranslationTable::clear(void)
{
int i;
for (i = 0; i < d_numEntries; i++) {
if (d_entry[i].name) {
delete[] d_entry[i].name;
d_entry[i].name = NULL;
}
d_entry[i].local_id = -1;
d_entry[i].remote_id = -1;
}
d_numEntries = 0;
}
vrpn_Log::vrpn_Log(vrpn_TranslationTable *senders, vrpn_TranslationTable *types)
: d_logFileName(NULL)
, d_logmode(vrpn_LOG_NONE)
, d_logTail(NULL)
, d_firstEntry(NULL)
, d_file(NULL)
, d_magicCookie(NULL)
, d_wroteMagicCookie(vrpn_FALSE)
, d_filters(NULL)
, d_senders(senders)
, d_types(types)
{
d_lastLogTime.tv_sec = 0;
d_lastLogTime.tv_usec = 0;
// Set up default value for the cookie received from the server
// because if we are using a file connection and want to
// write a log, we never receive a cookie from the server.
d_magicCookie = new char[vrpn_cookie_size() + 1];
if (!d_magicCookie) {
fprintf(stderr, "vrpn_Log: Out of memory.\n");
return;
}
write_vrpn_cookie(d_magicCookie, vrpn_cookie_size() + 1, vrpn_LOG_NONE);
}
vrpn_Log::~vrpn_Log(void)
{
if (d_file) {
close();
}
if (d_filters) {
vrpnLogFilterEntry *next;
while (d_filters) {
next = d_filters->next;
delete d_filters;
d_filters = next;
}
}
if (d_magicCookie) {
delete[] d_magicCookie;
}
}
char *vrpn_Log::getName()
{
if (this->d_logFileName == NULL)
return NULL;
else {
char *s = new char[strlen(this->d_logFileName) + 1];
strcpy(s, this->d_logFileName);
return s;
}
}
int vrpn_Log::open(void)
{
if (!d_logFileName) {
fprintf(stderr, "vrpn_Log::open: Log file has no name.\n");
return -1;
}
if (d_file) {
fprintf(stderr, "vrpn_Log::open: Log file is already open.\n");
return 0; // not a catastrophic failure
}
// If we can open the file for reading, then it already exists. If
// so, we don't want to overwrite it.
d_file = fopen(d_logFileName, "r");
if (d_file) {
fprintf(stderr, "vrpn_Log::open: "
"Log file \"%s\" already exists.\n",
d_logFileName);
fclose(d_file);
d_file = NULL;
}
else {
d_file = fopen(d_logFileName, "wb");
if (d_file == NULL) { // unable to open the file
fprintf(stderr, "vrpn_Log::open: "
"Couldn't open log file \"%s\": ",
d_logFileName);
perror(NULL /* no additional string */);
}
}
if (!d_file) { // Try to write to "/tmp/vrpn_emergency_log", unless it
// exists!
d_file = fopen("/tmp/vrpn_emergency_log", "r");
if (d_file) {
fclose(d_file);
d_file = NULL;
perror("vrpn_Log::open_log: "
"Emergency log file \"/tmp/vrpn_emergency_log\" "
"already exists.\n");
}
else {
d_file = fopen("/tmp/vrpn_emergency_log", "wb");
if (d_file == NULL) {
perror("vrpn_Log::open: "
"Couldn't open emergency log file "
"\"/tmp/vrpn_emergency_log\": ");
}
}
if (!d_file) {
return -1;
}
else {
fprintf(stderr, "Writing to /tmp/vrpn_emergency_log instead.\n");
}
}
return 0;
}
int vrpn_Log::close(void)
{
int final_retval = 0;
final_retval = saveLogSoFar();
if (fclose(d_file)) {
fprintf(stderr, "vrpn_Log::close: "
"close of log file failed!\n");
final_retval = -1;
}
d_file = NULL;
if (d_logFileName) {
delete[] d_logFileName;
d_logFileName = NULL;
}
return final_retval;
}
int vrpn_Log::saveLogSoFar(void)
{
vrpn_LOGLIST *lp;
int host_len;
int final_retval = 0;
size_t retval;
// If we aren't supposed to be logging, return with no error.
if (!logMode()) return 0;
// Make sure the file is open. If not, then error.
if (!d_file) {
fprintf(stderr, "vrpn_Log::saveLogSoFar: "
"Log file is not open!\n");
// Abort writing out log without destroying data needed to
// clean up memory.
d_firstEntry = NULL;
final_retval = -1;
}
if (!d_wroteMagicCookie && !final_retval) {
// Write out the log header (magic cookie)
// TCH 20 May 1999
// There's at least one hack here:
// What logging mode should a client that plays back the log at a
// later time be forced into? I believe NONE, but there might be
// arguments the other way? So, you may want to adjust the cookie
// to make the log mode 0.
retval = fwrite(d_magicCookie, 1, vrpn_cookie_size(), d_file);
if (retval != vrpn_cookie_size()) {
fprintf(stderr, "vrpn_Log::saveLogSoFar: "
"Couldn't write magic cookie to log file "
"(got %d, expected %d).\n",
static_cast<int>(retval),
static_cast<int>(vrpn_cookie_size()));
lp = d_logTail;
final_retval = -1;
}
d_wroteMagicCookie = vrpn_TRUE;
}
// Write out the messages in the log,
// starting at d_firstEntry and working backwards
for (lp = d_firstEntry; lp && !final_retval; lp = lp->prev) {
// This used to be a horrible hack that wrote the size of the
// structure (which included a pointer) to the file. This broke on
// 64-bit machines, but could also have broken on any architecture
// that packed structures differently from the common packing.
// Here, we pull out the entries in a way that avoids doing any
// sign changes and then write the array of values to disk.
// Unfortunately, to remain backward-compatible with earlier log
// files, we need to write the empty pointer.
vrpn_int32 values[6];
vrpn_int32 zero = 0;
memcpy(&(values[0]), &lp->data.type, sizeof(vrpn_int32));
memcpy(&(values[1]), &lp->data.sender, sizeof(vrpn_int32));
memcpy(&(values[2]), &lp->data.msg_time.tv_sec, sizeof(vrpn_int32));
memcpy(&(values[3]), &lp->data.msg_time.tv_usec, sizeof(vrpn_int32));
memcpy(&(values[4]), &lp->data.payload_len, sizeof(vrpn_int32));
memcpy(&(values[5]), &zero, sizeof(vrpn_int32)); // Bogus pointer.
retval = fwrite(values, sizeof(vrpn_int32), 6, d_file);
if (retval != 6) {
fprintf(stderr,
"vrpn_Log::saveLogSoFar: "
"Couldn't write log file (got %d, expected %lud).\n",
static_cast<int>(retval),
static_cast<unsigned long>(sizeof(lp->data)));
lp = d_logTail;
final_retval = -1;
continue;
}
host_len = ntohl(lp->data.payload_len);
// fprintf(stderr, "type %d, sender %d, payload length %d\n",
// htonl(lp->data.type), htonl(lp->data.sender), host_len);
retval = fwrite(lp->data.buffer, 1, host_len, d_file);
if (retval != host_len) {
fprintf(stderr, "vrpn_Log::saveLogSoFar: "
"Couldn't write log file.\n");
lp = d_logTail;
final_retval = -1;
continue;
}
}
// clean up the linked list
while (d_logTail) {
lp = d_logTail->next;
if (d_logTail->data.buffer) {
delete[](char *)d_logTail -> data.buffer; // ugly cast
}
delete d_logTail;
d_logTail = lp;
}
d_firstEntry = NULL;
return final_retval;
}
int vrpn_Log::logIncomingMessage(size_t payloadLen, struct timeval time,
vrpn_int32 type, vrpn_int32 sender,
const char *buffer)
{
// Log it the same way, whether it's a User or System message.
// (We used to throw away system messages that we didn't have a handler
// for, but I believe that was incorrect.)
if (logMode() & vrpn_LOG_INCOMING) {
// fprintf(stderr, "Logging incoming message of type %d.\n", type);
return logMessage(static_cast<vrpn_int32>(payloadLen), time, type,
sender, buffer, vrpn_TRUE);
}
// fprintf(stderr, "Not logging incoming messages (type %d)...\n", type);
return 0;
}
int vrpn_Log::logOutgoingMessage(vrpn_int32 payloadLen, struct timeval time,
vrpn_int32 type, vrpn_int32 sender,
const char *buffer)
{
if (logMode() & vrpn_LOG_OUTGOING) {
// fprintf(stderr, "Logging outgoing message of type %d.\n", type);
return logMessage(payloadLen, time, type, sender, buffer);
}
// fprintf(stderr, "Not logging outgoing messages (type %d)...\n", type);
return 0;
}
int vrpn_Log::logMessage(vrpn_int32 payloadLen, struct timeval time,
vrpn_int32 type, vrpn_int32 sender, const char *buffer,
vrpn_bool isRemote)
{
vrpn_LOGLIST *lp;
vrpn_int32 effectiveType;
vrpn_int32 effectiveSender;
if (isRemote) {
effectiveType = d_types->mapToLocalID(type);
effectiveSender = d_senders->mapToLocalID(sender);
}
else {
effectiveType = type;
effectiveSender = sender;
}
// Filter user messages
if (type >= 0) {
if (checkFilters(payloadLen, time, effectiveType, effectiveSender,
buffer)) {
// This is NOT a failure - do not return nonzero!
return 0;
}
}
// Make a log structure for the new message
lp = new vrpn_LOGLIST;
if (!lp) {
fprintf(stderr, "vrpn_Log::logMessage: "
"Out of memory!\n");
return -1;
}
lp->data.type = htonl(type);
lp->data.sender = htonl(sender);
lp->data.msg_time.tv_sec = htonl(time.tv_sec);
lp->data.msg_time.tv_usec = htonl(time.tv_usec);
d_lastLogTime.tv_sec = time.tv_sec;
d_lastLogTime.tv_usec = time.tv_usec;
lp->data.payload_len = htonl(payloadLen);
lp->data.buffer = NULL;
if (payloadLen > 0) {
lp->data.buffer = new char[payloadLen];
if (!lp->data.buffer) {
fprintf(stderr, "vrpn_Log::logMessage: "
"Out of memory!\n");
delete lp;
return -1;
}
// need to explicitly override the const
memcpy((char *)lp->data.buffer, buffer, payloadLen);
}
// Insert the new message into the log
lp->next = d_logTail;
lp->prev = NULL;
if (d_logTail) {
d_logTail->prev = lp;
}
d_logTail = lp;
if (!d_firstEntry) {
d_firstEntry = lp;
}
return 0;
}
int vrpn_Log::setCompoundName(const char *name, int index)
{
char newName[2048]; // HACK
const char *dot;
size_t len;
// Change foo.bar, 5 to foo-5.bar
// and foo, 5 to foo-5
dot = strrchr(name, '.');
if (dot) {
strncpy(newName, name, dot - name);
newName[dot - name] = 0;
}
else {
strcpy(newName, name);
}
len = strlen(newName);
sprintf(newName + len, "-%d", index);
if (dot) {
strcat(newName, dot);
}
return setName(newName);
}
int vrpn_Log::setName(const char *name) { return setName(name, strlen(name)); }
int vrpn_Log::setName(const char *name, size_t len)
{
if (d_logFileName) {
delete[] d_logFileName;
}
d_logFileName = new char[1 + len];
if (!d_logFileName) {
fprintf(stderr, "vrpn_Log::setName: Out of memory!\n");
return -1;
}
strncpy(d_logFileName, name, len);
d_logFileName[len] = '\0';
return 0;
}
int vrpn_Log::setCookie(const char *cookieBuffer)
{
if (d_magicCookie) {
delete[] d_magicCookie;
}
d_magicCookie = new char[1 + vrpn_cookie_size()];
if (!d_magicCookie) {
fprintf(stderr, "vrpn_Log::setCookie: Out of memory.\n");
return -1;
}
strncpy(d_magicCookie, cookieBuffer, vrpn_cookie_size());
return 0;
}
long &vrpn_Log::logMode(void) { return d_logmode; }
int vrpn_Log::addFilter(vrpn_LOGFILTER filter, void *userdata)
{
vrpnLogFilterEntry *newEntry;
newEntry = new vrpnLogFilterEntry;
if (!newEntry) {
fprintf(stderr, "vrpn_Log::addFilter: Out of memory.\n");
return -1;
}
newEntry->filter = filter;
newEntry->userdata = userdata;
newEntry->next = d_filters;
d_filters = newEntry;
return 0;
}
timeval vrpn_Log::lastLogTime() { return d_lastLogTime; }
int vrpn_Log::checkFilters(vrpn_int32 payloadLen, struct timeval time,
vrpn_int32 type, vrpn_int32 sender,
const char *buffer)
{
vrpnLogFilterEntry *next;
vrpn_HANDLERPARAM p;
p.type = type;
p.sender = sender;
p.msg_time.tv_sec = time.tv_sec;
p.msg_time.tv_usec = time.tv_usec;
p.payload_len = payloadLen;
p.buffer = buffer;
for (next = d_filters; next; next = next->next) {
if ((*next->filter)(next->userdata, p)) {
// Don't log
return 1;
}
}
return 0;
}
/**
* @class vrpn_TypeDispatcher
* Handles types, senders, and callbacks.
* Also handles system messages through the same non-orthogonal technique
* as always.
*/
class vrpn_TypeDispatcher {
public:
vrpn_TypeDispatcher(void);
~vrpn_TypeDispatcher(void);
// ACCESSORS
int numTypes(void) const;
const char *typeName(int which) const;
vrpn_int32 getTypeID(const char *name);
///< Returns -1 if not found.
int numSenders(void) const;
const char *senderName(int which) const;
vrpn_int32 getSenderID(const char *name);
///< Returns -1 if not found.
// MANIPULATORS
vrpn_int32 addType(const char *name);
vrpn_int32 addSender(const char *name);
vrpn_int32 registerType(const char *name);
///< Calls addType() iff getTypeID() returns -1.
///< vrpn_Connection doesn't call this because it needs to know
///< whether or not to send a type message.
vrpn_int32 registerSender(const char *name);
///< Calls addSender() iff getSenderID() returns -1.
///< vrpn_Connection doesn't call this because it needs to know
///< whether or not to send a sender message.
int addHandler(vrpn_int32 type, vrpn_MESSAGEHANDLER handler, void *userdata,
vrpn_int32 sender);
int removeHandler(vrpn_int32 type, vrpn_MESSAGEHANDLER handler,
void *userdata, vrpn_int32 sender);
void setSystemHandler(vrpn_int32 type, vrpn_MESSAGEHANDLER handler);
// It'd make a certain amount of sense to unify these next few, but
// there are some places in the code that depend on the side effect of
// do_callbacks_for() NOT dispatching system messages.
int doCallbacksFor(vrpn_int32 type, vrpn_int32 sender, timeval time,
vrpn_uint32 len, const char *buffer);
int doSystemCallbacksFor(vrpn_int32 type, vrpn_int32 sender, timeval time,
vrpn_uint32 len, const char *buffer,
void *userdata);
int doSystemCallbacksFor(vrpn_HANDLERPARAM p, void *userdata);
void clear(void);
protected:
struct vrpnLocalMapping {
char *name; // Name of type
vrpnMsgCallbackEntry *who_cares; // Callbacks
vrpn_int32 cCares; // TCH 28 Oct 97
};
int d_numTypes;
vrpnLocalMapping d_types[vrpn_CONNECTION_MAX_TYPES];
int d_numSenders;
char *d_senders[vrpn_CONNECTION_MAX_SENDERS];