aboutsummaryrefslogtreecommitdiff
path: root/nxcomp/src/Misc.cpp
blob: 5acbca0721e6db25463d129c46e2d05f9532b4c7 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com)          */
/* Copyright (c) 2008-2017 Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>  */
/* Copyright (c) 2014-2022 Ulrich Sibiller <uli42@gmx.de>                 */
/* Copyright (c) 2014-2019 Mihai Moldovan <ionic@ionic.de>                */
/* Copyright (c) 2011-2022 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>*/
/* Copyright (c) 2015-2016 Qindel Group (http://www.qindel.com)           */
/*                                                                        */
/* NXCOMP, NX protocol compression and NX extensions to this software     */
/* are copyright of the aforementioned persons and companies.             */
/*                                                                        */
/* Redistribution and use of the present software is allowed according    */
/* to terms specified in the file LICENSE.nxcomp which comes in the       */
/* source distribution.                                                   */
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
/* NOTE: This software has received contributions from various other      */
/* contributors, only the core maintainers and supporters are listed as   */
/* copyright holders. Please contact us, if you feel you should be listed */
/* as copyright holder, as well.                                          */
/*                                                                        */
/**************************************************************************/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <unistd.h>
#include <csignal>

#include <errno.h>
#include <string.h>

#include "NXproto.h"

#include "MD5.h"

#include "Misc.h"
#include "Proxy.h"

//
// Set the verbosity level.
//

#define PANIC
#define WARNING
#define OPCODES
#undef  TEST
#undef  DEBUG

//
// By default nxproxy binds to all network interfaces, setting
// DEFAULT_LOOPBACK_BIND to 1 enables binding to the loopback
// device only.
//

const int DEFAULT_LOOPBACK_BIND = 0;

//
// TCP port offset applied to any NX port specification.
//

const int DEFAULT_NX_PROXY_PORT_OFFSET = 4000;

//
// Default TCP port used by client proxy to listen to
// X clients and by server proxy to connect to remote.
//

const int DEFAULT_NX_PROXY_PORT = 8;

//
// Default X display number that client proxy imitates.
//

const int DEFAULT_NX_X_PORT = 8;

//
// Default ports used for listening for cups, samba, http,
// multimedia and auxiliary X connections. Arbitrary ports
// can be used by passing the service's port at the proxy
// startup. By default ports are determined by adding the
// offset below to the offset of the proxied display. For
// example, if the proxy is impersonating the display :8,
// SMB tunnels can be created by connecting to port 3008.
//
// Considering that the NX server uses to start the first
// session at display offset 1000, we must lower the CUPS
// and SMB ports to avoid interference with normal X ses-
// sions run on the server.
//
// Font server connections are used to let the X server on
// the client connect to a font server on the NX server.
//
// Slave channels can be originated by both sides so we need
// different offsets in the case the user runs both proxies
// on the same host.
//

const int DEFAULT_NX_CUPS_PORT_OFFSET  = 2000;
const int DEFAULT_NX_SMB_PORT_OFFSET   = 3000;
const int DEFAULT_NX_MEDIA_PORT_OFFSET = 7000;
const int DEFAULT_NX_AUX_PORT_OFFSET   = 8000;
const int DEFAULT_NX_HTTP_PORT_OFFSET  = 9000;
const int DEFAULT_NX_FONT_PORT_OFFSET  = 10000;

const int DEFAULT_NX_SLAVE_PORT_CLIENT_OFFSET = 11000;
const int DEFAULT_NX_SLAVE_PORT_SERVER_OFFSET = 12000;

//
// Usage info and copyright.
//

