summaryrefslogtreecommitdiffstats
path: root/x11vnc/misc/enhanced_tightvnc_viewer/bin/util/ssvnc.tcl
blob: 77e7c2717fd94908faf244b14476b2cb7c38ba17 (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
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
#!/bin/sh
# the next line restarts using wish \
exec wish "$0" "$@"

#
# Copyright (c) 2006 by Karl J. Runge <runge@karlrunge.com>
#
# ssvnc.tcl: gui wrapper to the programs in this
# package. Also sets up service port forwarding.
#

set buck_zero $argv0

proc center_win {w} {
	update
	set W [winfo screenwidth  $w]
	set W [expr $W + 1]
	wm geometry $w +$W+0
	update
	set x [expr [winfo screenwidth  $w]/2 - [winfo width  $w]/2]
	set y [expr [winfo screenheight $w]/2 - [winfo height $w]/2]
	wm geometry $w +$x+$y
	wm deiconify $w
	update
}

proc toplev {w} {
	catch {destroy $w}
	toplevel $w
	catch {wm withdraw $w}
}

proc apply_bg {w} {
	global is_windows system_button_face
	if {$is_windows && $system_button_face != ""} {
		catch {$w configure -bg "$system_button_face"}
	}
}

proc scroll_text {fr {w 80} {h 35}} {
	global help_font is_windows scroll_text_focus

	catch {destroy $fr}
	
	frame $fr -bd 0

	eval text $fr.t -width $w -height $h $help_font \
		 -setgrid 1 -bd 2 -yscrollcommand {"$fr.y set"} -relief ridge 

	apply_bg $fr.t

	scrollbar $fr.y -orient v -relief sunken -command "$fr.t yview"
	pack $fr.y -side right -fill y
	pack $fr.t -side top -fill both -expand 1

	if {$scroll_text_focus} {
		focus $fr.t
	}
}

proc scroll_text_dismiss {fr {w 80} {h 35}} {
	global help_font

	scroll_text $fr $w $h

	set up $fr
	regsub {\.[^.]*$} $up "" up

	button $up.d -text "Dismiss" -command "destroy $up"
	bind $up <Escape> "destroy $up"
	pack $up.d -side bottom -fill x
	pack $fr -side top -fill both -expand 1
}

proc jiggle_text {w} {
	global uname
	if {$uname == "Darwin"} {
		$w yview scroll 1 pages
		update idletasks
		$w yview scroll -1 pages
		update idletasks
	}
}

proc help {} {
	toplev .h

	scroll_text_dismiss .h.f

	center_win .h
	wm title .h "SSL/SSH VNC Viewer Help"

	set msg {
 Hosts:

    Enter the VNC host and display in the 'VNC Host:Display' entry box.
    
    It is of the form "host:number", where "host" is the hostname of the
    machine running the VNC Server and "number" is the VNC display number;
    it is often "0".  Examples:

           snoopy:0
           far-away.east:0
           sunray-srv1.west:17
           24.67.132.27:0
    
    Then click on "Connect".  When you do so the STUNNEL program will be
    started locally to provide you with an outgoing SSL tunnel.

    Once the STUNNEL is running, the TightVNC Viewer (Or Chicken-of-the-VNC
    on Mac OS X) will be automatically started directed to the local SSL
    tunnel which, in turn, encrypts and redirects the connection to the
    remote VNC server.

    The remote VNC server must support an initial SSL handshake before
    using the VNC protocol (i.e. VNC is tunnelled through the SSL channel
    after it is established).  "x11vnc -ssl ..."  does this, and any VNC
    server can be made to do this by using, e.g., STUNNEL on the remote side.

    *IMPORTANT*: If you do not take the steps to verify the VNC Server's
    SSL Certificate, you are vulnerable to a Man-In-The-Middle attack.
    (Only passive sniffing attacks are prevented). You can use the "Fetch
    Cert" button to retrieve the Cert and then after you check it is OK
    (say, via comparing the MD5 or other info)  you can save it and use
    it to verify connections.  See the Certs... Help for information on
    how to do this.

    Note that on Windows when the Viewer connection is finished you may
    need to terminate STUNNEL manually from the System Tray (right click
    on dark green icon) and selecting "Exit".

 VNC Password:

    On Unix or MacOSX if there is a VNC password for the server you
    can enter it in the "VNC Password:" entry box.  This is required on
    MacOSX when Chicken of the VNC (the default) is used.  On Unix if
    you choose not to enter the password you will be prompted for it in
    the terminal running TightVNC viewer.  On Windows TightVNC viewer
    should prompt you.  When you Save a VNC profile, the password is
    not saved (you need to enter it each time).

 SSH:

    Click on "Use SSH" or go to "Options ..." if you want to use an *SSH*
    tunnel instead of SSL (then the VNC Server does not need to speak SSL or
    use STUNNEL).  "Use SSH and SSL" is similar: see the Help under Options.


 Proxies:

    If an intermediate proxy is needed to make the SSL connection
    (e.g. web gateway out of a firewall) enter it in the "Proxy/Gateway"
    entry box, or Alternatively supply both hosts separated by spaces
    (with the proxy second) in the VNC Host:Display box:

           host:number   gwhost:port 

    E.g.:  far-away.east:0   mygateway.com:8080

    If the "double proxy" case is required (e.g. coming out of a web
    proxied firewall environment), separate them via a comma, e.g.:

           far-away:0   local-proxy:8080,mygateway.com:443

    (either as above, or putting the 2nd string in the "Proxy/Gateway"
    entry box).

    See the ss_vncviewer description and x11vnc FAQ for info on proxies:

           http://www.karlrunge.com/x11vnc/#ss_vncviewer
           http://www.karlrunge.com/x11vnc/#faq-ssl-java-viewer-proxy


 Remote SSH Command:

    In SSH or SSH and SSL mode you can also specify a remote command to run
    on the remote ssh host in the "Remote SSH Command" entry.  The default
    is just to sleep a bit (sleep 30) to make sure the port tunnels are
    active.  Alternatively you could have the remote command start the
    VNC server, e.g.  x11vnc -nopw -display :0 -rfbport 5900 -localhost

    You can also specify the remote SSH command by putting a string like
    
         cmd=x11vnc -nopw -display :0 -rfbport 5900 -localhost

    (use any command you wish to run) at the END of the VNC Host:Display
    entry.  In general, you can cram it all in the VNC Host:Display if
    you like:   host:disp  proxy:port  cmd=...  (this is the way it is
    stored internally).


 SSL Certificates:

    If you want to use a SSL Certificate (PEM) file to authenticate yourself
    to the VNC server ("MyCert") or to verify the identity of the VNC Server
    ("ServerCert" or "CertsDir") select the certificate file by clicking
    the "Certs ..." button before connecting.

    Certificate verification is needed to prevent Man-In-The-Middle attacks.
    See the x11vnc documentation: 

           http://www.karlrunge.com/x11vnc/ssl.html

    for how to create and use PEM SSL certificate files.  An easy way is:

           x11vnc -ssl SAVE ...

    where it will print out its automatically generated certificate to
    the screen and that can be safely copied to the viewer side.

    You can also use the "Create Certificate" feature of this program
    under "Certs ...".  Just click on it and follow the instructions in
    the dialog.  Then copy the cert file to the VNC Server and specify the
    other one in the "Certs ..." dialog.  Alternatively you can use the
    "Import Certificate" action to paste in a certificate or read one in
    from a file or use the "Fetch Cert" button on the main panel.


 More Options:

    To set other Options, e.g. to use SSH instead of STUNNEL SSL, or
    View-Only usage, click on the "Options ..." button and read the Help
    there.

    To load in a saved Options profile, click on the "Load" button.
    This is the same as the "Load Profile" button under "Options"
    See "Save Profile" under "Options" to save a profile.


 More Info:

    See these links for more information:

           http://www.karlrunge.com/x11vnc/#faq-ssl-tunnel-ext
           http://www.stunnel.org
           http://www.tightvnc.com


 Tips and Tricks:

     1) On Unix to get a 2nd GUI (e.g. for a 2nd connection) press Ctrl-N
        on the GUI.  If only the xterm window is visible you can press
        Ctrl-N or try Ctrl-LeftButton -> New SSVNC_GUI.  On Windows you
        will have to manually Start a new one: Start -> Run ..., etc.

     2) If you use "user@hostname cmd=SHELL" then you get an SSH shell only:
        no VNC viewer will be launched.  On Windows "user@hostname cmd=PUTTY"
        will try to use putty.exe (better terminal emulation than
        plink.exe).  A shortcut for this is Ctrl-S as long as user@hostname
        is present in the entry box.  You can also put the string in the
        "Remote SSH Command" entry.

     3) If you use "user@hostname cmd=KNOCK" then only the port-knocking 
        is performed.  A shortcut for this is Ctrl-P as long as hostname
        is present in the entry box.  If it matches cmd=KNOCKF, i.e. an
        extra "F", then the port-knocking "FINISH" sequence is sent, if any.
        A shortcut for this Shift-Ctrl-P as long as hostname is present.
        You can also put the string in the "Remote SSH Command" entry.

     4) Pressing the "Load" button or pressing Ctrl-L or Clicking the Right
        mouse button on the main GUI will invoke the Load Profile dialog.

     5) If you want to do a Direct VNC connection, with *NO* SSL or SSH
        encryption, use the "vnc://" prefix, e.g. vnc://far-away.east:0

}

	.h.f.t insert end $msg
	jiggle_text .h.f.t
}

proc help_certs {} {
	toplev .ch

	scroll_text_dismiss .ch.f 90 33

	center_win .ch
	wm resizable .ch 1 0

	wm title .ch "SSL Certificates Help"

	set msg {
 Description:

    *IMPORTANT*: Only with SSL Certificate verification can Man-In-The-Middle
    attacks be prevented. Otherwise, only passive snooping attacks are prevented
    with SSL.

    The SSL Certificate files described below can have been created externally
    (e.g. by x11vnc), you can import it via "Import Certificate" if you like.
    OR you can click on "Create Certificate ..." to use this program to generate a
    Certificate + Private Key pair.  In that case you will need to distribute one
    of the generated files to the VNC Server.

    You can also retrieve the remote VNC Server's Cert via the "Fetch Cert" button
    on the main panel.  After you check that it is the correct Cert (e.g. by
    comparing MD5 hash or other info), you can save it.  It will be set as the
    "ServerCert" to verify against for the connection.  To make this verification
    check permanent, you will need to save the profile via Options -> Save Profile.

    Note: due to a deficiency in openssl "Fetch Cert" is very slow on Windows.


 Your Certificate + Key:

    You can specify your own SSL certificate (PEM) file in "MyCert" in which case it
    is used to authenticate you (the viewer) to the remote VNC Server.  If this fails
    the remote VNC Server will drop the connection.


 Server Certificates:
    
    Server certs can be specified in one of two ways:
    
        - A single certificate (PEM) file for a single server
          or a single Certificate Authority (CA)
    
        - A directory of certificate (PEM) files stored in
          the special OpenSSL hash fashion.
    
    The former is set via "ServerCert" in this gui.
    The latter is set via "CertsDir" in this gui.
    
    The former corresponds to the "CAfile" STUNNEL parameter.
    The latter corresponds to the "CApath" STUNNEL parameter.
    See stunnel(8) or www.stunnel.org for more information.
    
    If the remote VNC Server fails to authenticate itself with respect to the specified
    certificate(s), then the VNC Viewer (your side) will drop the connection.


    Select which file or directory by clicking on the appropriate "Browse..."  button.
    Once selected, if you click Info or the Right Mouse button on "Browse..."
    then information about the certificate will be displayed.


 Notes:

    If "Use SSH" has been selected then SSL certs are disabled.

    See the x11vnc and STUNNEL documentation for how to create and use PEM
    certificate files:

        http://www.karlrunge.com/x11vnc/#faq-ssl-tunnel-ext
        http://www.karlrunge.com/x11vnc/ssl.html
        http://www.stunnel.org

    A common way to create and use a VNC Server certificate is:

        x11vnc -ssl SAVE ...

    and then copy the Server certificate to the local (viewer-side) machine.
    x11vnc prints out to the screen the Server certificate it generates.
    You can set "ServerCert" to it directly or use the "Import Certificate"
    action to save it to a file.  Or use the "Fetch Cert" method.

    x11vnc also has command line utilities to create server, client, and CA
    (Certificate Authority) certificates.  See the above URLs.
}

	.ch.f.t insert end $msg
	jiggle_text .ch.f.t
}

proc help_opts {} {
	toplev .oh

	scroll_text_dismiss .oh.f

	center_win .oh

	wm title .oh "SSL/SSH Viewer Options Help"

set msg {
  Use SSL:  The default, use SSL via STUNNEL (this requires SSL aware VNC
            server, e.g. x11vnc -ssl SAVE ...)

  Use SSH:  Instead of using STUNNEL SSL, use ssh(1) for the encrypted
            tunnel.  You must be able to log in via ssh to the remote host.

            On Unix the cmdline ssh(1) program (it must already be installed)
            will be run in an xterm for passphrase authentication, etc. On
            Windows the cmdline plink.exe program will be launched in
            a Windows Console window.

            You can set the "VNC Host:Display" to "user@host:disp" to indicate
            ssh should log in as "user" on "host".  NOTE: On Windows you MUST
            always supply the "user@" part (due to a plink deficiency). E.g.:

                  fred@far-away.east:0

            If an intermediate gateway machine must be used (e.g. to enter
            a firewall; the VNC Server is not running on it), put it in the
            Proxy/Gateway entry or you can put something like this in the
            "VNC Host:Display" entry box:

                  workstation:0   user@gateway-host:port
  
            ssh is used to login to user@gateway-host and then a -L port
            redirection is set up to go to workstation:0 from gateway-host.
            ":port" is optional, use it if the gateway-host SSH port is
            not the default value 22.

            One can also do a "double ssh", i.e. a first SSH to the
            gateway login machine then a 2nd ssh to the destination machine
            (presumably it is running the vnc server).  Unlike the above
            example, the "last leg" (gateway-host -> workstation) is also
            encrypted by SSH this way.  Do this by splitting the gateway
            in two with a comma, the part before it is the first SSH:

                  :0   user@gateway-host:port,user@workstation:port

            (or in the Proxy/Gateway entry).

            In the "Remote SSH Command" entry you can to indicate that a
            remote command to be run.  The default is "sleep 15".  Also, at
            the very end of the entry box, you can append a cmd=... string
            to to achieve the same thing.  E.g.

                  user@host:0   cmd=x11vnc -nopw -display :0

            (if a gateway is also needed, put it just before the cmd=...
            e.g.  host:0  user@gateway-host:port cmd=x11vnc -nopw )


            Trick: If you use "cmd=SHELL" then you get an SSH shell only:
            no VNC viewer will be launched.  On Windows "cmd=PUTTY" will
            try to use putty.exe (better terminal emulation than plink.exe)
            A shortcut for this is Ctrl-S as long as user@hostname is present
            in the "VNC Host:Display" box.

  Use SSH and SSL: Tunnel the SSL connection through a SSH tunnel.  Use this
            if you want end-to-end SSL and must use a SSH gateway (e.g. to
            enter a firewall) or if additional SSH port redirs are required
            (CUPS, Sound, SMB tunnelling: See Advanced Options).


  Putty PW:  On Windows only: use the supplied password for plink SSH logins.
             Unlike the other options the value is not saved when 'Save
             Profile' is performed.  This feature is useful when options under
             "Advanced" are set that require TWO SSH's: you just have
             to type the password once in this entry box.  The bundled
             pagent.exe and puttygen.exe programs can also be used to avoid
             repeatedly entering passwords (note this requires setting up
             and distributing SSH keys).  Start up pagent.exe or puttygen.exe
             and read the instructions there.
                
  ssh-agent: On Unix only: restart the GUI in the presence of ssh-agent(1)
             (e.g. in case you forgot to start your agent before starting
             this GUI).  An xterm will be used to enter passphrases, etc.
             This can avoid repeatedly entering passphrases for the
             SSH logins (note this requires setting up and distributing
             SSH keys).


  View Only:               Have VNC Viewer ignore mouse and keyboard input.
  
  Fullscreen:              Start the VNC Viewer in fullscreen mode.
  
  Raise On Beep:           Deiconify viewer when bell rings.
  
  Use 8bit color:          Request a very low-color pixel format.
  
  Cursor Alphablending:    Use the x11vnc alpha hack for translucent cursors
                           (requires Unix, 32bpp and same endianness)
  
  Use XGrabServer:         On Unix only, use the XGrabServer workaround for
                           old window managers.

  Do not use JPEG:         Do not use the jpeg aspect of the tight encoding.

  Compress Level/Quality:  Set TightVNC encoding parameters.

  Save and Load:   You can Save the current settings by clicking on Save
                   Profile (.vnc file) and you can also read in a saved one
                   with Load Profile.  Use the Browse... button to select
                   the filename via the GUI.

                   Pressing Ctrl-L or Clicking the Right mouse button on
                   the main GUI will invoke the Load Profile dialog.

                   Note: On Windows since the TightVNC Viewer will save
                   its own settings in the Registry, some unexpected
                   behavior is possible because the viewer is nearly
                   always directed to the VNC host "localhost:30".  E.g. if
                   you specify "View Only" in this gui once but not next
                   time the Windows VNC Viewer may remember the setting.
                   Unfortunately there is not a /noreg option for the Viewer.
                   

  Clear Options:   Set all options to their defaults (i.e. unset).

  Advanced:        Bring up the Advanced Options dialog.
}
	.oh.f.t insert end $msg
	jiggle_text .oh.f.t
}

proc help_fetch_cert {} {
	toplev .fh

	scroll_text_dismiss .fh.f 85 37

	center_win .fh
	wm resizable .fh 1 0

	wm title .fh "Fetch Certificates Help"

	set msg {
  The above SSL Certificate has been retrieved from the VNC Server via the
  "Fetch Cert" action.
  
  It has merely been downloaded via the SSL Protocol: IT HAS NOT BEEN VERIFIED
  IN ANY WAY.
  
  So, in principle, it could be a fake certificate being inserted by a bad
  person attempting to perform a Man-In-The-Middle attack on your SSL connection.
  
  If, however, by some external means you can verify the authenticity of
  this SSL Certificate you can use it for your VNC SSL connection to the
  VNC server you wish to connect to.  It will provide an authenticated and
  encrypted connection.
  
  You can verify the SSL Certificate by comparing the MD5 or SHA1 hash
  value via a method/channel you know is safe (i.e. not also under control
  of a Man-In-The-Middle attacker).  You could also check the text between
  the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- tags, etc.
  
  Once you are sure it is correct, you can press the Save button to save the
  certificate to a file on the local machine for use when you connect via
  VNC tunneled through SSL.  If you save it, then that file will be set as
  the Certificate to verify the VNC server against.  You can see this in
  the dialog started via the "Certs..." button on the main panel.
  
  NOTE: If you want to make PERMANENT the association of the saved SSL
  certificate file with the VNC server host, you MUST save the setting as
  a profile for loading later. To Save a Profile, click on Options -> Save
  Profile ..., and choose a name for the profile and then click on Save.
  
  To reload the profile at a later time, click on the "Load" button on
  the main panel and then select the name and click "Open".  If you want
  to be sure the certificate is still associated with the loaded in host,
  click on "Certs..." button and make sure the "ServerCert" points to the
  desired SSL filename.

  See the Certs... Help for more information.  A sophisticated method
  can be set up using a Certificate Authority key to verify never before
  seen certificates (i.e. like your web browser does).
}

	.fh.f.t insert end $msg
	jiggle_text .fh.f.t
}

proc win_nokill_msg {} {
	global help_font is_windows system_button_face
	toplev .w

	eval text .w.t -width 60 -height 11 $help_font
	button .w.d -text "Dismiss" -command {destroy .w}
	pack .w.t .w.d -side top -fill x

	apply_bg .w.t

	center_win .w
	wm resizable .w 1 0

	wm title .w "SSL/SSH Viewer: Warning"

	set msg {
    The VNC Viewer has exited.
    
    You will need to terminate STUNNEL manually.
    
    To do this go to the System Tray and right-click on the STUNNEL
    icon (dark green).  Then click "Exit".
    
    You can also double click on the STUNNEL icon to view the log
    for error messages and other information.
}
	.w.t insert end $msg
}

proc win_kill_msg {pids} {
	global terminate_pids
	global help_font
	toplev .w

	eval text .w.t -width 72 -height 19 $help_font
	button .w.d -text "Dismiss" -command {destroy .w; set terminate_pids no}
	button .w.k -text "Terminate STUNNEL" -command {destroy .w; set terminate_pids yes}
	pack .w.t .w.k .w.d -side top -fill x

	apply_bg .w.t

	center_win .w
	wm resizable .w 1 0

	wm title .w "SSL/SSH Viewer: Warning"

	set msg {
    The VNC Viewer has exited.
    
    We can terminate the following still running STUNNEL process(es):
    
}
	append msg "         $pids\n"

	append msg {
    Click on the "Terminate STUNNEL" button below to do so.
    
    Before terminating STUNNEL you can double click on the STUNNEL
    Tray icon to view its log for error messages and other information.

    Note: You may STILL need to terminate STUNNEL manually if we are
    unable to kill it.  To do this go to the System Tray and right-click
    on the STUNNEL icon (dark green).  Then click "Exit".  You will
    probably also need to hover the mouse over the STUNNEL Tray Icon to
    make the Tray notice STUNNEL is gone...
}
	.w.t insert end $msg
}

proc win9x_plink_msg {file} {
	global help_font win9x_plink_msg_done
	toplev .pl

	eval text .pl.t -width 90 -height 26 $help_font
	button .pl.d -text "OK" -command {destroy .pl; set win9x_plink_msg_done 1}
	wm protocol .pl WM_DELETE_WINDOW {catch {destroy .pl}; set win9x_plink_msg_done 1}
	pack .pl.t .pl.d -side top -fill x

	apply_bg .pl.t

	center_win .pl
	wm resizable .pl 1 0

	wm title .pl "SSL/SSH Viewer: Win9x Warning"

	set msg {
    Due to limitations on Window 9x you will have to manually start up
    a COMMAND.COM terminal and paste in the following command:

}
	set pwd [pwd]
	regsub -all {/} $pwd "\\" pwd
	append msg "        $pwd\\$file\n"  

	append msg {
    The reason for this is a poor Console application implementation that
    affects many text based applications.
    
    To start up a COMMAND.COM terminal, click on the Start -> Run, and then
    type COMMAND in the entry box and hit Return or click OK.

    To select the above command, highlight it with the mouse and then press
    Ctrl-C.  Then go over to the COMMAND.COM window and click on the
    Clipboard paste button.  Once pasted in, press Return to run the script.
    
    This will start up a PLINK.EXE ssh login to the remote computer,
    and after you log in successfully and indicate (QUICKLY!!) that the
    connection is OK by clicking OK in this dialog. If the SSH connection
    cannot be autodetected you will ALSO need to click "Success" in the
    "plink ssh status?" dialog, the VNC Viewer will be started going
    through the SSH tunnel.
}
	.pl.t insert end $msg
	wm deiconify .pl
}

proc mesg {str} {
	set maxx 53
	if {[string length $str] > $maxx} {
		set str [string range $str 0 $maxx]
		append str " ..."
	}
	.l configure -text $str
	update
}

proc get_ssh_hp {str} {
	regsub {cmd=.*$} $str "" str
	set str [string trim $str]
	regsub {[ 	].*$} $str "" str
	return $str
}

proc get_ssh_cmd {str} {
	set str [string trim $str]
	if [regexp {cmd=(.*$)} $str m cmd] {
		set cmd [string trim $cmd]
		regsub -nocase {^%x11vncr$} $cmd "x11vnc -nopw -display none -rawfb rand" cmd
		regsub -nocase {^%x11vnc$}  $cmd "x11vnc -nopw -display none -rawfb null" cmd
		return $cmd
	} else {
		return ""
	}
}

proc get_ssh_proxy {str} {
	set str [string trim $str]
	regsub {cmd=.*$} $str "" str
	set str [string trim $str]
	if { ![regexp {[ 	]} $str]} {
		return ""
	}
	regsub {^.*[ 	][ 	]*} $str "" str
	return $str
}

proc set_defaults {} {
	global defs

	global mycert svcert crtdir
	global use_alpha use_grab use_ssl use_ssh use_sshssl use_viewonly use_fullscreen use_bgr233
	global use_nojpeg use_raise_on_beep use_compresslevel use_quality
	global compresslevel_text quality_text
	global use_cups use_sound use_smbmnt
	global cups_local_server cups_remote_port cups_manage_rcfile
	global cups_local_smb_server cups_remote_smb_port
	global change_vncviewer change_vncviewer_path vncviewer_realvnc4
	global additional_port_redirs additional_port_redirs_list
	global sound_daemon_remote_cmd sound_daemon_remote_port sound_daemon_kill sound_daemon_restart
	global sound_daemon_local_cmd sound_daemon_local_port sound_daemon_local_kill sound_daemon_local_start 
	global smb_su_mode smb_mount_list
	global use_port_knocking port_knocking_list
	global ycrop_string
	global include_list

	set defs(use_viewonly) 0
	set defs(use_fullscreen) 0
	set defs(use_raise_on_beep) 0
	set defs(use_bgr233) 0
	set defs(use_alpha) 0
	set defs(use_grab) 0
	set defs(use_nojpeg) 0
	set defs(use_compresslevel) "default"
	set defs(use_quality) "default"
	set defs(compresslevel_text) "Compress Level: default"
	set defs(quality_text) "Quality: default"

	set defs(mycert) ""
	set defs(svcert) ""
	set defs(crtdir) ""

	set defs(use_cups) 0
	set defs(use_sound) 0
	set defs(use_smbmnt) 0

	set defs(change_vncviewer) 0 
	set defs(change_vncviewer_path) "" 
	set defs(cups_manage_rcfile) 0 
	set defs(vncviewer_realvnc4) 0

	set defs(additional_port_redirs) 0
	set defs(additional_port_redirs_list) ""

	set defs(cups_local_server) ""
	set defs(cups_remote_port) ""
	set defs(cups_local_smb_server) ""
	set defs(cups_remote_smb_port) ""

	set defs(smb_su_mode) "su"
	set defs(smb_mount_list) ""

	set defs(sound_daemon_remote_cmd) ""
	set defs(sound_daemon_remote_port) ""
	set defs(sound_daemon_kill) 0
	set defs(sound_daemon_restart) 0

	set defs(sound_daemon_local_cmd) ""
	set defs(sound_daemon_local_port) ""
	set defs(sound_daemon_local_start) 0
	set defs(sound_daemon_local_kill) 0

	set defs(use_port_knocking) 0
	set defs(ycrop_string) ""
	set defs(port_knocking_list) ""

	set defs(include_list) ""

	set defs(use_ssl) 1
	set defs(use_ssh) 0
	set defs(use_sshssl) 0

	foreach var [array names defs] {
		set $var $defs($var)	
	}

	global vncauth_passwd
	set vncauth_passwd ""

	ssl_ssh_adjust ssl
}