static const char UsageInfo[] =
"\n\
  Usage: nxproxy [OPTIONS] host:port\n\
\n\
  -C           Specify that nxproxy has to run on the 'X client'\n\
               side, listening for connections and impersonating\n\
               an X server.\n\
\n\
  -S           Specify that nxproxy has to run in 'X server' mode,\n\
               thus forwarding the connections to daemons running\n\
               on the client.\n\
\n\
  -h           Print this message.\n\
\n\
  -v           Print version information.\n\
\n\
  -d <n>       Set log level (0=FATAL, 1=ERROR, 2=WARNING, 3=INFO,\n\
               4=DEBUG). Default is 0.\n\
\n\
  -o <file>    Name of the logfile. Default is stderr.\n\
\n\
  -f <string>  Specify log format. The characters in <string> define\n\
               how the loglines are formatted. The following characters\n\
               are supported, default is 0:\n\
               0       only the plain text without any additions\n\
               u       include time\n\
               l       include loglevel\n\
               T       include thread ids\n\
               L       include the source code location of the log\n\
\n\
  host:port    Put at the end, specifies the host and port of the\n\
               listening proxy.\n\
\n\
  name=value   Set the NX option to the provided value.\n\
\n\
  Multiple NX options can be specified in the DISPLAY environment\n\
  or on the command line, by using the nx/nx,option=value notation.\n\
\n\
  Options:\n\
\n\
  link=s       An indication of the link speed that is going to be\n\
               used between the proxies. Usually the compression\n\
               and the other link parameters depend on this setting.\n\
               The value can be either 'modem', 'isdn', 'adsl',\n\
               'wan', 'lan', 'local' or a bandwidth specification,\n\
               like for example '56k', '1m', '100m', etc.\n\
\n\
  type=s       Type of session. Known types are: 'agent', 'proxy' and\n\
               'shadow'. The following types are also allowed and will\n\
               map to one of the three mentioned before: 'desktop',\n\
               'rootless', 'console', 'default', 'gnome', 'kde',\n\
               'cde', 'xdm', 'win', 'vnc', 'application', 'raw'\n\
\n\
  display=s    Specify the real display where X connections have\n\
               to be forwarded by the proxy running on the client.\n\
\n\
  listen=n     Local port used for accepting the proxy connection.\n\
\n\
  loopback=b   Bind to the loopback device only.\n\
\n\
  accept=s     Name or IP of host that can connect to the proxy.\n\
\n\
  connect=s    Name or IP of host that the proxy will connect to.\n\
\n\
  port=n       Remote port used for the connection.\n\
\n\
  retry=n      Number of connection attempts.\n\
\n\
  root=s       The root directory for the session. Usually is the\n\
               C-* or S-* in the .nx directory in the user's home,\n\
               with '*' being the virtual display.\n\
\n\
  session=s    Name of the session file. The default is the name\n\
               'session' in the session directory.\n\
\n\
  errors=s     Name of the log file used by the proxy. The default\n\
               is the name 'errors' in the session directory.\n\
\n\
  stats=s      Name of the file where the proxy statistics are writ-\n\
               ten to. The default is a file 'stats' in the session\n\
               directory. The proxy replaces the data in the file\n\
               whenever it receives a SIGUSR1 or SIGUSR2 signal:\n\
\n\
               SIGUSR1    Gives total statistics, i.e. statistics\n\
                          collected since the beginning of the\n\
                          session.\n\
\n\
               SIGUSR2    Gives partial statistics, i.e. statist-\n\
                          ics collected since the last time this\n\
                          signal was received.\n\
\n\
  cookie=s     Use the provided cookie for authenticating to the\n\
               remote proxy. The same cookie is used as the fake\n\
               value used for the X authorization. The fake cookie\n\
               is replaced on the X server side with the real cookie\n\
               to be used for the display, so that the real cookie\n\
               doesn't have to travel over the net. When not using\n\
               a proxy cookie, any host will be able to connect to\n\
               the proxy. See also the 'accept' parameter.\n\
\n\
  nodelay=b    A boolean indicating if TCP_NODELAY has to be set\n\
               on the proxy link. Old Linux kernels had problems\n\
               with handling TCP_NODELAY on PPP links.\n\
\n\
  policy=b     Let or not the agent decide when it is the best time\n\
               to flush the proxy link. If set to 0, the proxy will\n\
               flush any encoded data immediately. The option has\n\
               only effect on the X client side proxy.\n\
\n\
  render=b     Enable or disable use of the RENDER extension.\n\
\n\
  taint=b      Try to suppress trivial sources of X roundtrips by\n\
               generating the reply on the X client side.\n\
\n\
  delta=b      Enable X differential compression.\n\
\n\
  data=n       Enable or disable the ZLIB data compression. It is\n\
               possible to specify a value between 0 and 9. Usual-\n\
               ly the value is chosen automatically based on the\n\
               requested link setting.\n\
\n\
  stream=n     Enable or disable the ZLIB stream compression. The\n\
               value, between 0 and 9, is usually determined accor-\n\
               ding to the requested link setting.\n\
\n\
  limit=n      Specify a bitrate limit allowed for this session.\n\
\n\
  memory=n     Trigger memory optimizations used to keep the size\n\
               of X buffers small. This is useful on embedded plat-\n\
               forms, or where memory is scarce.\n\
\n\
  cache=n      Size of the in-memory X message cache. Setting the\n\
               value to 0 will disable the memory cache as well\n\
               as the NX differential compression.\n\
\n\
  images=n     Size of the persistent image cache.\n\
\n\
  shseg=n      Enable the use of the MIT-SHM extension between the\n\
               NX client proxy and the real X server. A value greater\n\
               than 1 is assumed to be the size of requested shared\n\
               memory segment. By default, the size of the segment is\n\
               determined based on the size of the in-memory cache.\n\
\n\
  load=b       Enable loading a persistent X message cache at the\n\
               proxy startup.\n\
\n\
  save=b       Enable saving a persistent X message cache at the\n\
               end of session.\n\
\n\
  cups=n       Enable or disable forwarding of CUPS connections,\n\
               by listening on the optional port 'n'.\n\
\n\
  aux=n        Enable or disable forwarding of the auxiliary X chan-\n\
               nel used for controlling the keyboard. The 'keybd=n'\n\
               form is accepted for backward compatibility.\n\
\n\
  smb=n        Enable or disable forwarding of SMB connections. The\n\
               'samba=n' form is accepted for backward compatibility.\n\
\n\
  media=n      Enable forwarding of audio connections.\n\
\n\
  http=n       Enable forwarding of HTTP connections.\n\
\n\
  font=n       Enable forwarding of reversed connections to a font\n\
               server running on the NX server.\n\
\n\
  file=n       Enable forwarding of file transfer connections.\n\
\n\
  mask=n       Determine the distribution of channel ids between the\n\
               proxies. By default, channels whose ids are multiple\n\
               of 8 (starting from 0) are reserved for the NX client\n\
               side. All the other channels can be allocated by the\n\
               NX server side.\n\
\n\
  timeout=t    Specify the keep-alive timeout used by proxies to\n\
               determine if there is a network problem preventing\n\
               communication with the remote peer. A value of 0\n\
               disables the check.\n\
\n\
  cleanup=t    Specify the number of seconds the proxy has to wait\n\
               at session shutdown before closing all channels.\n\
               The feature is used by the NX server to ensure that\n\
               services are disconnected before shutting down the\n\
               link.\n\
\n\
  pack=s       Determine the method used to compress images.\n\
\n\
  product=s    The product id of the client or server. The value is\n\
               ignored by the proxy, but the client or server can\n\
               provide it to facilitate the support.\n\
\n\
  core=b       Enable production of core dumps when aborting the\n\
               proxy connection.\n\
\n\
  options=s    Specify an additional file containing options that\n\
               has to be merged with option read from the command\n\
               line or the environment.\n\
\n\
  kill=n       Add the given process to the list of daemons that\n\
               must be terminated at session shutdown. Multiple\n\
               'kill=n' options can be specified. The proxy will\n\
               send them a SIGTERM signal just before exiting.\n\
\n\
  strict=b     Optimize for responsiveness, rather than for the best\n\
               use of all the available bandwidth.\n\
\n\
  encryption=b Should be set to 1 if the proxy is running as part of\n\
               a program providing encryption of the point to point\n\
               communication.\n\
\n\
autodpi=b\n\
autograb=b\n\
backingstore=n\n\
client=s\n\
clients=s\n\
clipboard=s\n\
composite=n\n\
copysize=n\n\
defer=n\n\
fullscreen=n\n\
geometry=s\n\
kbtype=s\n\
keyboard=s\n\
keyconv=s\n\
magicpixel=b\n\
menu=n\n\
resize=b\n\
rootless=b\n\
shadow=n\n\
shadowmode=s\n\
shadowuid=n\n\
shmem=b\n\
shpix=b\n\
sleep=n\n\
state=s\n\
streaming=n\n\
textclipboard=b\n\
tile=s\n\
tolerancechecks=s\n\
xinerama=b\n\
               These options are interpreted by the NX agent. They\n\
               are ignored by the proxy.\n\
\n\
  Environment:\n\
\n\
  NX_ROOT      The root NX directory is the place where the session\n\
               directory and the cache files are created. This is\n\
               usually overridden by passing the 'root=' option. By\n\
               default, the root NX directory is assumed to be the\n\
               directory '.nx' in the user's home.\n\
\n\
  NX_SYSTEM    The directory where NX programs and libraries reside.\n\
               If not set, the value is assumed to be '/usr/NX'.\n\
               Programs, libraries and data files are respectedly\n\
               searched in the 'bin', 'lib' and 'share' subdirecto-\n\
               ries.\n\
\n\
  NX_HOME      The NX user's home directory. If NX_ROOT is not set\n\
               or invalid, the user's NX directory is created here.\n\
\n\
  NX_TEMP      The directory where all temporary files are to be created.\n\
\n\
  NX_CLIENT    The full path to the nxclient executable. If the va-\n\
               riable is not set, the nxclient executable will be\n\
               run assuming that the program is in the system path.\n\
               This can be useful on platforms like Windows and the\n\
               Mac where nxclient is located in a different direct-\n\
               ory compared to the other programs, to make easier\n\
               for the user to execute the program from the shell.\n\
               The nxclient executable will be used for displaying\n\
               the menu and request windows to the user.\n\
\n\
  NX_SLAVE_CMD The full path to the slave channel handler. When the\n\
               slave channel is enabled, the agent will listen on a\n\
               port and forward the connection to the NX_SLAVE_CMD\n\
               program. This can be used to implement agent/proxy\n\
               communication for applications such as serial port and\n\
               USB forwarding.\n\
\n\
  Shell environment:\n\
\n\
  HOME         The variable is checked in the case NX_HOME is not\n\
               set, null or invalid.\n\
\n\
  TEMP         The variable is checked whenever the NX_TEMP direct-\n\
               ory is not set, null or invalid.\n\
\n\
  PATH         The path where all executables are searched, except\n\
               nxclient. If NX_CLIENT is not set, also the nxclient\n\
               executable is searched in the system path.\n\
\n\
  LD_LIBRARY_PATH\n\
               System-wide library search order. This should be set\n\
               by the program invoking the proxy.\n\
\n\
  DISPLAY      On the X server side, the DISPLAY variable indicates\n\
               the location of the X11 server. When nxcomp is used\n\
               as a transport library, the DISPLAY may represent a\n\
               NX transport specification and options can passed in\n\
               the form nx/nx,option=value...\n\
\n\
  XAUTHORITY   This is the file containing the X11 authorization\n\
               cookie. If not set, the file is assumed to be in\n\
               the user's home (either NX_HOME or HOME).\n\
\n\
";

const char *GetUsageInfo()
{
  return UsageInfo;
}

static const char CopyrightInfo[] =
"\
Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com)\n\
Copyright (c) 2008-2017 Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>\n\
Copyright (c) 2014-2022 Ulrich Sibiller <uli42@gmx.de>\n\
Copyright (c) 2014-2019 Mihai Moldovan <ionic@ionic.de>\n\
Copyright (c) 2011-2022 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>\n\
Copyright (c) 2015-2016 Qindel Group (http://www.qindel.com)\n\
\n\
NXCOMP, NX protocol compression and NX extensions to this software\n\
are copyright of the aforementioned persons and companies.\n\
\n\
Redistribution and use of the present software is allowed according\n\
to terms specified in the file LICENSE.nxcomp which comes in the\n\
source distribution.\n\
\n\
All rights reserved.\n\
\n\
NOTE: This software has received contributions from various other\n\
contributors, only the core maintainers and supporters are listed as\n\
copyright holders. Please contact us, if you feel you should be listed\n\
as copyright holder, as well.\n\
";

const char *GetCopyrightInfo()
{
  return CopyrightInfo;
}

static const char OtherCopyrightInfo[] =
"\
NX protocol compression is derived from DXPC project.\n\
\n\
Copyright (c) 1995,1996 Brian Pane\n\
Copyright (c) 1996,1997 Zachary Vonler and Brian Pane\n\
Copyright (c) 1999 Kevin Vigor and Brian Pane\n\
Copyright (c) 2000,2003 Gian Filippo Pinzari and Brian Pane\n\
\n\
All rights reserved.\n\
";

const char *GetOtherCopyrightInfo()
{
  return OtherCopyrightInfo;
}

int _hostBigEndian  = 0;
int _storeBigEndian = 0;