proc do_viewer_windows {n} {
	global use_alpha use_grab use_ssh use_sshssl use_viewonly use_fullscreen use_bgr233
	global use_nojpeg use_raise_on_beep use_compresslevel use_quality
	global change_vncviewer change_vncviewer_path vncviewer_realvnc4

	set cmd "vncviewer"
	if {$change_vncviewer && $change_vncviewer_path != ""} {
		set cmd [string trim $change_vncviewer_path]
		regsub -all {\\} $cmd {/} cmd
		if {[regexp {[ \t]} $cmd]} {
			if {[regexp -nocase {\.exe$} $cmd]} {
				if {! [regexp {["']} $cmd]} { #"
					# hmmm, not following instructions, are they?
					set cmd "\"$cmd\""
				}
			}
		}
	}
	if {$use_viewonly} {
		if {$vncviewer_realvnc4} {
			append cmd " viewonly=1"
		} else {
			append cmd " /viewonly"
		}
	}
	if {$use_fullscreen} {
		if {$vncviewer_realvnc4} {
			append cmd " fullscreen=1"
		} else {
			append cmd " /fullscreen"
		}
	}
	if {$use_bgr233} {
		if {$vncviewer_realvnc4} {
			append cmd " lowcolourlevel=1"
		} else {
			append cmd " /8bit"
		}
	}
	if {$use_nojpeg} {
		if {! $vncviewer_realvnc4} {
			append cmd " /nojpeg"
		}
	}
	if {$use_raise_on_beep} {
		if {! $vncviewer_realvnc4} {
			append cmd " /belldeiconify"
		}
	}
	if {$use_compresslevel != "" && $use_compresslevel != "default"} {
		if {$vncviewer_realvnc4} {
			append cmd " zliblevel=$use_compresslevel"
		} else {
			append cmd " /compresslevel $use_compresslevel"
		}
	}
	if {$use_quality != "" && $use_quality != "default"} {
		if {! $vncviewer_realvnc4} {
			append cmd " /quality $use_quality"
		}
	}
	append cmd " localhost:$n"
	
	mesg $cmd
	set emess ""
	set rc [catch {eval exec $cmd} emess]
	if {$rc != 0} {
		raise .
		tk_messageBox -type ok -icon error -message $emess -title "Error: $cmd"
	}
}

proc get_netstat {} {
	set ns ""
	catch {set ns [exec netstat -an]}
	return $ns
}

proc get_ipconfig {} {
	global is_win9x
	set ip ""
	if {! $is_win9x} {
		catch {set ip [exec ipconfig]}
		return $ip
	}

	set file "ip"
	append file [pid]
	append file ".txt"

	# VF
	catch {[exec winipcfg /Batch $file]}

	if [file exists $file] {
		set fh [open $file "r"]
		while {[gets $fh line] > -1} {
			append ip "$line\n"
		}
		close $fh
		catch {file delete $file}
	}
	return $ip
}

proc guess_nat_ip {} {
	global save_nat last_save_nat
	set s ""

	if {! [info exists save_nat]} {
		set save_nat ""
		set last_save_nat 0
	}
	if {$save_nat != ""} {
		set now [clock seconds]
		if {$now < $last_save_nat + 45} {
			return $save_nat
		}
	}
	set s ""
	catch {set s [socket "www.whatismyip.com" 80]}
	set ip "unknown"
	if {$s != ""} {
		fconfigure $s -buffering none
		puts $s "GET / HTTP/1.1"
		puts $s "Host: www.whatismyip.com"
		puts $s "Connection: close"
		puts $s ""
		flush $s
		set on 0
		while { [gets $s line] > -1 } {
			if {! $on && [regexp {<HEAD>}  $line]} {set on 1}
			if {! $on && [regexp {<HTML>}  $line]} {set on 1}
			if {! $on && [regexp {<TITLE>} $line]} {set on 1}
			if {! $on} {
				continue;
			}
			if [regexp {([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*)} $line ip] {
				break
			}
		}
		close $s
	}
	if {$ip != "unknown"} {
		set save_nat $ip
		set last_save_nat [clock seconds]
	}
	return $ip
}

proc guess_ip {} {
	global is_windows
	if {! $is_windows} {
		set out ""
		set out [get_hostname]
		if {$out != ""} {
			set hout ""
			catch {set hout [exec host $out]}
			if {$hout != ""} {
				if [regexp {has address ([.0-9][.0-9]*)} $hout mvar ip] {
					set ip [string trim $ip]
					return $ip
				}
			}
		}
		return ""
	} else {
		set out [get_ipconfig]
		set out [string trim $out]
		if {$out == ""} {
			return ""
		}
		foreach line [split $out "\n\r"] {
			if {[regexp -nocase {IP Address.*:[ \t]*([.0-9][.0-9]*)} $line mvar ip]} {
				set ip [string trim $ip]
				if [regexp {^[.0]*$} $ip] {
					continue
				}
				if [regexp {127\.0\.0\.1} $ip] {
					continue
				}
				if {$ip != ""} {
					return $ip
				}
			}
		}
	}
}

proc windows_start_sound_daemon {file} {
	global env
	global use_sound sound_daemon_local_cmd sound_daemon_local_start

	# VF
	regsub {\.bat} $file "snd.bat" file2
	set fh2 [open $file2 "w"]

	puts $fh2 $sound_daemon_local_cmd
	puts $fh2 "del $file2"
	close $fh2

	mesg "Starting SOUND daemon..."
	if [info exists env(COMSPEC)] {
		exec $env(COMSPEC) /c $file2 &
	} else {
		exec cmd.exe /c $file2 &
	}
	after 1500
}

proc windows_stop_sound_daemon {} {
	global is_win9x
	global use_sound sound_daemon_local_cmd sound_daemon_local_start

	set cmd [string trim $sound_daemon_local_cmd]

	regsub {[ \t].*$} $cmd "" cmd
	regsub {^.*\\} $cmd "" cmd
	regsub {^.*/} $cmd "" cmd

	if {$cmd == ""} {
		return
	}

	set output [get_task_list]
	
	foreach line [split $output "\n\r"] {
		if [regexp "$cmd" $line] {
			if [regexp {(-?[0-9][0-9]*)} $line m p] {
				set pids($p) $line
			}
		}
	}

	set count 0
	foreach pid [array names pids] {
		mesg "Stopping SOUND pid: $pid"
		if {$is_win9x} {
			catch {exec w98/kill.exe /f $pid}
		} else {
			catch {exec tskill.exe $pid}
		}
		if {$count == 0} {
			after 1200
		} else {
			after 500
		}
		incr count
	}
}

proc contag {} {
	global concount
	if {! [info exists concount]} {
		set concount 0
	}
	incr concount
	set str [pid]
	set str "-$str-$concount"
}

proc make_plink {} {
	toplev .plink
	#wm geometry .plink +700+500
	wm geometry .plink -40-40
	wm title .plink "plink SSH status?"
	set wd 37
	label .plink.l1 -anchor w -text "Login via plink/ssh to the remote server" -width $wd
	label .plink.l2 -anchor w -text "(supply username and password as needed)." -width $wd
	label .plink.l3 -anchor w -text "" -width $wd
	label .plink.l4 -anchor w -text "After ssh is set up, AND if the connection" -width $wd
	label .plink.l5 -anchor w -text "success is not autodetected, please click" -width $wd
	label .plink.l6 -anchor w -text "one of these buttons:" -width $wd
	global plink_status
	button .plink.fail -text "Failed" -command {destroy .plink; set plink_status no}
	button .plink.ok   -text "Success" -command {destroy .plink; set plink_status yes}
	pack .plink.l1 .plink.l2 .plink.l3 .plink.l4 .plink.l5 .plink.l6 .plink.fail .plink.ok -side top -fill x

	update
}

proc ssh_split {str} {
	if {! [regexp {:} $str]} {
		append str ":22"
	}
	regsub {:.*$} $str "" ssh_host
	regsub {^.*:} $str "" ssh_port
	if {$ssh_port == ""} {
		set ssh_port 22
	}
	if [regexp {@} $ssh_host] {
		regsub {@.*$} $ssh_host "" ssh_user
		regsub {^.*@} $ssh_host "" ssh_host
	} else {
		set ssh_user ""
	}
	return [list $ssh_user $ssh_host $ssh_port]
}

proc launch_windows_ssh {hp file n} {
	global is_win9x env
	global use_sshssl use_ssh putty_pw
	global port_knocking_list

	set hpnew  [get_ssh_hp $hp]
	set proxy  [get_ssh_proxy $hp]
	set sshcmd [get_ssh_cmd $hp]

	set vnc_host "localhost"
	set vnc_disp $hpnew
	regsub {^.*:} $vnc_disp "" vnc_disp

	if {![regexp {^[0-9][0-9]*$} $vnc_disp]} {
		if {[regexp {cmd=SHELL} $hp]} {
			;
		} elseif {[regexp {cmd=PUTTY} $hp]} {
			;
		} else {
			mesg "Bad vncdisp, missing :0 ?, $vnc_disp"
			bell
			return 0
		}
	}

	set vnc_port 5900
	if {![regexp {^[0-9][0-9]*$} $vnc_disp]} {
		;
	} elseif {$vnc_disp < 200} {
		set vnc_port [expr $vnc_disp + 5900]
	} else {
		set vnc_port $vnc_disp
	}

	set ssh_port 22
	set ssh_host $hpnew
	regsub {:.*$} $ssh_host "" ssh_host

	set double_ssh ""
	set p_port ""
	if {$proxy != ""} {
		if [regexp {,} $proxy] {
			if {$is_win9x} {
				mesg "Double proxy does not work on Win9x"
				bell
				return 0
			}
			# user1@gateway:port1,user2@workstation:port2
			set proxy1 ""
			set proxy2 ""
			set s [split $proxy ","]
			set proxy1 [lindex $s 0]
			set proxy2 [lindex $s 1]

			set p_port [expr 3000 + 1000 * rand()]	
			set p_port [expr round($p_port)]

			set s [ssh_split $proxy1]
			set ssh_user1 [lindex $s 0]
			set ssh_host1 [lindex $s 1]
			set ssh_port1 [lindex $s 2]

			set s [ssh_split $proxy2]
			set ssh_user2 [lindex $s 0]
			set ssh_host2 [lindex $s 1]
			set ssh_port2 [lindex $s 2]

			set u1 ""
			if {$ssh_user1 != ""} {
				set u1 "${ssh_user1}@"
			}
			set u2 ""
			if {$ssh_user2 != ""} {
				set u2 "${ssh_user2}@"
			}
		
			set double_ssh "-L $p_port:$ssh_host2:$ssh_port2 -P $ssh_port1 $u1$ssh_host1"
			set proxy_use "${u2}localhost:$p_port"

		} else {
			# user1@gateway:port1
			set proxy_use $proxy
		}

		set ssh_host $proxy_use
		regsub {:.*$} $ssh_host "" ssh_host
		set ssh_port $proxy_use
		regsub {^.*:} $ssh_port "" ssh_port
		if {$ssh_port == ""} {
			set ssh_port 22
		}

		set vnc_host $hpnew
		regsub {:.*$} $vnc_host "" vnc_host
		if {$vnc_host == ""} {
			set vnc_host "localhost"
		}
	}

	if {![regexp {^[^ 	][^ 	]*@} $ssh_host]} {
		mesg "You must supply a username: user@host..."
		bell
		return 0
	}

	set verb "-v"

	set pwd ""
	if {$is_win9x} {
		set pwd [pwd]
		regsub -all {/} $pwd "\\" pwd
	}
	if {! [regexp {^[0-9][0-9]*$} $n]} {
		set n 0
	}

	set use [expr $n + 5900]

	set_smb_mounts
	
	global use_smbmnt use_sound sound_daemon_kill 
	set do_pre 0
	if {$use_smbmnt}  {
		set do_pre 1
	} elseif {$use_sound && $sound_daemon_kill} {
		set do_pre 1
	}

	global skip_pre
	if {$skip_pre} {
		set do_pre 0
		set skip_pre 0
	}

	set pw ""
	if {$putty_pw != ""} {
		if {! [regexp {"} $putty_pw]} {  #"
			set pw "                                                      -pw                                                   \"$putty_pw\""
		}
	}

	set tag [contag]

	set file_double ""

	set file_pre ""
	set file_pre_cmd ""
	if {$do_pre} {
		set setup_cmds [ugly_setup_scripts pre $tag] 
		
		if {$setup_cmds != ""} {
			# VF
			regsub {\.bat} $file "pre.cmd" file_pre_cmd
			set fh [open $file_pre_cmd "w"]
			puts $fh "$setup_cmds sleep 10; "
			close $fh

			# VF
			regsub {\.bat} $file "pre.bat" file_pre
			set fh [open $file_pre "w"]
			set plink_str "plink.exe -ssh -C -P $ssh_port -m $file_pre_cmd $verb -t" 

			global smb_redir_0
			if {$smb_redir_0 != ""} {
				append plink_str " $smb_redir_0"
			}

			append plink_str "$pw $ssh_host" 

			if {$pw != ""} {
				puts $fh "echo off"
			}
			puts $fh $plink_str

			if {$file_pre_cmd != ""} {
				puts $fh "del $file_pre_cmd"
			}
			puts $fh "del $file_pre"

			close $fh
		}
	}

	if {$is_win9x} {
		set sleep 35
	} else {
		set sleep 20
	}

	set setup_cmds [ugly_setup_scripts post $tag] 

	set do_shell 0
	if {$sshcmd == "SHELL"} {
		set setup_cmds ""
		set sshcmd {$SHELL}
		set do_shell 1
	} elseif {$sshcmd == "PUTTY"} {
		set setup_cmds ""
		set do_shell 1
	}

	set file_cmd ""
	if {$setup_cmds != ""} {
		# VF
		regsub {\.bat} $file ".cmd" file_cmd
		set fh_cmd [open $file_cmd "w"]

		set str $setup_cmds
		if {$sshcmd != ""} {
			append str " $sshcmd; "
		} else {
			append str " sleep $sleep; "
		}
		puts $fh_cmd $str
		close $fh_cmd

		set sshcmd $setup_cmds
	}

	if {$sshcmd == ""} {
		set pcmd "echo; echo SSH connected OK.; echo If this state is not autodetected,; echo Go Click the Success button."
		set sshcmd "$pcmd; sleep $sleep"
	}

	global use_sound sound_daemon_local_cmd sound_daemon_local_start
	if {! $do_shell && ! $is_win9x && $use_sound && $sound_daemon_local_start && $sound_daemon_local_cmd != ""} {
		windows_start_sound_daemon $file
	}

	# VF
	set fh [open $file "w"]
	if {$is_win9x} {
		puts $fh "cd $pwd"
		if {$file_pre != ""} {
			puts $fh "echo Press Ctrl-C --HERE-- when done with the Pre-Command shell work."
			puts $fh "start /w command.com /c $file_pre"
		}
	}

	global use_cups use_smbmnt
	set extra_redirs ""
	if {$use_cups} {
		append extra_redirs [get_cups_redir]
	}
	if {$use_sound} {
		append extra_redirs [get_sound_redir]
	}
	global additional_port_redirs
	if {$additional_port_redirs} {
		append extra_redirs [get_additional_redir]
	}

	if {$vnc_host == ""} {
		set vnc_host "localhost"
	}

	set plink_str "plink.exe -ssh -P $ssh_port $verb -L $use:$vnc_host:$vnc_port $extra_redirs -t" 
	if {$extra_redirs != ""} {
		regsub {exe} $plink_str "exe -C" plink_str
	}
	if {$do_shell} {
		if {$sshcmd == "PUTTY"} {
		    if {$is_win9x} {
			set plink_str "putty.exe -ssh -C -P $ssh_port $extra_redirs -t $pw $ssh_host" 
		    } else {
			set plink_str "start \"putty $ssh_host\" putty.exe -ssh -C -P $ssh_port $extra_redirs -t $pw $ssh_host" 
			if [regexp {FINISH} $port_knocking_list] {
				regsub {start} $plink_str "start /wait" plink_str
			}
		    }
		} else {
			set plink_str "plink.exe -ssh -C -P $ssh_port $extra_redirs -t $pw $ssh_host" 
			append plink_str { "$SHELL"}
		}
	} elseif {$file_cmd != ""} {
		append plink_str " -m $file_cmd$pw $ssh_host"
	} else {
		append plink_str "$pw $ssh_host \"$sshcmd\""
	}

	if {$pw != ""} {
		puts $fh "echo off"
	}
	puts $fh $plink_str
	if {$file_cmd != ""} {
		puts $fh "del $file_cmd"
	}
	puts $fh "del $file"
	close $fh

	catch {destroy .o}
	catch {destroy .oa}

	if { ![do_port_knock $ssh_host start]} {
		catch {file delete $file}
		if {$file_cmd != ""} {
			catch {file delete $file_cmd}
		}
		if {$file_pre != ""} {
			catch {file delete $file_pre}
		}
		return 0
	}

	if {$double_ssh != ""} {
		set plink_str_double_ssh "plink.exe -ssh -t $pw $double_ssh \"echo sleep 60 ...; sleep 60; echo done.\"" 

		# VF
		regsub {\.bat} $file "dob.bat" file_double
		set fhdouble [open $file_double "w"]
		puts $fhdouble $plink_str_double_ssh
		puts $fhdouble "del $file_double"
		close $fhdouble

		set com "cmd.exe"
		if [info exists env(COMSPEC)] {
			set com $env(COMSPEC)
		}

		exec $com /c $file_double &

		set waited 0
		set gotit 0
		while {$waited < 30000} {
			after 500
			update
			set ns [get_netstat]
			set re ":$p_port"
			append re {[ 	][ 	]*[0:.][0:.]*[ 	][ 	]*LISTEN}
			if [regexp $re $ns] {
				set gotit 1
				break
			}
			set waited [expr "$waited + 500"]
		}
		if {! $gotit} {
			after 5000
		}
	}

	if {$is_win9x} {
		wm withdraw .
		update
		win9x_plink_msg $file
		global win9x_plink_msg_done
		set win9x_plink_msg_done 0
		vwait win9x_plink_msg_done
	} else {
		set com "cmd.exe"
		if [info exists env(COMSPEC)] {
			set com $env(COMSPEC)
		}

		if {$file_pre != ""} {
			set sl 0
			if {$use_smbmnt}  {
				global smb_su_mode
				if {$smb_su_mode == "su"} {
					set sl [expr $sl + 15]
				} elseif {$smb_su_mode == "sudo"} {
					set sl [expr $sl + 15]
				} else {
					set sl [expr $sl + 3]
				}
			}
			if {$pw == ""} {
				set sl [expr $sl + 5]
			}

			set sl [expr $sl + 5]
			set st [clock seconds]
			set dt 0
			global entered_gui_top button_gui_top
			set entered_gui_top 0
			set button_gui_top 0

			catch {wm geometry . "-40-40"}
			catch {wm withdraw .; update; wm deiconify .; raise .; update}
			mesg "Click on *This* Label when done with 1st SSH 0/$sl"
			after 600

			exec $com /c $file_pre &

			catch {lower .; update; raise .; update}

			while {$dt < $sl} {
				after 100
				set dt [clock seconds]
				set dt [expr $dt - $st]
				mesg "Click on *This* Label when done with 1st SSH $dt/$sl"
				update
				update idletasks
				if {$dt <= 1} {
					set button_gui_top 0
				}
				if {$button_gui_top != 0 && $dt >= 3} {
					mesg "Running 2nd SSH now ..."
					after 1000
					break
				}
			}
			mesg "Running 2nd SSH ..."
		}

		if {! $do_shell} {
			make_plink
		}
		wm withdraw .
		update
		if {$do_shell && [regexp {FINISH} $port_knocking_list]} {
			catch {exec $com /c $file}
		} else {
			exec $com /c $file &
		}
		after 1000
	}

	if {$do_shell} {
		wm deiconify .
		update
		if {[regexp {FINISH} $port_knocking_list]} {
			do_port_knock $ssh_host finish
		}
		return 1
	}
	if {$is_win9x} {
		make_plink
	}
	global plink_status
	set plink_status ""
	set waited 0
	set cnt 0
	while {$waited < 30000} {
		after 500
		update
		set ns [get_netstat]
		set re ":$use"
		append re {[ 	][ 	]*[0:.][0:.]*[ 	][ 	]*LISTEN}
		if [regexp $re $ns] {
			set plink_status yes
		}
		if {$plink_status != ""} {
			catch {destroy .plink}
			break
		}

		if {$waited == 0} {
			#wm deiconify .plink
		}
		set waited [expr "$waited + 500"]

		incr cnt
		if {$cnt >= 12} {
			set cnt 0
		}
	}
	if {$plink_status == ""} {
		vwait plink_status
	}

	if {$use_sshssl} {
		global launch_windows_ssh_files 
		if {$file != ""} {
			append launch_windows_ssh_files "$file "
		}
		if {$file_pre != ""} {
			append launch_windows_ssh_files "$file_pre "
		}
		if {$file_pre_cmd != ""} {
			append launch_windows_ssh_files "$file_pre_cmd "
		}
		regsub { *$} $launch_windows_ssh_files "" launch_windows_ssh_files
		return 1
	}

	if {$plink_status != "yes"} {
		wm deiconify .
	} else {
		after 1000
		do_viewer_windows $n
		wm deiconify .
		mesg "Disconnected from $hp"
	}
	update
	if [regexp {FINISH} $port_knocking_list] {
		do_port_knock $ssh_host finish
	}

	if {$file != ""} {
		catch {file delete $file}	
	}
	if {$file_pre != ""} {
		catch {file delete $file_pre}	
	}
	if {$file_pre_cmd != ""} {
		catch {file delete $file_pre_cmd}	
	}
	if {$file_double != ""} {
		catch {file delete $file_double}	
	}

	global sound_daemon_local_kill
	if {! $is_win9x && $use_sound && $sound_daemon_local_kill && $sound_daemon_local_cmd != ""} {
		windows_stop_sound_daemon
	}
	return 1
}

proc check_ssh_needed {} {
	globalize
	
	if {$use_ssh || $use_sshssl} {
		return
	}
	set must_cups 0
	set must_snd 0
	set must_smb 0
	set must_addl 0
	if {$use_cups} {
		if {$cups_local_server != ""} {set must_cups 1}
		if {$cups_remote_port != ""} {set must_cups 1}
		if {$cups_local_smb_server != ""} {set must_cups 1}
		if {$cups_remote_smb_port != ""} {set must_cups 1}
		if {$cups_manage_rcfile != ""} {set must_cups 1}
	}
	if {$use_sound} {
		if {$sound_daemon_remote_cmd != ""} {set must_snd 1}
		if {$sound_daemon_remote_port != ""} {set must_snd 1}
		if {$sound_daemon_kill} {set must_snd 1}
		if {$sound_daemon_restart} {set must_snd 1}
		if {$sound_daemon_local_cmd != ""} {set must_snd 1}
		if {$sound_daemon_local_port != ""} {set must_snd 1}
		if {$sound_daemon_local_kill} {set must_snd 1}
		if {$sound_daemon_local_start} {set must_snd 1}
	}
	if {$use_smbmnt} {
		if {[regexp {//} $smb_mount_list]} {set must_smb 1}
	}
	if {$additional_port_redirs} {
		set must_addl 1
	}
	if {$must_cups || $must_snd || $must_smb || $must_addl} {
#		set use_sshssl 1
#		ssl_ssh_adjust sshssl
#		mesg "Enabling \"Use SSH and SSL\" mode for port redir"
		mesg "Cannot do Port redirs in non-SSH mode (SSL)"
		set msg ""
		if {$must_smb} {
			append msg "  - SMB Mount Port Redirection\n"
		}
		if {$must_snd} {
			append msg "  - ESD Sound Port Redirection\n"
		}
		if {$must_cups} {
			append msg "  - CUPS Port Redirection\n"
		}
		if {$must_addl} {
			append msg "  - Additional Port Redirections\n"
		}
                set msg "\"Use SSL\" mode selected (no SSH)\nThe following options will be disabled:\n\n$msg"
		bell
		update
		raise .
                tk_messageBox -type ok -icon info -message $msg
	}
}

proc set_smb_mounts {} {
	global smb_redir_0 smb_mounts use_smbmnt 
	
	set smb_redir_0 ""
	set smb_mounts ""
	if {$use_smbmnt} {
		set l2 [get_smb_redir]
		set smb_redir_0 [lindex $l2 0]
		set smb_redir_0 [string trim $smb_redir_0]
		set smb_mounts  [lindex $l2 1]
	}
}

proc darwin_terminal_cmd {{title ""} {cmd ""} {bg 0}} {
	global darwin_terminal

	set tries ""
	lappend tries "/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal"

	if {! [info exists darwin_terminal]} {
		foreach try $tries {
			if [file exists $try] {
				if [file executable $try] {
					set darwin_terminal $try
					break
				}
			}
		}
		if {! [info exists darwin_terminal]} {
			set fh ""
			catch {set fh [open "| find /Applications -type f -name Terminal" "r"]}
			if {$fh != ""} {
				while {[gets $fh line] > -1} {
					if {! [file exists $line]} {
						continue
					}
					if {[file isdirectory $line]} {
						continue
					}
					if {! [regexp {/Terminal$} $line]} {
						continue
					}
					if {! [file executable $line]} {
						continue
					}
					set darwin_terminal $line
					break
				}
				close $fh
			}
		}
	}
	if {! [info exists darwin_terminal]} {
		raise .
		tk_messageBox -type ok -icon error -message "Cannot find Darwin Terminal program." -title "Cannot find Terminal program"
		return
	}

	global darwin_terminal_cnt
	set tmp /tmp/darwin_terminal_cmd.[pid]
	if {! [info exists darwin_terminal_cnt]} {
		set darwin_terminal_cnt 0
	}
	incr darwin_terminal_cnt
	append tmp ".$darwin_terminal_cnt"
	
	set fh ""
	catch {set fh [open $tmp w 0755]}
	if {$fh == ""} {
		raise .
		tk_messageBox -type ok -icon error -message "Cannot open temporary file: $tmp" -title "Cannot open file"
		return
	}
	global env
	puts $fh "#!/bin/sh"
	puts $fh "PATH=$env(PATH)"
	puts $fh "export PATH"
	puts $fh "tmp=$tmp"
	puts $fh "sleep 1"
	puts $fh {if [ "X$DDDBG" != "X" ]; then ps www; fi}
	puts $fh {termpid=`ps www | grep -w Terminal | grep $tmp | grep -v grep | awk '{print $1}' | sort -n | tail -1`}
	puts $fh {echo try-1: termpid=$termpid mypid=$$}
	puts $fh {if [ "X$termpid" = "X" ]; then}
	puts $fh {	termpid=`ps www | grep -w Terminal | grep -v grep | awk '{print $1}' | sort -n | tail -1`}
	puts $fh {	echo try-2: termpid=$termpid mypid=$$}
	puts $fh {fi}
	puts $fh {if [ "X$termpid" = "X" ]; then}
	puts $fh {	termpid=`ps wwwwaux | grep -w Terminal | grep $tmp | grep -v grep | awk '{print $2}' | sort -n | tail -1`}
	puts $fh {	echo try-3: termpid=$termpid mypid=$$}
	puts $fh {fi}
	puts $fh {if [ "X$termpid" = "X" ]; then}
	puts $fh {	termpid=$$}
	puts $fh {	echo termpid-find-fail: termpid=$termpid mypid=$$}
	puts $fh {fi}
	puts $fh {trap "rm -f $tmp; kill -TERM $termpid; kill -TERM $mypid; kill -KILL $mypid; exit 0" 0 2 15}
	puts $fh "$cmd"
	puts $fh "sleep 1"
	puts $fh {rm -f $tmp}
	puts $fh {kill -TERM $termpid}
	puts $fh {kill -TERM $mypid}
	puts $fh {kill -KILL $mypid}
	puts $fh "exit 0"
	close $fh
	if {$bg} {
		catch {exec $darwin_terminal $tmp &}
	} else {
		catch {exec $darwin_terminal $tmp}
	}
}

proc unix_terminal_cmd {{geometry "+100+100"} {title "xterm-command"} {cmd "echo test"} {bg 0} {xrm1 ""} {xrm2 ""} {xrm3 ""}} {
	global uname
	if {$uname == "Darwin"} {
		global env
		set doX  0;
		if [info exists env(DISPLAY)] {
			if {[in_path "xterm"] != ""} {
				set doX 1
			}
		}
		if {! $doX} {
			darwin_terminal_cmd $title $cmd $bg
			return
		}
	}
	if {$bg} {
		if {$xrm1 == ""} {
			exec xterm -geometry "$geometry" -title "$title" -e sh -c "$cmd" 2>@stdout &
		} else {
			exec xterm -geometry "$geometry" -title "$title" -xrm "$xrm1" -xrm "$xrm2" -xrm "$xrm3" -e sh -c "$cmd" 2>@stdout &
		}
	} else {
		if {$xrm1 == ""} {
			exec xterm -geometry "$geometry" -title "$title" -e sh -c "$cmd" 2>@stdout
		} else {
			exec xterm -geometry "$geometry" -title "$title" -xrm "$xrm1" -xrm "$xrm2" -xrm "$xrm3" -e sh -c "$cmd" 2>@stdout
		}
	}
}

proc xterm_center_geometry {} {
	set sh [winfo screenheight .]
	set sw [winfo screenwidth .]
	set gw 500
	set gh 300
	set x [expr $sw/2 - $gw/2]
	set y [expr $sh/2 - $gh/2]
	if {$x < 0} {
		set x 10
	}
	if {$y < 0} {
		set y 10
	}

	return "+$x+$y"
}

proc smbmnt_wait {tee} {
	if {$tee != ""} {
		set start [clock seconds]
		set cut 30
		while {1} {
			set now [clock seconds]
			if {$now > $start + $cut} {
				break;
			}
			if [file exists $tee] {
				set sz 0
				catch {set sz [file size $tee]}
				if {$sz > 50} {
					set cut 50
				}
			}
			set g ""
			catch {set g [exec grep vnc-helper-exiting $tee]}
			if [regexp {vnc-helper-exiting} $g] {
				break
			}
			after 1000
		}
		catch {file delete $tee}
	} else {
		global smb_su_mode
		if {$smb_su_mode == "su"} {
			after 15000
		} elseif {$smb_su_mode == "sudo"} {
			after 10000
		}
	}
}

proc do_unix_pre {tag proxy hp pk_hp}  {
	global env smb_redir_0 use_smbmnt
	global did_port_knock
	
	set setup_cmds [ugly_setup_scripts pre $tag] 
	set c "ss_vncviewer -ssh"

	if {$proxy == ""} {
		set pxy $hp
		regsub {:.*$} $pxy "" pxy
		set c "$c -proxy '$pxy'"
	} else {
		set c "$c -proxy '$proxy'"
	}

	if {$setup_cmds != ""} {
		set env(SS_VNCVIEWER_SSH_CMD) "$setup_cmds sleep 10"
		set env(SS_VNCVIEWER_SSH_ONLY) 1
		if {$smb_redir_0 != ""} {
			set c "$c -sshargs '$smb_redir_0'"
		}

		if {! [do_port_knock $pk_hp start]} {
			return
		}
		set did_port_knock 1

		if {$use_smbmnt} {
			set title "SSL/SSH VNC Viewer $hp -- SMB MOUNTS"
		} else {
			set title "SSL/SSH VNC Viewer $hp -- Pre Commands"
		}

		set tee ""
		if {$use_smbmnt} {
			set tee $env(HOME) 
			append tee "/.tee-etv$tag"
			set fh ""
			catch {set fh [open $tee "w"]}
			if {$fh == ""} {
				set tee ""
			} else {
				close $fh
				set c "$c | tee $tee"
			}
		}

		unix_terminal_cmd "80x25+100+100" "$title" "set -xv; $c" 1

		set env(SS_VNCVIEWER_SSH_CMD) ""
		set env(SS_VNCVIEWER_SSH_ONLY) ""

		if {$use_smbmnt} {
			smbmnt_wait $tee
		} else {
			after 2000
		}
	}
}
proc init_vncdisplay {} {
	global vncdisplay vncproxy remote_ssh_cmd
	set vncdisplay [string trim $vncdisplay] 

	if {$vncdisplay == ""} {
		set vncproxy ""
		set remote_ssh_cmd ""
		return
	}

	set hpnew  [get_ssh_hp $vncdisplay]
	set proxy  [get_ssh_proxy $vncdisplay]
	set sshcmd [get_ssh_cmd $vncdisplay]

	set vncdisplay $hpnew
	set vncproxy $proxy
	set remote_ssh_cmd $sshcmd

	if {$sshcmd != ""} {
		global use_ssl use_ssh use_sshssl
		set use_ssl 0
		if {! $use_ssh && ! $use_sshssl} {
			set use_ssh 1
		}
	}
	# ssl_ssh_adjust will be called.
}

proc get_vncdisplay {} {
	global vncdisplay vncproxy remote_ssh_cmd
	set vncdisplay [string trim $vncdisplay]

	set t $vncdisplay
	regsub {[ \t]*cmd=.*$} $t "" t
	set t [string trim $t]
	
	set str ""
	if [regexp {[ \t]} $t] {
		set str $t
	} else {
		if {$vncproxy != "" && $t == ""} {
			set str "--nohost-- $vncproxy"
		} else {
			set str "$t $vncproxy"
		}
	}
	if [regexp {cmd=.*$} $vncdisplay match] {
		if {$str == ""} {
			set str "--nohost--"
		}
		set str "$str $match"
	} else {
		if {$remote_ssh_cmd != ""} {
			if {$str == ""} {
				set str "--nohost--"
			}
			set str "$str cmd=$remote_ssh_cmd"
		}
	}
	set str [string trim $str]
	return $str
}

proc port_knock_only {hp {mode KNOCK}} {
	if {$hp == ""} {
		set hp [get_vncdisplay]
		if {$hp == ""} {
			mesg "No host port found"
			bell
			return
		}
	}
	set hpnew  [get_ssh_hp $hp]
	set proxy  [get_ssh_proxy $hp]
	set sshcmd [get_ssh_cmd $hp]
	set hp $hpnew

	set pk_hp ""
	if {$proxy != ""} {
		set pk_hp $proxy
	}
	if {$pk_hp == ""} {
		set pk_hp $hp
	}
	if {$mode == "KNOCK"} {
		do_port_knock $pk_hp start
	} elseif {$mode == "FINISH"} {
		do_port_knock $pk_hp finish
	}
}

proc direct_connect_msg {} {
	set msg ""
	globalize
	if {$use_sshssl} {
		append msg "  - SSH + SSL tunnelling\n"
	} elseif {$use_ssh} {
		append msg "  - SSH tunnelling\n"
	} else {
		append msg "  - SSL tunnelling\n"
	}
	if {$use_smbmnt} {
		append msg "  - SMB Mount Port Redirection\n"
	}
	if {$use_sound} {
		append msg "  - ESD Sound Port Redirection\n"
	}
	if {$use_cups} {
		append msg "  - CUPS Port Redirection\n"
	}
	if {$additional_port_redirs} {
		append msg "  - Additional Port Redirections\n"
	}
	if {$mycert != "" || $svcert != "" || $crtdir != ""} {
		append msg "  - SSL certificate authentication\n"
	}
	if {$msg != ""} {
		set msg "Direct connect via vnc://hostname\nThe following options will be disabled:\n\n$msg"
		raise .
		tk_messageBox -type ok -icon info -message $msg
	}
}

proc fetch_cert {} {
	global vncdisplay is_windows
	set hp [get_vncdisplay]

	regsub {[ 	]*cmd=.*$} $hp "" tt
	if {[regexp {^[ 	]*$} $tt]} {
		mesg "No host:disp supplied."
		bell
		catch {raise .}
		return
	}
	if {[regexp -- {--nohost--} $tt]} {
		mesg "No host:disp supplied."
		bell
		catch {raise .}
		return
	}
	if {! [regexp ":" $hp]} {
		if {! [regexp {cmd=} $hp]} {
			append hp ":0"
		}
	}
	set hpnew  [get_ssh_hp $hp]
	set proxy  [get_ssh_proxy $hp]

	mesg "Fetching $hpnew Cert..."
	global cert_text
	set cert_text ""
	.f4.getcert configure -state disabled
	update
	if {$is_windows} {
		set cert_text [fetch_cert_windows $hp]
	} else {
		catch {set cert_text [fetch_cert_unix $hp]}
	}
	.f4.getcert configure -state normal
	mesg "Fetched $hpnew Cert"

	set n 47
	set ok 1
	if {$cert_text == ""} {
		set cert_text "An Error occurred in fetching SSL Certificate from $hp"
		set ok 0
		set n 4
	} elseif {! [regexp {BEGIN CERTIFICATE} $cert_text]} {
		set cert_text "An Error occurred in fetching $hp\n\n$cert_text"
		set ok 0
	} else {
		set text "" 
		set on 0
		foreach line [split $cert_text "\n"] {
			if [regexp -- {-----BEGIN CERTIFICATE-----} $line] {
				set on 1
			}
			if {! $on} {
				continue;
			}
			append text "$line\n"
			if [regexp -- {-----END CERTIFICATE-----} $line] {
				set on 0
			}
		}
		global is_windows
		set tmp "/tmp/cert.hsh.[pid]"
		if {$is_windows} {
			# VF
			set tmp cert.hsh
		}
		set fh ""
		catch {set fh [open $tmp "w"]}
		if {$fh != ""} {
			puts $fh $text
			close $fh
			set info ""
			catch {set info [get_x509_info $tmp]}
			catch {file delete $tmp}
			if [regexp -nocase {MD5 Finger[^\n]*} $info mvar] {
				set cert_text "$mvar\n\n$cert_text"
			}
			if [regexp -nocase {SHA. Finger[^\n]*} $info mvar] {
				set cert_text "$mvar\n\n$cert_text"
			}
		}
		set cert_text "SSL Certificate from $hp\n\n$cert_text"
	}
	
	toplev .fetch

	scroll_text_dismiss .fetch.f 90 $n

	if {$ok} {
		button .fetch.save -text Save -command "destroy .fetch; save_cert $hpnew"
		button .fetch.help -text Help -command "help_fetch_cert"
		pack .fetch.help .fetch.save -side bottom -fill x
	}

	center_win .fetch
	wm title .fetch "$hp Certificate"

	.fetch.f.t insert end $cert_text
	jiggle_text .fetch.f.t
}

proc fetch_cert_unix {hp} {
	set hpnew  [get_ssh_hp $hp]
	set proxy  [get_ssh_proxy $hp]
	if {$proxy != ""} {
		return [exec ss_vncviewer -proxy $proxy -showcert $hpnew 2>/dev/null]
	} else {
		return [exec ss_vncviewer -showcert $hpnew]
	}
}

proc fetch_cert_windows {hp} {
	set hpnew  [get_ssh_hp $hp]
	set proxy  [get_ssh_proxy $hp]

	set list [split $hpnew ":"] 

	set host [lindex $list 0]
	if {$host == ""} {
		set host "localhost"
	}

	if [regexp {^.*@} $host match] {
		mesg "Trimming \"$match\" from hostname"
		regsub {^.*@} $host "" host
	}

	set disp [lindex $list 1]
	set disp [string trim $disp]
	regsub { .*$} $disp "" disp

	if {$disp == "" || ! [regexp {^[0-9][0-9]*$} $disp]} {
		set disp 0
	}
	set port [expr "$disp + 5900"]

	if {$proxy != ""} {
		global env

		set port2 5991
		set env(SSVNC_PROXY) $proxy
		set env(SSVNC_LISTEN) $port2
		set env(SSVNC_DEST) "$host:$port"

		set host localhost
		set port $port2
		mesg "Starting TCP helper on port $port2 ..."
		after 600
		set proxy_pid [exec "connect_br.exe" &]
		unset -nocomplain env(SSVNC_PROXY)
		unset -nocomplain env(SSVNC_LISTEN)
		unset -nocomplain env(SSVNC_DEST)
	}

	set ossl [get_openssl]
	update
	# VF
	set tin tmpin.txt
	set tou tmpout.txt
	set fh ""
	catch {set fh [open $tin "w"]}
	if {$fh != ""} {
		puts $fh "Q"
		puts $fh "GET /WOMBAT HTTP/1.1\r\nHost: wombat.com\r\n\r\n\r\n"
		close $fh
	}
	if {1} {
		set ph ""
		set ph [open "| $ossl s_client -connect $host:$port < $tin 2>NUL" "r"]
#		set ph [open "| $ossl s_client -connect $host:$port" "r"]
		set text ""
		if {$ph != ""} {
			set pids [pid $ph]
			set got 0
			while {[gets $ph line] > -1} {
				append text "$line\n"
#mesg "line: $line"; after 10
				if [regexp {END CERT} $line] {
					set got 1
				}
				if {$got && [regexp {^ *Verify return code} $line]} {
					break
				}
				if [regexp {^RFB } $line] {
					break
				}
				if [regexp {^DONE} $line] {
					break
				}
			}
			foreach pid $pids {
				global is_win9x
				if {$pid == ""} {
					;
				} elseif {$is_win9x} {
					catch {exec w98/kill.exe /f $pid}
				} else {
					catch {exec tskill.exe $pid}
				}
			}
			catch {close $ph}
			catch {file delete $tin $tou}
			return $text
		}
	} else {
		set pids ""
if {1} {
		set ph2 [open "| $ossl s_client -connect $host:$port > $tou 2>NUL" "w"]
		set pids [pid $ph2]
		after 500
		for {set i 0} {$i < 128} {incr i} {
			puts $ph2 "Q"
		}
		catch {close $ph2}
	
} else {
		set pids [exec $ossl s_client -connect $host:$port < $tin >& $tou &]
}
		for {set i 0} {$i < 10} {incr i} {
			after 500
			set got 0
			set ph ""
			catch {set ph [open $tou "r"]}
#mesg "open: $tou"
			if {$ph != ""} {
				while {[gets $ph line] > -1} {
#mesg "line: $line"; after 10
					if [regexp {END CERT} $line] {
						set got 1
						break
					}
				}
				close $ph
			}
#mesg "clse: $tou"
			if {$got} {
				break
#mesg "GOT"; after 200
			}
		}
		global is_win9x
		foreach pid $pids {
#mesg "kill -- $pid"
			if {$pid == ""} {
				;
			} elseif {$is_win9x} {
				catch {exec w98/kill.exe /f $pid}
			} else {
				catch {exec tskill.exe $pid}
			}
		}
		after 500
		set ph ""
		catch {set ph [open $tou "r"]}
	}
	set text ""
	if {$ph != ""} {
		while {[gets $ph line] > -1} {
			append text "$line\n"
		}
		close $ph
	}
	catch {file delete $tin $tou}
	return $text
}

proc launch_unix {hp} {
	global smb_redir_0 smb_mounts env
	global vncauth_passwd

	globalize

	set cmd ""

	check_ssh_needed

	set_smb_mounts

	global did_port_knock
	set did_port_knock 0
	set pk_hp ""

	set skip_ssh 0
	if [regexp {vnc://} $hp] {
		set skip_ssh 1
		direct_connect_msg
	}

	if {$use_ssh || $use_sshssl} {
		if {$skip_ssh} {
			set cmd "ss_vncviewer"
		} elseif {$use_ssh} {
			set cmd "ss_vncviewer -ssh"
		} else {
			set cmd "ss_vncviewer -sshssl"
			if {$mycert != ""} {
				set cmd "$cmd -mycert '$mycert'"
			}
			if {$svcert != ""} {
				set cmd "$cmd -verify '$svcert'"
			} elseif {$crtdir != ""} {
				set cmd "$cmd -verify '$crtdir'"
			}
		}
		set hpnew  [get_ssh_hp $hp]
		set proxy  [get_ssh_proxy $hp]
		set sshcmd [get_ssh_cmd $hp]
		set hp $hpnew

		if {$proxy != ""} {
			set cmd "$cmd -proxy '$proxy'"
			set pk_hp $proxy
		}
		if {$pk_hp == ""} {
			set pk_hp $hp
		}

		set do_pre 0
		if {$use_smbmnt}  {
			set do_pre 1
		} elseif {$use_sound && $sound_daemon_kill} {
			set do_pre 1
		}
		global skip_pre
		if {$skip_pre || $skip_ssh} {
			set do_pre 0
			set skip_pre 0
		}

		set tag [contag]

		if {$do_pre} {
			do_unix_pre $tag $proxy $hp $pk_hp
		}


		set setup_cmds [ugly_setup_scripts post $tag] 
		if {$skip_ssh} {
			set setup_cmds ""
		}

		if {$sshcmd == "SHELL"} {
			set env(SS_VNCVIEWER_SSH_CMD) {$SHELL}
			set env(SS_VNCVIEWER_SSH_ONLY) 1
		} elseif {$setup_cmds != ""} {
			set env(SS_VNCVIEWER_SSH_CMD) "$setup_cmds$sshcmd"
		} else {
			if {$sshcmd != ""} {
				set cmd "$cmd -sshcmd '$sshcmd'"
			}
		}
		
		set sshargs ""
		if {$use_cups} {
			append sshargs [get_cups_redir]
		}
		if {$use_sound} {
			append sshargs [get_sound_redir]
		}
		if {$additional_port_redirs} {
			append sshargs [get_additional_redir]
		}

		set sshargs [string trim $sshargs]
		if {$skip_ssh} {
			set sshargs ""
		}
		if {$sshargs != ""} {
			set cmd "$cmd -sshargs '$sshargs'"
			set env(SS_VNCVIEWER_USE_C) 1
		}
		if {$sshcmd == "SHELL"} {
			set env(SS_VNCVIEWER_SSH_ONLY) 1
			if {$proxy == ""} {
				set hpt $hpnew
				regsub {:[0-9]*$} $hpt "" hpt
				set cmd "$cmd -proxy '$hpt'"
			}
			set geometry [xterm_center_geometry]
			if {$pk_hp == ""} {
				set pk_hp $hp
			}
			if {! $did_port_knock} {
				if {! [do_port_knock $pk_hp start]} {
					return
				}
				set did_port_knock 1
			}

			if {[regexp {FINISH} $port_knocking_list]} {
				wm withdraw .
				update
				unix_terminal_cmd $geometry "SHELL to $hp" "$cmd"
				wm deiconify .
				update
				do_port_knock $pk_hp finish
			} else {
				unix_terminal_cmd $geometry "SHELL to $hp" "$cmd" 1
			}
			set env(SS_VNCVIEWER_SSH_CMD) ""
			set env(SS_VNCVIEWER_SSH_ONLY) ""
			set env(SS_VNCVIEWER_USE_C) ""
			return
		}
	} else {
		set cmd "ssvnc_cmd"
		set hpnew  [get_ssh_hp $hp]
		set proxy  [get_ssh_proxy $hp]
		if {$mycert != ""} {
			set cmd "$cmd -mycert '$mycert'"
		}
		if {$svcert != ""} {
			set cmd "$cmd -verify '$svcert'"
		} elseif {$crtdir != ""} {
			set cmd "$cmd -verify '$crtdir'"
		}
		if {$proxy != ""} {
			set cmd "$cmd -proxy '$proxy'"
		}
		set hp $hpnew
		if [regexp {^.*@} $hp match] {
			catch {raise .; update}
			mesg "Trimming \"$match\" from hostname"
			after 1000
			regsub {^.*@} $hp "" hp
		}
		if [regexp {@} $proxy] {
			bell
			catch {raise .; update}
			mesg "WARNING: SSL proxy contains \"@\" sign"
			after 2000
		}
	}

	if {$use_alpha} {
		set cmd "$cmd -alpha"
	}
	if {$use_grab} {
		set cmd "$cmd -grab"
	}

	global darwin_cotvnc
	if {$darwin_cotvnc} {
		set env(DARWIN_COTVNC) 1
	}

	set cmd "$cmd $hp"

	set do_vncspacewrapper 0
	if {$change_vncviewer && $change_vncviewer_path != ""} {
		set path [string trim $change_vncviewer_path]
		if [regexp {^["'].} $path]  {	# "
			set tmp "/tmp/vncspacewrapper."
			set do_vncspacewrapper 1
			append tmp [clock clicks -milliseconds]
			catch {file delete $tmp}
			if {[file exists $tmp]} {
				catch {destroy .c}
				mesg "file still exists: $tmp"
				bell
				return
			}
			catch {set fh [open $tmp "w"]}
			catch {exec chmod 700 $tmp}
			if {! [file exists $tmp]} {
				catch {destroy .c}
				mesg "cannot create: $tmp"
				bell
				return
			}
			puts $fh "#!/bin/sh"
			puts $fh "echo $tmp; set -xv"
			puts $fh "$path \"\$@\""
			puts $fh "sleep 1; rm -f $tmp"
			close $fh
			set path $tmp
		}
		set env(VNCVIEWERCMD) $path
	} else {
		if [info exists env(VNCVIEWERCMD_OVERRIDE)] {
			set env(VNCVIEWERCMD) $env(VNCVIEWERCMD_OVERRIDE)
		} else {
			set env(VNCVIEWERCMD) ""
		}
	}

	set realvnc4 $vncviewer_realvnc4
	set realvnc3 0
	set flavor ""
	if {! $darwin_cotvnc} {
		set done 0
		if {$do_vncspacewrapper} {
			if [regexp -nocase {ultra} $change_vncviewer_path] {
				set done 1
				set flavor "ultravnc"
			} elseif [regexp -nocase {chicken.of} $change_vncviewer_path] {
				set done 1
				set flavor "cotvnc"
			}
		}
		if {! $done} {
			catch {set flavor [exec ss_vncviewer -viewerflavor 2>/dev/null]}
		}
	}
	if [regexp {realvnc4} $flavor] {
		set realvnc4 1
	}
	if [regexp {tightvnc} $flavor] {
		set realvnc4 0
	}
	if [regexp {realvnc3} $flavor] {
		set realvnc4 0
		set realvnc3 1
	}

	set passwdfile ""
	if {$vncauth_passwd != ""} {
		set passwdfile "$env(HOME)/.vncauth_tmp.[pid]"
		catch {exec vncstorepw $vncauth_passwd $passwdfile}
		catch {exec chmod 600 $passwdfile}
		catch {exec sh -c "sleep 15; rm $passwdfile" &}
		if {$darwin_cotvnc} {
			set cmd "$cmd --PasswordFile $passwdfile"
		} else {
			set cmd "$cmd -passwd $passwdfile"
		}
	}

	if {$use_viewonly} {
		if {$darwin_cotvnc} {
			set cmd "$cmd --ViewOnly"
		} elseif {$flavor == "ultravnc"} {
			set cmd "$cmd /viewonly"
		} else {
			set cmd "$cmd -viewonly"
		}
	}
	if {$use_fullscreen} {
		if {$darwin_cotvnc} {
			set cmd "$cmd --FullScreen"
		} elseif {$flavor == "ultravnc"} {
			set cmd "$cmd /fullscreen"
		} else {
			set cmd "$cmd -fullscreen"
		}
	}
	if {$use_bgr233} {
		if {$realvnc4} {
			set cmd "$cmd -lowcolourlevel 1"
		} elseif {$flavor == "ultravnc"} {
			set cmd "$cmd /8bit"
		} else {
			set cmd "$cmd -bgr233"
		}
	}
	if {$use_nojpeg} {
		if {$darwin_cotvnc} {
			;
		} elseif {$flavor == "ultravnc"} {
			;
		} elseif {! $realvnc4 && ! $realvnc3} {
			set cmd "$cmd -nojpeg"
		}
	}
	if {! $use_raise_on_beep} {
		if {$darwin_cotvnc} {
			;
		} elseif {$flavor == "ultravnc"} {
			;
		} elseif {! $realvnc4 && ! $realvnc3} {
			set cmd "$cmd -noraiseonbeep"
		}
	}
	if {$use_compresslevel != "" && $use_compresslevel != "default"} {
		if {$realvnc3} {
			;
		} elseif {$flavor == "ultravnc"} {
			;
		} elseif {$realvnc4} {
			set cmd "$cmd -zliblevel '$use_compresslevel'"
		} else {
			set cmd "$cmd -compresslevel '$use_compresslevel'"
		}
	}
	if {$use_quality != "" && $use_quality != "default"} {
		if {$darwin_cotvnc} {
			;
		} elseif {$flavor == "ultravnc"} {
			;
		} elseif {! $realvnc4 && ! $realvnc3} {
			set cmd "$cmd -quality '$use_quality'"
		}
	}
	if {$use_ssh || $use_sshssl} {
		# realvnc4 -preferredencoding zrle
		if {$darwin_cotvnc} {
			;
		} elseif {$flavor == "ultravnc"} {
			;
		} elseif {$realvnc4} {
			set cmd "$cmd -preferredencoding zrle"
		} else {
			set cmd "$cmd -encodings 'copyrect tight zrle zlib hextile'"
		}
	}

	global ycrop_string
	catch {unset env(VNCVIEWER_SBWIDTH)}
	catch {unset env(VNCVIEWER_YCROP)}
	if {[info exists ycrop_string] && $ycrop_string != ""}  {
		set t $ycrop_string
		if [regexp {,sb=([0-9][0-9]*)} $t m mv1]  {
			set env(VNCVIEWER_SBWIDTH) $mv1
		}
		regsub {,sb=([0-9][0-9]*)} $t "" t
		if {$t != ""} {
			set env(VNCVIEWER_YCROP) $t
		}
		#catch {puts "VNCVIEWER_SBWIDTH $env(VNCVIEWER_SBWIDTH)"}
		#catch {puts "VNCVIEWER_YCROP   $env(VNCVIEWER_YCROP)"}
	}

	catch {destroy .o}
	catch {destroy .oa}
	update

	if {$use_sound && $sound_daemon_local_start && $sound_daemon_local_cmd != ""} {
		mesg "running: $sound_daemon_local_cmd"
		exec sh -c "$sound_daemon_local_cmd" >& /dev/null </dev/null &
		update
		after 500
	}

	if {$pk_hp == ""} {
		set pk_hp $hp
	}
	if {! $did_port_knock} {
		if {! [do_port_knock $pk_hp start]} {
			wm deiconify .
			update
			return
		}
		set did_port_knock 1
	}
	wm withdraw .
	update

	set geometry [xterm_center_geometry]
	set xrm1 "*.srinterCommand:true"
	set xrm2 $xrm1
	set xrm3 $xrm1
	if {[info exists env(SSVNC_GUI_CMD)]} {
		set xrm1 "*.printerCommand:env XTERM_PRINT=1 $env(SSVNC_GUI_CMD)"
		set xrm2 "XTerm*VT100*translations:#override Shift<Btn3Down>:print()\\nCtrl<Key>N:print()"
		set xrm3 "*mainMenu*print*Label:  New SSVNC_GUI"
	}
	set m "Done. You Can X-out or Ctrl-C this Terminal if you like.  Ctrl-\\\\ to pause."
	global uname
	if {$uname == "Darwin"} {
		regsub {X-out or } $m "" m
	}
	unix_terminal_cmd $geometry "SSL/SSH VNC Viewer $hp" \
	"set -xv; $cmd; set +xv; ulimit -c 0; trap 'printf \"Paused. Press Enter to exit:\"; read x' QUIT; echo; echo $m; echo; echo sleep 5; echo; sleep 6" 0 $xrm1 $xrm2 $xrm3

	set env(SS_VNCVIEWER_SSH_CMD) ""
	set env(SS_VNCVIEWER_USE_C) ""

	if {$use_sound && $sound_daemon_local_kill && $sound_daemon_local_cmd != ""} {
		set daemon [string trim $sound_daemon_local_cmd]
		regsub {^gw[ \t]*} $daemon "" daemon
		regsub {[ \t].*$} $daemon "" daemon
		regsub {^.*/} $daemon "" daemon
		mesg "killing sound daemon: $daemon"
		if {$daemon != ""} {
			catch {exec sh -c "killall $daemon"  >/dev/null 2>/dev/null </dev/null &}
			catch {exec sh -c "pkill -x $daemon" >/dev/null 2>/dev/null </dev/null &}
		}
	}
	if {$passwdfile != ""} {
		catch {file delete $passwdfile}
	}
	wm deiconify .
	mesg "Disconnected from $hp"
	if {[regexp {FINISH} $port_knocking_list]} {
		do_port_knock $pk_hp finish
	}
}

proc kill_stunnel {pids} {
	global is_win9x

	set count 0
	foreach pid $pids {
		mesg "killing STUNNEL pid: $pid"
		if {$is_win9x} {
			catch {exec w98/kill.exe /f $pid}
		} else {
			catch {exec tskill.exe $pid}
		}
		if {$count == 0} {
			after 1200
		} else {
			after 500
		}
		incr count
	}
}

proc get_task_list {} {
	global is_win9x
	
	set output1 ""
	set output2 ""
	if {! $is_win9x} {
		# try for tasklist on XP pro
		catch {set output1 [exec tasklist.exe]}
	}
	catch {set output2 [exec w98/tlist.exe]}

	set output $output1
	append output "\n"
	append output $output2

	return $output
}

proc note_stunnel_pids {when} {
	global is_win9x pids_before pids_after pids_new

	if {$when == "before"} {
		array unset pids_before
		array unset pids_after
		set pids_new {}
		set pids_before(none) "none"
		set pids_after(none)  "none"
	}

	set output [get_task_list]
	
	foreach line [split $output "\n\r"] {
		if [regexp -nocase {stunnel} $line] {
			if [regexp {(-?[0-9][0-9]*)} $line m p] {
				if {$when == "before"} {
					set pids_before($p) $line
				} else {
					set pids_after($p) $line
				}
			}
		}
	}
	if {$when == "after"} {
		foreach new [array names pids_after] {
			if {! [info exists pids_before($new)]} {
				lappend pids_new $new
			}
		}
	}
}

proc del_launch_windows_ssh_files {} {
	global launch_windows_ssh_files
	
	if {$launch_windows_ssh_files != ""} {
		foreach tf [split $launch_windows_ssh_files] {
			if {$tf == ""} {
				continue
			}
			catch {file delete $tf}
		}
	}
}

proc launch_shell_only {} {
	global is_windows
	global skip_pre

	set hp [get_vncdisplay]
	regsub {cmd=.*$} $hp "" hp
	set hp [string trim $hp]
	if {$is_windows} {
		append hp " cmd=PUTTY"
	} else {
		append hp " cmd=SHELL"
	}
	set skip_pre 1
	launch $hp
}

proc launch {{hp ""}} {
	global tcl_platform is_windows
	global mycert svcert crtdir
	global pids_before pids_after pids_new
	global env
	global use_ssh use_sshssl

	set debug 0
	if {$hp == ""} {
		set hp [get_vncdisplay]
	}

	regsub {[ 	]*cmd=.*$} $hp "" tt

	if {[regexp {^[ 	]*$} $tt]} {
		mesg "No host:disp supplied."
		bell
		catch {raise .}
		return
	}
	if {[regexp -- {--nohost--} $tt]} {
		mesg "No host:disp supplied."
		bell
		catch {raise .}
		return
	}
	if {! [regexp ":" $hp]} {
		if {! [regexp {cmd=} $hp]} {
			append hp ":0"
		}
	}

	mesg "Using: $hp"
	after 600

	set sc [get_ssh_cmd $hp]
	if {[regexp {^KNOCK} $sc]} {
		if [regexp {^KNOCKF} $sc] {
			port_knock_only $hp "FINISH"
		} else {
			port_knock_only $hp "KNOCK"
		}
		return
	}

	if {$debug} {
		mesg "\"$tcl_platform(os)\" | \"$tcl_platform(osVersion)\""
		after 1000
	}
	if {! $is_windows} {
		launch_unix $hp
		return
	}

	check_ssh_needed

	if {! $use_ssh} {
		if {$mycert != ""} {
			if {! [file exists $mycert]} {
				mesg "MyCert does not exist: $mycert"
				bell
				return
			}
		}
		if {$svcert != ""} {
			if {! [file exists $svcert]} {
				mesg "ServerCert does not exist: $svcert"
				bell
				return
			}
		} elseif {$crtdir != ""} {
			if {! [file exists $crtdir]} {
				mesg "CertsDir does not exist: $crtdir"
				bell
				return
			}
		}
	}

	# VF
	set prefix "stunnel-vnc"
	set suffix "conf"
	if {$use_ssh || $use_sshssl} {
		set prefix "plink_vnc"
		set suffix "bat"
	}

	set file ""
	set n ""
	set file2 ""
	set n2 ""
	set now [clock seconds]

	set proxy [get_ssh_proxy $hp]
	if {$use_sshssl} {
		set proxy ""
	}

	for {set i 30} {$i < 90} {incr i}  {
		set try "$prefix-$i.$suffix"
		if {[file exists $try]}  {
			set mt [file mtime $try]
			set age [expr "$now - $mt"]
			set week [expr "7 * 3600 * 24"]
			if {$age > $week} {
				catch {file delete $file}
			}
		}
		if {! [file exists $try]}  {
			if {$use_sshssl || $proxy != ""} {
				if {$file != ""} {
					set file2 $try
					set n2 $i
					break
				}
			}
			set file $try
			set n $i
			if {! $use_sshssl && $proxy == ""} {
				break
			}
		}
	}

	if {$file == ""} {
		mesg "could not find free stunnel file"
		bell
		return
	}

	global launch_windows_ssh_files 
	set launch_windows_ssh_files ""

	set did_port_knock 0

	if {$use_sshssl} {
		set rc [launch_windows_ssh $hp $file2 $n2]
		if {$rc == 0} {
			catch {file delete $file}
			catch {file delete $file2}
			del_launch_windows_ssh_files
			return
		}
		set did_port_knock 1
	} elseif {$use_ssh} {
		launch_windows_ssh $hp $file $n
		return
	}

	set list [split $hp ":"] 

	set host [lindex $list 0]
	if {$host == ""} {
		set host "localhost"
	}

	if [regexp {^.*@} $host match] {
		catch {raise .; update}
		mesg "Trimming \"$match\" from hostname"
		after 1000
		regsub {^.*@} $host "" host
	}

	set disp [lindex $list 1]
	set disp [string trim $disp]
	regsub { .*$} $disp "" disp
	if {$disp == "" || ! [regexp {^[0-9][0-9]*$} $disp]} {
		set disp 0
	}
	set port [expr "$disp + 5900"]

	if {$proxy != ""} {
		if [regexp {@} $proxy] {
			bell
			catch {raise .; update}
			mesg "WARNING: SSL proxy contains \"@\" sign"
			after 2000
		}
		set env(SSVNC_PROXY) $proxy
		set env(SSVNC_LISTEN) [expr "$n2 + 5900"]
		set env(SSVNC_DEST) "$host:$port"
	}

	if {$debug} {
		mesg "file: $file"
		after 1000
	}

	set fail 0

	set fh [open $file "w"]

	puts $fh "client = yes"
	puts $fh "options = ALL"
	puts $fh "taskbar = yes"
	puts $fh "RNDbytes = 2048"
	puts $fh "RNDfile = bananarand.bin"
	puts $fh "RNDoverwrite = yes"
	puts $fh "debug = 6"
	if {$mycert != ""} {
		if {! [file exists $mycert]} {
			mesg "MyCert does not exist: $mycert"
			bell
			set fail 1
		}
		puts $fh "cert = $mycert"
	}
	if {$svcert != ""} {
		if {! [file exists $svcert]} {
			mesg "ServerCert does not exist: $svcert"
			bell
			set fail 1
		}
		puts $fh "CAfile = $svcert"
		puts $fh "verify = 2"
	} elseif {$crtdir != ""} {
		if {! [file exists $crtdir]} {
			mesg "CertsDir does not exist: $crtdir"
			bell
			set fail 1
		}
		puts $fh "CApath = $crtdir"
		puts $fh "verify = 2"
	}

	if {$n == ""} {
		set n 10
	}
	if {$n2 == ""} {
		set n2 11
	}
	puts $fh "\[vnc$n\]"
	set port2 [expr "$n + 5900"] 
	puts $fh "accept = localhost:$port2"

	if {$use_sshssl || $proxy != ""} {
		set port [expr "$n2 + 5900"]
		puts $fh "connect = localhost:$port"
	} else {
		puts $fh "connect = $host:$port"
	}

	puts $fh "delay = no"
	puts $fh ""
	close $fh

	if {! $did_port_knock} {
		if {! [do_port_knock $host start]} {
			set fail 1
		}
		set did_port_knock 1
	}

	if {$fail} {
		catch {file delete $file}
		return
	}

	set proxy_pid ""
	if {$proxy != ""} {
		mesg "Starting TCP helper on port $port ..."
		after 600
		set proxy_pid [exec "connect_br.exe" &]
		unset -nocomplain env(SSVNC_PROXY)
		unset -nocomplain env(SSVNC_LISTEN)
		unset -nocomplain env(SSVNC_DEST)
	}

	mesg "Starting STUNNEL on port $port2 ..."
	after 600

	note_stunnel_pids "before"

	set pids [exec stunnel $file &]

	after 1300

	note_stunnel_pids "after"

	if {$debug} {
		after 1000
		mesg "pids $pids"
		after 1000
	} else {
		catch {destroy .o}
		catch {destroy .oa}
		wm withdraw .
	}

	do_viewer_windows $n

	del_launch_windows_ssh_files

	catch {file delete $file}

	if {$debug} {
		;
	} else {
		wm deiconify .
	}
	mesg "Disconnected from $hp."

	global port_knocking_list
	if [regexp {FINISH} $port_knocking_list] {
		do_port_knock $host finish
	}

	if {[llength $pids_new] > 0} {
		set plist [join $pids_new ", "]
		global terminate_pids
		set terminate_pids ""
		win_kill_msg $plist
		update
		vwait terminate_pids
		if {$terminate_pids == "yes"} {
			kill_stunnel $pids_new
		}
	} else {
		win_nokill_msg
	}
	mesg "Disconnected from $hp."

	global is_win9x use_sound sound_daemon_local_kill sound_daemon_local_cmd
	if {! $is_win9x && $use_sound && $sound_daemon_local_kill && $sound_daemon_local_cmd != ""} {
		windows_stop_sound_daemon
	}
}

proc get_idir_certs {str} {
	global is_windows env
	set idir ""
	if {$str != ""} {
		if [file isdirectory $str] {
			set idir $str
		} else {
			set idir [file dirname $str]
		}
		if {$is_windows} {
			regsub -all {\\} $idir "/" idir
			regsub -all {//*} $idir "/" idir
		}
	}
	if {$idir == ""} {
		if {$is_windows} {
			if [info exists env(HOME)] {
				set t "$env(HOME)/ss_vnc"	
				regsub -all {\\} $t "/" t
				regsub -all {//*} $t "/" t
				if {! [file isdirectory $t]} {
					catch {file mkdir $t}
				}
				set t "$env(HOME)/ss_vnc/certs"	
				regsub -all {\\} $t "/" t
				regsub -all {//*} $t "/" t
				if {! [file isdirectory $t]} {
					catch {file mkdir $t}
				}
				if [file isdirectory $t] {
					set idir $t
				}
			}
			if {$idir == ""} {
				set t [file dirname [pwd]]
				set t "$t/certs"
				if [file isdirectory $t] {
					set idir $t
				}
			}
		}
		if {$idir == ""} {
			if [info exists env(HOME)] {
				set t "$env(HOME)/.vnc/certs"	
				if [file isdirectory $t] {
					set idir $t
				}
			}
		}
	}
	if {$idir == ""} {
		if {$is_windows} {
			set idir [get_profiles_dir]
		}
		if {$idir == ""} {
			set idir [pwd]
		}
	}
	return $idir
}

proc set_mycert {{parent "."}} {
	global mycert
	set idir [get_idir_certs $mycert]
	set t ""
	if {$idir != ""} {
		set t [tk_getOpenFile -parent $parent -initialdir $idir]
	} else {
		set t [tk_getOpenFile -parent $parent]
	}
	if {$t != ""} {
		set mycert $t
	}
	catch {wm deiconify .c}
	v_mycert
	update
}


proc show_cert {crt} {
	if {$crt == ""} {
		bell
		return
	}
	if {! [file exists $crt]} {
		bell
		return
	}
	set info ""
	catch {set info [get_x509_info $crt]}
	if {$info == ""} {
		bell
		return
	}

	set w .show_certificate
	toplev $w
	scroll_text $w.f
	button $w.b -text Dismiss -command "destroy $w"
	bind $w <Escape> "destroy $w"
	$w.f.t insert end $info

	pack $w.b -side bottom -fill x
	pack $w.f -side top -fill both -expand 1
	center_win $w
	catch {raise $w}
}

proc v_svcert {} {
	global svcert
	if {$svcert == "" || ! [file exists $svcert]} {
		catch {.c.svcert.i configure -state disabled}
	} else {
		catch {.c.svcert.i configure -state normal}
	}
	return 1
}

proc v_mycert {} {
	global mycert
	if {$mycert == "" || ! [file exists $mycert]} {
		catch {.c.mycert.i configure -state disabled}
	} else {
		catch {.c.mycert.i configure -state normal}
	}
	return 1
}

proc show_mycert {} {
	global mycert
	show_cert $mycert
}

proc show_svcert {} {
	global svcert
	show_cert $svcert
}

proc set_svcert {{parent "."}} {
	global svcert crtdir
	set idir [get_idir_certs $svcert]
	set t ""
	if {$idir != ""} {
		set t [tk_getOpenFile -parent $parent -initialdir $idir]
	} else {
		set t [tk_getOpenFile -parent $parent]
	}
	if {$t != ""} {
		set crtdir ""
		set svcert $t
	}
	catch {wm deiconify .c}
	v_svcert
	update
}

proc set_crtdir {{parent "."}} {
	global svcert crtdir
	set idir [get_idir_certs $crtdir]
	set t ""
	if {$idir != ""} {
		set t [tk_chooseDirectory -parent $parent -initialdir $idir]
	} else {
		set t [tk_chooseDirectory -parent $parent]
	}
	if {$t != ""} {
		set svcert ""
		set crtdir $t
	}
	catch {wm deiconify .c}
	update
}

proc set_createcert_file {} {
	global ccert
	if {[info exists ccert(FILE)]} {
		set idir [get_idir_certs $ccert(FILE)]
	}
	if {$idir != ""} {
		set t [tk_getSaveFile -parent .ccrt -defaultextension ".pem" -initialdir $idir]
	} else {
		set t [tk_getSaveFile -parent .ccrt -defaultextension ".pem"]
	}
	if {$t != ""} {
		set ccert(FILE) $t
	}
	catch {raise .ccrt}
	update
}

proc check_pp {} {
	global ccert
	if {$ccert(ENC)} {
		catch {.ccrt.pf.e configure -state normal}
		catch {focus .ccrt.pf.e}
		catch {.ccrt.pf.e icursor end}
	} else {
		catch {.ccrt.pf.e configure -state disabled}
	}
}

proc get_openssl {} {
	global is_windows
	if {$is_windows} {
		set ossl "openssl.exe"
	} else {
		set ossl "openssl"
	}
}

proc get_x509_info {crt} {
	set ossl [get_openssl]
	set info ""
	update
	set ph [open "| $ossl x509 -text -fingerprint -in \"$crt\"" "r"]
	while {[gets $ph line] > -1} {
		append info "$line\n"
	}
	close $ph
	return $info
}

proc do_oss_create {} {
	global is_windows is_win9x

	set cfg {
[ req ]
default_bits            = 2048
encrypt_key             = yes
distinguished_name      = req_distinguished_name

[ req_distinguished_name ]
countryName                     = Country Name (2 letter code)
countryName_default             = %CO
countryName_min                 = 2
countryName_max                 = 2

stateOrProvinceName             = State or Province Name (full name)
stateOrProvinceName_default     = %ST

localityName                    = Locality Name (eg, city)
localityName_default            = %LOC

0.organizationName              = Organization Name (eg, company)
0.organizationName_default      = %ON

organizationalUnitName          = Organizational Unit Name (eg, section)
organizationalUnitName_default  = %OUN

commonName                      = Common Name (eg, YOUR name)
commonName_default              = %CN
commonName_max                  = 64

emailAddress                    = Email Address
emailAddress_default            = %EM
emailAddress_max                = 64
}

	global ccert

	if {$ccert(FILE) == ""} {
		catch {destroy .c}
		mesg "No output cert file supplied"
		bell
		return
	}
	if {! [regexp {\.pem$} $ccert(FILE)]} {
		append ccert(FILE) ".pem"
	}
	set pem $ccert(FILE)
	regsub {\.pem$} $ccert(FILE) ".crt" crt

	if {$ccert(ENC)} {
		if {[string length $ccert(PASS)] < 4} {
			catch {destroy .c}
			mesg "Passphrase must be at least 4 characters long."
			bell
			return
		}
	}
	if {[string length $ccert(CO)] != 2} {
		catch {destroy .c}
		mesg "Country Name must be at exactly 2 characters long."
		bell
		return
	}
	if {[string length $ccert(CN)] > 64} {
		catch {destroy .c}
		mesg "Common Name must be less than 65 characters long."
		bell
		return
	}
	if {[string length $ccert(EM)] > 64} {
		catch {destroy .c}
		mesg "Email Address must be less than 65 characters long."
		bell
		return
	}
		
	foreach t {EM CN OUN ON LOC ST CO} {

		set val $ccert($t)
		if {$val == ""} {
			set val "none"
		}
		regsub "%$t" $cfg "$val" cfg
	}

	global is_windows

	if {$is_windows} {
		# VF
		set tmp "cert.cfg"
	} else {
		set tmp "/tmp/cert.cfg."
		append tmp [clock clicks -milliseconds]
		catch {file delete $tmp}
		if {[file exists $tmp]} {
			catch {destroy .c}
			mesg "file still exists: $tmp"
			bell
			return
		}
		catch {set fh [open $tmp "w"]}
		catch {exec chmod 600 $tmp}
		if {! [file exists $tmp]} {
			catch {destroy .c}
			mesg "cannot create: $tmp"
			bell
			return
		}
	}
	set fh ""
	catch {set fh [open $tmp "w"]}
	if {$fh == ""} {
		catch {destroy .c}
		mesg "cannot create: $tmp"
		bell
		catch {file delete $tmp}
		return
	}

	puts $fh $cfg
	close $fh

	set ossl [get_openssl]

	set cmd "$ossl req -config $tmp -nodes -new -newkey rsa:2048 -x509 -batch"
	if {$ccert(DAYS) != ""} {
		set cmd "$cmd -days $ccert(DAYS)"
	}
	if {$is_windows} {
		set cmd "$cmd -keyout {$pem} -out {$crt}"
	} else {
		set cmd "$cmd -keyout \"$pem\" -out \"$crt\""
	}

	if {$is_windows} {
		set emess ""
		if {$is_win9x} {
			catch {file delete $pem}
			catch {file delete $crt}
			update
			eval exec $cmd &
			catch {raise .}
			set sl 0
			set max 100
			#if {$ccert(ENC)} {
			#	set max 100
			#}
			set maxms [expr $max * 1000]
			while {$sl < $maxms} {
				set s2 [expr $sl / 1000]
				mesg "running openssl ... $s2/$max"
				if {[file exists $pem] && [file exists $crt]} {
					after 2000
					break
				}
				after 500
				set sl [expr $sl + 500]
			}
			mesg ""
		} else {
			update
			set rc [catch {eval exec $cmd} emess]
			if {$rc != 0 && [regexp -nocase {error:} $emess]} {
				raise .
				tk_messageBox -type ok -icon error -message $emess -title "OpenSSL req command failed"
				return
			}
		}
	} else {
		set geometry [xterm_center_geometry]
		update
		unix_terminal_cmd $geometry "Running OpenSSL" "$cmd"
		catch {file attributes $pem -permissions go-rw}
		catch {file attributes $crt -permissions go-w}
	}
	catch {file delete $tmp}

	set bad ""
	if {! [file exists $pem]} {
		set bad "$pem "
	}
	if {! [file exists $crt]} {
		set bad "$crt"
	}
	if {$bad != ""} {
		raise .
		tk_messageBox -type ok -icon error -message "Not created: $bad" -title "OpenSSL could not create cert"
		catch {raise .c}
		return
	}

	if {$ccert(ENC) && $ccert(PASS) != ""} {
		set cmd "$ossl rsa -in \"$pem\" -des3 -out \"$pem\" -passout stdin"
		set ph ""
		set emess ""
		update
		set rc [catch {set ph [open "| $cmd" "w"]} emess]
		if {$rc != 0 || $ph == ""} {
			raise .
			tk_messageBox -type ok -icon error -message $emess -title "Count not encrypt private key"
			catch {file delete $pem}
			catch {file delete $crt}
			return
		}
		puts $ph $ccert(PASS)
		set emess ""
		set rc [catch {close $ph} emess]
		#puts $emess
		#puts $rc
	}

	set in  [open $crt "r"]
	set out [open $pem "a"]
	while {[gets $in line] > -1} {
		puts $out $line
	}
	close $in
	close $out

	catch {raise .c}
	set p .
	if [winfo exists .c] {
		set p .c
	}
	
	set reply [tk_messageBox -parent $p -type yesno -title "View Cert" -message "View Certificate and Info?"]
	catch {raise .c}
	if {$reply == "yes"} {
		set w .view_cert
		toplev $w
		scroll_text $w.f
		set cert ""
		set fh ""
		catch {set fh [open $crt "r"]}
		if {$fh != ""} {
			while {[gets $fh line] > -1} {
				append cert "$line\n"
			}
			catch {close $fh}
		}

		global yegg
		set yegg ""
		button $w.b -text Dismiss -command "destroy $w; set yegg 1"
		pack $w.b -side bottom -fill x
		bind $w <Escape> "destroy $w; set yegg 1"
		
		$w.f.t insert end "\n"
		$w.f.t insert end "$crt:\n"
		$w.f.t insert end "\n"
		$w.f.t insert end $cert
		$w.f.t insert end "\n"

		set info [get_x509_info $crt]
		$w.f.t insert end $info

		pack $w.f -side top -fill both -expand 1
		center_win $w
		catch {raise $w}
		vwait yegg
		catch {raise .c}
	}

	set p .
	if [winfo exists .c] {
		set p .c
	}
	set reply [tk_messageBox -parent $p -type yesno -title "View Private Key" -message "View Private Key?"]
	catch {raise .c}
	if {$reply == "yes"} {
		set w .view_key
		toplev $w
		scroll_text $w.f
		set key ""
		set fh [open $pem "r"]
		while {[gets $fh line] > -1} {
			append key "$line\n"
		}
		close $fh

		global yegg
		set yegg ""
		button $w.b -text Dismiss -command "destroy $w; set yegg 1"
		pack $w.b -side bottom -fill x
		bind $w <Escape> "destroy $w; set yegg 1"
		
		$w.f.t insert end "\n"
		$w.f.t insert end "$pem:\n"
		$w.f.t insert end "\n"
		$w.f.t insert end $key
		$w.f.t insert end "\n"

		pack $w.f -side top -fill both -expand 1
		center_win $w
		catch {raise $w}
		vwait yegg
		catch {raise .c}
	}
}
	
proc create_cert {} {

	toplev .ccrt
	wm title .ccrt "Create SSL Certificate"

	global uname
	if {$uname == "Darwin"} {
		scroll_text .ccrt.f 80 20
	} else {
		scroll_text .ccrt.f 80 30
	}

	set msg {
    This dialog helps you to create a simple self-signed SSL certificate.  

    On Unix the openssl(1) program must be installed and in $PATH.
    On Windows, a copy of the openssl program is provided for convenience.

    The resulting certificate files can be used for either:

       1) authenticating yourself (VNC Viewer) to a VNC Server
    or 2) your verifying the identity of a remote VNC Server.

    In either case you will need to safely copy one of the generated
    certificate files to the remote VNC Server and have the VNC Server use
    it.  Or you could send it to the system administrator of the VNC Server.

    For the purpose of description, assume that the filename selected in the
    "Save to file" entry is "vnccert.pem".  That file will be generated
    by this process and so will the "vnccert.crt" file.  "vnccert.pem"
    contains both the Private Key and the Public Certificate.  "vnccert.crt"
    only contains the Public Certificate.

    For case 1) you would copy "vnccert.crt" to the VNC Server side and 
    instruct the server to use it.  For x11vnc it would be for example:

        x11vnc -sslverify /path/to/vnccert.crt -ssl SAVE ...

    (it is also possible to handle many client certs at once in a directory,
    see the -sslverify documentation).  Then you would use "vnccert.pem"
    as the MyCert entry in the SSL Certificates dialog.

    For case 2) you would copy "vnccert.pem" to the VNC Server side and 
    instruct the server to use it.  For x11vnc it would be for example:

        x11vnc -ssl /path/to/vnccert.pem

    Then you would use "vnccert.crt" as the as the ServerCert entry in the
    "SSL Certificates" dialog.


    Creating the Certificate:
    
    Choose a output filename (ending in .pem) in the "Save to file" entry.

    Then fill in the identification information (Country, State or Province,
    etc).

    The click on "Create" to generate the certificate files.

    Encrypting the Private Key:  It is a very good idea to encrypt the
    Private Key that goes in the "vnccert.pem".  The downside is that
    whenever that key is used (e.g. starting up x11vnc using it) then
    the passphrase will need to be created.  If you do not encrypt it and
    somebody steals a copy of the "vnccert.pem" file then they can pretend
    to be you.

    After you have created the certificate files, you must copy and import
    either "vnccert.pem" or "vnccert.pem" to the remote VNC Server and
    also select the other file in the "SSL Certificates" dialog.
    See the description above.

    For more information see:

           http://www.karlrunge.com/x11vnc/ssl.html
           http://www.karlrunge.com/x11vnc/#faq-ssl-tunnel-int

    The first one describes how to use x11vnc to create Certificate
    Authority (CA) certificates in addition to self-signed ones.


    Tip: if you choose the "Common Name" to be the internet hostname
    (e.g. gateway.mydomain.com) that connections will be made to or
    from that will avoid many dialogs when connecting mentioning that
    the hostname does not match the Common Name.
}
	.ccrt.f.t insert end $msg

	global ccert ccert_init tcert


	if {! [info exists ccert_init]} {
		set ccert_init 1
		set ccert(CO) "US"
		set ccert(ST) "Massachusetts"
		set ccert(LOC) "Boston"
		set ccert(ON) "My Company"
		set ccert(OUN) "Product Development"
		set ccert(CN) "www.nowhere.none"
		set ccert(EM) "admin@nowhere.none"
		set ccert(DAYS) "365"
		set ccert(FILE) ""
	}

	set ccert(ENC) 0
	set ccert(PASS) ""
		
	set tcert(CO) "Country Name (2 letter code):"
	set tcert(ST) "State or Province Name (full name):"
	set tcert(LOC) "Locality Name (eg, city):"
	set tcert(ON) "Organization Name (eg, company):"
	set tcert(OUN) "Organizational Unit Name (eg, section):"
	set tcert(CN) "Common Name (eg, YOUR name):"
	set tcert(EM) "Email Address:"
	set tcert(DAYS) "Days until expiration:"

	if {$ccert(FILE) == ""} {
		set idir [get_idir_certs ""]
		set ccert(FILE) "$idir/vnccert.pem"
	}

	button .ccrt.cancel -text "Cancel" -command {destroy .ccrt; catch {raise .c}}
	bind .ccrt <Escape> {destroy .ccrt; catch {raise .c}}

	button .ccrt.create -text "Generate Cert" -command {destroy .ccrt; catch {raise .c}; do_oss_create}

	pack .ccrt.cancel .ccrt.create -side bottom -fill x

	set ew 40

	set w .ccrt.pf
	frame $w
	checkbutton $w.check -anchor w -variable ccert(ENC) -text \
		"Encrypt Key with Passphrase" -command {check_pp}

	entry $w.e -width $ew -textvariable ccert(PASS) -state disabled \
		-show *

	pack $w.e -side right
	pack $w.check -side left -expand 1 -fill x
	pack $w -side bottom -fill x

	set w .ccrt.fl
	frame $w
	label $w.l -anchor w -text "Save to file:"

	entry $w.e -width $ew -textvariable ccert(FILE)
	button $w.b -text "Browse..." -command {set_createcert_file; catch {raise .ccrt}}

	pack $w.e -side right
	pack $w.b -side right
	pack $w.l -side left -expand 1 -fill x
	pack $w -side bottom -fill x

	set i 0
	foreach t {DAYS EM CN OUN ON LOC ST CO} {
		set w .ccrt.f$i
		frame $w
		label $w.l -anchor w -text "$tcert($t)"
		entry $w.e -width $ew -textvariable ccert($t)
		pack $w.e  -side right
		pack $w.l  -side left -expand 1 -fill x
		pack $w -side bottom -fill x
		incr i
	}

	pack .ccrt.f -side top -fill both -expand 1

	center_win .ccrt
}

proc import_check_mode {w} {
	global import_mode
	if {$import_mode == "paste"} {
		$w.mf.b configure -state disabled
		$w.mf.e configure -state disabled
		$w.plab configure -state normal
		$w.paste.t configure -state normal
	} else {
		$w.mf.b configure -state normal
		$w.mf.e configure -state normal
		$w.plab configure -state disabled
		$w.paste.t configure -state disabled
	}
}
	
proc import_browse {} {
	global import_file

	set idir ""
	if {$import_file != ""} {
		set idir [get_idir_certs $import_file]
	}
	if {$idir != ""} {
		set t [tk_getOpenFile -parent .icrt -initialdir $idir]
	} else {
		set t [tk_getOpenFile -parent .icrt]
	}
	if {$t != ""} {
		set import_file $t
	}
	catch {raise .icrt}
	update
}

proc import_save_browse {{par ".icrt"}} {
	global import_save_file

	set idir ""
	if {$import_save_file != ""} {
		set idir [get_idir_certs $import_save_file]
	}
	if {$idir == ""} {
		set idir [get_idir_certs ""]
	}
	if {$idir != ""} {
		set t [tk_getSaveFile -parent $par -defaultextension ".crt" -initialdir $idir]
	} else {
		set t [tk_getSaveFile -parent $par -defaultextension ".crt"]
	}
	if {$t != ""} {
		set import_save_file $t
	}
	catch {raise $par}
	update
}

proc do_save {} {
	global import_mode import_file import_save_file
	
	if {$import_save_file == ""} {
		tk_messageBox -parent .icrt -type ok -icon error \
			-message "No Save File supplied" -title "Save File"
		return
	}

	set str ""
	if {$import_mode == "save_cert_text"} {
		global save_cert_text
		set str $save_cert_text
	} elseif {$import_mode == "paste"} {
		set str [.icrt.paste.t get 1.0 end]
	} else {
		if {! [file exists $import_file]} {
			tk_messageBox -parent .icrt -type ok -icon error \
				-message "Input file \"$import_file\" does not exist." -title "Import File"
			return
		}
		set fh ""
		set emess ""
		set rc [catch {set fh [open $import_file "r"]} emess]
		if {$rc != 0 || $fh == ""} {
			tk_messageBox -parent .icrt -type ok -icon error \
				-message $emess -title "Import File: $import_file"
			return
		}
		while {[gets $fh line] > -1} {
			append str "$line\n"
		}
		close $fh
	}

	if {! [regexp {BEGIN CERTIFICATE} $str]} {
		tk_messageBox -parent .icrt -type ok -icon error \
			-message "Import Text does not contain \"BEGIN CERTIFICATE\"" -title "Imported Text"
		return
	}
	if {! [regexp {END CERTIFICATE} $str]} {
		tk_messageBox -parent .icrt -type ok -icon error \
			-message "Import Text does not contain \"END CERTIFICATE\"" -title "Imported Text"
		return
	}

	set fh ""
	set emess ""
	set rc [catch {set fh [open $import_save_file "w"]} emess]
	if {$rc != 0 || $fh == ""} {
		tk_messageBox -parent .icrt -type ok -icon error \
			-message $emess -title "Save File: $import_save_file"
		return
	}
	global is_windows
	if {! $is_windows} {
		catch {file attributes $import_save_file -permissions go-w}
		if {[regexp {PRIVATE} $str] || [regexp {\.pem$} $import_save_file]} {
			catch {file attributes $import_save_file -permissions go-rw}
		}
	}
	puts -nonewline $fh $str
	close $fh
	catch {destroy .icrt}
	set p .c
	if {![winfo exists .c]} {
		getcerts
		update	
	}
	if {![winfo exists .c]} {
		set p .
	}
	catch {raise .c}
	catch {destroy .scrt}
	tk_messageBox -parent $p -type ok -icon info \
		-message "Saved to file: $import_save_file" -title "Save File: $import_save_file"
}

proc import_cert {} {

	toplev .icrt
	wm title .icrt "Import SSL Certificate"

	global scroll_text_focus
	set scroll_text_focus 0
	global uname
	if {$uname == "Darwin"} {
		scroll_text .icrt.f 90 16
	} else {
		scroll_text .icrt.f 90 20
	}
	set scroll_text_focus 1

	set msg {
    This dialog lets you import a SSL Certificate by either pasting one in or by
    loading from another file.  Choose which input mode you want to use by the toggle
    "Paste / Read from File".

    There are two types of files we use 1) Certificate only, and 2) Private Key
    and Certificate.

    Type 1) would be used to verify the identity of a remote VNC Server, whereas
    type 2) would be used to authenticate ourselves to the remote VNC Server.

    A type 1) by convention ends with file suffix ".crt" and looks like:

-----BEGIN CERTIFICATE-----
MIID2jCCAsKgAwIBAgIJALKypfV8BItCMA0GCSqGSIb3DQEBBAUAMIGgMQswCQYD
(more lines) ...
TCQ+tbQ/DOiTXGKx1nlcKoPdkG+QVQVJthlQcpam
-----END CERTIFICATE-----

    A type 2) by convention ends with file suffix ".pem" and looks like:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA4sApd7WaPKQRWnFe9T04D4pglQB0Ti0/dCVHxg8WEVQ8OdcW
(more lines) ...
9kBmNotUiTpvRM+e7E/zRemhvY9qraFooqMWzi9JrgYfeLfSvvFfGw==
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIID2jCCAsKgAwIBAgIJALKypfV8BItCMA0GCSqGSIb3DQEBBAUAMIGgMQswCQYD
(more lines) ...
TCQ+tbQ/DOiTXGKx1nlcKoPdkG+QVQVJthlQcpam
-----END CERTIFICATE-----

    You do not need to use the ".crt" or ".pem" convention if you do not want to.

    First, either paste in the text or set the "Read from File" filename.

    Next, set the "Save to File" name to the file where the imported certificate
    will be saved.

    Then, click on "Save" to save the imported Certificate.

    After you have imported the Certificate (or Key + Certificate), select it to
    use for a connection via the "MyCert" or "ServerCert" dialog.
}
	.icrt.f.t insert end $msg

	global icert import_mode

	set import_mode "paste"

	set w .icrt.mf
	frame $w

	radiobutton $w.p -pady 1 -anchor w -variable import_mode -value paste \
		-text "Paste" -command "import_check_mode .icrt"

	radiobutton $w.f -pady 1 -anchor w -variable import_mode -value file \
		-text "Read from File:" -command "import_check_mode .icrt"

	global import_file
	set import_file ""
	entry $w.e -width 40 -textvariable import_file

	button $w.b -pady 1 -anchor w -text "Browse..." -command import_browse
	pack $w.b -side right
	pack $w.p $w.f -side left
	pack $w.e -side left -expand 1 -fill x

	$w.b configure -state disabled
	$w.e configure -state disabled

	label .icrt.plab -anchor w -text "Paste Certificate here:" 
	if {$uname == "Darwin"} {
		scroll_text .icrt.paste 90 11
	} else {
		scroll_text .icrt.paste 90 22
	}

	button .icrt.cancel -text "Cancel" -command {destroy .icrt; catch {raise .c}}
	bind .icrt <Escape> {destroy .icrt; catch {raise .c}}

	button .icrt.save -text "Save" -command {do_save}

	set w .icrt.sf
	frame $w

	label $w.l -text "Save to File:" -anchor w
	global import_save_file
	set import_save_file ""
	entry $w.e -width 40 -textvariable import_save_file
	button $w.b -pady 1 -anchor w -text "Browse..." -command import_save_browse

	pack $w.b -side right
	pack $w.l -side left
	pack $w.e -side left -expand 1 -fill x

	pack .icrt.cancel .icrt.save .icrt.sf .icrt.mf -side bottom -fill x
	pack .icrt.paste .icrt.plab -side bottom -fill x

	pack .icrt.f -side top -fill both -expand 1

	.icrt.paste.t insert end ""

	focus .icrt.paste.t

	center_win .icrt
}

proc save_cert {hp} {

	toplev .scrt
	wm title .scrt "Import SSL Certificate"

	global scroll_text_focus
	set scroll_text_focus 0
	global uname
	scroll_text .scrt.f 90 17
	set scroll_text_focus 1

	set msg {
    This dialog lets you import a SSL Certificate retrieved from a VNC server.

    Be sure to have verified its authenticity via an external means (checking
    the MD5 hash value, etc)

    Set the "Save to File" name to the file where the imported certificate
    will be saved.

    Then, click on "Save" to save the imported Certificate.

    After you have imported the Certificate it will be automatically selected 
    as the "ServerCert" for this host: %HOST

    To make the ServerCert setting to the imported cert file PERMANENT, 
    select Options -> Save Profile to save it in a profile.
}

	regsub {%HOST} $msg "$hp" msg
	.scrt.f.t insert end $msg

	set w .scrt.mf
	frame $w

	global import_file
	set import_file ""
	entry $w.e -width 40 -textvariable import_file

	scroll_text .scrt.paste 90 26

	button .scrt.cancel -text "Cancel" -command {destroy .scrt; catch {raise .c}}
	bind .scrt <Escape> {destroy .scrt; catch {raise .c}}

	global import_save_file
	button .scrt.save -text "Save" -command {do_save; set svcert $import_save_file}

	set w .scrt.sf
	frame $w

	label $w.l -text "Save to File:" -anchor w
	set import_save_file "server:$hp.crt"
	global is_windows
	if {$is_windows} {
		regsub -all {:} $import_save_file "_" import_save_file
	}
	set import_save_file [get_idir_certs ""]/$import_save_file
	entry $w.e -width 40 -textvariable import_save_file
	button $w.b -pady 1 -anchor w -text "Browse..." -command {import_save_browse .scrt}

	pack $w.b -side right
	pack $w.l -side left
	pack $w.e -side left -expand 1 -fill x

	pack .scrt.cancel .scrt.save .scrt.sf .scrt.mf -side bottom -fill x
	pack .scrt.paste -side bottom -fill x

	pack .scrt.f -side top -fill both -expand 1

	global cert_text
	set text "" 
	set on 0
	foreach line [split $cert_text "\n"] {
		if [regexp -- {-----BEGIN CERTIFICATE-----} $line] {
			set on 1
		}
		if {! $on} {
			continue;
		}
		append text "$line\n"
		if [regexp -- {-----END CERTIFICATE-----} $line] {
			set on 0
		}
	}
	global save_cert_text
	set save_cert_text $text
	.scrt.paste.t insert end "$text"
	global import_mode
	set import_mode "save_cert_text"

	focus .scrt.paste.t

	center_win .scrt
}


proc getcerts {} {
	global mycert svcert crtdir
	global use_ssh use_sshssl
	toplev .c
	wm title .c "SSL Certificates"
	frame .c.mycert
	frame .c.svcert
	frame .c.crtdir
	label .c.mycert.l -anchor w -width 12 -text "MyCert:"
	label .c.svcert.l -anchor w -width 12 -text "ServerCert:"
	label .c.crtdir.l -anchor w -width 12 -text "CertsDir:"
	
	entry .c.mycert.e -width 32 -textvariable mycert -vcmd v_mycert
	entry .c.svcert.e -width 32 -textvariable svcert -vcmd v_svcert
	bind .c.mycert.e <Enter> {.c.mycert.e validate}
	bind .c.mycert.e <Leave> {.c.mycert.e validate}
	bind .c.svcert.e <Enter> {.c.svcert.e validate}
	bind .c.svcert.e <Leave> {.c.svcert.e validate}
	entry .c.crtdir.e -width 32 -textvariable crtdir
	button .c.mycert.b -text "Browse..." -command {set_mycert .c; catch {raise .c}}
	button .c.svcert.b -text "Browse..." -command {set_svcert .c; catch {raise .c}}
	button .c.crtdir.b -text "Browse..." -command {set_crtdir .c; catch {raise .c}}
	button .c.mycert.i -text "Info" -command {show_mycert}
	button .c.svcert.i -text "Info" -command {show_svcert}
	button .c.crtdir.i -text "Info" -command {}
	bind .c.mycert.b <Enter> "v_mycert"
	bind .c.svcert.b <Enter> "v_svcert"
	.c.mycert.i configure -state disabled
	.c.svcert.i configure -state disabled
	.c.crtdir.i configure -state disabled
	bind .c.mycert.b <B3-ButtonRelease>   "show_mycert"
	bind .c.svcert.b <B3-ButtonRelease>   "show_svcert"

	button .c.create -text "Create Certificate ..." -command {create_cert}
	button .c.import -text "Import Certificate ..." -command {import_cert}

	frame .c.b
	button .c.b.done -text "Done" -command {catch {destroy .c}}
	bind .c <Escape> {destroy .c}
	button .c.b.help -text "Help" -command help_certs
	pack .c.b.help .c.b.done -fill x -expand 1 -side left

	foreach w [list mycert svcert crtdir] {
		pack .c.$w.l -side left
		pack .c.$w.e -side left -expand 1 -fill x
		pack .c.$w.b -side left
		pack .c.$w.i -side left
		bind .c.$w.e <Return> ".c.$w.b invoke"
		if {$use_ssh} {
			.c.$w.l configure -state disabled	
			.c.$w.e configure -state disabled	
			.c.$w.b configure -state disabled	
		}	
	}

	if {$mycert != ""} {
		v_mycert
	}
	if {$svcert != ""} {
		v_svcert
	}

	pack .c.mycert .c.svcert .c.crtdir .c.create .c.import .c.b -side top -fill x
	center_win .c
	wm resizable .c 1 0

	focus .c
}

proc get_profiles_dir {} {
	global env is_windows
	
	set dir ""
	if {$is_windows} {
		if [info exists env(HOME)] {
			set t "$env(HOME)/ss_vnc"
			regsub -all {\\} $t "/" t
			regsub -all {//*} $t "/" t
			if {! [file isdirectory $t]} {
				catch {file mkdir $t}
			}
			if [file isdirectory $t] {
				set dir $t
				set s "$t/profiles"
				if {! [file exists $s]} {
					catch {file mkdir $s}
				}
			}
		}
		if {$dir == ""} {
			set t [file dirname [pwd]]
			set t "$t/profiles"
			if [file isdirectory $t] {
				set dir $t
			}
		}
	} elseif [info exists env(HOME)] {
		set t "$env(HOME)/.vnc"
		if [file isdirectory $t] {
			set dir $t
			set s "$t/profiles"
			if {! [file exists $s]} {
				catch {file mkdir $s}
			}
		}
	}
	
	if {$dir != ""} {
		
	} elseif [info exists env(SSVNC_BASEDIR)] {
		set dir $env(SSVNC_BASEDIR)
	} else {
		set dir [pwd]
	}
	if [file isdirectory "$dir/profiles"] {
		set dir "$dir/profiles"
	}
	return $dir
}

proc globalize {} {
	global defs
	foreach var [array names defs] {
		uplevel global $var
	}
}
	
proc load_include {include dir} {
	global include_vars defs

	if [info exists include_vars] {
		unset include_vars
	}
	
	foreach inc [split $include ", "] {
		set f [string trim $inc]
#puts "f=$f";
		if {$f == ""} {
			continue
		}
		set try ""
		if {[regexp {/} $f] || [regexp {\\} $f]} {
			set try $f;
		} else {
			set try "$dir/$f"
		}
		if {! [file exists $try]} {
			set try "$dir/$f.vnc"
		}
#puts "try: $try"
		if [file exists $try] {
			set fh ""
			catch {set fh [open $try "r"]}
			if {$fh == ""} {
				continue
			}
			while {[gets $fh line] > -1} {
				append inc_str "$line\n"
				if [regexp {^([^=]*)=(.*)$} $line m var val] {
					if {! [info exists defs($var)]} {
						continue
					}
					if {$var == "include_list"} {
						continue
					}
					set pct 0
					if {$var == "smb_mount_list"} {
						set pct 1
					}
					if {$var == "port_knocking_list"} {
						set pct 1
					}
					if {$pct} {
						regsub -all {%%%} $val "\n" val
					}
					if {$val != $defs($var)} {
#puts "include_vars $var $val"
						set include_vars($var) $val
					}
				}
			}
			catch {close $fh}
		}
	}
}

proc load_profile {{parent "."}} {
	global profdone
	global vncdisplay

	globalize

	set dir [get_profiles_dir]

	set file [tk_getOpenFile -parent $parent -defaultextension ".vnc" \
		-initialdir $dir -title "Load VNC Profile"]
	if {$file == ""} {
		set profdone 1
		return
	}
	set fh [open $file "r"]
	if {! [info exists fh]} {
		set profdone 1
		return
	}
	set str ""
	set include ""
	while {[gets $fh line] > -1} {
		append str "$line\n"
		if [regexp {^include_list=(.*)$} $line m val] {
			set include $val
		}
	}
	close $fh

	if {$include != ""} {
		load_include $include $dir
	}

	set_defaults

	global include_vars
	if [info exists include_vars] {
		foreach var [array names include_vars] {
			set $var $include_vars($var)
		}
	}

	global use_ssl use_ssh use_sshssl
	set use_ssl 0
	set use_ssh 0
	set use_sshssl 0

	global defs
	foreach line [split $str "\n"] {
		set line [string trim $line]
		if [regexp {^#} $line] {
			continue
		}
		if [regexp {^([^=]*)=(.*)$} $line m var val] {
			if {$var == "disp"} {
				set vncdisplay $val
				continue
			}
			if [info exists defs($var)] {
				set pct 0
				if {$var == "smb_mount_list"} {
					set pct 1
				}
				if {$var == "port_knocking_list"} {
					set pct 1
				}
				if {$pct} {
					regsub -all {%%%} $val "\n" val
				}
				set $var $val
			}
		}
	}

	init_vncdisplay
	if {! $use_ssl && ! $use_ssh && ! $use_sshssl} {
		set use_ssl 1
	}
	if {$use_ssl} {
		set use_ssh 0
		set use_sshssl 0
	} elseif {$use_ssh && $use_sshssl} {
		set use_ssh 0
	}
	if {$use_ssl} {
		ssl_ssh_adjust ssl
	} elseif {$use_ssh} {
		ssl_ssh_adjust ssh
	} elseif {$use_sshssl} {
		ssl_ssh_adjust sshssl
	}

	set compresslevel_text "Compress Level: $use_compresslevel"
	set quality_text "Quality: $use_quality"

	set profdone 1
	putty_pw_entry check
}

proc save_profile {{parent "."}} {
	global is_windows uname
	global profdone
	global include_vars defs

	globalize
	
	set dir [get_profiles_dir]

	set vncdisp [get_vncdisplay]

	set disp [string trim $vncdisp]
	if {$disp != ""} {
		regsub {[ 	].*$} $disp "" disp
		regsub -all {/} $disp "" disp
	}
	if {$is_windows || $uname == "Darwin"} {
		regsub -all {:} $disp "_" disp
	}

	set file [tk_getSaveFile -parent $parent -defaultextension ".vnc" \
		-initialdir $dir -initialfile "$disp" -title "Save VNC Profile"]
	if {$file == ""} {
		set profdone 1
		return
	}
	set fh [open $file "w"]
	if {! [info exists fh]} {
		set profdone 1
		return
	}
	set h [string trim $vncdisp]
	set p $h
	regsub {:.*$} $h "" h
	set host $h
	regsub {[ 	].*$} $p "" p
	regsub {^.*:} $p "" p
	regsub { .*$} $p "" p
	if {$p == ""} {
		set p 0
	}
	if {$p < 200} {
		set port [expr $p + 5900]
	} else {
		set port $p
	}

	set h [string trim $vncdisp]
	regsub {cmd=.*$} $h "" h
	set h [string trim $h]
	if {! [regexp {[ 	]} $h]} {
		set h ""
	} else {
		regsub {^.*[ 	]} $h "" h
	}
	if {$h == ""} {
		set proxy ""
		set proxyport ""
	} else {
		set p $h
		regsub {:.*$} $h "" h
		set proxy $h
		regsub {[ 	].*$} $p "" p
		regsub {^.*:} $p "" p
		if {$p == ""} {
			set proxyport 0
		} else {
			set proxyport $p
		}
	}
	
	puts $fh "\[connection\]"
	puts $fh "host=$host"
	puts $fh "port=$port"
	puts $fh "proxyhost=$proxy"
	puts $fh "proxyport=$proxyport"
	puts $fh "disp=$vncdisp"
	puts $fh "\n\[options\]"

	if {$include_list != ""} {
		load_include $include_list [get_profiles_dir]
	}

	foreach var [lsort [array names defs]] {
		eval set val \$$var
		set pre ""
		if {$val == $defs($var)} {
			set pre "#"
		}
		set pct 0
		if {$var == "smb_mount_list"} {
			set pct 1
		}
		if {$var == "port_knocking_list"} {
			set pct 1
		}
		if {$include_list != "" && [info exists include_vars($var)]} {
			if {$val == $include_vars($var)} {
				if {$pct} {
					regsub -all "\n" $val "%%%" val
				}
				puts $fh "#from include: $var=$val"
				continue
			}
		}
		if {$pct} {
			regsub -all "\n" $val "%%%" val
		}
		puts $fh "$pre$var=$val"
	}

	close $fh
	set profdone 1
}

proc set_ssh {} {
	global use_ssl
	if {$use_ssl} {
		ssl_ssh_adjust ssh
	}
}

proc expand_IP {redir} {
	if {! [regexp {:IP:} $redir]} {
		return $redir
	}
	if {! [regexp {(-R).*:IP:} $redir]} {
		return $redir
	}

	set ip [guess_ip]
	set ip [string trim $ip]
	if {$ip == ""} {
		return $redir
	}

	regsub -all {:IP:} $redir ":$ip:" redir
	return $redir
}

proc get_cups_redir {} {
	global cups_local_server cups_remote_port
	global cups_local_smb_server cups_remote_smb_port
	set redir "$cups_remote_port:$cups_local_server"
	regsub -all {['" 	]} $redir {} redir; #"
	set redir " -R $redir"
	if {$cups_local_smb_server != "" && $cups_remote_smb_port != ""} {
		set redir2 "$cups_remote_smb_port:$cups_local_smb_server"
		regsub -all {['" 	]} $redir2 {} redir2; #"
		set redir "$redir -R $redir2"
	}
	set redir [expand_IP $redir]
	return $redir
}

proc get_additional_redir {} {
	global additional_port_redirs additional_port_redirs_list
	if {! $additional_port_redirs || $additional_port_redirs_list == ""} {
		return ""
	}
	set redir [string trim $additional_port_redirs_list]
	regsub -all {['"]} $redir {} redir; #"
	set redir " $redir"
	set redir [expand_IP $redir]
	return $redir
}

proc get_sound_redir {} {
	global sound_daemon_remote_port sound_daemon_local_port
	set loc $sound_daemon_local_port
	if {! [regexp {:} $loc]} {
		set loc "localhost:$loc"
	}
	set redir "$sound_daemon_remote_port:$loc"
	regsub -all {['" 	]} $redir {} redir; #"
	set redir " -R $redir"
	set redir [expand_IP $redir]
	return $redir
}

proc get_smb_redir {} {
	global smb_mount_list

	set s [string trim $smb_mount_list]
	if {$s == ""} {
		return ""
	}

	set did(0) 1
	set redir ""
	set mntlist ""

	foreach line [split $s "\r\n"] {
		set str [string trim $line] 
		if {$str == ""} {
			continue
		}
		if {[regexp {^#} $str]} {
			continue
		}

		set port ""
		if [regexp {^([0-9][0-9]*)[ \t][ \t]*(.*)} $str mvar port rest] {
			# leading port
			set str [string trim $rest]
		}

		# grab:  //share /dest [host[:port]]
		set share ""
		set dest ""
		set hostport ""
		foreach item [split $str] {
			if {$item == ""} {
				continue
			}
			if {$share == ""} {
				set share [string trim $item]
			} elseif {$dest == ""} {
				set dest [string trim $item]
			} elseif {$hostport == ""} {
				set hostport [string trim $item]
			}
		}

		regsub {^~/} $dest {$HOME/} dest

		# work out the local host:port
		set lhost ""
		set lport ""
		if {$hostport != ""} {
			if [regexp {(.*):(.*)} $hostport mvar lhost lport] {
				;
			} else {
				set lhost $hostport
				set lport 139
			}
		} else {
			if [regexp {//([^/][^/]*)/} $share mvar h] {
				if [regexp {(.*):(.*)} $h mvar lhost lport] {
					;
				} else {
					set lhost $h
					set lport 139
				}
			} else {
				set lhost localhost
				set lport 139
			}
		}

		if {$port == ""} {
			if [info exists did("$lhost:$lport")] {
				# reuse previous one:
				set port $did("$lhost:$lport")
			} else {
				# choose one at random:
				for {set i 0} {$i < 3} {incr i} {
					set port [expr 20100 + 9000 * rand()]	
					set port [expr round($port)]
					if { ! [info exists did($port)] } {
						break
					}
				}
			}
			set did($port) 1
		}

		if {$mntlist != ""} {
			append mntlist " "
		}
		append mntlist "$share,$dest,$port"

		if { ! [info exists did("$lhost:$lport")] } {
			append redir " -R $port:$lhost:$lport"
			set did("$lhost:$lport") $port
		}
	}

	regsub -all {['"]} $redir {} redir; #"
	set redir [expand_IP $redir]

	regsub -all {['"]} $mntlist {} mntlist; #"

	set l [list]
	lappend l $redir
	lappend l $mntlist
	return $l
}

proc ugly_setup_scripts {mode tag} {

set cmd(1) {
	SSHD_PID=""
	FLAG=$HOME/.vnc-helper-flag__PID__

	if [ "X$USER" = "X" ]; then
		USER=$LOGNAME
	fi

	DO_CUPS=0
	cups_dir=$HOME/.cups
	cups_cfg=$cups_dir/client.conf
	cups_host=localhost
	cups_port=NNNN

	DO_SMB=0
	DO_SMB_SU=0
	DO_SMB_WAIT=0
	smb_mounts=
	DONE_PORT=NNNN
	smb_script=$HOME/.smb-mounts__PID__.sh

	DO_SOUND=0
	DO_SOUND_KILL=0
	DO_SOUND_RESTART=0
	sound_daemon_remote_prog=
	sound_daemon_remote_args=

	findpid() {
		i=1
		back=10
		touch $FLAG

		if [ "X$TOPPID" = "X" ]; then
			TOPPID=$$
			back=50
		fi

		while [ $i -lt $back ]
		do
			try=`expr $TOPPID - $i`
			if ps $try 2>/dev/null | grep sshd >/dev/null; then
				SSHD_PID="$try"	
				echo SSHD_PID=$try
				echo
				break
			fi
			i=`expr $i + 1`
		done
		echo MY_PID=$$
		tty
		echo
	}

	wait_til_ssh_gone() {
		try_perl=""
		if type perl >/dev/null 2>&1; then
			try_perl=1
		fi
		uname=`uname`
		if [ "X$uname" != "XLinux" -a "X$uname" != "XSunOS" ]; then
			try_perl=""
		fi
		if [ "X$try_perl" = "X1" ]; then
			# try to avoid wasting pids:
			perl -e "while (1) {if(! -e \"/proc/$SSHD_PID\"){exit} if(! -f \"$FLAG\"){exit} sleep 1;}"
		else
			while [ 1 ]
			do
				ps $SSHD_PID > /dev/null 2>&1
				if [ $? != 0 ]; then
					break
				fi
				if [ ! -f $FLAG ]; then
					break
				fi
				sleep 1
			done
		fi
		rm -f $FLAG
		if [ "X$DO_SMB_WAIT" = "X1" ]; then
			rm -f $smb_script
		fi
	}
};

set cmd(2) {
	update_client_conf() {
		mkdir -p $cups_dir
		if [ -f $cups_cfg ]; then
			cp -p $cups_cfg $cups_cfg.back
		else
			touch $cups_cfg.back
		fi
		sed -e "s/^ServerName/#-etv-#ServerName/" $cups_cfg.back > $cups_cfg
		echo "ServerName $cups_host:$cups_port" >> $cups_cfg
		echo
		echo "--------------------------------------------------------------"
		echo "The CUPS $cups_cfg config file has been set to:"
		echo
		cat $cups_cfg
		echo
		echo "If there are problems automatically restoring it, edit or"
		echo "remove the file to go back to local CUPS settings."
		echo
		echo "A backup has been placed in: $cups_cfg.back"
		echo
		echo "See the help description for more details on printing."
		echo
		echo "done."
		echo "--------------------------------------------------------------"
		echo
	}

	reset_client_conf() {
		cp -p $cups_cfg $cups_cfg.tmp
		grep -v "^ServerName" $cups_cfg.tmp | sed -e "s/^#-etv-#ServerName/ServerName/" > $cups_cfg
		rm -f $cups_cfg.tmp
	}

	cupswait() {
		trap "" INT QUIT HUP
		wait_til_ssh_gone
		reset_client_conf
	}
};

#		if [ "X$DONE_PORT" != "X" ]; then
#			if type perl >/dev/null 2>&1; then
#				perl -e "use IO::Socket::INET; \$SIG{INT} = \"IGNORE\"; \$SIG{QUIT} = \"IGNORE\"; \$SIG{HUP} = \"INGORE\"; my \$client = IO::Socket::INET->new(Listen => 5, LocalAddr => \"localhost\", LocalPort => $DONE_PORT, Proto => \"tcp\")->accept(); \$line = <\$client>; close \$client; unlink \"$smb_script\";" </dev/null >/dev/null 2>/dev/null &
#				if [ $? = 0 ]; then
#					have_perl_done="1"
#				fi
#			fi
#		fi

set cmd(3) {
	smbwait() {
		trap "" INT QUIT HUP
		wait_til_ssh_gone
	}
	do_smb_mounts() {
		if [ "X$smb_mounts" = "X" ]; then
			return
		fi
		echo > $smb_script
		have_perl_done=""
		echo "echo" >> $smb_script 
		dests=""
		for mnt in $smb_mounts
		do
			smfs=`echo "$mnt" | awk -F, "{print \\\$1}"`
			dest=`echo "$mnt" | awk -F, "{print \\\$2}"`
			port=`echo "$mnt" | awk -F, "{print \\\$3}"`
			dest=`echo "$dest" | sed -e "s,__USER__,$USER,g" -e "s,__HOME__,$HOME,g"`
			if [ ! -d $dest ]; then
				mkdir -p $dest
			fi
			echo "echo SMBMOUNT:" >> $smb_script
			echo "echo smbmount $smfs $dest -o uid=$USER,ip=127.0.0.1,ttl=20000,port=$port" >> $smb_script
			echo "smbmount \"$smfs\" \"$dest\" -o uid=$USER,ip=127.0.0.1,ttl=20000,port=$port" >> $smb_script
			echo "echo; df \"$dest\"; echo" >> $smb_script
			dests="$dests $dest"
		done
		#}
};

set cmd(4) {
		echo "(" >> $smb_script
		echo "trap \"\" INT QUIT HUP" >> $smb_script

		try_perl=""
		if type perl >/dev/null 2>&1; then
			try_perl=1
		fi
		uname=`uname`
		if [ "X$uname" != "XLinux" -a "X$uname" != "XSunOS" ]; then
			try_perl=""
		fi

		if [ "X$try_perl" = "X" ]; then
			echo "while [ -f $smb_script ]" >> $smb_script
			echo "do" >> $smb_script
			echo "     sleep 1" >> $smb_script
			echo "done" >> $smb_script
		else
			echo "perl -e \"while (-f \\\\\"$smb_script\\\\\") {sleep 1;} exit 0;\"" >> $smb_script
		fi
		for dest in $dests
		do
			echo "echo smbumount $dest" >> $smb_script
			echo "smbumount \"$dest\"" >> $smb_script
		done
		echo ") &" >> $smb_script
		echo "--------------------------------------------------------------"
		if [ "$DO_SMB_SU" = "0" ]; then
			echo "We now run the smbmount script as user $USER"
			echo
			echo sh $smb_script
			sh $smb_script
			rc=0
		elif [ "$DO_SMB_SU" = "1" ]; then
			echo "We now run the smbmount script via su(1)"
			echo
			echo "The first \"Password:\" will be for that of root to run the smbmount script."
			echo
			echo "Subsequent \"Password:\" will be for the SMB share(s) (hit Return if no passwd)"
			echo
			echo SU:
			echo "su root -c \"sh $smb_script\""
			su root -c "sh $smb_script"
			rc=$?
		elif [ "$DO_SMB_SU" = "2" ]; then
			echo "We now run the smbmount script via sudo(8)"
			echo
			echo "The first \"Password:\" will be for that of the sudo(8) password."
			echo
			echo "Subsequent \"Password:\" will be for the SMB shares (hit enter if no passwd)"
			echo
			echo SUDO:
			echo sudo sh $smb_script
			sudo sh $smb_script
			rc=$?
		fi
};

set cmd(5) {
		#{
		echo
		if [ "$rc" = 0 ]; then
			if [ "X$have_perl_done" = "X1" -o 1 = 1 ] ; then
				echo
				echo "Your SMB shares will be unmounted when the VNC connection closes,"
				echo "*As Long As* No Applications have any of the share files opened or are"
				echo "cd-ed into any of the share directories."
				echo
				echo "Try to make sure nothing is accessing the SMB shares before disconnecting"
				echo "the VNC session.  If you fail to do that follow these instructions:"
			fi
			echo
			echo "To unmount your SMB shares make sure no applications are still using any of"
			echo "the files and no shells are still cd-ed into the share area, then type:"
			echo 
			echo "   rm -f $smb_script"
			echo 
			echo "In the worst case run: smbumount /path/to/mount/point for each mount as root"
			echo "Even with the remote redirection gone the kernel should umount after a timeout."
		else
			echo 
			if [ "$DO_SMB_SU" = "1" ]; then
				echo "su(1) to run smbmount(8) failed."
			elif [ "$DO_SMB_SU" = "2" ]; then
				echo "sudo(8) to run smbmount(8) failed."
			fi
			rm -f $smb_script
		fi
		echo
		echo "done."
		echo "--------------------------------------------------------------"
		echo
	}
};

set cmd(6) {

	setup_sound() {
		dpid=""
		d=$sound_daemon_remote_prog
		if type pgrep >/dev/null 2>/dev/null; then
			dpid=`pgrep -U $USER -x $d | head -1`
		else
			dpid=`env PATH=/usr/ucb:$PATH ps wwwwaux | grep -w $USER | grep -w $d | grep -v grep | head -1`
		fi
		echo "--------------------------------------------------------------"
		echo "Setting up Sound: pid=$dpid"
		if [ "X$dpid" != "X" ]; then
			dcmd=`env PATH=/usr/ucb:$PATH ps wwwwaux | grep -w $USER | grep -w $d | grep -w $dpid | grep -v grep | head -1 | sed -e "s/^.*$d/$d/"`
			if [ "X$DO_SOUND_KILL" = "X1" ]; then
				echo "Stopping sound daemon: $sound_daemon_remote_prog $dpid"
				echo "sound cmd: $dcmd"
				kill -TERM $dpid
			fi
		fi
		echo
		echo "done."
		echo "--------------------------------------------------------------"
		echo
	}

	reset_sound() {
		if [ "X$DO_SOUND_RESTART" = "X1" ]; then
			d=$sound_daemon_remote_prog
			a=$sound_daemon_remote_args
			echo "Restaring sound daemon: $d $a"
			$d $a </dev/null >/dev/null 2>&1 &
		fi
	}

	soundwait() {
		trap "" INT QUIT HUP
		wait_til_ssh_gone
		reset_sound
	}

	findpid

	if [ $DO_SMB = 1 ]; then
		do_smb_mounts
	fi

	waiter=0

	if [ $DO_CUPS = 1 ]; then
		update_client_conf
		cupswait </dev/null >/dev/null 2>/dev/null &
		waiter=1
	fi

	if [ $DO_SOUND = 1 ]; then
		setup_sound
		soundwait </dev/null >/dev/null 2>/dev/null &
		waiter=1
	fi
	if [ $DO_SMB_WAIT = 1 ]; then
		if [ $waiter != 1 ]; then
			smbwait </dev/null >/dev/null 2>/dev/null &
			waiter=1
		fi
	fi


	#FINMSG
	echo
	echo "--vnc-helper-exiting--"
	echo
	#cat $0
	rm -f $0
	exit 0
};

	set cmdall ""

	for {set i 1} {$i <= 6} {incr i} {
		set v $cmd($i);
		regsub -all "\n" $v "%" v
		set cmd($i) $v
		append cmdall "echo "
		if {$i == 1} {
			append cmdall {TOPPID=$$%} 
		}
		append cmdall {'}
		append cmdall $cmd($i)
		append cmdall {' | tr '%' '\n'}
		if {$i == 1} {
			append cmdall {>}
		} else {
			append cmdall {>>}
		}
		append cmdall {$HOME/.vnc-helper-cmd__PID__; }
	}
	append cmdall {sh $HOME/.vnc-helper-cmd__PID__; }

	regsub -all {vnc-helper-cmd} $cmdall "vnc-helper-cmd-$mode" cmdall
	if {$tag == ""} {
		set tag [pid]
	}
	regsub -all {__PID__} $cmdall "$tag" cmdall

	set orig $cmdall

	global use_cups cups_local_server cups_remote_port cups_manage_rcfile
	if {$use_cups && $cups_manage_rcfile} {
		if {$mode == "post"} {
			regsub {DO_CUPS=0} $cmdall {DO_CUPS=1} cmdall
			regsub {cups_port=NNNN} $cmdall "cups_port=$cups_remote_port" cmdall
		}
	}
	
	global use_smbmnt smb_su_mode smb_mounts 
	if {$use_smbmnt} {
		if {$smb_mounts != ""} {
			set smbm $smb_mounts
			regsub -all {%USER} $smbm "__USER__" smbm
			regsub -all {%HOME} $smbm "__HOME__" smbm
			if {$mode == "pre"} {
				regsub {DO_SMB=0} $cmdall {DO_SMB=1} cmdall
				if {$smb_su_mode == "su"} {
					regsub {DO_SMB_SU=0} $cmdall {DO_SMB_SU=1} cmdall
				} elseif {$smb_su_mode == "sudo"} {
					regsub {DO_SMB_SU=0} $cmdall {DO_SMB_SU=2} cmdall
				} elseif {$smb_su_mode == "none"} {
					regsub {DO_SMB_SU=0} $cmdall {DO_SMB_SU=0} cmdall
				} else {
					regsub {DO_SMB_SU=0} $cmdall {DO_SMB_SU=1} cmdall
				}
				regsub {smb_mounts=} $cmdall "smb_mounts=\"$smbm\"" cmdall
			} elseif {$mode == "post"} {
				regsub {DO_SMB_WAIT=0} $cmdall {DO_SMB_WAIT=1} cmdall
			}
		}
	}

	global use_sound
	if {$use_sound} {
		if {$mode == "pre"} {
			global sound_daemon_remote_cmd sound_daemon_kill sound_daemon_restart
			if {$sound_daemon_kill} {
				regsub {DO_SOUND_KILL=0} $cmdall {DO_SOUND_KILL=1} cmdall
				regsub {DO_SOUND=0} $cmdall {DO_SOUND=1} cmdall
			}
			if {$sound_daemon_restart} {
				regsub {DO_SOUND_RESTART=0} $cmdall {DO_SOUND_RESTART=1} cmdall
				regsub {DO_SOUND=0} $cmdall {DO_SOUND=1} cmdall
			}
			set sp [string trim $sound_daemon_remote_cmd]
			regsub {[ \t].*$} $sp "" sp
			set sa [string trim $sound_daemon_remote_cmd]
			regsub {^[^ \t][^ \t]*[ \t][ \t]*} $sa "" sa
			regsub {sound_daemon_remote_prog=} $cmdall "sound_daemon_remote_prog=\"$sp\"" cmdall
			regsub {sound_daemon_remote_args=} $cmdall "sound_daemon_remote_args=\"$sa\"" cmdall
		}
	}
	
	if {$mode == "pre"} {
		set dopre 0
		if {$use_smbmnt && $smb_mounts != ""} {
			set dopre 1
		}
		if {$use_sound && $sound_daemon_kill} {
			set dopre 1
		}
		if {$dopre} {
			global is_windows
			if {$is_windows} {
				regsub {#FINMSG} $cmdall {echo "Now Go Click on the Label to Start the 2nd SSH"} cmdall
			} else {
				regsub {#FINMSG} $cmdall {echo "Finished with the 1st SSH tasks, the 2nd SSH should start shortly..."} cmdall
			}
		}
	}

	if {"$orig" == "$cmdall"} {
		return ""
	} else {
		return $cmdall
	}
}

proc cups_dialog {} {

	toplev .cups
	wm title .cups "CUPS Tunnelling"
	global cups_local_server cups_remote_port cups_manage_rcfile
	global cups_local_smb_server cups_remote_smb_port

	global uname
	if {$uname == "Darwin"} {
		scroll_text .cups.f 80 25
	} else {
		scroll_text .cups.f
	}
		

	set msg {
    CUPS Printing requires SSH be used to set up the Print service port
    redirection.  This will be either of the "Use SSH" or "Use SSH and
    SSL" modes under "Options".  Pure SSL tunnelling will not work.

    This method requires working CUPS software setups on both the remote
    and local sides of the connection.

    (See Method #1 below for perhaps the easiest way to get applications to
    print through the tunnel; it requires printing admin privileges however).

    You choose an actual remote CUPS port below under "Use Remote CUPS
    Port:" (6631 is just our default and used in the examples below).
    Note that the normal default CUPS server port is 631.

    The port you choose must be unused on the VNC server machine (n.b. no
    checking is done).  Print requests connecting to it are redirected to
    your local machine through the SSH tunnel.  Note: root permission is
    needed for ports less than 1024 (this is not recommended).

    Then enter the VNC Viewer side (i.e. where you are sitting) CUPS server
    under "Local CUPS Server".  E.g. use "localhost:631" if there is one
    on the viewer machine, or, say, "my-print-srv:631" for a nearby CUPS
    print server.

    Several methods are now described for how to get applications to
    print through the port redirected tunnel.

    Method #0: Create or edit the file $HOME/.cups/client.conf on the VNC
    server side by putting in something like this in it:

    	ServerName localhost:6631

    based on the port you selected above.
    
    NOTE: For this client.conf ServerName setting to work with lp(1)
    and lpr(1) CUPS 1.2 or greater is required.  The cmdline option 
    "-h localhost:6631" can be used for older versions.  For client.conf to
    work in general (e.g. Openoffice, Firefox), a bugfix found in CUPS 1.2.3
    is required.  Two Workarounds (Methods #1 and #2) are described below.

    After the remote VNC Connection is finished, to go back to the non-SSH
    tunnelled CUPS server and either remove the client.conf file or comment
    out the ServerName line.  This restores the normal CUPS server for
    you on the remote machine.

    Select "Manage ServerName in the $HOME/.cups/client.conf file for me" to
    attempt to do this editing of the CUPS config file for you automatically.

    Method #1: If you have admin permission on the VNC Server machine you
    can likely "Add a Printer" via a GUI dialog, wizard, lpadmin(8), etc.
    This makes the client.conf ServerName parameter unnecessary.  You will
    need to tell the GUI dialog that the printer is at, e.g., localhost:6631,
    and anything else needed to identify the printer (type, model, etc).

    Method #2: Restarting individual applications with the IPP_PORT
    set will enable redirected printing for them, e.g.:

       env IPP_PORT=6631 firefox

    If you can only get Method #2 to work, an extreme application would
    be to run the whole desktop, e.g. env IPP_PORT=6631 gnome-session, but
    then you would need some sort of TCP redirector (ssh -L comes to mind),
    to direct it to 631 when not connected remotely.

    Windows/SMB Printers:  Under "Local SMB Print Server" you can set
    a port redirection for a Windows (non-CUPS) SMB printer.  E.g. port
    6632 -> localhost:139.  If localhost:139 does not work, try IP:139,
    etc. or put in the IP address manually.  Then at the least you can
    print using the smbspool(8) program like this:

       smbspool smb://localhost:6632/lp job user title 1 "" myfile.ps

    You could put this in a script, "myprinter".  It appears for the URI,
    only the number of copies ("1" above) and the file itself are important.
    (XXX this might only work for Samba printers...)

    If you have root or print admin permission you can configure CUPS to
    know about this printer via lpadmin(8), etc.  You basically give it
    the smb://... URI.

    For more info see: http://www.karlrunge.com/x11vnc/#faq-cups
}
	.cups.f.t insert end $msg

	if {$cups_local_server == ""} {
		set cups_local_server "localhost:631"
	}
	if {$cups_remote_port == ""} {
		set cups_remote_port "6631"
	}
	if {$cups_local_smb_server == ""} {
		global is_windows
		if {$is_windows} {
			set cups_local_smb_server "IP:139"
		} else {
			set cups_local_smb_server "localhost:139"
		}
	}
	if {$cups_remote_smb_port == ""} {
		set cups_remote_smb_port "6632"
	}

	frame .cups.serv
	label .cups.serv.l -anchor w -text "Local CUPS Server:      "
	entry .cups.serv.e -width 40 -textvariable cups_local_server
	pack .cups.serv.e -side right
	pack .cups.serv.l -side left -expand 1 -fill x

	frame .cups.port
	label .cups.port.l -anchor w -text "Use Remote CUPS Port:"
	entry .cups.port.e -width 40 -textvariable cups_remote_port
	pack .cups.port.e -side right
	pack .cups.port.l -side left -expand 1 -fill x

	frame .cups.smbs
	label .cups.smbs.l -anchor w -text "Local SMB Print Server:      "
	entry .cups.smbs.e -width 40 -textvariable cups_local_smb_server
	pack .cups.smbs.e -side right
	pack .cups.smbs.l -side left -expand 1 -fill x

	frame .cups.smbp
	label .cups.smbp.l -anchor w -text "Use Remote SMB Print Port:"
	entry .cups.smbp.e -width 40 -textvariable cups_remote_smb_port
	pack .cups.smbp.e -side right
	pack .cups.smbp.l -side left -expand 1 -fill x

	checkbutton .cups.cupsrc -anchor w -variable cups_manage_rcfile -text \
		"Manage ServerName in the remote \$HOME/.cups/client.conf file for me"

	button .cups.cancel -text "Cancel" -command {destroy .cups; set use_cups 0}
	bind .cups <Escape> {destroy .cups; set use_cups 0}
	button .cups.done -text "Done" -command {destroy .cups; if {$use_cups} {set_ssh}}

	button .cups.guess -text "Help me decide ..." -command {}
	.cups.guess configure -state disabled

	pack .cups.done .cups.cancel .cups.guess .cups.cupsrc .cups.smbp .cups.smbs .cups.port .cups.serv -side bottom -fill x
	pack .cups.f -side top -fill both -expand 1

	center_win .cups
}

proc sound_dialog {} {

	global is_windows

	toplev .snd
	wm title .snd "ESD/ARTSD Sound Tunnelling"

	global uname
	if {$uname == "Darwin"} {
		scroll_text .snd.f 80 20
	} else {
		scroll_text .snd.f 80 30
	}

	set msg {
    Sound tunnelling to a sound daemon requires SSH be used to set up
    the service port redirection.  This will be either of the "Use SSH"
    or "Use SSH and SSL" modes under "Options".  Pure SSL tunnelling
    will not work.

    This method requires working Sound daemon (e.g. ESD or ARTSD) software
    setups on both the remote and local sides of the connection.

    Often this means you want to run your ENTIRE remote desktop with ALL
    applications instructed to use the sound daemon's network port.  E.g.

        esddsp -s localhost:16001  startkde
        esddsp -s localhost:16001  gnome-session

    and similarly for artsdsp, etc.  You put this in your ~/.xession,
    or other startup file.  This is non standard.  If you do not want to
    do this you still can direct *individual* sound applications through
    the tunnel, for example "esddsp -s localhost:16001 soundapp", where
    "soundapp" is some application that makes noise (say xmms or mpg123).

    Also, usually the remote Sound daemon must be killed BEFORE the SSH port
    redir is established (because it is listening on the port we want to use
    for the SSH redir), and, presumably, restarted when the VNC connection
    finished.

    One may also want to start and kill a local sound daemon that will
    play the sound received over the network on the local machine.

    You can indicate the remote and local Sound daemon commands below and
    how they should be killed and/or restart.  Some examples:

        esd -promiscuous -as 5 -port 16001 -tcp -bind 127.0.0.1
        artsd -n -p 7265 -F 10 -S 4096 -n -s 5 -m artsmessage -l 3 -f

    or you can leave some or all blank and kill/start them manually.

    For convenience, a Windows port of ESD is provided in the util/esound
    directory, and so this might work for a Local command:

        esound\esd -promiscuous -as 5 -port 16001 -tcp -bind 127.0.0.1

    NOTE: If you indicate "Remote Sound daemon: Kill at start." below,
    then THERE WILL BE TWO SSH'S: THE FIRST ONE TO KILL THE DAEMON.
    So you may need to supply TWO SSH PASSWORDS, unless you are using
    something like ssh-agent(1), the Putty PW setting, etc.

    You will also need to supply the remote and local sound ports for
    the SSH redirs.  For esd the default port is 16001, but you can choose
    another one if you prefer.

    For "Local Sound Port" you can also supply "host:port" instead of just
    a numerical port to specify non-localhost connections, e.g. to another
    nearby machine.

    For more info see: http://www.karlrunge.com/x11vnc/#faq-sound
}
	.snd.f.t insert end $msg

	global sound_daemon_remote_port sound_daemon_local_port sound_daemon_local_cmd
	if {$sound_daemon_remote_port == ""} {
		set sound_daemon_remote_port 16001
	}
	if {$sound_daemon_local_port == ""} {
		set sound_daemon_local_port 16001
	}

	if {$sound_daemon_local_cmd == ""} {
		global is_windows
		if {$is_windows} {
			set sound_daemon_local_cmd {esound\esd -promiscuous -as 5 -port %PORT -tcp -bind 127.0.0.1}
		} else {
			set sound_daemon_local_cmd {esd -promiscuous -as 5 -port %PORT -tcp -bind 127.0.0.1}
		}
		regsub {%PORT} $sound_daemon_local_cmd $sound_daemon_local_port sound_daemon_local_cmd
	}


	frame .snd.remote
	label .snd.remote.l -anchor w -text "Remote Sound daemon cmd: "
	entry .snd.remote.e -width 45 -textvariable sound_daemon_remote_cmd
	pack .snd.remote.e -side right
	pack .snd.remote.l -side left -expand 1 -fill x

	frame .snd.local
	label .snd.local.l -anchor w -text "Local Sound daemon cmd:     "
	entry .snd.local.e -width 45 -textvariable sound_daemon_local_cmd
	pack .snd.local.e -side right
	pack .snd.local.l -side left -expand 1 -fill x

	frame .snd.rport
	label .snd.rport.l -anchor w -text "Remote Sound Port: "
	entry .snd.rport.e -width 45 -textvariable sound_daemon_remote_port
	pack .snd.rport.e -side right
	pack .snd.rport.l -side left -expand 1 -fill x

	frame .snd.lport
	label .snd.lport.l -anchor w -text "Local Sound Port:     "
	entry .snd.lport.e -width 45 -textvariable sound_daemon_local_port
	pack .snd.lport.e -side right
	pack .snd.lport.l -side left -expand 1 -fill x


	checkbutton .snd.sdk -anchor w -variable sound_daemon_kill -text \
		"Remote Sound daemon: Kill at start."

	checkbutton .snd.sdr -anchor w -variable sound_daemon_restart -text \
		"Remote Sound daemon: Restart at end."

	checkbutton .snd.sdsl -anchor w -variable sound_daemon_local_start -text \
		"Local Sound daemon: Run at start."

	checkbutton .snd.sdkl -anchor w -variable sound_daemon_local_kill -text \
		"Local Sound daemon: Kill at end."

	button .snd.guess -text "Help me decide ..." -command {}
	.snd.guess configure -state disabled

	global is_win9x 
	if {$is_win9x} {
		.snd.local.e configure -state disabled
		.snd.local.l configure -state disabled
		.snd.sdsl configure -state disabled
		.snd.sdkl configure -state disabled
	}

	button .snd.cancel -text "Cancel" -command {destroy .snd; set use_sound 0}
	bind .snd <Escape> {destroy .snd; set use_sound 0}
	button .snd.done -text "Done" -command {destroy .snd; if {$use_sound} {set_ssh}}

	pack .snd.done .snd.cancel .snd.guess .snd.sdkl .snd.sdsl .snd.sdr .snd.sdk .snd.lport .snd.rport \
		.snd.local .snd.remote -side bottom -fill x
	pack .snd.f -side bottom -fill both -expand 1

	center_win .snd
}

# Share ideas.
# 
# Unix:
# 
# if type smbclient
# first parse smbclient -L localhost -N
# and/or      smbclient -L `hostname` -N
# Get Sharenames and Servers and Domain.
# 
# loop over servers, doing smbclient -L server -N
# pile this into a huge list, sep by disk and printers.
# 
# WinXP:
# 
# parse "NET VIEW" output similarly.
# 
# Have checkbox for each disk.  Set default root to /var/tmp/${USER}-mnts
# Let them change that at once and have it populate. 
# 
# use   //hostname/share  /var/tmp/runge-mnts/hostname/share
# 
# 
# Printers, hmmm.  Can't add to remote cups list...  I guess have the list
# ready for CUPS dialog to suggest which SMB servers they want to redirect
# to...

proc get_hostname {} {
	global is_windows is_win9x
	set str ""
	if {$is_windows} {
		if {1} {
			catch {set str [exec hostname]}
			regsub -all {[\r]} $str "" str
		} else {
			catch {set str [exec net config]}
			if [regexp -nocase {Computer name[ \t]+\\\\([^ \t]+)} $str mv str] {
				;
			} else {
				set str ""
			}
		}
	} else {
		catch {set str [exec hostname]}
	}
	set str [string trim $str]
	return $str
}

proc smb_list_windows {smbhost} {
	global smb_local smb_local_hosts smb_this_host
	global is_win9x
	set dbg 0

	set domain ""

	if {$is_win9x} {
		# exec net view ... doesn't work.
		set smb_this_host "unknown"
		return
	}

	set this_host [get_hostname]
	set This_host [string toupper $this_host]
	set smb_this_host $This_host

	if {$smbhost == $smb_this_host} {
		catch {set out0 [exec net view]}
		regsub -all {[\r]} $out0 "" out0
		foreach line [split $out0 "\n"] {
			if [regexp -nocase {in workgroup ([^ \t]+)} $line mv wg] {
				regsub -all {[.]} $wg "" wg
				set domain $wg
			} elseif [regexp {^\\\\([^ \t]+)[ \t]*(.*)} $line mv host comment] {
				set smb_local($smbhost:server:$host) $comment
			}
		}
	}

	set out1 ""
	set h "\\\\$smbhost"
	catch {set out1 [exec net view $h]}
	regsub -all {[\r]} $out1 "" out1

	if {$dbg} {puts "SMBHOST: $smbhost"}

	set mode ""
	foreach line [split $out1 "\n"] {
		if [regexp {^[ \t]*---} $line] {
			continue
		}
		if [regexp -nocase {The command} $line] {
			continue
		}
		if [regexp -nocase {Shared resources} $line] {
			continue
		}
		if [regexp -nocase {^[ \t]*Share[ \t]*name} $line] {
			set mode "shares"
			continue
		}
		set line [string trim $line]
		if {$line == ""} {
			continue
		}
		if {$mode == "shares"} {
			if [regexp {^([^ \t]+)[ \t]+([^ \t]+)[ \t]*(.*)$} $line mv name type comment] {
				if {$dbg} {
					puts "SHR: $name"
					puts "---: $type"
					puts "---: $comment"
				}
				if [regexp -nocase {^Disk$} $type] {
					set smb_local($smbhost:disk:$name) $comment
				} elseif [regexp -nocase {^Print} $type] {
					set smb_local($smbhost:printer:$name) $comment
				}
			}
		}
	}

	set smb_local($smbhost:domain) $domain
}

proc smb_list_unix {smbhost} {
	global smb_local smb_local_hosts smb_this_host
	set smbclient [in_path smbclient]
	if {[in_path smbclient] == ""} {
		return ""
	}
	set dbg 0

	set this_host [get_hostname]
	set This_host [string toupper $this_host]
	set smb_this_host $This_host

	set out1 ""
	catch {set out1 [exec smbclient -N -L $smbhost 2>@ stdout]}

	if {$dbg} {puts "SMBHOST: $smbhost"}
	if {$smbhost == $this_host || $smbhost == $This_host} {
		if {$out1 == ""} {
			catch {set out1 [exec smbclient -N -L localhost 2>@ stdout]}
		}
	}

	set domain ""
	set mode ""
	foreach line [split $out1 "\n"] {
		if [regexp {^[ \t]*---} $line] {
			continue
		}
		if [regexp {Anonymous login} $line] {
			continue
		}
		if {$domain == "" && [regexp {Domain=\[([^\]]+)\]} $line mv domain]} {
			if {$dbg} {puts "DOM: $domain"}
			continue
		}
		if [regexp {^[ \t]*Sharename} $line] {
			set mode "shares"
			continue
		}
		if [regexp {^[ \t]*Server} $line] {
			set mode "server"
			continue
		}
		if [regexp {^[ \t]*Workgroup} $line] {
			set mode "workgroup"
			continue
		}
		set line [string trim $line]
		if {$mode == "shares"} {
			if [regexp {^([^ \t]+)[ \t]+([^ \t]+)[ \t]*(.*)$} $line mv name type comment] {
				if {$dbg} {
					puts "SHR: $name"
					puts "---: $type"
					puts "---: $comment"
				}
				if [regexp -nocase {^Disk$} $type] {
					set smb_local($smbhost:disk:$name) $comment
				} elseif [regexp -nocase {^Printer$} $type] {
					set smb_local($smbhost:printer:$name) $comment
				}
			}
		} elseif {$mode == "server"} {
			if [regexp {^([^ \t]+)[ \t]*(.*)$} $line mv host comment] {
				if {$dbg} {
					puts "SVR: $host"
					puts "---: $comment"
				}
				set smb_local($smbhost:server:$host) $comment
			}
		} elseif {$mode == "workgroup"} {
			if [regexp {^([^ \t]+)[ \t]+(.*)$} $line mv work host] {
				if {$dbg} {
					puts "WRK: $work"
					puts "---: $host"
				}
				if {$host != ""} {
					set smb_local($smbhost:master:$work) $host
				}
			}
		}
	}

	set smb_local($smbhost:domain) $domain
}

proc smb_list {} {
	global is_windows smb_local smb_local_hosts
	global smb_host_list

	set smb_local(null) ""

	if {! [info exists smb_host_list]} {
		set smb_host_list ""
	}
	if [info exists smb_local] {
		unset smb_local
	}
	if [info exists smb_local_hosts] {
		unset smb_local_hosts
	}
			
	set this_host [get_hostname]
	set this_host [string toupper $this_host]
	if {$is_windows} {
		smb_list_windows $this_host
	} else {
		smb_list_unix $this_host
	}
	set did($this_host) 1 
	set keys [array names smb_local]
	foreach item [split $smb_host_list] {
		if {$item != ""} {
			set item [string toupper $item]
			lappend keys "$this_host:server:$item"
		}
	}
	foreach key $keys {
		if [regexp "^$this_host:server:(.*)\$" $key mv host]  {
			if {$host == ""} {
				continue
			}
			set smb_local_hosts($host) 1
			if {! [info exists did($host)]} {
				if {$is_windows} {
					smb_list_windows $host
				} else {
					smb_list_unix $host
				}
				set did($host) 1 
			}
		}
	}
}

proc smb_check_selected {} {
	global smbmount_exists smbmount_sumode
	global smb_selected smb_selected_mnt smb_selected_cb smb_selected_en

	set ok 0
	if {$smbmount_exists && $smbmount_sumode != "dontknow"} {
		set ok 1
	}
	set state disabled
	if {$ok} {
		set state normal
	}

	foreach cb [array names smb_selected_cb] {
		catch {$cb configure -state $state}
	}
	foreach en [array names smb_selected_en] {
		catch {$en configure -state $state}
	}
}

proc make_share_widgets {w} {
	
	set share_label $w.f.hl
	catch {$share_label configure -text "Share Name: PROBING ..."}
	update

	smb_list

	set saw_f 0
	foreach child [winfo children $w] {
		if {$child == "$w.f"} {
			set saw_f 1
			continue
		}
		catch {destroy $child}
	}

	set w1 47
	set w2 44

	if {! $saw_f} {
		set wf $w.f
		frame $wf
		label $wf.hl -width $w1 -text "Share Name:" -anchor w
		label $wf.hr -width $w2 -text "  Mount Point:" -anchor w

		pack $wf.hl $wf.hr -side left -expand 1
		pack $wf -side top -fill x

		.smbwiz.f.t window create end -window $w
	}

	global smb_local smb_local_hosts smb_this_host smb_selected smb_selected_mnt
	global smb_selected_host smb_selected_name
	global smb_selected_cb smb_selected_en
	global smb_host_list
	if [info exists smb_selected]      {array unset smb_selected }
	if [info exists smb_selected_mnt]  {array unset smb_selected_mnt}
	if [info exists smb_selected_cb]   {array unset smb_selected_cb}
	if [info exists smb_selected_en]   {array unset smb_selected_en}
	if [info exists smb_selected_host] {array unset smb_selected_host}
	if [info exists smb_selected_name] {array unset smb_selected_name}

	set hosts [list $smb_this_host]
	lappend hosts [lsort [array names smb_local_hosts]]

	set smb_host_list ""
	set i 0

	global smb_mount_prefix
	set smb_mount_prefix "/var/tmp/%USER-mnts"

	foreach host [lsort [array names smb_local_hosts]] {

		if [info exists did($host)] {
			continue
		}
		set did($host) 1

		append smb_host_list "$host "

		foreach key [lsort [array names smb_local]] {
			if [regexp {^([^:]+):([^:]+):(.*)$} $key mv host2 type name] {
				if {$host2 != $host}  {
					continue
				}
				if {$type != "disk"} {
					continue
				}
				set wf $w.f$i
				frame $wf
				checkbutton $wf.c -anchor w -width $w1 -variable smb_selected($i) \
					-text "//$host/$name" -relief ridge 
				if {! [info exists smb_selected($i)]} {
					set smb_selected($i) 0
				}

				entry $wf.e -width $w2 -textvariable smb_selected_mnt($i)
				set smb_selected_mnt($i) "$smb_mount_prefix/$host/$name"

				set smb_selected_host($i) $host
				set smb_selected_name($i) $name

				set smb_selected_cb($wf.c) $i
				set smb_selected_en($wf.e) $i
				set comment $smb_local($key)

				bind $wf.c <Enter> "$share_label configure -text {Share Name: $comment}"
				bind $wf.c <Leave> "$share_label configure -text {Share Name:}"

				$wf.c configure -state disabled
				$wf.e configure -state disabled

				pack $wf.c $wf.e -side left -expand 1
				pack $wf -side top -fill x
				incr i
			}
		}
	}
	if {$i == 0} {
		global is_win9x
		$share_label configure -text {Share Name: No SMB Share Hosts were found!}
		if {$is_win9x} {
			.smbwiz.f.t insert end "\n(this feature does not work on Win9x you have have to enter them manually: //HOST/share /var/tmp/mymnt)\n"
		}
	} else {
		$share_label configure -text "Share Name: Found $i SMB Shares"
	}
	smb_check_selected
}

proc smb_help_me_decide {} {
	global is_windows
	global smb_local smb_local_hosts smb_this_host smb_selected smb_selected_mnt
	global smb_selected_host smb_selected_name
	global smb_selected_cb smb_selected_en
	global smb_host_list

	toplev .smbwiz
	set title "SMB Filesystem Tunnelling -- Help Me Decide"
	wm title .smbwiz $title
	set id "  "

	scroll_text .smbwiz.f 100 40

	set msg {
For now you will have to verify the following information manually.

You can do this by either logging into the remote machine to find the info or asking the sysadmin for it.  

}

	if {! $is_windows} {
		.smbwiz.f.t configure -font {Helvetica -12 bold}
	}
	.smbwiz.f.t insert end $msg

	set w .smbwiz.f.t.f1
	frame $w -bd 1 -relief ridge -cursor {top_left_arrow}

	.smbwiz.f.t insert end "\n"

	.smbwiz.f.t insert end "1) Indicate the existence of the 'smbmount' command on the remote system:\n"
	.smbwiz.f.t insert end "\n$id"
	global smbmount_exists
	set smbmount_exists 0

	checkbutton $w.smbmount_exists -pady 1 -anchor w -variable smbmount_exists \
		-text "Yes, the 'smbmount' command exists on the remote system." \
		-command smb_check_selected

	pack $w.smbmount_exists
	.smbwiz.f.t window create end -window $w

	.smbwiz.f.t insert end "\n\n\n"

	set w .smbwiz.f.t.f2
	frame $w -bd 1 -relief ridge -cursor {top_left_arrow}

	.smbwiz.f.t insert end "2) Indicate your authorization to run 'smbmount' on the remote system:\n"
	.smbwiz.f.t insert end "\n$id"
	global smbmount_sumode
	set smbmount_sumode "dontknow"

	radiobutton $w.dk -pady 1 -anchor w -variable smbmount_sumode -value dontknow \
		-text "I do not know if I can mount SMB shares on the remote system via 'smbmount'" \
		-command smb_check_selected
	pack $w.dk -side top -fill x

	radiobutton $w.su -pady 1 -anchor w -variable smbmount_sumode -value su \
		-text "I know the Password to run commands as root on the remote system via 'su'" \
		-command smb_check_selected
	pack $w.su -side top -fill x

	radiobutton $w.sudo -pady 1 -anchor w -variable smbmount_sumode -value sudo \
		-text "I know the Password to run commands as root on the remote system via 'sudo'" \
		-command smb_check_selected
	pack $w.sudo -side top -fill x

	radiobutton $w.ru -pady 1 -anchor w -variable smbmount_sumode -value none \
		-text "I do not need to be root on the remote system to mount SMB shares via 'smbmount'" \
		-command smb_check_selected
	pack $w.ru -side top -fill x

	.smbwiz.f.t window create end -window $w

	global smb_wiz_done
	set smb_wiz_done 0

	button .smbwiz.cancel -text "Cancel" -command {set smb_wiz_done 1}
	button .smbwiz.done -text "Done" -command {set smb_wiz_done 1}
	pack .smbwiz.done -side bottom -fill x 
	pack .smbwiz.f -side top -fill both -expand 1

	wm protocol .smbwiz WM_DELETE_WINDOW {set smb_wiz_done 1}
	center_win .smbwiz

	wm title .smbwiz "Searching for Local SMB shares..."
	update
	wm title .smbwiz $title

	global smb_local smb_this_host
	.smbwiz.f.t insert end "\n\n\n"

	set w .smbwiz.f.t.f3
	catch {destroy $w}
	frame $w -bd 1 -relief ridge -cursor {top_left_arrow}

	.smbwiz.f.t insert end "3) Select SMB shares to mount and their mount point on the remote system:\n"
	.smbwiz.f.t insert end "\n${id}"

	make_share_widgets $w

	.smbwiz.f.t insert end "\n(%USER will be expanded to the username on the remote system and %HOME the home directory)\n"

	.smbwiz.f.t insert end "\n\n\n"

	.smbwiz.f.t insert end "You can change the list of Local SMB hosts to probe and the mount point prefix here:\n"
	.smbwiz.f.t insert end "\n$id"
	set w .smbwiz.f.t.f4
	frame $w -bd 1 -relief ridge -cursor {top_left_arrow}
	set wf .smbwiz.f.t.f4.f
	frame $wf
	label $wf.l -text "SMB Hosts:  "  -anchor w
	entry $wf.e -textvariable smb_host_list -width 60
	button $wf.b -text "Apply" -command {make_share_widgets .smbwiz.f.t.f3}
	bind $wf.e <Return> "$wf.b invoke"
	pack $wf.l $wf.e $wf.b -side left
	pack $wf
	pack $w

	.smbwiz.f.t window create end -window $w

	.smbwiz.f.t insert end "\n$id"

	set w .smbwiz.f.t.f5
	frame $w -bd 1 -relief ridge -cursor {top_left_arrow}
	set wf .smbwiz.f.t.f5.f
	frame $wf
	label $wf.l -text "Mount Prefix:"  -anchor w
	entry $wf.e -textvariable smb_mount_prefix -width 60
	button $wf.b -text "Apply" -command {apply_mount_point_prefix .smbwiz.f.t.f5.f.e}
	bind $wf.e <Return> "$wf.b invoke"
	pack $wf.l $wf.e $wf.b -side left
	pack $wf
	pack $w

	.smbwiz.f.t window create end -window $w

	.smbwiz.f.t insert end "\n\n\n"

	.smbwiz.f.t see 1.0
	.smbwiz.f.t configure -state disabled
	update

	vwait smb_wiz_done
	catch {destroy .smbwiz}

	if {! $smbmount_exists || $smbmount_sumode == "dontknow"} {
		tk_messageBox -type ok -parent .oa -icon warning -message "Sorry we couldn't help out!\n'smbmount' info on the remote system is required for SMB mounting" -title "SMB mounting -- aborting"
		global use_smbmnt
		set use_smbmnt 0
		catch {raise .oa}
		return
	}
	global smb_su_mode
	set smb_su_mode $smbmount_sumode

	set max 0
	foreach en [array names smb_selected_en] {
		set i $smb_selected_en($en)
		set host $smb_selected_host($i)
		set name $smb_selected_name($i)

		set len [string length "//$host/$name"]
		if {$len > $max} {
			set max $len
		}
	}

	set max [expr $max + 8]

	set strs ""
	foreach en [array names smb_selected_en] {
		set i $smb_selected_en($en)
		if {! $smb_selected($i)} {
			continue
		}
		set host $smb_selected_host($i)
		set name $smb_selected_name($i)
		set mnt $smb_selected_mnt($i)

		set share "//$host/$name"
		set share [format "%-${max}s" $share]
		
		lappend strs "$share $mnt"
	}
	set text ""
	foreach str [lsort $strs] {
		append text "$str\n"
	}

	global smb_mount_list
	set smb_mount_list $text

	smb_dialog
}

proc apply_mount_point_prefix {w} {
	global smb_selected_host smb_selected_name
	global smb_selected_en smb_selected_mnt

	set prefix ""
	catch {set prefix [$w get]}
	if {$prefix == ""} {
		mesg "No mount prefix."
		bell
		return
	}

	foreach en [array names smb_selected_en] {
		set i $smb_selected_en($en)
		set host $smb_selected_host($i)
		set name $smb_selected_name($i)
		set smb_selected_mnt($i) "$prefix/$host/$name"
	}
}

proc smb_dialog {} {
	toplev .smb
	wm title .smb "SMB Filesystem Tunnelling"
	global smb_su_mode smb_mount_list
	global use_smbmnt

	global help_font

	global uname
	if {$uname == "Darwin"} {
		scroll_text .smb.f 80 25
	} else {
		scroll_text .smb.f
	}

	set msg {
    Windows/Samba Filesystem mounting requires SSH be used to set up the
    SMB service port redirection.  This will be either of the "Use SSH"
    or "Use SSH and SSL" modes under "Options".  Pure SSL tunnelling
    will not work.

    This method requires a working Samba software setup on the remote
    side of the connection (VNC server) and existing Samba or Windows file
    server(s) on the local side (VNC viewer).

    The smbmount(8) program MUST be installed on the remote side. This
    evidently limits the mounting to Linux systems.  Let us know of similar
    utilities on other Unixes.  Mounting onto remote Windows machines is
    currently not supported (our SSH mode with services setup only works
    to Unix).

    Depending on how smbmount is configured you may be able to run it
    as a regular user, or it may require running under su(1) or sudo(8)
    (root password or user password required, respectively).  You select
    which one you want via the checkbuttons below.

    In addition to a possible su(1) or sudo(8) password, you may ALSO
    need to supply passwords to mount each SMB share. This is an SMB passwd.
    If it has no password just hit enter after the "Password:" prompt.

    The passwords are supplied when the 1st SSH connection starts up;
    be prepared to respond to them.

    NOTE: USE OF SMB TUNNELLING MODE WILL REQUIRE TWO SSH'S, AND SO YOU
    MAY NEED TO SUPPLY TWO LOGIN PASSWORDS UNLESS YOU ARE USING SOMETHING
    LIKE ssh-agent(1) or the Putty PW setting.
    %WIN

    To indicate the Windows/Samba shares to mount enter them one per line
    in one of the forms:

      //machine1/share   ~/Desktop/my-mount1
      //machine2/fubar   /var/tmp/my-foobar2  192.168.100.53:3456
      1139  //machine3/baz  /var/tmp/baz      [...]

    The first part is the standard SMB host and share name //hostname/dir
    (note this share is on the local viewer-side not on the remote end).
    A leading '#' will cause the entire line to be skipped.

    The second part, e.g. /var/tmp/my-foobar2, is the directory to mount
    the share on the remote (VNC Server) side.  You must be able to
    write to this directory.  It will be created if it does not exist.
    A leading character ~ will be expanded to $HOME.  So will the string
    %HOME.  The string %USER will get expanded to the remote username.

    An optional part like 192.168.100.53:3456 is used to specify the real
    hostname or IP address, and possible non-standard port, on the local
    side if for some reason the //hostname is not sufficient.

    An optional leading numerical value, 1139 in the above example, indicates
    which port to use on the Remote side to SSH redirect to the local side.
    Otherwise a random one is tried (a unique one is needed for each SMB
    server:port combination).  A fixed one is preferred: choose a free
    remote port.

    The standard SMB service ports (local side) are 445 and 139.  139 is
    used by this application.

    Sometimes "localhost" will not work on Windows machines for a share
    hostname, and you will have to specify a different network interface
    (e.g. the machine's IP address).  If you use the literal string "IP"
    it will be attempted to replace it with the numerical IP address, e.g.:

      //machine1/share   ~/Desktop/my-mount1   IP

    VERY IMPORTANT: Before terminating the VNC Connection, make sure no
    applications are using any of the SMB shares (or shells are cd-ed
    into the share).  This way the shares will be automatically unmounted.
    Otherwise you will need to log in again, stop processes from using
    the share, become root and umount the shares manually ("smbumount
    /path/to/share", etc.)

    For more info see: http://www.karlrunge.com/x11vnc/#faq-smb-shares
}

	set msg2 {
    To speed up moving to the next step, iconify the first SSH console
    when you are done entering passwords, etc. and then click on the
    main panel 'VNC Host:Display' label.
}

	global is_windows
	if {! $is_windows} {
		regsub { *%WIN} $msg "" msg
	} else {
		set msg2 [string trim $msg2]
		regsub { *%WIN} $msg "    $msg2" msg
	}
	.smb.f.t insert end $msg

	frame .smb.r
	label .smb.r.l -text "smbmount(8) auth mode:" -relief ridge
	radiobutton .smb.r.none -text "None" -variable smb_su_mode -value "none"
	radiobutton .smb.r.su   -text "su(1)" -variable smb_su_mode -value "su"
	radiobutton .smb.r.sudo -text "sudo(8)" -variable smb_su_mode -value "sudo"

	pack .smb.r.l .smb.r.none .smb.r.sudo .smb.r.su -side left -fill x

	label .smb.info -text "Supply the mounts (one per line) below:" -anchor w -relief ridge

	eval text .smb.mnts -width 80 -height 5 $help_font
	.smb.mnts insert end $smb_mount_list

	button .smb.guess -text "Help me decide ..." -command {destroy .smb; smb_help_me_decide}

	button .smb.cancel -text "Cancel" -command {set use_smbmnt 0; destroy .smb}
	bind .smb <Escape> {set use_smbmnt 0; destroy .smb}
	button .smb.done -text "Done" -command {if {$use_smbmnt} {set_ssh; set smb_mount_list [.smb.mnts get 1.0 end]}; destroy .smb}

	pack .smb.done .smb.cancel .smb.guess .smb.mnts .smb.info .smb.r -side bottom -fill x
	pack .smb.f -side top -fill both -expand 1

	center_win .smb
}

proc help_advanced_opts {} {
	toplev .ah

	scroll_text_dismiss .ah.f

	center_win .ah

	wm title .ah "Advanced Options Help"

	set msg {
    These Advanced Options that may require extra software installed on
    the VNC server-side (the remote server machine) and/or on the VNC
    client-side (where this gui is running).

    The Service redirection options, CUPS, ESD/ARTSD, and SMB will
    require that you use SSH for tunneling so that they can use the -R
    port redirection will be enabled for each service.  I.e. "Use SSH"
    or "Use SSH and SSL" mode.

    These options may also require additional configuration to get them
    to work properly.  Please submit bug reports if it appears it should
    be working for your setup but is not.

    Brief descriptions:

         CUPS Print tunnelling: redirect localhost:6631 (say) on the VNC
         server to your local CUPS server.

         ESD/ARTSD Audio tunnelling: redirect localhost:16001 (say) on
         the VNC server to your local ESD, etc. sound server.

         SMB mount tunnelling: redirect localhost:1139 (say) on the VNC
         server and through that mount SMB file shares from your local
         server.  The remote machine must be Linux with smbmount installed.

         Change vncviewer: specify a non-bundled VNC Viewer (e.g.
         UltraVNC or RealVNC) to run instead of the bundled TightVNC Viewer.

         Extra Redirs: specify additional -L port:host:port and 
         -R port:host:port cmdline options for SSH to enable additional
         services.

         Port Knocking: for "closed port" services, first "knock" on the
         firewall ports in a certain way to open the door for SSH or SSL.
         The port can also be closed when the encrypted VNC connection
         finishes.

	 Y Crop: this is for x11vnc's -ncache client side caching scheme
	 with our Unix TightVNC viewer.  Sets the Y value to "crop" the
	 viewer size at (below the cut is the pixel cache region you do
	 not want to see).  If the screen is tall (H > 2*W) ycropping
	 will be autodetected, or you can set to -1 to force autodection.
	 Otherwise, set it to the desired Y value.  You can also set
	 the scrollbar width (very thin by default) by appending ",sb=N"
	 (or use ",sb=N" by itself to just set the scrollbar width).

         Include:  Profile template(s) to load before loading a profile
         (see Load Profile under "Options").  For example if you Save a
         profile called "globals" that has some settings you use often,
         then just supply "Include: globals" to have them applied.
         You may supply a comma or space separated list of templates
         to include.  They can be full path names or basenames relative
         to the profiles directory.  You do not need to supply the .vnc
         suffix.  The non-default settings in them will be applied first,
         and then any values in the loaded Profile will override them.


    About the CheckButtons:

         Ahem, Well...., yes quite a klunky UI: you have to toggle the
         CheckButton to pull up the Dialog box a 2nd, etc. time... don't
         worry your settings will still be there!
}

	.ah.f.t insert end $msg
	jiggle_text .ah.f.t
}

proc set_viewer_path {} {
	global change_vncviewer_path
	set change_vncviewer_path [tk_getOpenFile -parent .chviewer]
	catch {raise .chviewer}
	update
}

proc change_vncviewer_dialog {} {
	global change_vncviewer change_vncviewer_path vncviewer_realvnc4
	
	toplev .chviewer
	wm title .chviewer "Change VNC Viewer"

	global help_font
	eval text .chviewer.t -width 90 -height 24 $help_font
	apply_bg .chviewer.t

	set msg {
    To use your own VNC Viewer (i.e. one installed by you, not included in this
    package), e.g. UltraVNC or RealVNC, type in the program name, or browse for
    the full path to it.  You can put command line arguments after the program.

    Note that due to incompatibilities with respect to command line options
    there may be issues, especially if many command line options are supplied.
    You can specify your own command line options below if you like (and try to
    avoid setting any others in this GUI under "Options").

    If the path to the program name has any spaces it in, please surround it with
    double quotes, e.g.

        "C:\Program Files\My Vnc Viewer\VNCVIEWER.EXE"

    Make sure the very first character is a quote.  You should quote the command
    even if it is only the command line arguments that need extra protection:

        "wine" -- "/home/fred/Program Flies/UltraVNC-1.0.2.exe" /64colors

    Since the command line options differ between them greatly, if you know it
    is of the RealVNC 4.x flavor, indicate on the check box. Otherwise we guess.
}
	.chviewer.t insert end $msg

	frame .chviewer.path
	label .chviewer.path.l -text "VNC Viewer:"
	entry .chviewer.path.e -width 40 -textvariable change_vncviewer_path
	button .chviewer.path.b -text "Browse..." -command set_viewer_path
	checkbutton .chviewer.path.r -anchor w -variable vncviewer_realvnc4 -text \
		"RealVNC 4.x"

	pack .chviewer.path.l -side left
	pack .chviewer.path.e -side left -expand 1 -fill x
	pack .chviewer.path.b -side left
	pack .chviewer.path.r -side left

	button .chviewer.cancel -text "Cancel" -command {destroy .chviewer; set change_vncviewer 0}
	bind .chviewer <Escape> {destroy .chviewer; set change_vncviewer 0}
	button .chviewer.done -text "Done" -command {destroy .chviewer; catch {raise .oa}}

	pack .chviewer.t .chviewer.path .chviewer.cancel .chviewer.done -side top -fill x

	center_win .chviewer
	wm resizable .chviewer 1 0

	focus .chviewer.path.e 
}

proc port_redir_dialog {} {
	global additional_port_redirs additional_port_redirs_list
	
	toplev .redirs
	wm title .redirs "Additional Port Redirections"

	global help_font uname
	if {$uname == "Darwin"} {
		eval text .redirs.t -width 80 -height 35 $help_font
	} else {
		eval text .redirs.t -width 80 -height 35 $help_font
	}
	apply_bg .redirs.t

	set msg {
    Specify any additional SSH port redirections you desire for the
    connection.  Put as many as you want separated by spaces.  These only
    apply to SSH and SSH+SSL connections, they do not apply to Pure SSL
    connections.

    -L port1:host:port2  will listen on port1 on the local machine (where
                         you are sitting) and redirect them to port2 on
                         "host".  "host" is relative to the remote side
                         (VNC Server).  Use "localhost" for the remote
                         machine itself.

    -R port1:host:port2  will listen on port1 on the remote machine
                         (where the VNC server is running) and redirect
                         them to port2 on "host".  "host" is relative
                         to the local side (where you are sitting).
                         Use "localhost" for this machine.

    Perhaps you want a redir to a web server inside an intranet:

        -L 8001:web-int:80

    Or to redir a remote port to your local SSH daemon:

        -R 5022:localhost:22

    etc.  There are many interesting possibilities.

    Sometimes, especially for Windows Shares, you cannot do a -R redir to
    localhost, but need to supply the IP address of the network interface
    (e.g. by default the Shares do not listen on localhost:139).  As a
    convenience you can do something like -R 1139:IP:139 (for any port
    numbers) and the IP will be attempted to be expanded.  If this fails
    for some reason you will have to use the actual numerical IP address.
}
	.redirs.t insert end $msg

	frame .redirs.path
	label .redirs.path.l -text "Port Redirs:"
	entry .redirs.path.e -width 40 -textvariable additional_port_redirs_list

	pack .redirs.path.l -side left
	pack .redirs.path.e -side left -expand 1 -fill x

	button .redirs.cancel -text "Cancel" -command {set additional_port_redirs 0; destroy .redirs}
	bind .redirs <Escape> {set additional_port_redirs 0; destroy .redirs}
	button .redirs.done -text "Done" -command {destroy .redirs}

	pack .redirs.t .redirs.path .redirs.cancel .redirs.done -side top -fill x

	center_win .redirs
	wm resizable .redirs 1 0

	focus .redirs.path.e
}

proc find_netcat {} {
	global is_windows

	set nc ""

	if {! $is_windows} {
		set nc [in_path "netcat"]
		if {$nc == ""} {
			set nc [in_path "nc"]
		}
	} else {
		set try "netcat.exe"
		if [file exists $try] {
			set nc $try
		}
	}
	return $nc
}

proc pk_expand {cmd host} {
	global tcl_platform
	set secs [clock seconds]
	set msecs [clock clicks -milliseconds]
	set user $tcl_platform(user)
	if [regexp {%IP} $cmd] {
		set ip [guess_ip]
		if {$ip == ""} {
			set ip "unknown"
		}
		regsub -all {%IP} $cmd $ip cmd
	}
	if [regexp {%NAT} $cmd] {
		set ip [guess_nat_ip]
		regsub -all {%NAT} $cmd $ip cmd
	}
	regsub -all {%HOST} $cmd $host cmd
	regsub -all {%USER} $cmd $user cmd
	regsub -all {%SECS} $cmd $secs cmd
	regsub -all {%MSECS} $cmd $msecs cmd

	return $cmd
}

proc backtick_expand {str} {
	set str0 $str
	set collect ""
	set count 0
	while {[regexp {^(.*)`([^`]+)`(.*)$} $str mv p1 cmd p2]} {
		set out [eval exec $cmd]
		set str "$p1$out$p2"
		incr count
		if {$count > 10}  {
			break
		}
	}
	return $str
}

proc read_from_pad {file} {
	set fh ""
	if {[catch {set fh [open $file "r"]}] != 0} {
		return "FAIL"
	}

	set accum ""
	set match ""
	while {[gets $fh line] > -1} {
		if [regexp {^[ \t]*#} $line] {
			append accum "$line\n"
		} elseif [regexp {^[ \t]*$} $line] {
			append accum "$line\n"
		} elseif {$match == ""} {
			set match $line
			append accum "# $line\n"
		} else {
			append accum "$line\n"
		}
	}

	close $fh

	if {$match == ""} {
		return "FAIL"
	}
	
	if {[catch {set fh [open $file "w"]}] != 0} {
		return "FAIL"
	}

	puts -nonewline $fh $accum

	return $match
}

proc do_port_knock {hp mode} {
	global use_port_knocking port_knocking_list
	global is_windows

	if {! $use_port_knocking} {
		return 1
	}
	if {$port_knocking_list == ""} {
		return 1
	}
	set list $port_knocking_list

	if {$mode == "finish"} {
		if {! [regexp {FINISH} $list]} {
			mesg "PortKnock(finish): done"
			return 1
		} else {
			regsub {^.*FINISH} $list "" list
		}
	} elseif {$mode == "start"} {
		if {[regexp {FINISH} $list]} {
			regsub {FINISH.*$} $list "" list
		}
	}

	set default_delay 150

	set host [string trim $hp]
	regsub {^vnc://} $host "" host
	regsub {^.*@} $host "" host
	regsub {:.*$} $host "" host
	set host0 [string trim $host]

	if {$host0 == ""} {
		bell
		mesg "PortKnock: No host: $hp"
		return 0
	}

	set m ""
	
	if [regexp {PAD=([^\n]+)} $list mv padfile] {
		set tlist [read_from_pad $padfile] 
		set tlist [string trim $tlist]
		if {$tlist == "" || $tlist == "FAIL"} {
			raise .
			tk_messageBox -type ok -icon error \
				-message "Failed to read entry from $padfile" \
				-title "Error: Padfile $padfile"
			return 0
		}
		regsub -all {PAD=([^\n]+)} $list $tlist list
	}

	set spl ",\n\r"
	if [regexp {CMD=}   $list] {set spl "\n\r"}
	if [regexp {CMDX=}  $list] {set spl "\n\r"}
	if [regexp {SEND=}  $list] {set spl "\n\r"}
	if [regexp {SENDX=} $list] {set spl "\n\r"}

	set i 0
	set pi 0

	foreach line [split $list $spl] {
		set line [string trim $line]
		set line0 $line

		if {$line == ""} {
			continue
		}
		if [regexp {^#} $line] {
			continue
		}

		if [regexp {^sleep[ \t][ \t]*([0-9][0-9]*)} $line mv sl] {
			set m "PortKnock: sleep $sl"
			mesg $m
			after $sl
			continue
		}
		if [regexp {^delay[ \t][ \t]*([0-9][0-9]*)} $line mv sl] {
			set m "PortKnock: delay=$sl"
			mesg $m
			set default_delay $sl
			continue
		}

		if [regexp {^CMD=(.*)} $line mv cmd] {
			set m "PortKnock: CMD: $cmd"
			mesg $m
			eval exec $cmd
			continue
		}
		if [regexp {^CMDX=(.*)} $line mv cmd] {
			set cmd [pk_expand $cmd $host0]
			set m "PortKnock: CMDX: $cmd"
			mesg $m
			eval exec $cmd
			continue
		}
	
		if [regexp {`} $line] {
			#set line [backtick_expand $line]
		}

		set snd ""
		if [regexp {^(.*)SEND=(.*)$} $line mv line snd]  {
			set line [string trim $line]
			set snd [string trim $snd]
			regsub -all {%NEWLINE} $snd "\n" snd
		} elseif [regexp {^(.*)SENDX=(.*)$} $line mv line snd]  {
			set line [string trim $line]
			set snd [string trim $snd]
			set snd [pk_expand $snd $host0]
			regsub -all {%NEWLINE} $snd "\n" snd
		}

		set udp 0
		if [regexp -nocase {[/:]udp} $line] {
			set udp 1
			regsub -all -nocase {[/:]udp} $line " " line
			set line [string trim $line]
		}
		regsub -all -nocase {[/:]tcp} $line " " line
		set line [string trim $line]

		set delay 0
		if [regexp {^(.*)[ \t][ \t]*([0-9][0-9]*)$} $line mv first delay] {
			set line [string trim $first]
		}

		if {[regexp {^(.*):(.*)$} $line mv host port]} {
			;
		} else {
			set host $host0
			set port $line
		}
		set host [string trim $host]
		set port [string trim $port]

		if {$host == ""} {
			set host $host0
		}

		if {$port == ""} {
			bell
			set m "PortKnock: No port found: \"$line0\""
			mesg $m
			return 0
		}
		if {! [regexp {^[0-9][0-9]*$} $port]} {
			bell
			set m "PortKnock: Invalid port: \"$port\""
			mesg $m
			return 0
		}
		regsub {,.*$} $host "" host
		if {[regexp {[ \t]} $host]} {
			bell
			set m "PortKnock: Invalid host: \"$host\""
			mesg $m
			return 0
		}
		if {! [regexp {^[-A-z0-9_.][-A-z0-9_.]*$} $host]} {
			bell
			set m "PortKnock: Invalid host: \"$host\""
			mesg $m
			return 0
		}

		set nc ""
		if {$udp || $snd != ""} {
			set nc [find_netcat]
			if {$nc == ""} {
				bell
				set m "PortKnock: UDP: netcat(1) not found"
				mesg $m
				after 1000
				continue
			}
		}

		if {$snd != ""} {
			global env
			set pfile "payload$pi.txt" 
			if {! $is_windows} {
				set pfile "$env(HOME)/.$pfile"
			}
			set pfiles($pi) $pfile
			incr pi
			set fh [open $pfile "w"]
			puts -nonewline $fh "$snd"
			close $fh

			set m "PortKnock: SEND: $host $port"
			mesg $m
			if {$is_windows} {
				if {$udp} {
					catch {exec $nc -d -u -w 1 "$host" "$port" < $pfile &}
				} else {
					catch {exec $nc -d    -w 1 "$host" "$port" < $pfile &}
				}
			} else {
				if {$udp} {
					catch {exec $nc    -u -w 1 "$host" "$port" < $pfile &}
				} else {
					catch {exec $nc       -w 1 "$host" "$port" < $pfile &}
				}
			}
			catch {after 50; file delete $pfile}
			
		} elseif {$udp} {
			set m "PortKnock: UDP: $host $port"
			mesg $m
			if {! $is_windows} {
				catch {exec echo a | $nc -u -w 1 "$host" "$port" &}
			} else {
				set fh [open "nc_in.txt" "w"]
				puts $fh "a"
				close $fh
				catch {exec $nc -d -u -w 1 "$host" "$port" < "nc_in.txt" &}
			}
		} else {
			set m "PortKnock: TCP: $host $port"
			mesg $m
			set s ""
			set emess ""
			set rc [catch {set s [socket -async $host $port]} emess]
			if {$rc != 0} {
				raise .
				tk_messageBox -type ok -icon error -message $emess -title "Error: socket -async $host $port"
			}
			set socks($i) $s
			# seems we have to close it immediately to avoid multiple SYN's.
			# does not help on Win9x.
			catch {after 30; close $s};
			incr i
		}

		if {$delay == 0} {
			if {$default_delay > 0} {
				after $default_delay
			}
		} elseif {$delay > 0} {
			after $delay
		}
	}

	if {0} {
		for {set j 0} {$j < $i} {incr j} {
			set $s $socks($j)
			if {$s != ""} {
				catch {close $s}	
			}
		}
	}
	for {set j 0} {$j < $pi} {incr j} {
		set f $pfiles($j)
		if {$f != ""} {
			if [file exists $f] {
				after 100
			}
			catch {file delete $f}	
		}
	}
	if {$is_windows} {
		catch {file delete "nc_in.txt"}
	}
	if {$m != ""} {
		set m "$m,"
	}
	if {$mode == "finish"} {
		mesg "PortKnock(finish): done"
	} else {
		mesg "PortKnock: done"
	}
	return 1
}

proc port_knocking_dialog {} {
	toplev .pk
	wm title .pk "Port Knocking"
	global use_port_knocking port_knocking_list

	global help_font

	global uname
	if {$uname == "Darwin"} {
		scroll_text .pk.f 85 25
	} else {
		scroll_text .pk.f 85
	}

	set msg {
 Description:

    Port Knocking is where a network connection to a service is not provided
    to just any client, but rather only to those that immediately prior to
    connecting send a more or less secret pattern of connections to other
    ports on the firewall.

    Somewhat like "knocking" on the door with the correct sequence before it
    being opened (but not necessarily letting you in yet).  It is also possible
    to have a single encrypted packet (e.g. UDP) payload communicate with the
    firewall instead of knocking on a sequence of ports.

    Only after the correct sequence of ports is observed by the firewall does
    it allow the IP address of the client to attempt to connect to the service.

    So, for example, instead of allowing any host on the internet to connect
    to your SSH service and then try to login with a username and password, the
    client first must "tickle" your firewall with the correct sequence of ports.
    Only then will it be allowed to connect to your SSH service at all.

    This does not replace the authentication and security of SSH, it merely
    puts another layer of protection around it. E.g., suppose an exploit for
    SSH was discovered, you would most likely have more time to fix/patch
    the problem than if any client could directly connect to your SSH server.

    For more information http://www.portknocking.org/ and
    http://www.linuxjournal.com/article/6811


 Tip:

    If you just want to use the Port Knocking for an SSH shell and not
    for a VNC tunnel, then specify something like "user@hostname cmd=SHELL"
    (or "user@hostname cmd=PUTTY" on Windows) in the VNC Host:Display entry box
    on the main panel.  This will do everything short of starting the viewer.
    A shortcut for this is Ctrl-S as long as user@hostname is present.
    

 Specifying the Knocks:

    In the text area below "Supply port knocking pattern" you put in the pattern
    of "knocks" needed for this connection.  You can separate the knocks by
    commas or put them one per line.

    Each "knock" is of this form:

           [host:]port[/udp] [delay]

    In the simplest form just a numerical port, e.g. 5433, is supplied.
    Items inside [...] are optional and described below.

    The packet is sent to the same host that the VNC (or SSH) connection will
    be made to.  If you want it to go to a different host or IP use the [host:]
    prefix.  It can be either a hostname or numerical IP.

    A TCP packet is sent by default.

    If you need to send a UDP packet, the netcat (aka "nc") program must be
    installed on Unix (tcl/tk does not support udp connections).  Indicate this
    with "/udp" following the port number (you can also use "/tcp", but since
    it is the default it is not necessary).  (You can also use ":udp" to match
    the knockd syntax).  See the example below.  For convenience a Windows netcat
    binary is supplied.

    The last field, [delay], is an optional number of milliseconds to delay
    before continuing on to the next knock.


 Examples:

           5433, 12321, 1661

           fw.example.com:5433, 12321/udp 3000, 1661 2000

           fw.example.com:5433
           12321/udp 3000
           1661 2000

    Note how the first two examples separate their knocks via commas ",".
    The 3rd example is equivalent to the 2nd and splits them up by new lines.

    Note for each knock any second number (e.g. the "2000" in "1661 2000") is
    a DELAY in milliseconds, not a port number.  If you had a comma separating
    them: "1661, 2000" that would mean two separate knocks: one to port 1661
    followed by one to 2000 (with basically no delay between them).

    In examples 2 and 3, "fw.example.com" represents some machine other than
    the VNC/SSH host.  By default, the VNC/SSH host is the one the packet is
    sent to.

    If one of the items is the string "FINISH", then the part before it is
    used prior to connecting and the part after is used once the connection
    is finished.  This can be used, say, to close the firewall port.  Example:

           5433, 12321, FINISH, 7659, 2314

    (or one can split them up via lines as above.)


 Advanced port knock actions:

    If the string in the text field contains anywhere the strings "CMD=", "CMDX=",
    or "SEND=", then splitting on commas is not done: it is only split on lines.

    Then, if a line begins CMD=... the string after the = is run as an
    external command.  The command could be anything you want, e.g. it could
    be a port-knocking client that does the knocking, perhaps encrypting the
    "knocks" pattern somehow or using a Single Packet Authorization method such
    as http://www.cipherdyne.com/fwknop/

    Extra quotes (sometimes "'foo bar'") may be needed to preserve spaces in
    command line arguments because the tcl/tk eval(n) command is used.  You
    can also use {...} for quoting strings with spaces.

    If a line begins CMDX=... then before the command is run the following
    tokens are expanded to strings:

      %IP       Current machine's IP address (NAT may make this not useful).
      %NAT      Try to get effective IP by contacting http://www.whatismyip.com
      %HOST     The remote host of the connection.
      %USER     The current user.
      %SECS     The current time in seconds (platform dependent).
      %MSECS    Platform dependent time having at least millisecond granularity.

   Lines not matching CMD= or CMDX= are treated as normal port knocks but with
   one exception.  If a line ends in SEND=... (i.e. after the [host:]port,
   etc., part) then the string after the = is sent as a payload for the tcp
   or udp connection to [host:]port.  netcat is used for these SEND cases
   (and must be available on Unix).  If newlines (\n) are needed in the
   SEND string, use %NEWLINE.  Sending binary data is not yet supported;
   use CMD= with your own program.


 Advanced Examples:

      CMD=port_knock_client -password wombat33
      CMDX=port_knock_client -password wombat33 -host %HOST -src %NAT

      fw.example.com:5433/udp SEND=ASDLFKSJDF


 More tricks:

      To temporarily "comment out" a knock, insert a leading "#" character.

      Use "sleep N" to insert a raw sleep for N milliseconds (e.g. between
      CMD=... items or at the very end of the knocks to wait).

      If a knock entry matches "delay N" the default delay is set to
      N milliseconds (it is 150 initially).


 One Time Pads:

      If the text contains a (presumably single) line of the form:

           PAD=/path/to/a/one/time/pad/file

      then that file is opened and the first non-blank line not beginning
      with "#" is used as the knock pattern.  The pad file is rewritten
      with that line starting with a "#" (so it will be skipped next time).

      The PAD=... string is replaced with the read-in knock pattern line.
      So, if needed, one can preface the PAD=... with "delay N" to set the
      default delay, and one can also put a "sleep N" after the PAD=...
      line to indicate a final sleep.  One can also surround the PAD=
      line with other knock and CMD= CMDX= lines, but that usage sounds
      a bit rare.  Example:

           delay 1000
           PAD=C:\My Pads\work-pad1.txt
           sleep 4000


 Port knock only:

      If, in the 'VNC Host:Display' entry, you use "user@hostname cmd=KNOCK"
      then only the port-knocking is performed.  A shortcut for this is
      Ctrl-P as long as hostname is present in the entry box.  If it
      matches cmd=KNOCKF, i.e. an extra "F", then the port-knocking
      "FINISH" sequence is sent, if any.  A shortcut for this Shift-Ctrl-P
      as long as hostname is present.
}
	.pk.f.t insert end $msg

	label .pk.info -text "Supply port knocking pattern:" -anchor w -relief ridge

	eval text .pk.rule -width 80 -height 5 $help_font
	.pk.rule insert end $port_knocking_list

	button .pk.cancel -text "Cancel" -command {set use_port_knocking 0; destroy .pk}
	bind .pk <Escape> {set use_port_knocking 0; destroy .pk}
	button .pk.done -text "Done" -command {if {$use_port_knocking} {set port_knocking_list [.pk.rule get 1.0 end]}; destroy .pk}

	pack .pk.done .pk.cancel .pk.rule .pk.info -side bottom -fill x
	pack .pk.f -side top -fill both -expand 1

	center_win .pk
}


proc set_advanced_options {} {
	global use_cups use_sound use_smbmnt
	global change_vncviewer
	global use_port_knocking port_knocking_list

	catch {destroy .o}
	toplev .oa
	wm title .oa "Advanced Options"

	set i 1

	checkbutton .oa.b$i -anchor w -variable use_cups -text \
		"Enable CUPS Print tunnelling" \
		-command {if {$use_cups} {cups_dialog}}
	incr i

	checkbutton .oa.b$i -anchor w -variable use_sound -text \
		"Enable ESD/ARTSD Audio tunnelling" \
		-command {if {$use_sound} {sound_dialog}}
	incr i

	checkbutton .oa.b$i -anchor w -variable use_smbmnt -text \
		"Enable SMB mount tunnelling" \
		-command {if {$use_smbmnt} {smb_dialog}}
	incr i


	checkbutton .oa.b$i -anchor w -variable change_vncviewer -text \
		"Change VNC Viewer" \
		-command {if {$change_vncviewer} {change_vncviewer_dialog}}
	incr i

	checkbutton .oa.b$i -anchor w -variable additional_port_redirs -text \
		"Additional Port Redirs" \
		-command {if {$additional_port_redirs} {port_redir_dialog}}
	incr i

	checkbutton .oa.b$i -anchor w -variable use_port_knocking -text \
		"Port Knocking" \
		-command {if {$use_port_knocking} {port_knocking_dialog}}
	incr i

	global ycrop_string
	frame .oa.b$i
	label .oa.b$i.l -text "Y Crop: "
	entry .oa.b$i.e -width 10 -textvariable ycrop_string
	pack .oa.b$i.l -side left
	pack .oa.b$i.e -side right -expand 1 -fill x

	incr i

	global include_list
	frame .oa.b$i
	label .oa.b$i.l -text "Include:"
	entry .oa.b$i.e -width 10 -textvariable include_list
	pack .oa.b$i.l -side left
	pack .oa.b$i.e -side right -expand 1 -fill x

	incr i

	for {set j 1} {$j < $i} {incr j} {
		pack .oa.b$j -side top -fill x
	}

#	button .oa.connect -text "Connect" -command launch
#	pack .oa.connect -side top -fill x 

	frame .oa.b
	button .oa.b.done -text "Done" -command {destroy .oa}
	bind .oa <Escape> {destroy .oa}
	button .oa.b.help -text "Help" -command help_advanced_opts

	button .oa.b.connect -text "Connect" -command launch

	pack .oa.b.help .oa.b.connect .oa.b.done -fill x -expand 1 -side left

	pack .oa.b -side top -fill x 

	center_win .oa
	wm resizable .oa 1 0
	focus .oa
}

proc in_path {cmd} {
	global env
	set p $env(PATH)
	foreach dir [split $p ":"] {
		set try "$dir/$cmd"
		if [file exists $try] {
			return "$try"
		}
	}
	return ""
}

proc ssh_agent_restart {} {
	global env 

	set got_ssh_agent 0
	set got_ssh_add 0
	set got_ssh_agent2 0
	set got_ssh_add2 0

	if {[in_path "ssh-agent"]  != ""} {set got_ssh_agent 1}
	if {[in_path "ssh-agent2"] != ""} {set got_ssh_agent2 1}
	if {[in_path "ssh-add"]    != ""} {set got_ssh_add 1}
	if {[in_path "ssh-add2"]   != ""} {set got_ssh_add2 1}

	set ssh_agent ""
	set ssh_add ""
	if {[info exists env(USER)] && $env(USER) == "runge"} {
		if {$got_ssh_agent2} {
			set ssh_agent "ssh-agent2"
		}
		if {$got_ssh_add2} {
			set ssh_add "ssh-add2"
		}
	}
	if {$ssh_agent == "" && $got_ssh_agent} {
		set ssh_agent "ssh-agent"
	}
	if {$ssh_add == "" && $got_ssh_add} {
		set ssh_add "ssh-add"
	}
	if {$ssh_agent == ""} {
		bell
		mesg "could not find ssh-agent in PATH"
		return
	}
	if {$ssh_add == ""} {
		bell
		mesg "could not find ssh-add in PATH"
		return
	}
	set tmp $env(HOME)/.vnc-sa[pid]
	set fh ""
	catch {set fh [open $tmp "w"]}
	if {$fh == ""} {
		bell
		mesg "could not open tmp file $tmp"
		return
	}

	puts $fh "#!/bin/sh"
	puts $fh "eval `$ssh_agent -s`"
	puts $fh "$ssh_add"
	puts $fh "SSVNC_GUI_CHILD=\"\"" 
	puts $fh "export SSVNC_GUI_CHILD" 

	global buck_zero
	set cmd $buck_zero
	
	if [info exists env(SSVNC_GUI_CMD)] {
		set cmd $env(SSVNC_GUI_CMD) 
	}
	#puts $fh "$cmd </dev/null 1>/dev/null 2>/dev/null &"
	puts $fh "nohup $cmd &"
	puts $fh "sleep 1"
	puts $fh "#rm -f $tmp"
	close $fh

	wm withdraw .
	catch {wm withdraw .o}
	catch {wm withdraw .oa}

	unix_terminal_cmd "+200+200" "Restarting with ssh-agent/ssh-add" "sh $tmp" 1
	after 10000
	destroy .
	exit
}

proc putty_pw_entry {mode} {
	if {$mode == "check"} {
		global use_sshssl use_ssh
		if {$use_sshssl || $use_ssh} {
			putty_pw_entry enable
		} else {
			putty_pw_entry disable
		}
		return
	}
	if {$mode == "disable"} {
		catch {.o.pw.l configure -state disabled}
		catch {.o.pw.e configure -state disabled}
	} else {
		catch {.o.pw.l configure -state normal}
		catch {.o.pw.e configure -state normal}
	}
}

proc ssl_ssh_adjust {which} {
	global use_ssl use_ssh use_sshssl sshssl_sw	
	global remote_ssh_cmd_list

	if {$which == "ssl"} {
		set use_ssl 1
		set use_ssh 0
		set use_sshssl 0
		set sshssl_sw "ssl"
		catch {.f4.getcert configure -state normal}
	} elseif {$which == "ssh"} {
		set use_ssl 0
		set use_ssh 1
		set use_sshssl 0
		set sshssl_sw "ssh"
		catch {.f4.getcert configure -state disabled}
	} elseif {$which == "sshssl"} {
		set use_ssl 0
		set use_ssh 0
		set use_sshssl 1
		set sshssl_sw "sshssl"
		catch {.f4.getcert configure -state disabled}
	}

	if [info exists remote_ssh_cmd_list] {
		if {$use_ssh || $use_sshssl} {
			foreach w $remote_ssh_cmd_list {
				$w configure -state normal
			}
		}
		if {$use_ssl} {
			foreach w $remote_ssh_cmd_list {
				$w configure -state disabled
			}
		}
	}

	if {! $use_ssl && ! $use_ssh && ! $use_sshssl} {
		set use_ssl 1
		set sshssl_sw "ssl"
	}
	
	putty_pw_entry check
}

proc set_options {} {
	global use_alpha use_grab use_ssh use_sshssl use_viewonly use_fullscreen use_bgr233
	global use_nojpeg use_raise_on_beep use_compresslevel use_quality
	global compresslevel_text quality_text
	global env is_windows darwin_cotvnc

	toplev .o
	wm title .o "SSL/SSH VNC Options"

	set i 1

	radiobutton .o.b$i -anchor w -variable sshssl_sw -value ssl -text \
		"Use SSL" -command {ssl_ssh_adjust ssl}
	incr i

	radiobutton .o.b$i -anchor w -variable sshssl_sw -value ssh -text \
		"Use SSH" -command {ssl_ssh_adjust ssh}
	incr i

	radiobutton .o.b$i -anchor w -variable sshssl_sw -value sshssl -text \
		"Use SSH and SSL" -command {ssl_ssh_adjust sshssl}
	set iss $i
	incr i

	checkbutton .o.b$i -anchor w -variable use_viewonly -text \
		"View Only"
	incr i

	checkbutton .o.b$i -anchor w -variable use_fullscreen -text \
		"Fullscreen"
	incr i

	checkbutton .o.b$i -anchor w -variable use_raise_on_beep -text \
		"Raise On Beep"
	if {$darwin_cotvnc} {.o.b$i configure -state disabled}
	incr i

	checkbutton .o.b$i -anchor w -variable use_bgr233 -text \
		"Use 8bit color (-bgr233)"
	if {$darwin_cotvnc} {.o.b$i configure -state disabled}
	incr i

	checkbutton .o.b$i -anchor w -variable use_alpha -text \
		"Cursor alphablending (32bpp required)"
	if {$darwin_cotvnc} {.o.b$i configure -state disabled}
	set ia $i
	incr i

	checkbutton .o.b$i -anchor w -variable use_grab -text \
		"Use XGrabServer"
	if {$darwin_cotvnc} {.o.b$i configure -state disabled}
	set ix $i
	incr i

	checkbutton .o.b$i -anchor w -variable use_nojpeg -text \
		"Do not use JPEG (-nojpeg)"
	if {$darwin_cotvnc} {.o.b$i configure -state disabled}
	incr i

	menubutton .o.b$i -anchor w -menu .o.b$i.m -textvariable compresslevel_text
	set compresslevel_text "Compress Level: $use_compresslevel"
	if {$darwin_cotvnc} {.o.b$i configure -state disabled}

	menu .o.b$i.m -tearoff 0
	for {set j -1} {$j < 10} {incr j} {
		set v $j
		set l $j
		if {$j == -1} {
			set v "default"
			set l "default"
		}
		.o.b$i.m add radiobutton -variable use_compresslevel \
			-value $v -label $l -command \
			{set compresslevel_text "Compress Level: $use_compresslevel"}
	}
	incr i

	menubutton .o.b$i -anchor w -menu .o.b$i.m -textvariable quality_text
	set quality_text "Quality: $use_quality"
	if {$darwin_cotvnc} {.o.b$i configure -state disabled}

	menu .o.b$i.m -tearoff 0
	for {set j -1} {$j < 10} {incr j} {
		set v $j
		set l $j
		if {$j == -1} {
			set v "default"
			set l "default"
		}
		.o.b$i.m add radiobutton -variable use_quality \
			-value $v -label $l -command \
			{set quality_text "Quality: $use_quality"}
	}
	incr i

	for {set j 1} {$j < $i} {incr j} {
		pack .o.b$j -side top -fill x
	}

	if {$is_windows} {
		.o.b$ia configure -state disabled
		.o.b$ix configure -state disabled
	}

	if {$is_windows} {
		frame .o.pw	
		label .o.pw.l -text "Putty PW:"
		entry .o.pw.e -width 10 -show * -textvariable putty_pw
		pack .o.pw.l -side left
		pack .o.pw.e -side left -expand 1 -fill x
		pack .o.pw -side top -fill x 
		putty_pw_entry check
	} else {
		button .o.sa -text "Use ssh-agent" -command ssh_agent_restart
		pack .o.sa -side top -fill x 
	}

	button .o.s_prof -text "Save Profile ..." -command {save_profile .o; raise .o}
	button .o.l_prof -text " Load Profile ..." -command {load_profile .o; raise .o}
	button .o.advanced -text "Advanced ..." -command set_advanced_options
#	button .o.connect -text "Connect" -command launch
	button .o.clear -text "Clear Options" -command set_defaults
#	pack .o.connect -side top -fill x 
	pack .o.clear -side top -fill x 
	pack .o.s_prof -side top -fill x 
	pack .o.l_prof -side top -fill x 
	pack .o.advanced -side top -fill x 

	frame .o.b
	button .o.b.done -text "Done" -command {destroy .o}
	bind .o <Escape> {destroy .o}
	button .o.b.help -text "Help" -command help_opts
	button .o.b.connect -text "Connect" -command launch

	pack .o.b.help .o.b.connect .o.b.done -fill x -expand 1 -side left

	pack .o.b -side top -fill x 

	center_win .o
	wm resizable .o 1 0
	focus .o
}

proc check_writable {} {
	set test test[pid].txt
	catch {set f [open $test "w"]; puts $f "test"; close $f}

	###catch {file delete -force $test}	# testing.

	if ![file exists $test] {
		global env
		if [info exists env(HOME)] {
			set dir "$env(HOME)/ss_vnc/cache"	
			catch {file mkdir $dir}
			if ![file exists $dir] {
				return
			}
			foreach f [glob -type f * */* */*/*] {
				set dest "$dir/$f"
				set dirn [file dirname $dest]
				catch {file mkdir $dirn}
				catch {file copy -force -- $f $dest}
			}
			cd $dir
			###catch {set f [open $test "w"]; puts $f "test"; close $f}
		}
	} else {
		catch {file delete -force $test}
	}
}

global env
set is_windows 0
set help_font "-font fixed"
if { [regexp -nocase {Windows} $tcl_platform(os)]} {
	cd util
	set help_font ""
	set is_windows 1
}

if {[regexp -nocase {Windows.9} $tcl_platform(os)]} {
	set is_win9x 1
} else {
	set is_win9x 0
}

if {$is_windows} {
	check_writable
}

set uname ""
if {! $is_windows} {
	catch {set uname [exec uname]}
}

set darwin_cotvnc 0
if {$uname == "Darwin"} {
	if {! [info exists env(DISPLAY)]} {
		set darwin_cotvnc 1
	}
	if [info exists env(HOME)] {
		set t "$env(HOME)/.vnc"
		if {! [file exists $t]} {
			catch {file mkdir $t}
		}
	}
	set help_font "-font {Monaco 10}"
}

set putty_pw ""

global scroll_text_focus
set scroll_text_focus 1

set multientry 1

wm withdraw .
wm title . "SSL/SSH VNC Viewer"
wm resizable . 1 0

set_defaults
set skip_pre 0

set vncdisplay ""
set vncproxy ""
set remote_ssh_cmd ""
set vncauth_passwd ""

label .l -text "SSL/SSH VNC Viewer" -relief ridge

set wl 21
set we 40
frame .f0
if {$multientry} {
	label .f0.l -width $wl -anchor w -text "VNC Host:Display" -relief ridge
} else {
	label .f0.l -anchor w -text "VNC Host:Display" -relief ridge
}
entry .f0.e -width $we -textvariable vncdisplay
pack .f0.l -side left 
pack .f0.e -side left -expand 1 -fill x
bind .f0.e <Return> launch

frame .f1
label .f1.l -width $wl -anchor w -text "VNC Password:" -relief ridge
entry .f1.e -width $we -textvariable vncauth_passwd -show *
pack .f1.l -side left 
pack .f1.e -side left -expand 1 -fill x
bind .f1.e <Return> launch

frame .f2
label .f2.l -width $wl -anchor w -text "Proxy/Gateway:" -relief ridge
entry .f2.e -width $we -textvariable vncproxy
pack .f2.l -side left 
pack .f2.e -side left -expand 1 -fill x

frame .f3
label .f3.l -width $wl -anchor w -text "Remote SSH Command:" -relief ridge
entry .f3.e -width $we -textvariable remote_ssh_cmd
pack .f3.l -side left 
pack .f3.e -side left -expand 1 -fill x
.f3.l configure -state disabled
.f3.e configure -state disabled

set remote_ssh_cmd_list {.f3.e .f3.l} 

frame .f4
radiobutton .f4.ssl -anchor w    -variable sshssl_sw -value ssl    -command {ssl_ssh_adjust ssl}    -text "Use SSL"
radiobutton .f4.ssh -anchor w    -variable sshssl_sw -value ssh    -command {ssl_ssh_adjust ssh}    -text "Use SSH"
radiobutton .f4.sshssl -anchor w -variable sshssl_sw -value sshssl -command {ssl_ssh_adjust sshssl} -text "Use SSH and SSL"
button .f4.getcert -command {fetch_cert} -text "Fetch Cert"
pack .f4.ssl .f4.ssh .f4.sshssl -side left -fill x
pack .f4.getcert -side right -fill x

ssl_ssh_adjust ssl

frame .b
button .b.help  -text "Help" -command help
button .b.certs -text "Certs ..." -command getcerts
button .b.opts  -text "Options ..." -command set_options
button .b.load  -text "Load" -command {load_profile}
button .b.conn  -text "Connect" -command launch
button .b.exit  -text "Exit" -command {destroy .; exit}


pack .b.certs .b.opts .b.load .b.conn .b.help .b.exit -side left -expand 1 -fill x

if {$multientry} {
	if {! $is_windows} {
		pack .l .f0 .f1 .f2 .f3 .f4 .b -side top -fill x
	} else {
		pack .l .f0     .f2 .f3 .f4 .b -side top -fill x
	}
} else {
	pack .l .f0 .b -side top -fill x
}
if {![info exists env(SSVNC_GUI_CHILD)] || $env(SSVNC_GUI_CHILD) == ""} {
	center_win .
}
focus .f0.e
wm deiconify .

global system_button_face
set system_button_face ""
foreach item [.b.help configure -bg] {
	set system_button_face $item
}

if {[info exists env(SSVNC_GUI_CMD)]} {
	set env(SSVNC_GUI_CHILD) 1
	bind . <Control-n> "exec $env(SSVNC_GUI_CMD) &"
}
bind . <Control-q> "destroy .; exit"
bind . <Shift-Escape> "destroy .; exit"
bind . <Control-s> "launch_shell_only"
bind . <Control-p> {port_knock_only "" "KNOCK"}
bind . <Control-P> {port_knock_only "" "FINISH"}
bind . <Control-l> {load_profile}
bind . <B3-ButtonRelease> {load_profile}

global entered_gui_top button_gui_top
set entered_gui_top 0
set button_gui_top 0
bind . <Enter> {set entered_gui_top 1}
bind .l <ButtonPress> {set button_gui_top 1}
bind .f0.l <ButtonPress> {set button_gui_top 1}

update