const unsigned int IntMask[33] =
{
  0x00000000,
  0x00000001,
  0x00000003,
  0x00000007,
  0x0000000f,
  0x0000001f,
  0x0000003f,
  0x0000007f,
  0x000000ff,
  0x000001ff,
  0x000003ff,
  0x000007ff,
  0x00000fff,
  0x00001fff,
  0x00003fff,
  0x00007fff,
  0x0000ffff,
  0x0001ffff,
  0x0003ffff,
  0x0007ffff,
  0x000fffff,
  0x001fffff,
  0x003fffff,
  0x007fffff,
  0x00ffffff,
  0x01ffffff,
  0x03ffffff,
  0x07ffffff,
  0x0fffffff,
  0x1fffffff,
  0x3fffffff,
  0x7fffffff,
  0xffffffff
};

unsigned int GetUINT(unsigned const char *buffer, int bigEndian)
{
  //
  // It doesn't work on SPARCs if the buffer
  // is not aligned to the word boundary. We
  // should check the CPU, not the OS as this
  // surely applies to other architectures.
  //

  #ifndef __sun

  if (_hostBigEndian == bigEndian)
  {
    return *((unsigned short *) buffer);
  }

  #else

  if (_hostBigEndian == bigEndian && ((unsigned int) buffer) & 0x1 == 0)
  {
    return *((unsigned short *) buffer);
  }

  #endif

  unsigned int result;

  if (bigEndian)
  {
    result = *buffer;

    result <<= 8;

    result += buffer[1];
  }
  else
  {
    result = buffer[1];

    result <<= 8;

    result += *buffer;
  }

  return result;
}

unsigned int GetULONG(unsigned const char *buffer, int bigEndian)
{
  //
  // It doesn't work on SPARCs if the buffer
  // is not aligned to word the boundary.
  //

  #ifndef __sun

  if (_hostBigEndian == bigEndian)
  {
    return *((unsigned int *) buffer);
  }

  #else

  if (_hostBigEndian == bigEndian && ((unsigned int) buffer) & 0x3 == 0)
  {
    return *((unsigned int *) buffer);
  }

  #endif

  const unsigned char *next = (bigEndian ? buffer : buffer + 3);

  unsigned int result = 0;

  for (int i = 0; i < 4; i++)
  {
    result <<= 8;

    result += *next;

    if (bigEndian)
    {
      next++;
    }
    else
    {
      next--;
    }
  }

  return result;
}

void PutUINT(unsigned int value, unsigned char *buffer, int bigEndian)
{
  if (_hostBigEndian == bigEndian)
  {
    *((unsigned short *) buffer) = value;

    return;
  }

  if (bigEndian)
  {
    buffer[1] = (unsigned char) (value & 0xff);

    value >>= 8;

    *buffer = (unsigned char) value;
  }
  else
  {
    *buffer = (unsigned char) (value & 0xff);

    value >>= 8;

    buffer[1] = (unsigned char) value;
  }
}

void PutULONG(unsigned int value, unsigned char *buffer, int bigEndian)
{
  if (_hostBigEndian == bigEndian)
  {
    *((unsigned int *) buffer) = value;

    return;
  }

  if (bigEndian)
  {
    buffer += 3;

    for (int i = 4; i > 0; i--)
    {
      *buffer-- = (unsigned char) (value & 0xff);

      value >>= 8;
    }
  }
  else
  {
    for (int i = 4; i > 0; i--)
    {
      *buffer++ = (unsigned char) (value & 0xff);

      value >>= 8;
    }
  }
}

int CheckData(istream *fs)
{
  if (fs == NULL || fs -> fail())
  {
    return -1;
  }

  return 1;
}

int CheckData(ostream *fs)
{
  if (fs == NULL || fs -> fail())
  {
    return -1;
  }

  return 1;
}

int PutData(ostream *fs, const unsigned char *buffer, int size)
{
  fs -> write((char *) buffer, size);

  #ifdef DEBUG
  *logofs << "PutData: Written " << size << " bytes with eof "
          << fs -> eof() << " fail " << fs -> fail() << " and bad "
          << fs -> bad() << ".\n" << logofs_flush;
  #endif

  if (fs -> fail())
  {
    return -1;
  }

  return size;
}

int GetData(istream *fs, unsigned char *buffer, int size)
{
  fs -> read((char *) buffer, size);

  #ifdef DEBUG
  *logofs << "GetData: Read " << size << " bytes with eof "
          << fs -> eof() << " fail " << fs -> fail()
          << " and bad " << fs -> bad() << ".\n"
          << logofs_flush;
  #endif

  #ifdef __APPLE__

  if (fs -> bad())
  {
    return -1;
  }

  #else

  if (fs -> fail())
  {
    return -1;
  }

  #endif

  return size;
}

int FlushData(ostream *fs)
{
  fs -> flush();

  if (fs -> fail())
  {
    return -1;
  }

  return 1;
}

unsigned int RoundUp2(unsigned int x)
{
  unsigned int y = x / 2;

  y *= 2;

  if (y != x)
  {
    y += 2;
  }

  return y;
}

unsigned int RoundUp4(unsigned int x)
{
  unsigned int y = x / 4;

  y *= 4;

  if (y != x)
  {
    y += 4;
  }

  return y;
}

unsigned int RoundUp8(unsigned int x)
{
  unsigned int y = x / 8;

  y *= 8;

  if (y != x)
  {
    y += 8;
  }

  return y;
}

const char *DumpSignal(int signal)
{
  switch (signal)
  {
    case SIGCHLD:
    {
      return "SIGCHLD";
    }
    case SIGUSR1:
    {
      return "SIGUSR1";
    }
    case SIGUSR2:
    {
      return "SIGUSR2";
    }
    case SIGHUP:
    {
      return "SIGHUP";
    }
    case SIGINT:
    {
      return "SIGINT";
    }
    case SIGTERM:
    {
      return "SIGTERM";
    }
    case SIGPIPE:
    {
      return "SIGPIPE";
    }
    case SIGALRM:
    {
      return "SIGALRM";
    }
    case SIGVTALRM:
    {
      return "SIGVTALRM";
    }
    case SIGWINCH:
    {
      return "SIGWINCH";
    }
    case SIGIO:
    {
      return "SIGIO";
    }
    case SIGTSTP:
    {
      return "SIGTSTP";
    }
    case SIGTTIN:
    {
      return "SIGTTIN";
    }
    case SIGTTOU:
    {
      return "SIGTTOU";
    }
    case SIGSEGV:
    {
      return "SIGSEGV";
    }
    case SIGABRT:
    {
      return "SIGABRT";
    }
    default:
    {
      return "Unknown";
    }
  }
}

const char *DumpPolicy(int type)
{
  switch ((T_flush_policy) type)
  {
    case policy_immediate:
    {
      return "immediate";
    }
    case policy_deferred:
    {
      return "deferred";
    }
    default:
    {
      #ifdef PANIC
      *logofs << "Misc: PANIC! Unknown policy type '"
              << type << "'.\n" << logofs_flush;
      #endif

      cerr << "Error" << ": Unknown policy type '"
           << type << "'.\n";

      HandleCleanup();
    }
  }
}

const char *DumpAction(int type)
{
  T_store_action action = (T_store_action) type;

  if (action == IS_HIT)
  {
    return "is_hit";
  }
  else if (action == IS_ADDED)
  {
    return "is_added";
  }
  else if (action == is_discarded)
  {
    return "is_discarded";
  }
  else if (action == is_removed)
  {
    return "is_removed";
  }
  else
  {
    #ifdef PANIC
    *logofs << "Misc: PANIC! Unknown store action '"
            << type << "'.\n" << logofs_flush;
    #endif

    cerr << "Error" << ": Unknown store action '"
         << type << "'.\n";

    HandleCleanup();
  }
}

const char *DumpState(int type)
{
  switch ((T_split_state) type)
  {
    case split_added:
    {
      return "split_added";
    }
    case split_missed:
    {
      return "split_missed";
    }
    case split_loaded:
    {
      return "split_loaded";
    }
    case split_aborted:
    {
      return "split_aborted";
    }
    case split_notified:
    {
      return "split_notified";
    }
    default:
    {
      #ifdef PANIC
      *logofs << "Misc: PANIC! Unknown split state '"
              << type << "'.\n" << logofs_flush;
      #endif

      cerr << "Error" << ": Unknown split state '"
           << type << "'.\n";

      HandleCleanup();
    }
  }
}

const char *DumpControl(int code)
{
  switch ((T_proxy_code) code)
  {
    case code_new_x_connection:
    {
      return "code_new_x_connection";
    }
    case code_new_cups_connection:
    {
      return "code_new_cups_connection";
    }
    case code_new_aux_connection:
    {
      return "code_new_aux_connection";
    }
    case code_new_smb_connection:
    {
      return "code_new_smb_connection";
    }
    case code_new_media_connection:
    {
      return "code_new_media_connection";
    }
    case code_switch_connection:
    {
      return "code_switch_connection";
    }
    case code_drop_connection:
    {
      return "code_drop_connection";
    }
    case code_finish_connection:
    {
      return "code_finish_connection";
    }
    case code_begin_congestion:
    {
      return "code_begin_congestion";
    }
    case code_end_congestion:
    {
      return "code_end_congestion";
    }
    case code_alert_request:
    {
      return "code_alert_request";
    }
    case code_alert_reply:
    {
      return "code_alert_reply";
    }
    case code_reset_request:
    {
      return "code_reset_request";
    }
    case code_reset_reply:
    {
      return "code_reset_reply";
    }
    case code_load_request:
    {
      return "code_load_request";
    }
    case code_load_reply:
    {
      return "code_load_reply";
    }
    case code_save_request:
    {
      return "code_save_request";
    }
    case code_save_reply:
    {
      return "code_save_reply";
    }
    case code_shutdown_request:
    {
      return "code_shutdown_request";
    }
    case code_shutdown_reply:
    {
      return "code_shutdown_reply";
    }
    case code_control_token_request:
    {
      return "code_control_token_request";
    }
    case code_control_token_reply:
    {
      return "code_control_token_reply";
    }
    case code_configuration_request:
    {
      return "code_configuration_request";
    }
    case code_configuration_reply:
    {
      return "code_configuration_reply";
    }
    case code_statistics_request:
    {
      return "code_statistics_request";
    }
    case code_statistics_reply:
    {
      return "code_statistics_reply";
    }
    case code_new_http_connection:
    {
      return "code_new_http_connection";
    }
    case code_sync_request:
    {
      return "code_sync_request";
    }
    case code_sync_reply:
    {
      return "code_sync_reply";
    }
    case code_new_font_connection:
    {
      return "code_new_font_connection";
    }
    case code_new_slave_connection:
    {
      return "code_new_slave_connection";
    }
    case code_finish_listeners:
    {
      return "code_finish_listeners";
    }
    case code_split_token_request:
    {
      return "code_split_token_request";
    }
    case code_split_token_reply:
    {
      return "code_split_token_reply";
    }
    case code_data_token_request:
    {
      return "code_data_token_request";
    }
    case code_data_token_reply:
    {
      return "code_data_token_reply";
    }
    default:
    {
      #ifdef WARNING
      *logofs << "Misc: WARNING! Unknown control code '"
              << code << "'.\n" << logofs_flush;
      #endif

      cerr << "Warning" << ": Unknown control code '"
           << code << "'.\n";

      return "unknown";
    }
  }
}

const char *DumpSession(int code)
{
  switch ((T_session_mode) code)
  {
    case session_agent:
    {
      return "session_agent";
    }
    case session_shadow:
    {
      return "session_shadow";
    }
    case session_proxy:
    {
      return "session_proxy";
    }
    default:
    {
      #ifdef WARNING
      *logofs << "Misc: WARNING! Unknown session type '"
              << code << "'.\n" << logofs_flush;
      #endif

      cerr << "Warning" << ": Unknown session type '"
           << code << "'.\n";

      return "unknown";
    }
  }
}

const char *DumpToken(int type)
{
  switch ((T_token_type) type)
  {
    case token_control:
    {
      return "token_control";
    }
    case token_split:
    {
      return "token_split";
    }
    case token_data:
    {
      return "token_data";
    }
    default:
    {
      #ifdef WARNING
      *logofs << "Misc: WARNING! Unknown token type '"
              << type << "'.\n" << logofs_flush;
      #endif

      cerr << "Warning" << ": Unknown token type '"
           << type << "'.\n";

      return "unknown";
    }
  }
}

//
// Always include this in code as it is generally
// needed to test channels and split store.
//

const char *DumpChecksum(const void *checksum)
{
  static char string[MD5_LENGTH * 2 + 1];

  if (checksum != NULL)
  {
    for (unsigned int i = 0; i < MD5_LENGTH; i++)
    {
      sprintf(string + (i * 2), "%02X", ((unsigned char *) checksum)[i]);
    }
  }
  else
  {
    strcpy(string, "null");
  }

  return string;
}

//
// Define OPCODES here and in the channel
// if you want to log the opcode literal.
//

#ifdef OPCODES

const char *DumpOpcode(const int &opcode)
{
  switch (opcode)
  {
    case X_CreateWindow:
    {
      return "X_CreateWindow";
    }
    case X_ChangeWindowAttributes:
    {
      return "X_ChangeWindowAttributes";
    }
    case X_GetWindowAttributes:
    {
      return "X_GetWindowAttributes";
    }
    case X_DestroyWindow:
    {
      return "X_DestroyWindow";
    }
    case X_DestroySubwindows:
    {
      return "X_DestroySubwindows";
    }
    case X_ChangeSaveSet:
    {
      return "X_ChangeSaveSet";
    }
    case X_ReparentWindow:
    {
      return "X_ReparentWindow";
    }
    case X_MapWindow:
    {
      return "X_MapWindow";
    }
    case X_MapSubwindows:
    {
      return "X_MapSubwindows";
    }
    case X_UnmapWindow:
    {
      return "X_UnmapWindow";
    }
    case X_UnmapSubwindows:
    {
      return "X_UnmapSubwindows";
    }
    case X_ConfigureWindow:
    {
      return "X_ConfigureWindow";
    }
    case X_CirculateWindow:
    {
      return "X_CirculateWindow";
    }
    case X_GetGeometry:
    {
      return "X_GetGeometry";
    }
    case X_QueryTree:
    {
      return "X_QueryTree";
    }
    case X_InternAtom:
    {
      return "X_InternAtom";
    }
    case X_GetAtomName:
    {
      return "X_GetAtomName";
    }
    case X_ChangeProperty:
    {
      return "X_ChangeProperty";
    }
    case X_DeleteProperty:
    {
      return "X_DeleteProperty";
    }
    case X_GetProperty:
    {
      return "X_GetProperty";
    }
    case X_ListProperties:
    {
      return "X_ListProperties";
    }
    case X_SetSelectionOwner:
    {
      return "X_SetSelectionOwner";
    }
    case X_GetSelectionOwner:
    {
      return "X_GetSelectionOwner";
    }
    case X_ConvertSelection:
    {
      return "X_ConvertSelection";
    }
    case X_SendEvent:
    {
      return "X_SendEvent";
    }
    case X_GrabPointer:
    {
      return "X_GrabPointer";
    }
    case X_UngrabPointer:
    {
      return "X_UngrabPointer";
    }
    case X_GrabButton:
    {
      return "X_GrabButton";
    }
    case X_UngrabButton:
    {
      return "X_UngrabButton";
    }
    case X_ChangeActivePointerGrab:
    {
      return "X_ChangeActivePointerGrab";
    }
    case X_GrabKeyboard:
    {
      return "X_GrabKeyboard";
    }
    case X_UngrabKeyboard:
    {
      return "X_UngrabKeyboard";
    }
    case X_GrabKey:
    {
      return "X_GrabKey";
    }
    case X_UngrabKey:
    {
      return "X_UngrabKey";
    }
    case X_AllowEvents:
    {
      return "X_AllowEvents";
    }
    case X_GrabServer:
    {
      return "X_GrabServer";
    }
    case X_UngrabServer:
    {
      return "X_UngrabServer";
    }
    case X_QueryPointer:
    {
      return "X_QueryPointer";
    }
    case X_GetMotionEvents:
    {
      return "X_GetMotionEvents";
    }
    case X_TranslateCoords:
    {
      return "X_TranslateCoords";
    }
    case X_WarpPointer:
    {
      return "X_WarpPointer";
    }
    case X_SetInputFocus:
    {
      return "X_SetInputFocus";
    }
    case X_GetInputFocus:
    {
      return "X_GetInputFocus";
    }
    case X_QueryKeymap:
    {
      return "X_QueryKeymap";
    }
    case X_OpenFont:
    {
      return "X_OpenFont";
    }
    case X_CloseFont:
    {
      return "X_CloseFont";
    }
    case X_QueryFont:
    {
      return "X_QueryFont";
    }
    case X_QueryTextExtents:
    {
      return "X_QueryTextExtents";
    }
    case X_ListFonts:
    {
      return "X_ListFonts";
    }
    case X_ListFontsWithInfo:
    {
      return "X_ListFontsWithInfo";
    }
    case X_SetFontPath:
    {
      return "X_SetFontPath";
    }
    case X_GetFontPath:
    {
      return "X_GetFontPath";
    }
    case X_CreatePixmap:
    {
      return "X_CreatePixmap";
    }
    case X_FreePixmap:
    {
      return "X_FreePixmap";
    }
    case X_CreateGC:
    {
      return "X_CreateGC";
    }
    case X_ChangeGC:
    {
      return "X_ChangeGC";
    }
    case X_CopyGC:
    {
      return "X_CopyGC";
    }
    case X_SetDashes:
    {
      return "X_SetDashes";
    }
    case X_SetClipRectangles:
    {
      return "X_SetClipRectangles";
    }
    case X_FreeGC:
    {
      return "X_FreeGC";
    }
    case X_ClearArea:
    {
      return "X_ClearArea";
    }
    case X_CopyArea:
    {
      return "X_CopyArea";
    }
    case X_CopyPlane:
    {
      return "X_CopyPlane";
    }
    case X_PolyPoint:
    {
      return "X_PolyPoint";
    }
    case X_PolyLine:
    {
      return "X_PolyLine";
    }
    case X_PolySegment:
    {
      return "X_PolySegment";
    }
    case X_PolyRectangle:
    {
      return "X_PolyRectangle";
    }
    case X_PolyArc:
    {
      return "X_PolyArc";
    }
    case X_FillPoly:
    {
      return "X_FillPoly";
    }
    case X_PolyFillRectangle:
    {
      return "X_PolyFillRectangle";
    }
    case X_PolyFillArc:
    {
      return "X_PolyFillArc";
    }
    case X_PutImage:
    {
      return "X_PutImage";
    }
    case X_GetImage:
    {
      return "X_GetImage";
    }
    case X_PolyText8:
    {
      return "X_PolyText8";
    }
    case X_PolyText16:
    {
      return "X_PolyText16";
    }
    case X_ImageText8:
    {
      return "X_ImageText8";
    }
    case X_ImageText16:
    {
      return "X_ImageText16";
    }
    case X_CreateColormap:
    {
      return "X_CreateColormap";
    }
    case X_FreeColormap:
    {
      return "X_FreeColormap";
    }
    case X_CopyColormapAndFree:
    {
      return "X_CopyColormapAndFree";
    }
    case X_InstallColormap:
    {
      return "X_InstallColormap";
    }
    case X_UninstallColormap:
    {
      return "X_UninstallColormap";
    }
    case X_ListInstalledColormaps:
    {
      return "X_ListInstalledColormaps";
    }
    case X_AllocColor:
    {
      return "X_AllocColor";
    }
    case X_AllocNamedColor:
    {
      return "X_AllocNamedColor";
    }
    case X_AllocColorCells:
    {
      return "X_AllocColorCells";
    }
    case X_AllocColorPlanes:
    {
      return "X_AllocColorPlanes";
    }
    case X_FreeColors:
    {
      return "X_FreeColors";
    }
    case X_StoreColors:
    {
      return "X_StoreColors";
    }
    case X_StoreNamedColor:
    {
      return "X_StoreNamedColor";
    }
    case X_QueryColors:
    {
      return "X_QueryColors";
    }
    case X_LookupColor:
    {
      return "X_LookupColor";
    }
    case X_CreateCursor:
    {
      return "X_CreateCursor";
    }
    case X_CreateGlyphCursor:
    {
      return "X_CreateGlyphCursor";
    }
    case X_FreeCursor:
    {
      return "X_FreeCursor";
    }
    case X_RecolorCursor:
    {
      return "X_RecolorCursor";
    }
    case X_QueryBestSize:
    {
      return "X_QueryBestSize";
    }
    case X_QueryExtension:
    {
      return "X_QueryExtension";
    }
    case X_ListExtensions:
    {
      return "X_ListExtensions";
    }
    case X_ChangeKeyboardMapping:
    {
      return "X_ChangeKeyboardMapping";
    }
    case X_GetKeyboardMapping:
    {
      return "X_GetKeyboardMapping";
    }
    case X_ChangeKeyboardControl:
    {
      return "X_ChangeKeyboardControl";
    }
    case X_GetKeyboardControl:
    {
      return "X_GetKeyboardControl";
    }
    case X_Bell:
    {
      return "X_Bell";
    }
    case X_ChangePointerControl:
    {
      return "X_ChangePointerControl";
    }
    case X_GetPointerControl:
    {
      return "X_GetPointerControl";
    }
    case X_SetScreenSaver:
    {
      return "X_SetScreenSaver";
    }
    case X_GetScreenSaver:
    {
      return "X_GetScreenSaver";
    }
    case X_ChangeHosts:
    {
      return "X_ChangeHosts";
    }
    case X_ListHosts:
    {
      return "X_ListHosts";
    }
    case X_SetAccessControl:
    {
      return "X_SetAccessControl";
    }
    case X_SetCloseDownMode:
    {
      return "X_SetCloseDownMode";
    }
    case X_KillClient:
    {
      return "X_KillClient";
    }
    case X_RotateProperties:
    {
      return "X_RotateProperties";
    }
    case X_ForceScreenSaver:
    {
      return "X_ForceScreenSaver";
    }
    case X_SetPointerMapping:
    {
      return "X_SetPointerMapping";
    }
    case X_GetPointerMapping:
    {
      return "X_GetPointerMapping";
    }
    case X_SetModifierMapping:
    {
      return "X_SetModifierMapping";
    }
    case X_GetModifierMapping:
    {
      return "X_GetModifierMapping";
    }
    case X_NoOperation:
    {
      return "X_NoOperation";
    }
    case X_NXInternalGenericData:
    {
      return "X_NXInternalGenericData";
    }
    //
    // case X_NXInternalGenericReply:
    // {
    //   return "X_NXInternalGenericReply";
    // }
    //
    case X_NXInternalGenericRequest:
    {
      return "X_NXInternalGenericRequest";
    }
    case X_NXInternalShapeExtension:
    {
      return "X_NXInternalShapeExtension";
    }
    case X_NXGetControlParameters:
    {
      return "X_NXGetControlParameters";
    }
    case X_NXGetCleanupParameters:
    {
      return "X_NXGetCleanupParameters";
    }
    case X_NXGetImageParameters:
    {
      return "X_NXGetImageParameters";
    }
    case X_NXGetUnpackParameters:
    {
      return "X_NXGetUnpackParameters";
    }
    case X_NXGetShmemParameters:
    {
      return "X_NXGetShmemParameters";
    }
    case X_NXGetFontParameters:
    {
      return "X_NXGetFontParameters";
    }
    case X_NXSetExposeParameters:
    {
      return "X_NXSetExposeParameters";
    }
    case X_NXSetCacheParameters:
    {
      return "X_NXSetCacheParameters";
    }
    case X_NXStartSplit:
    {
      return "X_NXStartSplit";
    }
    case X_NXEndSplit:
    {
      return "X_NXEndSplit";
    }
    case X_NXSplitData:
    {
      return "X_NXSplitData";
    }
    case X_NXSplitEvent:
    {
      return "X_NXSplitEvent";
    }
    case X_NXCommitSplit:
    {
      return "X_NXCommitSplit";
    }
    case X_NXFinishSplit:
    {
      return "X_NXFinishSplit";
    }
    case X_NXAbortSplit:
    {
      return "X_NXAbortSplit";
    }
    case X_NXFreeSplit:
    {
      return "X_NXFreeSplit";
    }
    case X_NXSetUnpackGeometry:
    {
      return "X_NXSetUnpackGeometry";
    }
    case X_NXSetUnpackColormap:
    {
      return "X_NXSetUnpackColormap";
    }
    case X_NXSetUnpackAlpha:
    {
      return "X_NXSetUnpackAlpha";
    }
    case X_NXPutPackedImage:
    {
      return "X_NXPutPackedImage";
    }
    case X_NXFreeUnpack:
    {
      return "X_NXFreeUnpack";
    }
    default:
    {
      if (opcode > 127)
      {
        return "Extension";
      }
      else
      {
        return "?";
      }
    }
  }
}

#else /* #ifdef OPCODES */

const char *DumpOpcode(const int &opcode)
{
  return "?";
}

#endif /* #ifdef OPCODES */

void DumpData(const unsigned char *buffer, unsigned int size)
{
  if (buffer != NULL)
  {
    unsigned int i = 0;

    while (i < size)
    {
      *logofs << "[" << i << "]\t";

      for (unsigned int ii = 0; i < size && ii < 8; i++, ii++)
      {
        *logofs << (unsigned int) (buffer[i]) << "\t";
      }

      *logofs << "\n" << logofs_flush;
    }
  }
}

void DumpChecksum(const unsigned char *buffer, unsigned int size)
{
  if (buffer != NULL)
  {
    md5_byte_t md5_digest[MD5_LENGTH];

    md5_state_t md5_state;

    md5_init(&md5_state);

    md5_append(&md5_state, buffer, size);

    md5_finish(&md5_state, md5_digest);

    char md5_string[MD5_LENGTH * 2 + 1];

    for (unsigned int i = 0; i < MD5_LENGTH; i++)
    {
      sprintf(md5_string + (i * 2), "%02X", md5_digest[i]);
    }

    *logofs << "[" << md5_string << "]" << logofs_flush;
  }
}

void DumpBlockChecksums(const unsigned char *buffer,
                            unsigned int size, unsigned int block)
{
  for (unsigned int i = 0; i < (size / block); i++)
  {
    *logofs << "[" << i * block << "]";

    DumpChecksum(buffer + (i * block), block);

    *logofs << "\n";
  }

  if (size % block > 0)
  {
    *logofs << "[" << size / block * block << "]";

    DumpChecksum(buffer + (size / block * block), size % block);

    *logofs << "\n";
  }
}

void DumpHexData(const unsigned char *buffer, unsigned int size)
{
  char message [65536];
  char ascii   [17];

  unsigned int index = 0;
  unsigned int linescan = 0;
  unsigned int index_ascii = 0;

  sprintf  (message,"\n####  Start Dump Buffer of [%.5d] Bytes ####\n\n",size);

  *logofs << message << logofs_flush;

  //
  // "Index    0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f  Ascii           "
  // "-----   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --  ----------------"
  // "00000 : 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................"
  //

  sprintf (message,"Index   0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f  Ascii           \n");
  *logofs << message << logofs_flush;
  sprintf (message,"-----  -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --  ----------------\n");
  *logofs << message << logofs_flush;

  index = 0;

  while (index < size)
  {
    memset (ascii, ' ', sizeof(ascii));

    ascii[16] = '\0';

    sprintf  (message,"%.5d  ", index);

    for (index_ascii = 0, linescan = index;
             ((index < (linescan + 16)) && (index < size));
                  index++, index_ascii++)
    {
      if (isprint(buffer [index]))
      {
        ascii[index_ascii] = buffer [index];
      }
      else
      {
        ascii[index_ascii] = '.';
      }

      sprintf  (&message [strlen (message)],"%.2x ", (unsigned char) buffer [index]);
    }

    for (linescan = index_ascii; linescan < 16; linescan++)
    {
      strcat (&message [strlen (message)], "   ");
    }

    sprintf  (&message [strlen (message)]," %s\n", ascii);

    *logofs << message << logofs_flush;
  }

  sprintf  (message,"\n####  End Dump Buffer ####\n\n");

  *logofs << message << logofs_flush;
}