open62541-sys 0.6.1

Low-level, unsafe bindings for the C11 library open62541, an open source and free implementation of OPC UA (OPC Unified Architecture).
Documentation
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *    Copyright 2017-2022 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
 *    Copyright 2017-2019 (c) Fraunhofer IOSB (Author: Mark Giraud)
 *    Copyright 2025 (c) Siemens AG (Author: Tin Raic)
 *    Copyright 2025 (c) o6 Automation GmbH (Author: Julius Pfrommer)
 */

#include <open62541/types.h>

#include "open62541/transport_generated.h"
#include "ua_client_internal.h"
#include "../ua_types_encoding_binary.h"
#include "mp_printf.h"

/* Some OPC UA servers only return all Endpoints if the EndpointURL used during
 * the HEL/ACK handshake exactly matches -- including the path following the
 * address and port! Hence for the first connection we only call FindServers and
 * reopen a new TCP connection using then EndpointURL found there.
 *
 * The overall process is this:
 * - Connect with the EndpointURL provided by the user (HEL/ACK)
 * - Call FindServers
 *   - If one of the results has an exactly matching EndpointUrl, continue.
 *   - Otherwise select a matching server, update the endpointURL member of
 *     UA_Client and reconnect.
 * - Call GetEndpoints and select an Endpoint
 * - Open a SecureChannel and Session for that Endpoint
 * - Read the namespaces array of the server (and create the namespaces mapping)
 */

#define UA_MINMESSAGESIZE 8192
#define MAX_DATA_SIZE 4096

static void initConnect(UA_Client *client);
static UA_StatusCode createSessionAsync(UA_Client *client);
static UA_UserTokenPolicy *
findUserTokenPolicy(UA_Client *client, UA_EndpointDescription *endpoint,
                    char *logPrefix);

/* Get the EndpointUrl to be used right now.
 * This is adjusted during the discovery process.
 * We fall back if connecting to an EndpointUrl fails. */
static UA_String
getEndpointUrl(UA_Client *client) {
    if(client->endpoint.endpointUrl.length > 0)
        return client->endpoint.endpointUrl;
    if(client->discoveryUrl.length > 0)
        return client->discoveryUrl;
    return client->config.endpointUrl;
}

/* If an EndpointUrl doesn't work (TCP connection fails), fall back to the
 * initial EndpointUrl */
static UA_StatusCode
fallbackEndpointUrl(UA_Client* client) {
    /* Cannot fallback, the initial EndpointUrl is already in use */
    UA_String currentUrl = getEndpointUrl(client);
    if(UA_String_equal(&currentUrl, &client->config.endpointUrl)) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Could not open a TCP connection to the Endpoint at %S",
                     client->config.endpointUrl);
        return UA_STATUSCODE_BADCONNECTIONREJECTED;
    }

    if(client->endpoint.endpointUrl.length > 0) {
        /* Overwrite the EndpointUrl of the Endpoint */
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                       "Could not open a TCP connection to the Endpoint at %S. "
                       "Overriding the endpoint description with the initial "
                       "EndpointUrl at %S.",
                       client->config.endpoint.endpointUrl,
                       client->config.endpointUrl);
        UA_String_clear(&client->endpoint.endpointUrl);
        return UA_String_copy(&client->config.endpointUrl,
                              &client->endpoint.endpointUrl);
    } else {
        /* Overwrite the DiscoveryUrl returned by FindServers */
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                       "The DiscoveryUrl returned by the FindServers service (%S) "
                       "could not be connected. Continuing with the initial EndpointUrl "
                       "%S for the GetEndpoints service.",
                       client->config.endpointUrl, client->config.endpointUrl);
        UA_String_clear(&client->discoveryUrl);
        return UA_String_copy(&client->config.endpointUrl, &client->discoveryUrl);
    }
}

static UA_SecurityPolicy *
getSecurityPolicy(UA_Client *client, UA_String policyUri) {
    for(size_t i = 0; i < client->config.securityPoliciesSize; i++) {
        if(UA_String_equal(&policyUri, &client->config.securityPolicies[i].policyUri))
            return &client->config.securityPolicies[i];
    }
    return NULL;
}

/* Match PolicyUri and certificate. The returned SecurityPolicy instance carries
 * the private key to sign with the given certificate. When the certificate is
 * NULL, only the PolicyUri is matched (used for non-X509 token types). */
static UA_SecurityPolicy *
getAuthSecurityPolicy(UA_Client *client, const UA_String policyUri,
                      const UA_ByteString *certificate) {
    for(size_t i = 0; i < client->config.authSecurityPoliciesSize; i++) {
        UA_SecurityPolicy *sp = &client->config.authSecurityPolicies[i];
        if(!UA_String_equal(&policyUri, &sp->policyUri))
            continue;
        if(certificate && !UA_ByteString_equal(certificate, &sp->localCertificate))
            continue;
        return sp;
    }
    return NULL;
}

/* The endpoint is unconfigured if the description is all zeroed-out */
static UA_Boolean
endpointUnconfigured(const UA_EndpointDescription *endpoint) {
    UA_EndpointDescription tmp;
    UA_EndpointDescription_init(&tmp);
    return UA_equal(&tmp, endpoint, &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
}

UA_Boolean
isFullyConnected(UA_Client *client) {
    /* No SecureChannel */
    if(client->channel.state != UA_SECURECHANNELSTATE_OPEN)
        return false;

    /* GetEndpoints handshake ongoing or not yet done */
    if(client->endpointsHandshake || endpointUnconfigured(&client->endpoint))
        return false;

    /* FindServers handshake ongoing or not yet done */
    if(client->findServersHandshake || client->discoveryUrl.length == 0)
        return false;

    if(!client->config.noSession) {
        /* No Session, but is required */
        if(client->sessionState != UA_SESSIONSTATE_ACTIVATED)
            return false;

        /* NamespaceArray not yet read */
        if(client->namespacesHandshake || !client->haveNamespaces)
            return false;
    }

    return true;
}

static UA_StatusCode
initUserTokenPolicy(UA_Client *client, const UA_UserTokenPolicy **outUtp,
                    char *logPrefix) {
    const UA_UserTokenPolicy *utp =
        findUserTokenPolicy(client, &client->endpoint, logPrefix);
    if(!utp) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "%s: Could not find a matching UserTokenPolicy "
                     "in the endpoint", logPrefix);
        return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
    }

    UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                "%s: Using UserTokenPolicy %S", logPrefix, utp->policyId);

    /* If not specifically defined in the UserTokenPolicy, then the
     * SecurityPolicy of the underlying endpoint (SecureChannel) is used. */
    UA_String tokenSecurityPolicyUri = (utp->securityPolicyUri.length > 0) ?
        utp->securityPolicyUri : client->endpoint.securityPolicyUri;

    /* Get the SecurityPolicy for the UserIdentityToken. X509 tokens sign with
     * a private key, so they must use an authSecurityPolicy (matched by
     * PolicyUri and certificate). Other tokens only encrypt with the server
     * certificate, so fall back to the SecureChannel securityPolicies. */
    UA_SecurityPolicy *utsp;
    if(utp->tokenType == UA_USERTOKENTYPE_CERTIFICATE) {
        UA_X509IdentityToken *token = (UA_X509IdentityToken*)
            client->config.userIdentityToken.content.decoded.data;
        utsp = getAuthSecurityPolicy(client, tokenSecurityPolicyUri,
                                     &token->certificateData);
    } else {
        utsp = getAuthSecurityPolicy(client, tokenSecurityPolicyUri, NULL);
        if(!utsp)
            utsp = getSecurityPolicy(client, tokenSecurityPolicyUri);
    }
    if(!utsp) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "%s: SecurityPolicy %S not available for the "
                     "UserTokenPolicy", logPrefix, tokenSecurityPolicyUri);
        return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
    }

    /* ExistingSecurityPolicy matches? */
    if(client->utpSp) {
        if(!UA_String_equal(&client->utpSp->policyUri,
                            &tokenSecurityPolicyUri)) {
            UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                         "%s: SecurityPolicy %S cannot be instantiated. "
                         "A different SecurityPolicy %S is in place already",
                         logPrefix, tokenSecurityPolicyUri,
                         client->utpSp->policyUri);
            return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
        }

        /* Set the output and return */
        *outUtp = utp;
        return UA_STATUSCODE_GOOD;
    }

    /* Create an instance of the SecurityPolicy using the server certificate
     * from the endpoint */
    UA_StatusCode res =
        utsp->newChannelContext(utsp, &client->endpoint.serverCertificate,
                                &client->utpSpContext);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "%s: UserTokenPolicy %S could not be instantiated with the "
                     "server certificate", logPrefix, tokenSecurityPolicyUri);
        return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
    }
    client->utpSp = utsp;

    /* Set the output and return */
    *outUtp = utp;
    return UA_STATUSCODE_GOOD;
}

/* Legacy (pre-v1.05.07) signature: the leaf of the remote (peer) certificate
 * concatenated with the server's session nonce, signed with the given
 * SecurityPolicy/context. Shared by the application ClientSignature and the
 * X.509 user-token signature. The leaf is used (not the raw, possibly-chained
 * remoteCertificate) so the bytes match the server's verify, which is computed
 * over its single localCertificate. */
static UA_StatusCode
signLegacyCertNonce(const UA_SecurityPolicy *sp, void *spContext,
                    const UA_ByteString *remoteCertificate,
                    const UA_ByteString *serverNonce, UA_ByteString *outSignature) {
    UA_ByteString leaf = getLeafCertificate(*remoteCertificate);
    size_t signDataSize = leaf.length + serverNonce->length;
    if(signDataSize > MAX_DATA_SIZE)
        return UA_STATUSCODE_BADINTERNALERROR;
    UA_Byte buf[MAX_DATA_SIZE];
    UA_ByteString signData = {signDataSize, buf};
    memcpy(buf, leaf.data, leaf.length);
    memcpy(buf + leaf.length, serverNonce->data, serverNonce->length);
    return sp->asymSignatureAlgorithm.sign(sp, spContext, &signData, outSignature);
}

/* Function to create a signature using remote certificate and nonce.
 * This uses the SecurityPolicy of the SecureChannel. */
static UA_StatusCode
signClientSignature(UA_Client *client, UA_ActivateSessionRequest *request) {
    UA_SecureChannel *channel = &client->channel;
    const UA_SecurityPolicy *sp = channel->securityPolicy;
    void *cc = channel->channelContext;

    UA_SignatureData *sd = &request->clientSignature;
    const UA_SecurityPolicySignatureAlgorithm *signAlg = &sp->asymSignatureAlgorithm;

    /* OPC UA Part 4 v1.05.07: for SecurityPolicies with
     * secureChannelEnhancements = true, the algorithm field in
     * SignatureData shall be NULL or empty and receivers shall
     * ignore the value. */
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
    if(!UA_SecurityPolicy_isEnhancedSecurity(sp))
        retval = UA_String_copy(&signAlg->uri, &sd->algorithm);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    /* Allocate memory for the signature */
    size_t signatureSize = signAlg->getLocalSignatureSize(sp, cc);
    retval = UA_ByteString_allocBuffer(&sd->signature, signatureSize);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    if(UA_SecurityPolicy_isEnhancedSecurity(sp)) {
        /* Channel-bound v1.05.07 ClientSignature (see the cert-role table at
         * UA_SecureChannel_buildActivateSessionSignatureData). */
        UA_ByteString signData = UA_BYTESTRING_NULL;
        retval = UA_SecureChannel_buildActivateSessionSignatureData(
            channel, &client->serverSessionNonce, &client->clientSessionNonce,
            &channel->remoteCertificate, &channel->remoteCertificate,
            &sp->localCertificate, &signData);
        if(retval != UA_STATUSCODE_GOOD)
            return retval;
        retval = signAlg->sign(sp, cc, &signData, &sd->signature);
        UA_ByteString_clear(&signData);
        return retval;
    }

    /* Legacy (v1.05.06): leaf(serverCert) + serverNonce. */
    return signLegacyCertNonce(sp, cc, &channel->remoteCertificate,
                               &client->serverSessionNonce, &sd->signature);
}

/* This uses the SecurityPolicy of the UserTokenPolicy */
static UA_StatusCode
signUserTokenSignature(UA_Client *client,
                       UA_ActivateSessionRequest *request) {
    UA_assert(client->config.userIdentityToken.content.decoded.type ==
              &UA_TYPES[UA_TYPES_X509IDENTITYTOKEN]);

    UA_SecurityPolicy *utpSp = client->utpSp;
    UA_assert(utpSp);

    UA_SecureChannel *channel = &client->channel;
    UA_SecurityPolicySignatureAlgorithm *signAlg = &utpSp->asymSignatureAlgorithm;
    UA_SignatureData *utsd = &request->userTokenSignature;

    /* Stricter servers reject an empty user-token algorithm - so always send
     * the policy's signature URI (the AesGcm policy carries its SecurityPolicy
     * URI there; RSA carries the RSA URI; plain ECC carries an empty
     * string). */
    UA_StatusCode retval = UA_String_copy(&signAlg->uri, &utsd->algorithm);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    /* Allocate memory for the signature */
    size_t sigLen = signAlg->getLocalSignatureSize(utpSp, client->utpSpContext);
    retval = UA_ByteString_allocBuffer(&utsd->signature, sigLen);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    /* Channel-bound v1.05.07 user-token signature (see the cert-role table at
     * UA_SecureChannel_buildUserTokenSignatureData), produced with the user's
     * private key (utpSp context). Used only when BOTH the SecureChannel AND the
     * user-token SecurityPolicy are enhanced; a legacy RSA / old-ECC user token
     * uses the legacy layout even over an enhanced (AesGcm) SecureChannel. */
    if(UA_SecurityPolicy_isEnhancedSecurity(channel->securityPolicy) &&
       UA_SecurityPolicy_isEnhancedSecurity(utpSp)) {
        const UA_ByteString *clientCert = &channel->securityPolicy->localCertificate;
        UA_ByteString signData = UA_BYTESTRING_NULL;
        retval = UA_SecureChannel_buildUserTokenSignatureData(
            channel, &client->serverSessionNonce, &client->clientSessionNonce,
            &channel->remoteCertificate, &channel->remoteCertificate,
            clientCert, clientCert, &signData);
        if(retval == UA_STATUSCODE_GOOD)
            retval = signAlg->sign(utpSp, client->utpSpContext, &signData, &utsd->signature);
        UA_ByteString_clear(&signData);
        return retval;
    }

    /* Legacy (v1.05.06): leaf(serverCert) + serverNonce (same as the
     * application ClientSignature), signed with the user's key. */
    return signLegacyCertNonce(utpSp, client->utpSpContext,
                               &channel->remoteCertificate,
                               &client->serverSessionNonce, &utsd->signature);
}

/* UserName and IssuedIdentity can be encrypted. This uses the SecurityPolicy
 * instance for the UserTokenPolicy. So it can keep the ECC ephemeral keys
 * across multiple SecureChannels. */
static UA_StatusCode
encryptUserIdentityToken(UA_Client *client, UA_ExtensionObject *userIdentityToken) {
    UA_IssuedIdentityToken *iit = NULL;
    UA_UserNameIdentityToken *unit = NULL;
    UA_String *encryptionAlg;
    UA_ByteString *tokenData;

    const UA_DataType *tokenType = userIdentityToken->content.decoded.type;
    if(tokenType == &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN]) {
        iit = (UA_IssuedIdentityToken*)userIdentityToken->content.decoded.data;
        tokenData = &iit->tokenData;
        encryptionAlg = &iit->encryptionAlgorithm;
    } else { /* tokenType == &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN] */
        UA_assert(tokenType == &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN]);
        unit = (UA_UserNameIdentityToken*)userIdentityToken->content.decoded.data;
        tokenData = &unit->password;
        encryptionAlg = &unit->encryptionAlgorithm;
    }

    /* The sessionSp is instantiated during CreateSession */
    UA_SecurityPolicy *utpSp = client->utpSp;
    UA_assert(utpSp);

    /* Nothing to encrypt */
    if(utpSp->policyType == UA_SECURITYPOLICYTYPE_NONE) {
        /* Warn if a token is transmitted in cleartext. This needs to be allowed
         * with the allowNonePolicyPassword setting and is checked in
         * findUserTokenPolicy. */
        if(client->channel.securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
            UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                           "!!! Warning !!! AuthenticationToken is transmitted "
                           "without encryption");
        return UA_STATUSCODE_GOOD;
    }

    /* Encrypt the TokenData */
    UA_StatusCode res = UA_STATUSCODE_GOOD;
    if(UA_SecurityPolicy_isEcc(utpSp)) {
        res = encryptUserIdentityTokenEcc(client->config.logging, &client->channel,
                                          utpSp, client->utpSpContext, tokenData,
                                          client->serverSessionNonce,
                                          client->serverEphemeralPubKey);
        /* Don't reuse the Ephemeral Public Key */
        UA_ByteString_clear(&client->serverEphemeralPubKey);

        /* The EccEncryptedSecret identifies its algorithm via the SecurityPolicy
         * URI embedded in the secret header, so the UserIdentityToken's
         * encryptionAlgorithm field is left EMPTY (matching the OPC UA reference
         * stack, which sets it to null for the EncryptedSecret format). Sending
         * the policy's asymEncryptionAlgorithm URI here makes strict servers
         * reject the token with BadIdentityTokenInvalid */
        return res;
    }

    res = encryptSecretLegacy(utpSp, client->utpSpContext,
                              client->serverSessionNonce, tokenData);

    /* Legacy RSA EncryptedData: carry the asymmetric encryption algorithm URI */
    return res | UA_String_copy(&utpSp->asymEncryptionAlgorithm.uri, encryptionAlg);
}

/* Verifies the signature corresponds to ClientNonce using the SecurityPolicy of
 * the SecureChannel */
static UA_StatusCode
checkCreateSessionSignature(UA_Client *client, const UA_SecureChannel *channel,
                            const UA_CreateSessionResponse *response) {
    if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
       channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
        return UA_STATUSCODE_GOOD;

    if(!channel->securityPolicy)
        return UA_STATUSCODE_BADINTERNALERROR;

    const UA_SecurityPolicy *sp = channel->securityPolicy;
    const UA_ByteString *lc = &sp->localCertificate;

    UA_ByteString dataToVerify = UA_BYTESTRING_NULL;
    UA_StatusCode retval;
    if(UA_SecurityPolicy_isEnhancedSecurity(sp)) {
        /* Channel-bound v1.05.07 CreateSession ServerSignature (see the
         * cert-role table at UA_SecureChannel_buildCreateSessionSignatureData). */
        retval = UA_SecureChannel_buildCreateSessionSignatureData(
            channel, &client->clientSessionNonce, &response->serverNonce,
            &channel->remoteCertificate, lc, &dataToVerify);
    } else {
        retval = UA_ByteString_allocBuffer(&dataToVerify,
                                           lc->length + client->clientSessionNonce.length);
        if(retval == UA_STATUSCODE_GOOD) {
            memcpy(dataToVerify.data, lc->data, lc->length);
            memcpy(dataToVerify.data + lc->length, client->clientSessionNonce.data,
                   client->clientSessionNonce.length);
        }
    }
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    const UA_SecurityPolicySignatureAlgorithm *signAlg = &sp->asymSignatureAlgorithm;
    retval = signAlg->verify(sp, channel->channelContext, &dataToVerify,
                             &response->serverSignature.signature);
    UA_ByteString_clear(&dataToVerify);
    return retval;
}

/***********************/
/* Open the Connection */
/***********************/

void
processERRResponse(UA_Client *client, const UA_ByteString *chunk) {
    size_t offset = 0;
    UA_TcpErrorMessage errMessage;
    UA_StatusCode res =
        UA_decodeBinaryInternal(chunk, &offset, &errMessage,
                                &UA_TRANSPORT[UA_TRANSPORT_TCPERRORMESSAGE], NULL);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(client->config.logging, &client->channel,
                             "Received an ERR response that could not be decoded "
                             "with StatusCode %s", UA_StatusCode_name(res));
        setConnectStatus(client, res);
        return;
    }

    UA_LOG_ERROR_CHANNEL(client->config.logging, &client->channel,
                         "Received an ERR response with StatusCode %s and "
                         "the following reason: \"%S\"",
                         UA_StatusCode_name(errMessage.error),
                         errMessage.reason);
    setConnectStatus(client, errMessage.error);
    UA_TcpErrorMessage_clear(&errMessage);
}

void
processACKResponse(UA_Client *client, const UA_ByteString *chunk) {
    UA_SecureChannel *channel = &client->channel;
    if(channel->state != UA_SECURECHANNELSTATE_HEL_SENT) {
        UA_LOG_ERROR_CHANNEL(client->config.logging, channel,
                             "SecureChannel not in the HEL-sent state");
        setConnectStatus(client, UA_STATUSCODE_BADSECURECHANNELCLOSED);
        return;
    }

    /* Decode the message */
    size_t offset = 0;
    UA_TcpAcknowledgeMessage ackMessage;
    UA_StatusCode res =
        UA_decodeBinaryInternal(chunk, &offset, &ackMessage,
                                &UA_TRANSPORT[UA_TRANSPORT_TCPACKNOWLEDGEMESSAGE], NULL);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_NETWORK,
                     "Decoding ACK message failed");
        setConnectStatus(client, res);
        return;
    }

    res = UA_SecureChannel_processHELACK(channel, &ackMessage);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_NETWORK,
                     "Processing the ACK message failed with StatusCode %s",
                     UA_StatusCode_name(res));
        setConnectStatus(client, res);
        return;
    }

    client->channel.state = UA_SECURECHANNELSTATE_ACK_RECEIVED;
}

static UA_StatusCode
sendHELMessage(UA_Client *client) {
    UA_ConnectionManager *cm = client->channel.connectionManager;
    if(!UA_SecureChannel_isConnected(&client->channel))
        return UA_STATUSCODE_BADNOTCONNECTED;

    /* Get a buffer */
    UA_ByteString message;
    UA_StatusCode retval = cm->allocNetworkBuffer(cm, client->channel.connectionId,
                                                  &message, UA_MINMESSAGESIZE);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    /* Prepare the HEL message and encode at offset 8 */
    UA_TcpHelloMessage hello;
    hello.protocolVersion = 0;
    hello.receiveBufferSize = client->config.localConnectionConfig.recvBufferSize;
    hello.sendBufferSize = client->config.localConnectionConfig.sendBufferSize;
    hello.maxMessageSize = client->config.localConnectionConfig.localMaxMessageSize;
    hello.maxChunkCount = client->config.localConnectionConfig.localMaxChunkCount;
    hello.endpointUrl = getEndpointUrl(client);

    UA_Byte *bufPos = &message.data[8]; /* skip the header */
    const UA_Byte *bufEnd = &message.data[message.length];
    retval = UA_encodeBinaryInternal(&hello, &UA_TRANSPORT[UA_TRANSPORT_TCPHELLOMESSAGE],
                                     &bufPos, &bufEnd, NULL, NULL, NULL);
    if(retval != UA_STATUSCODE_GOOD) {
        cm->freeNetworkBuffer(cm, client->channel.connectionId, &message);
        return retval;
    }

    /* Encode the message header at offset 0 */
    UA_TcpMessageHeader messageHeader;
    messageHeader.messageTypeAndChunkType = UA_CHUNKTYPE_FINAL + UA_MESSAGETYPE_HEL;
    messageHeader.messageSize = (UA_UInt32) ((uintptr_t)bufPos - (uintptr_t)message.data);
    bufPos = message.data;
    retval = UA_encodeBinaryInternal(&messageHeader,
                                     &UA_TRANSPORT[UA_TRANSPORT_TCPMESSAGEHEADER],
                                     &bufPos, &bufEnd, NULL, NULL, NULL);
    if(retval != UA_STATUSCODE_GOOD) {
        cm->freeNetworkBuffer(cm, client->channel.connectionId, &message);
        return retval;
    }

    /* Send the HEL message */
    message.length = messageHeader.messageSize;
    retval = cm->sendWithConnection(cm, client->channel.connectionId,
                                    &UA_KEYVALUEMAP_NULL, &message);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "Sending HEL failed");
        setConnectStatus(client, retval);
        return retval;
    }

    UA_LOG_DEBUG(client->config.logging, UA_LOGCATEGORY_CLIENT,
                 "Sent HEL message");

    client->channel.state = UA_SECURECHANNELSTATE_HEL_SENT;
    return UA_STATUSCODE_GOOD;
}

void processRHEMessage(UA_Client *client, const UA_ByteString *chunk) {
    UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT, "RHE received");

    size_t offset = 0; /* Go to the beginning of the TcpHelloMessage */
    UA_TcpReverseHelloMessage rheMessage;
    static const UA_DataType *rheType = &UA_TRANSPORT[UA_TRANSPORT_TCPREVERSEHELLOMESSAGE];
    UA_StatusCode res = UA_decodeBinaryInternal(chunk, &offset, &rheMessage, rheType, NULL);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_NETWORK,
                     "Decoding RHE message failed");
        setConnectStatus(client, res);
        return;
    }

    /* Set the internal DisocveryUrl */
    UA_String_clear(&client->discoveryUrl);
    client->discoveryUrl = rheMessage.endpointUrl;
    UA_String_init(&rheMessage.endpointUrl);
    UA_TcpReverseHelloMessage_clear(&rheMessage);

    /* Send the HEL message */
    setConnectStatus(client, sendHELMessage(client));
}

void
processOPNResponse(UA_Client *client, const UA_ByteString *message) {
    size_t offset = 0;
    UA_NodeId responseId;
    UA_OpenSecureChannelResponse response;
    UA_NodeId expectedId = UA_NS0ID(OPENSECURECHANNELRESPONSE_ENCODING_DEFAULTBINARY);

    /* Decode the type NodeId */
    UA_StatusCode res = UA_NodeId_decodeBinary(message, &offset, &responseId);
    if(res != UA_STATUSCODE_GOOD)
        goto finish_decode;

    /* Is the response of the expected type? */
    if(!UA_NodeId_equal(&responseId, &expectedId)) {
        res = UA_STATUSCODE_BADDECODINGERROR;
        goto finish_decode;
    }

    /* Decode the response */
    res = UA_decodeBinaryInternal(message, &offset, &response,
                                  &UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE], NULL);

    finish_decode:
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(client->config.logging, &client->channel,
                             "Could not decode the OpenSecureChannelResponse");
        setConnectStatus(client, res);
        return;
    }

    /* Check whether the nonce was reused */
    if(client->channel.securityMode != UA_MESSAGESECURITYMODE_NONE &&
       UA_ByteString_equal(&client->channel.remoteNonce, &response.serverNonce)) {
        UA_LOG_ERROR_CHANNEL(client->config.logging, &client->channel,
                             "The server reused the last nonce");
        setConnectStatus(client, UA_STATUSCODE_BADSECURITYCHECKSFAILED);
        return;
    }

    /* Check the nonce length */
    if(response.serverNonce.length < client->channel.securityPolicy->nonceLength) {
        UA_LOG_ERROR_CHANNEL(client->config.logging, &client->channel,
                             "The server nonce is too short");
        setConnectStatus(client, UA_STATUSCODE_BADSECURITYCHECKSFAILED);
        return;
    }

    /* Move the nonce out of the response */
    UA_ByteString_clear(&client->channel.remoteNonce);
    client->channel.remoteNonce = response.serverNonce;
    UA_ByteString_init(&response.serverNonce);
    UA_ResponseHeader_clear(&response.responseHeader);

    /* Replace the token. Keep the current token as the old token. Messages
     * might still arrive for the old token. */
    client->channel.altSecurityToken = client->channel.securityToken;
    client->channel.securityToken = response.securityToken;
    client->channel.renewState = UA_SECURECHANNELRENEWSTATE_NEWTOKEN_CLIENT;

    /* Log a warning if the SecurityToken is not "fresh". Use the normal system
     * clock to do the comparison. */
    UA_EventLoop *el = client->config.eventLoop;
    UA_DateTime wallClockNow = el->dateTime_now(el);
    UA_ChannelSecurityToken *st = &client->channel.securityToken;
    if(wallClockNow - st->createdAt >= UA_DATETIME_SEC * 10 ||
       wallClockNow - st->createdAt <= -UA_DATETIME_SEC * 10)
        UA_LOG_WARNING_CHANNEL(client->config.logging, &client->channel,
                               "The \"CreatedAt\" timestamp of the received "
                               "ChannelSecurityToken does not match "
                               "with the local system clock");

    /* The internal "monotonic" clock is used by the SecureChannel to validate
     * that the SecurityToken is still valid. The monotonic clock is independent
     * from the system clock getting changed or synchronized to a master clock
     * during runtime. */
    client->channel.securityToken.createdAt = el->dateTime_nowMonotonic(el);

    /* Response.securityToken.revisedLifetime is UInt32, we need to cast it to
     * DateTime=Int64. After 75% of the lifetime the renewal takes place as
     * described in standard */
    client->nextChannelRenewal = client->channel.securityToken.createdAt +
        (UA_DateTime) (response.securityToken.revisedLifetime *
                       (UA_Double) UA_DATETIME_MSEC * 0.75);

    /* Compute the new local keys. The remote keys are updated when a message
     * with the new SecurityToken is received. */
    res = UA_SecureChannel_generateLocalKeys(&client->channel);
    if(res != UA_STATUSCODE_GOOD) {
        setConnectStatus(client, res);
        return;
    }

    UA_Float lifetime = (UA_Float)response.securityToken.revisedLifetime / 1000;
    UA_Boolean renew = (client->channel.state == UA_SECURECHANNELSTATE_OPEN);
    if(renew) {
        UA_LOG_INFO_CHANNEL(client->config.logging, &client->channel, "SecureChannel "
                            "renewed with a revised lifetime of %.2fs", lifetime);
    } else {
        UA_LOG_INFO_CHANNEL(client->config.logging, &client->channel,
                            "SecureChannel opened with SecurityMode %s for "
                            "SecurityPolicy %S and a revised lifetime of %.2fs",
                            securityModeNames[client->channel.securityMode],
                            client->channel.securityPolicy->policyUri,
                            lifetime);
    }

    client->channel.state = UA_SECURECHANNELSTATE_OPEN;
}

/* OPN messges to renew the channel are sent asynchronous */
static UA_StatusCode
sendOPNAsync(UA_Client *client, UA_Boolean renew) {
    if(!UA_SecureChannel_isConnected(&client->channel))
        return UA_STATUSCODE_BADINTERNALERROR;

    UA_StatusCode res = UA_SecureChannel_generateLocalNonce(&client->channel);
    if(res != UA_STATUSCODE_GOOD)
        return res;

    UA_EventLoop *el = client->config.eventLoop;

    /* Prepare the OpenSecureChannelRequest */
    UA_OpenSecureChannelRequest opnSecRq;
    UA_OpenSecureChannelRequest_init(&opnSecRq);
    opnSecRq.requestHeader.timestamp = el->dateTime_now(el);
    opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
    opnSecRq.securityMode = client->channel.securityMode;
    opnSecRq.clientNonce = client->channel.localNonce;
    opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
    if(renew) {
        opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
        UA_LOG_DEBUG_CHANNEL(client->config.logging, &client->channel,
                             "Requesting to renew the SecureChannel");
    } else {
        opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
        UA_LOG_DEBUG_CHANNEL(client->config.logging, &client->channel,
                             "Requesting to open a SecureChannel");
    }

    /* Prepare the entry for the linked list */
    UA_UInt32 requestId = ++client->requestId;

    /* Send the OPN message */
    UA_LOG_DEBUG(client->config.logging, UA_LOGCATEGORY_SECURECHANNEL,
                 "Requesting to open a SecureChannel");
    static const UA_DataType *opnReqType = &UA_TYPES[UA_TYPES_OPENSECURECHANNELREQUEST];
    res = UA_SecureChannel_sendOPN(&client->channel, requestId, &opnSecRq, opnReqType);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_SECURECHANNEL,
                      "Sending OPN message failed with error %s",
                      UA_StatusCode_name(res));
        return res;
    }

    /* Update the state */
    client->channel.renewState = UA_SECURECHANNELRENEWSTATE_SENT;
    if(client->channel.state < UA_SECURECHANNELSTATE_OPN_SENT)
        client->channel.state = UA_SECURECHANNELSTATE_OPN_SENT;

    UA_LOG_DEBUG(client->config.logging, UA_LOGCATEGORY_SECURECHANNEL,
                 "OPN message sent");

    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
__Client_renewSecureChannel(UA_Client *client) {
    UA_LOCK_ASSERT(&client->clientMutex);

    UA_EventLoop *el = client->config.eventLoop;
    UA_DateTime now = el->dateTime_nowMonotonic(el);

    /* Check if OPN has been sent or the SecureChannel is still valid */
    if(client->channel.state != UA_SECURECHANNELSTATE_OPEN ||
       client->channel.renewState == UA_SECURECHANNELRENEWSTATE_SENT ||
       client->nextChannelRenewal > now)
        return UA_STATUSCODE_GOODCALLAGAIN;

    UA_StatusCode res = sendOPNAsync(client, true);
    setConnectStatus(client, res);

    return res;
}

UA_StatusCode
UA_Client_renewSecureChannel(UA_Client *client) {
    lockClient(client);
    UA_StatusCode res = __Client_renewSecureChannel(client);
    unlockClient(client);
    return res;
}

static void
responseReadNamespacesArray(UA_Client *client, void *userdata,
                            UA_UInt32 requestId, void *response) {
    client->namespacesHandshake = false;
    client->haveNamespaces = true;

    UA_ReadResponse *resp = (UA_ReadResponse *)response;

    /* Add received namespaces to the local array. */
    if(!resp->results || !resp->results[0].value.data) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "No result in the read namespace array response");
        return;
    }
    UA_String *ns = (UA_String *)resp->results[0].value.data;
    size_t nsSize = resp->results[0].value.arrayLength;
    UA_String_copy(&ns[1], &client->namespaces[1]);
    for(size_t i = 2; i < nsSize; ++i) {
        UA_UInt16 nsIndex = 0;
        UA_Client_addNamespace(client, ns[i], &nsIndex);
    }

    /* Set up the mapping. */
    UA_NamespaceMapping *nsMapping = (UA_NamespaceMapping*)
        UA_calloc(1, sizeof(UA_NamespaceMapping));
    if(!nsMapping) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Namespace mapping creation failed. Out of Memory.");
        return;
    }
    UA_StatusCode retval =
        UA_Array_copy(client->namespaces, client->namespacesSize,
                      (void**)&nsMapping->namespaceUris,
                      &UA_TYPES[UA_TYPES_STRING]);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Failed to copy the namespaces with StatusCode %s.",
                     UA_StatusCode_name(retval));
        UA_NamespaceMapping_delete(nsMapping);
        return;
    }
    nsMapping->namespaceUrisSize = client->namespacesSize;

    nsMapping->remote2local = (UA_UInt16*)UA_calloc( nsSize, sizeof(UA_UInt16));
    if(!nsMapping->remote2local) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Namespace mapping creation failed. Out of Memory.");
        UA_NamespaceMapping_delete(nsMapping);
        return;
    }
    nsMapping->remote2localSize = nsSize;
    nsMapping->remote2local[0] = 0;
    nsMapping->remote2local[1] = 1;

    for(size_t i = 2; i < nsSize; ++i) {
        UA_UInt16 nsIndex = 0;
        UA_Client_getNamespaceIndex(client, ns[i], &nsIndex);
        nsMapping->remote2local[i] = nsIndex;
    }

    size_t l2rSize = client->namespacesSize > nsSize ? client->namespacesSize : nsSize;
    nsMapping->local2remote = (UA_UInt16*)UA_calloc(l2rSize, sizeof(UA_UInt16));
    if(!nsMapping->local2remote) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Namespace mapping creation failed. Out of Memory.");
        UA_NamespaceMapping_delete(nsMapping);
        return;
    }
    nsMapping->local2remoteSize = l2rSize;
    nsMapping->local2remote[0] = 0;
    nsMapping->local2remote[1] = 1;

    for(size_t i = 2; i < nsMapping->remote2localSize; ++i) {
        UA_UInt16 localIndex = nsMapping->remote2local[i];
        nsMapping->local2remote[localIndex] = (UA_UInt16)i;
    }

    client->channel.namespaceMapping = nsMapping;
}

/* We read the namespaces right after the session has opened. The user might
 * already requests other services in parallel. That leaves a short time where
 * requests can be made before the namespace mapping is configured. */
static void
readNamespacesArrayAsync(UA_Client *client) {
    UA_LOCK_ASSERT(&client->clientMutex);

    /* Check the connection status */
    if(client->sessionState != UA_SESSIONSTATE_CREATED &&
       client->sessionState != UA_SESSIONSTATE_ACTIVATED) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Cannot read the namespaces array, session neither created nor "
                     "activated. Actual state: '%u'", client->sessionState);
        return;
    }

    /* Set up the read request */
    UA_ReadRequest rr;
    UA_ReadRequest_init(&rr);

    UA_ReadValueId nodesToRead;
    UA_ReadValueId_init(&nodesToRead);
    nodesToRead.nodeId = UA_NS0ID(SERVER_NAMESPACEARRAY);
    nodesToRead.attributeId = UA_ATTRIBUTEID_VALUE;

    rr.nodesToRead = &nodesToRead;
    rr.nodesToReadSize = 1;

    /* Send the async read request */
    UA_StatusCode res =
        __Client_AsyncService(client, &rr, &UA_TYPES[UA_TYPES_READREQUEST],
                              (UA_ClientAsyncServiceCallback)responseReadNamespacesArray,
                              &UA_TYPES[UA_TYPES_READRESPONSE],
                              NULL, NULL);

    if(res == UA_STATUSCODE_GOOD)
        client->namespacesHandshake = true;
    else
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Could not read the namespace array with error code %s",
                     UA_StatusCode_name(res));
}

static void
extractEphemeralKeyFromAddHeader(UA_Client *client, UA_ExtensionObject *ah) {
    const UA_DataType *ahType = &UA_TYPES[UA_TYPES_ADDITIONALPARAMETERSTYPE];
    if(!UA_ExtensionObject_hasDecodedType(ah, ahType))
        return;

    UA_LOG_DEBUG(client->config.logging, UA_LOGCATEGORY_SESSION,
                 "Server Ephemeral Key in the response");

    /* KeyValueMap has the identical structure the UA_AdditionalParametersType */
    UA_KeyValueMap *map = (UA_KeyValueMap*)ah->content.decoded.data;

    /* TODO: Handle the ECDHPolicyUri */

    /* Get the Ephemeral Key */
    UA_EphemeralKeyType *ephKey = (UA_EphemeralKeyType*)(uintptr_t)
        UA_KeyValueMap_getScalar(map, UA_QUALIFIEDNAME(0, "ECDHKey"),
                                 &UA_TYPES[UA_TYPES_EPHEMERALKEYTYPE]);
    if(!ephKey)
        return; /* TODO: Security error? */

    /* Move the Ephemeral Key into the client */
    UA_ByteString_clear(&client->serverEphemeralPubKey);
    client->serverEphemeralPubKey = ephKey->publicKey;
    UA_ByteString_init(&ephKey->publicKey);

    /* TODO: Validate the signature of the ephemeral key */
}

static void
responseActivateSession(UA_Client *client, void *userdata,
                        UA_UInt32 requestId, void *response) {
    UA_LOCK_ASSERT(&client->clientMutex);

    UA_ActivateSessionResponse *ar = (UA_ActivateSessionResponse*)response;
    if(ar->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
        /* Activating the Session failed */
        cleanupSession(client);

        /* Configuration option to not create a new Session */
        if(client->config.noNewSession) {
            UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                         "Session cannot be activated with StatusCode %s. "
                         "The client is configured not to create a new Session.",
                         UA_StatusCode_name(ar->responseHeader.serviceResult));
            setConnectStatus(client, ar->responseHeader.serviceResult);
            return;
        }

        /* The Session is no longer usable. Create a brand new one. */
        if(ar->responseHeader.serviceResult == UA_STATUSCODE_BADSESSIONIDINVALID ||
           ar->responseHeader.serviceResult == UA_STATUSCODE_BADSESSIONCLOSED) {
            UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                           "Session to be activated no longer exists. Create a new Session.");
            setConnectStatus(client, createSessionAsync(client));
            return;
        }

        /* Something else is wrong. Maybe the credentials no longer work. Give up. */
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Session cannot be activated with StatusCode %s. "
                     "The client cannot recover from this, closing the connection.",
                     UA_StatusCode_name(ar->responseHeader.serviceResult));
        setConnectStatus(client, ar->responseHeader.serviceResult);
        return;
    }

    /* Check the (session) nonce length. The session nonce is the application
     * nonce (>= 32 bytes), independent of the SecurityPolicy's SecureChannel
     * nonce length (e.g. the 64-byte ECC ephemeral key). */
    if(ar->serverNonce.length < 32) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Session cannot be activated with a nonce "
                     "that is too short");
        setConnectStatus(client, UA_STATUSCODE_BADSECURITYCHECKSFAILED);
        return;
    }

    /* Replace the nonce */
    UA_ByteString_clear(&client->serverSessionNonce);
    client->serverSessionNonce = ar->serverNonce;
    UA_ByteString_init(&ar->serverNonce);

    /* Extract the server's ECC ephemeral public key from the ActivateSession
     * response */
    extractEphemeralKeyFromAddHeader(client, &ar->responseHeader.additionalHeader);

    client->sessionState = UA_SESSIONSTATE_ACTIVATED;
    notifyClientState(client);

    /* Read the namespaces array if we don't already have it */
    if(!client->haveNamespaces)
        readNamespacesArrayAsync(client);

    /* Immediately check if publish requests are outstanding - for example when
     * an existing Session has been reattached / activated. */
#ifdef UA_ENABLE_SUBSCRIPTIONS
    __Client_Subscriptions_backgroundPublish(client);
#endif
}

static UA_StatusCode
activateSessionAsync(UA_Client *client) {
    UA_LOCK_ASSERT(&client->clientMutex);

    /* We should not try to activate in the current state */
    if(client->sessionState != UA_SESSIONSTATE_CREATED &&
       client->sessionState != UA_SESSIONSTATE_ACTIVATED) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Can not activate session, session neither created nor activated. "
                     "Actual state: '%u'", client->sessionState);
        return UA_STATUSCODE_BADSESSIONCLOSED;
    }

    /* Select the UserTokenPolicy based on the client configuration and the
     * endpoint information. Also instantiates the UserTokenPolicy if not
     * already there. This can happen when an existing Session is
     * transferred. */
    const UA_UserTokenPolicy *utp = NULL;
    UA_StatusCode retval = initUserTokenPolicy(client, &utp, "ActivateSession");
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    /* Initialize the request */
    UA_ActivateSessionRequest request;
    UA_ActivateSessionRequest_init(&request);

    /* Set the requested LocaleIds */
    if(client->config.sessionLocaleIdsSize && client->config.sessionLocaleIds) {
        retval = UA_Array_copy(client->config.sessionLocaleIds,
                               client->config.sessionLocaleIdsSize,
                               (void **)&request.localeIds, &UA_TYPES[UA_TYPES_LOCALEID]);
        if(retval != UA_STATUSCODE_GOOD)
            return retval;
        request.localeIdsSize = client->config.sessionLocaleIdsSize;
    }

    /* Set the User Identity Token. If not defined use an anonymous token. Use
     * the PolicyId from the UserTokenPolicy. All token types have the PolicyId
     * string as the first element. */
    UA_AnonymousIdentityToken anonToken;
    retval = UA_ExtensionObject_copy(&client->config.userIdentityToken,
                                     &request.userIdentityToken);
    if(request.userIdentityToken.encoding != UA_EXTENSIONOBJECT_ENCODED_NOBODY) {
        UA_String *policyId = (UA_String*)request.userIdentityToken.content.decoded.data;
        UA_String_clear(policyId);
        retval = UA_String_copy(&utp->policyId, policyId);
        if(retval != UA_STATUSCODE_GOOD) {
            UA_ActivateSessionRequest_clear(&request);
            return retval;
        }
    } else {
        UA_AnonymousIdentityToken_init(&anonToken);
        UA_ExtensionObject_setValueNoDelete(&request.userIdentityToken, &anonToken,
                                            &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN]);
        anonToken.policyId = utp->policyId;
    }

    switch(utp->tokenType) {
    case UA_USERTOKENTYPE_ANONYMOUS:
        break; /* The anonymous token is not encrypted */
    case UA_USERTOKENTYPE_USERNAME:
    case UA_USERTOKENTYPE_ISSUEDTOKEN:
        /* Encrypt the UserIdentityToken */
        retval = encryptUserIdentityToken(client, &request.userIdentityToken);
        break;
    case UA_USERTOKENTYPE_CERTIFICATE:
        /* Create the UserTokenSignature */
        retval = signUserTokenSignature(client, &request);
        break;
    default:
        retval = UA_STATUSCODE_BADINTERNALERROR;
    }
    if(retval != UA_STATUSCODE_GOOD) {
        UA_ActivateSessionRequest_clear(&request);
        return retval;
    }

    /* Create the client signature with the SecurityPolicy of the SecureChannel */
    UA_SecureChannel *channel = &client->channel;
    if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
       channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
        retval |= signClientSignature(client, &request);

    /* Send the request */
    if(UA_LIKELY(retval == UA_STATUSCODE_GOOD))
        retval = __Client_AsyncService(client, &request,
                                       &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
                                       (UA_ClientAsyncServiceCallback)responseActivateSession,
                                       &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE],
                                       NULL, NULL);

    /* On success, advance the session state */
    if(retval == UA_STATUSCODE_GOOD)
        client->sessionState = UA_SESSIONSTATE_ACTIVATE_REQUESTED;
    else
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "ActivateSession failed when sending the request with error code %s",
                     UA_StatusCode_name(retval));

    /* Clean up */
    UA_ActivateSessionRequest_clear(&request);
    return retval;
}

static const UA_String binaryTransport =
    UA_STRING_STATIC("http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary");

/* Find a matching endpoint -- the UserTokenPolicy is matched later */
static UA_Boolean
matchEndpoint(UA_Client *client, const UA_EndpointDescription *endpoint, unsigned i) {
    /* Matching ApplicationUri if defined */
    if(client->config.applicationUri.length > 0 &&
       !UA_String_equal(&client->config.applicationUri,
                        &endpoint->server.applicationUri)) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "Endpoint %u: Rejected, the server's ApplicationUri %S "
                    "does not match the client configuration", i,
                    endpoint->server.applicationUri);
        return false;
    }

    /* Look out for binary transport endpoints.
     * Note: Siemens returns empty ProfileUrl, we will accept it as binary. */
    if(endpoint->transportProfileUri.length != 0 &&
       !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport)) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "Endpoint %u: Rejected, the TransportProfileUri %S "
                    "is not supported", i, endpoint->transportProfileUri);
        return false;
    }

    /* Valid SecurityMode? */
    if(endpoint->securityMode < 1 || endpoint->securityMode > 3) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "Endpoint %u: Rejected, invalid SecurityMode %u",
                    i, (unsigned)endpoint->securityMode);
        return false;
    }

    UA_MessageSecurityMode configuredSM = client->config.securityMode;
    if(configuredSM > UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Bad SecurityMode set in the client config");
        return false;
    }

    /* Selected SecurityMode? */
    if(configuredSM > 0 && configuredSM != endpoint->securityMode) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "Endpoint %u: Rejected, the SecurityMode %s "
                    "does not match the client configuration (%s)",
                    i, securityModeNames[endpoint->securityMode],
                    securityModeNames[configuredSM]);
        return false;
    }

    /* Matching SecurityPolicy? */
    if(client->config.securityPolicyUri.length > 0 &&
       !UA_String_equal(&client->config.securityPolicyUri,
                        &endpoint->securityPolicyUri)) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "Endpoint %u: Rejected, the SecurityPolicy %S does not "
                    "match the configuration", i, endpoint->securityPolicyUri);
        return false;
    }

    /* SecurityPolicy available? */
    if(!getSecurityPolicy(client, endpoint->securityPolicyUri)) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "Endpoint %u: Rejected, the SecurityPolicy %S not supported",
                    i, endpoint->securityPolicyUri);
        return false;
    }

    return true;
}

/* Match the policy with the configured user token */
static UA_Boolean
matchUserToken(UA_Client *client,
               const UA_UserTokenPolicy *tokenPolicy) {
    const UA_DataType *tokenType =
        client->config.userIdentityToken.content.decoded.type;

    if(tokenPolicy->tokenType == UA_USERTOKENTYPE_ANONYMOUS &&
       (tokenType == &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN] || !tokenType))
        return true;

    if(tokenPolicy->tokenType == UA_USERTOKENTYPE_USERNAME &&
       tokenType == &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN])
        return true;

    if(tokenPolicy->tokenType == UA_USERTOKENTYPE_CERTIFICATE &&
       tokenType == &UA_TYPES[UA_TYPES_X509IDENTITYTOKEN])
        return true;

    if(tokenPolicy->tokenType == UA_USERTOKENTYPE_ISSUEDTOKEN &&
       tokenType == &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN])
        return true;

    return false;
}

static UA_Boolean
matchUserTokenPolicy(UA_Client *client, UA_EndpointDescription *endpoint,
                     UA_UserTokenPolicy *utp, char *logPrefix) {
    /* Match with the configured UserToken */
    if(!matchUserToken(client, utp)) {
        if(logPrefix) {
            UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                        "%s: UserTokenPolicy %S rejected -- does not match "
                        "the type of UserIdentityToken configured in the client",
                        logPrefix, utp->policyId);
        }
        return false;
    }

    /* If not defined, use the SecurityPolicy of the SecureChannel */
    UA_String tokenPolicyUri =
        (UA_String_isEmpty(&utp->securityPolicyUri)) ?
        endpoint->securityPolicyUri : utp->securityPolicyUri;

    /* SecurityPolicyUri matches the configuration? */
    if(!UA_String_isEmpty(&client->config.authSecurityPolicyUri) &&
       !UA_String_equal(&client->config.authSecurityPolicyUri,
                        &tokenPolicyUri)) {
        if(logPrefix) {
            UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                        "%s: UserTokenPolicy %S rejected -- uses SecurityPolicy %S, "
                        "but the client configuration requires SecurityPolicy %S",
                        logPrefix, utp->policyId,
                        tokenPolicyUri, client->config.authSecurityPolicyUri);
        }
        return false;
    }

    /* Anoymous authentication */
    if(utp->tokenType == UA_USERTOKENTYPE_ANONYMOUS)
        return true;

    /* Get the SecurityPolicy for the UserIdentityToken (see
     * initUserTokenPolicy for the authSecurityPolicies/securityPolicies
     * lookup rationale). */
    UA_SecurityPolicy *utsp;
    if(utp->tokenType == UA_USERTOKENTYPE_CERTIFICATE) {
        UA_X509IdentityToken *token = (UA_X509IdentityToken*)
            client->config.userIdentityToken.content.decoded.data;
        utsp = getAuthSecurityPolicy(client, tokenPolicyUri,
                                     &token->certificateData);
    } else {
        utsp = getAuthSecurityPolicy(client, tokenPolicyUri, NULL);
        if(!utsp)
            utsp = getSecurityPolicy(client, tokenPolicyUri);
    }
    if(!utsp) {
        if(logPrefix) {
            UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                        "%s: UserTokenPolicy %S rejected -- the "
                        "SecurityPolicy %S is not available",
                        logPrefix, utp->policyId, tokenPolicyUri);
        }
        return false;
    }

    /* Check if a secret is transmitted in cleartext */
    if(endpoint->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT &&
       utsp->policyType == UA_SECURITYPOLICYTYPE_NONE) {
        if(!client->config.allowNonePolicyPassword) {
            if(logPrefix) {
                UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                            "%s: UserTokenPolicy %S rejected -- the "
                            "AuthenticationToken must not be transmitted "
                            "without encryption (override with"
                            "allowNonePolicyPassword setting)",
                            logPrefix, utp->policyId);
            }
            return false;
        }
    }

    /* Found a match */
    return true;
}

/* Returns a matching UserTokenPolicy from the EndpointDescription. If a
 * UserTokenPolicy is configured in the client config, then we need an exact
 * match. */
static UA_UserTokenPolicy *
findUserTokenPolicy(UA_Client *client, UA_EndpointDescription *endpoint,
                    char *logPrefix) {
    /* Was a UserTokenPolicy configured? Then we need an exact match. */
    UA_UserTokenPolicy *requiredTokenPolicy = NULL;
    UA_UserTokenPolicy tmp;
    UA_UserTokenPolicy_init(&tmp);
    if(!UA_equal(&tmp, &client->config.userTokenPolicy,
                 &UA_TYPES[UA_TYPES_USERTOKENPOLICY]))
        requiredTokenPolicy = &client->config.userTokenPolicy;

    /* Return the first UserTokenPolicy matching the config */
    for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
        UA_UserTokenPolicy *tokenPolicy = &endpoint->userIdentityTokens[j];

        /* Need the extact configured policy */
        if(requiredTokenPolicy &&
           !UA_equal(requiredTokenPolicy, tokenPolicy,
                     &UA_TYPES[UA_TYPES_USERTOKENPOLICY])) {
            if(logPrefix) {
                UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                            "%s: UserTokenPolicy %S rejected -- a different "
                            "UserTokenPolicy %S is specified in the client config",
                            logPrefix, tokenPolicy->policyId,
                            requiredTokenPolicy->policyId);
            }
            continue;
        }

        /* Match with the client configured */
        if(matchUserTokenPolicy(client, endpoint, tokenPolicy, logPrefix))
            return tokenPolicy;
    }

    return NULL;
}

/* Combination of UA_Client_getEndpointsInternal and getEndpoints */
static void
responseGetEndpoints(UA_Client *client, void *userdata,
                     UA_UInt32 requestId, void *response) {
    UA_LOCK_ASSERT(&client->clientMutex);

    client->endpointsHandshake = false;

    UA_LOG_DEBUG(client->config.logging, UA_LOGCATEGORY_CLIENT,
                 "Received GetEndpointsResponse");

    UA_GetEndpointsResponse *resp = (UA_GetEndpointsResponse*)response;

    /* GetEndpoints not possible. Fail the connection */
    if(resp->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
        /* Fail the connection attempt if the SecureChannel is still connected.
         * If the SecureChannel is (intentionally or unintentionally) closed,
         * the connectStatus should come from there. */
        if(UA_SecureChannel_isConnected(&client->channel)) {
           UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                        "GetEndpointRequest failed with error code %s",
                        UA_StatusCode_name(resp->responseHeader.serviceResult));
           setConnectStatus(client, resp->responseHeader.serviceResult);
        }

        UA_GetEndpointsResponse_clear(resp);
        return;
    }

    /* Warn if the Endpoints look incomplete / don't match the EndpointUrl */
    Client_warnEndpointsResult(client, resp, &client->discoveryUrl);

    const size_t notFound = (size_t)-1;
    size_t bestEndpointIndex = notFound;
    UA_Byte bestEndpointLevel = 0;
    UA_UserTokenPolicy *utp = NULL;

    /* Find a matching combination of Endpoint and UserTokenPolicy */
    for(size_t i = 0; i < resp->endpointsSize; ++i) {
        UA_EndpointDescription* endpoint = &resp->endpoints[i];

        /* Do we already have a better candidate? */
        if(endpoint->securityLevel < bestEndpointLevel) {
            UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                        "Endpoint %u: Rejected, better SecurityLevel found before",
                        (unsigned)i);
            continue;
        }

        /* Does the endpoint match the client configuration? */
        if(!matchEndpoint(client, endpoint, (unsigned)i))
            continue;

        /* Do we want a session? If yes, then the endpoint needs to have a
         * UserTokenPolicy that matches the configuration. */
        if(!client->config.noSession) {
            char logPrefix[32];
            mp_snprintf(logPrefix, 32, "Endpoint %u", (unsigned)i);
            utp = findUserTokenPolicy(client, endpoint, logPrefix);
            if(!utp) {
                UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                            "Endpoint %u: Rejected, no matching UserTokenPolicy",
                            (unsigned)i);
                continue;
            }
        }

        /* Best endpoint so far */
        bestEndpointLevel = endpoint->securityLevel;
        bestEndpointIndex = i;
        if(utp) {
            UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                        "Endpoint %u: Best endpoint so far with "
                        "UserTokenPolicy %S", (unsigned)i, utp->policyId);
        } else {
            UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                        "Endpoint %u: Best endpoint so far", (unsigned)i);
        }
    }

    /* No matching endpoint found */
    if(bestEndpointIndex == notFound) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "No suitable endpoint found");
        setConnectStatus(client, UA_STATUSCODE_BADIDENTITYTOKENREJECTED);
        return;
    }

    /* Store the endpoint description in the client. It contains the
     * ApplicationDescription and the UserTokenPolicies. We continue to look up
     * the matching UserTokenPolicy from there. */
    UA_EndpointDescription_clear(&client->endpoint);
    client->endpoint = resp->endpoints[bestEndpointIndex];
    UA_EndpointDescription_init(&resp->endpoints[bestEndpointIndex]);

    if(utp) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "Endpoint %u selected with SecurityMode "
                    "%s, SecurityPolicy %S and UserTokenPolicy %S",
                    bestEndpointIndex,
                    securityModeNames[client->endpoint.securityMode],
                    client->endpoint.securityPolicyUri,
                    utp->policyId);
    } else {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "Endpoint %u selected with SecurityMode "
                    "%s and SecurityPolicy %S", bestEndpointIndex,
                    securityModeNames[client->endpoint.securityMode],
                    client->endpoint.securityPolicyUri);
    }

    /* A different SecurityMode or SecurityPolicy is defined by the Endpoint.
     * Close the SecureChannel and reconnect. */
    UA_SecurityPolicy *sp = client->channel.securityPolicy;
    if(client->endpoint.securityMode != client->channel.securityMode ||
       !UA_String_equal(&client->endpoint.securityPolicyUri, &sp->policyUri)) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "A different SecurityMode or SecurityPolicy is defined "
                    "by the selected Endpoint. Close the SecureChannel "
                    "and reconnect.");
        closeSecureChannel(client);
        return;
    }

    /* We were using a distinct discovery URL and we are switching away from it.
     * Close the SecureChannel to reopen with the EndpointUrl. If an endpoint
     * was selected, then we use the endpointUrl for the HEL message. */
    if(client->discoveryUrl.length > 0 &&
       !UA_String_equal(&client->discoveryUrl, &client->endpoint.endpointUrl)) {
        UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                    "The selected endpoint defines an EndpointUrl %S different "
                    "from the Url %S used to connect before calling "
                    "GetEndpoints. Close the SecureChannel and reconnect with "
                    "the new EndpointUrl to ensure the Endpoint is available.",
                    client->discoveryUrl, client->endpoint.endpointUrl);
        closeSecureChannel(client);
        return;
    }

    /* We have selected an endpoint that we can use to open a Session on the
     * current SecureChannel. The remote certificate was validated during
     * processing of the OPN response. But if client->endpoint.serverCertificate
     * is empty we do not compare against the expectation from the endpoint. */

    /* Is the same certificate used for the SecureChannel and the selected
     * endpoint?
     *
     * Both the clientCertificate of this request and the remoteCertificate of
     * the channel may contain a partial or a complete certificate chain. The
     * compareCertificate function will compare the first certificate of each
     * chain. The end certificate shall be located first in the chain according
     * to the OPC UA specification Part 6 (1.04), chapter 6.2.3.*/
    if(client->channel.securityMode != UA_MESSAGESECURITYMODE_NONE) {
        void *cc = client->channel.channelContext;
        UA_StatusCode res = sp->compareCertificate(sp, cc,
                                                   &client->endpoint.serverCertificate);
        if(res != UA_STATUSCODE_GOOD) {
            UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                        "The selected endpoint defines a different server certificate "
                        "from then one used by the server for the initial SecureChannel "
                        "(to call GetEndpoints). Close the SecureChannel and reconnect.");
            closeSecureChannel(client);
            return;
        }
    }

    /* Continue with the current SecureChannel */
}

static UA_StatusCode
requestGetEndpoints(UA_Client *client) {
    UA_LOCK_ASSERT(&client->clientMutex);

    UA_GetEndpointsRequest request;
    UA_GetEndpointsRequest_init(&request);
    request.endpointUrl = getEndpointUrl(client);

    UA_StatusCode retval =
        __Client_AsyncService(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
                              (UA_ClientAsyncServiceCallback) responseGetEndpoints,
                              &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE], NULL, NULL);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "RequestGetEndpoints failed when sending the request with error code %s",
                     UA_StatusCode_name(retval));
        return retval;
    }

    client->endpointsHandshake = true;
    return UA_STATUSCODE_GOOD;
}

static void
responseFindServers(UA_Client *client, void *userdata,
                    UA_UInt32 requestId, void *response) {
    client->findServersHandshake = false;
    UA_LOG_DEBUG(client->config.logging, UA_LOGCATEGORY_CLIENT,
                 "Received FindServersResponse");

    /* Error handling. Log the error but continue to connect with the current
     * EndpointURL. */
    UA_FindServersResponse *fsr = (UA_FindServersResponse*)response;
    if(fsr->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                       "FindServers failed with error code %s. Continue with the "
                       "EndpointURL %S.",
                       UA_StatusCode_name(fsr->responseHeader.serviceResult),
                       client->config.endpointUrl);
        UA_String_clear(&client->discoveryUrl);
        UA_String_copy(&client->config.endpointUrl, &client->discoveryUrl);
        return;
    }

    /* Check if one of the returned servers matches the EndpointURL already used */
    for(size_t i = 0; i < fsr->serversSize; i++) {
        UA_ApplicationDescription *server = &fsr->servers[i];

        /* Filter by the ApplicationUri if defined */
        if(client->config.applicationUri.length > 0 &&
           !UA_String_equal(&client->config.applicationUri, &server->applicationUri))
            continue;

        for(size_t j = 0; j < server->discoveryUrlsSize; j++) {
            if(UA_String_equal(&client->config.endpointUrl, &server->discoveryUrls[j])) {
                UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                            "The initially defined EndpointURL %S "
                            "is valid for the server", client->config.endpointUrl);
                UA_String_clear(&client->discoveryUrl);
                client->discoveryUrl = server->discoveryUrls[j];
                UA_String_init(&server->discoveryUrls[j]);
                return;
            }
        }
    }

    /* The current EndpointURL is not usable. Pick the first "opc.tcp" DiscoveryUrl of a
     * returned server. */
    for(size_t i = 0; i < fsr->serversSize; i++) {
        UA_ApplicationDescription *server = &fsr->servers[i];
        if(server->applicationType != UA_APPLICATIONTYPE_SERVER &&
            server->applicationType != UA_APPLICATIONTYPE_CLIENTANDSERVER &&
            server->applicationType != UA_APPLICATIONTYPE_DISCOVERYSERVER)
            continue;

        /* Filter by the ApplicationUri if defined */
        if(client->config.applicationUri.length > 0 &&
           !UA_String_equal(&client->config.applicationUri, &server->applicationUri))
            continue;

        for(size_t j = 0; j < server->discoveryUrlsSize; j++) {
            /* Try to parse the DiscoveryUrl. This weeds out http schemas (etc.)
             * and invalid DiscoveryUrls in general. */
            UA_String hostname, path;
            UA_UInt16 port;
            UA_StatusCode res =
                UA_parseEndpointUrl(&server->discoveryUrls[j], &hostname, &port, &path);
            if(res != UA_STATUSCODE_GOOD)
                continue;

            /* Use this DiscoveryUrl in the client */
            UA_String_clear(&client->discoveryUrl);
            client->discoveryUrl = server->discoveryUrls[j];
            UA_String_init(&server->discoveryUrls[j]);

            UA_LOG_INFO(client->config.logging, UA_LOGCATEGORY_CLIENT,
                        "Use the EndpointURL %S returned from FindServers and reconnect",
                        client->discoveryUrl);

            /* Close the SecureChannel to build it up new with the correct
             * EndpointURL in the HEL/ACK handshake. In closeSecureChannel the
             * received client->endpoint is reset also. */
            closeSecureChannel(client);
            return;
        }
    }

    /* Could not find a suitable server. Try to continue with the
     * original EndpointURL. */
    UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                   "FindServers did not returned a suitable DiscoveryURL. "
                   "Continue with the EndpointURL %S.", client->config.endpointUrl);
    UA_String_clear(&client->discoveryUrl);
    UA_String_copy(&client->config.endpointUrl, &client->discoveryUrl);
}

static UA_StatusCode
requestFindServers(UA_Client *client) {
    UA_FindServersRequest request;
    UA_FindServersRequest_init(&request);
    request.requestHeader.timeoutHint = 10000;
    request.endpointUrl = client->config.endpointUrl;
    UA_StatusCode retval =
        __Client_AsyncService(client, &request, &UA_TYPES[UA_TYPES_FINDSERVERSREQUEST],
                              (UA_ClientAsyncServiceCallback) responseFindServers,
                              &UA_TYPES[UA_TYPES_FINDSERVERSRESPONSE], NULL, NULL);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "FindServers failed when sending the request with error code %s",
                     UA_StatusCode_name(retval));
        return retval;
    }

    client->findServersHandshake = true;
    return UA_STATUSCODE_GOOD;
}

static void
createSessionCallback(UA_Client *client, void *userdata,
                      UA_UInt32 requestId, void *response) {
    UA_LOCK_ASSERT(&client->clientMutex);

    UA_CreateSessionResponse *csr = (UA_CreateSessionResponse*)response;
    UA_StatusCode res = csr->responseHeader.serviceResult;
    if(res != UA_STATUSCODE_GOOD)
        goto cleanup;

    if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
       client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
        /* Verify the session response was created with the same certificate as
         * the SecureChannel */
        if(!UA_ByteString_equal(&csr->serverCertificate,
                                &client->channel.remoteCertificate)) {
            res = UA_STATUSCODE_BADCERTIFICATEINVALID;
            goto cleanup;
        }

        /* Verify the client signature */
        res = checkCreateSessionSignature(client, &client->channel, csr);
        if(res != UA_STATUSCODE_GOOD)
            goto cleanup;
    }

    /* Copy the SessionId */
    UA_NodeId_clear(&client->sessionId);
    res |= UA_NodeId_copy(&csr->sessionId, &client->sessionId);

    /* Check the (session) nonce length. The session nonce is the application
     * nonce (>= 32 bytes), independent of the SecurityPolicy's SecureChannel
     * nonce length (e.g. the 64-byte ECC ephemeral key). */
    if(csr->serverNonce.length < 32) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Session cannot be created with a nonce "
                     "that is too short");
        res = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
        goto cleanup;
    }

    /* Copy nonce and AuthenticationToken */
    UA_ByteString_clear(&client->serverSessionNonce);
    UA_NodeId_clear(&client->authenticationToken);
    res |= UA_ByteString_copy(&csr->serverNonce, &client->serverSessionNonce);
    res |= UA_NodeId_copy(&csr->authenticationToken, &client->authenticationToken);
    if(res != UA_STATUSCODE_GOOD)
        goto cleanup;

    /* Extract the server's ECC ephemeral public key from the CreateSession
     * response */
    extractEphemeralKeyFromAddHeader(client, &csr->responseHeader.additionalHeader);

    /* Activate the new Session */
    client->sessionState = UA_SESSIONSTATE_CREATED;

 cleanup:
    setConnectStatus(client, res);
    if(client->connectStatus != UA_STATUSCODE_GOOD)
        client->sessionState = UA_SESSIONSTATE_CLOSED;
}

/* OPC UA Part 6 ECC: request an ephemeral ECDH key from the server by adding an
 * "ECDHPolicyUri" entry (value = the user-token SecurityPolicy URI) to the
 * request's AdditionalHeader. The server returns its ephemeral public key under
 * "ECDHKey" in the response AdditionalHeader, which the client needs to encrypt
 * an ECC UserIdentityToken. For non-ECC user-token policies this is a no-op.
 * The caller must clear the AdditionalHeader after sending. */
static UA_StatusCode
requestServerEphemeralKey(UA_Client *client, UA_RequestHeader *rh) {
    UA_SecurityPolicy *utpSp = client->utpSp;
    if(!UA_SecurityPolicy_isEcc(utpSp))
        return UA_STATUSCODE_GOOD;

    UA_AdditionalParametersType *ap = UA_AdditionalParametersType_new();
    if(!ap)
        return UA_STATUSCODE_BADOUTOFMEMORY;
    ap->parameters = (UA_KeyValuePair*)
        UA_Array_new(1, &UA_TYPES[UA_TYPES_KEYVALUEPAIR]);
    if(!ap->parameters) {
        UA_AdditionalParametersType_delete(ap);
        return UA_STATUSCODE_BADOUTOFMEMORY;
    }
    ap->parametersSize = 1;
    ap->parameters[0].key = UA_QUALIFIEDNAME_ALLOC(0, "ECDHPolicyUri");
    UA_StatusCode res =
        UA_Variant_setScalarCopy(&ap->parameters[0].value, &utpSp->policyUri,
                                 &UA_TYPES[UA_TYPES_STRING]);
    if(res != UA_STATUSCODE_GOOD) {
        UA_AdditionalParametersType_delete(ap);
        return res;
    }
    UA_ExtensionObject_setValue(&rh->additionalHeader, ap,
                                &UA_TYPES[UA_TYPES_ADDITIONALPARAMETERSTYPE]);
    return UA_STATUSCODE_GOOD;
}

static UA_StatusCode
createSessionAsync(UA_Client *client) {
    UA_LOCK_ASSERT(&client->clientMutex);

    /* Select the UserTokenPolicy based on the client configuration and the
     * endpoint information. Also instantiates the UserTokenPolicy if not
     * already there. */
    const UA_UserTokenPolicy *utp = NULL;
    UA_StatusCode res = initUserTokenPolicy(client, &utp, "CreateSession");
    if(res != UA_STATUSCODE_GOOD)
        return res;
    (void)utp;

    /* Create the CreateSession ClientNonce: a 32-byte random nonce when the
     * SecureChannel is secured. For ECC SecurityPolicies the ClientNonce is
     * NOT the session ephemeral key — the ephemeral keys are exchanged
     * separately (the server's arrives in the response AdditionalHeader; the
     * client's, when needed for UserIdentityToken encryption, is carried in
     * the EccEncryptedSecret). Sending the ephemeral key as the nonce is
     * rejected by conformant servers with BadNonceInvalid. */
    UA_SecurityPolicy *sp = client->channel.securityPolicy;
    if(sp && client->channel.securityMode != UA_MESSAGESECURITYMODE_NONE) {
        size_t nonceLength = 32;
        if(client->clientSessionNonce.length != nonceLength) {
            UA_ByteString_clear(&client->clientSessionNonce);
            res = UA_ByteString_allocBuffer(&client->clientSessionNonce, nonceLength);
            if(res != UA_STATUSCODE_GOOD)
                return res;
        }
        /* Ensure data[0] is not the 'e' of the "eph" ECC ephemeral-key
         * trigger, so generateNonce produces plain random data. */
        client->clientSessionNonce.data[0] = 0;
        res = sp->generateNonce(sp, client->channel.channelContext,
                                &client->clientSessionNonce);
        if(res != UA_STATUSCODE_GOOD) {
            UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                         "CreateSession could not create the client nonce");
            return res;
        }
    }

    /* Prepare the request */
    UA_CreateSessionRequest request;
    UA_CreateSessionRequest_init(&request);
    request.clientNonce = client->clientSessionNonce;
    request.requestedSessionTimeout = client->config.requestedSessionTimeout;
    request.maxResponseMessageSize = UA_INT32_MAX;
    request.endpointUrl = client->endpoint.endpointUrl;
    request.clientDescription = client->config.clientDescription;
    request.sessionName = client->config.sessionName;

    /* Send the certificate that is used for the UserIdentiyToken as the
     * ApplicationCertificate. (sp == client->channel.securityPolicy; guarded
     * so static analysis sees it cannot be a NULL dereference.) */
    if(sp)
        request.clientCertificate = sp->localCertificate;

    /* For ECC policies, request the server's ephemeral ECDH key (needed to
     * encrypt the UserIdentityToken in ActivateSession). */
    res = requestServerEphemeralKey(client, &request.requestHeader);
    if(res != UA_STATUSCODE_GOOD)
        return res;

    /* Send the request */
    res = __Client_AsyncService(client, &request,
                                &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
                                (UA_ClientAsyncServiceCallback)createSessionCallback,
                                &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE], NULL, NULL);

    /* The request is encoded+sent synchronously; release the AdditionalHeader. */
    UA_ExtensionObject_clear(&request.requestHeader.additionalHeader);

    if(res == UA_STATUSCODE_GOOD)
        client->sessionState = UA_SESSIONSTATE_CREATE_REQUESTED;
    else
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "CreateSession failed when sending the request with "
                     "error code %s", UA_StatusCode_name(res));

    return res;
}

static UA_StatusCode
initSecurityPolicy(UA_Client *client) {
    /* Find the SecurityPolicy. Use #None if the endpoint is not (yet)
     * configured. */
    UA_String secPolicyUri = client->endpoint.securityPolicyUri;
    if(secPolicyUri.length == 0)
        secPolicyUri = UA_SECURITY_POLICY_NONE_URI;
    UA_SecurityPolicy *sp = getSecurityPolicy(client, secPolicyUri);

    /* Unknown SecurityPolicy */
    if(!sp) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "SecurityPolicy %S not available", secPolicyUri);
        return UA_STATUSCODE_BADINTERNALERROR;
    }

    /* Already initialized -- check we are using the same SecurityPolicy */
    if(client->channel.securityPolicy)
        return (client->channel.securityPolicy == sp) ?
            UA_STATUSCODE_GOOD : UA_STATUSCODE_BADINTERNALERROR;

    /* Verify the remote server certificate */
    UA_StatusCode res;
    if(client->endpoint.serverCertificate.length > 0) {
        res = client->config.certificateVerification.
            verifyCertificate(&client->config.certificateVerification,
                              &client->endpoint.serverCertificate);
        if(res != UA_STATUSCODE_GOOD) {
            UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                         "Cannot validate the server certificate "
                         "defined for the selected endpoint");
            return res;
        }
    }

    /* If the sender provides a chain of certificates then we shall extract the
     * ApplicationInstanceCertificate and ignore the extra bytes. See also: OPC
     * UA Part 6, V1.04, 6.7.2.3 Security Header, Table 42 - Asymmetric
     * algorithm Security header */
    UA_ByteString appInstCert =
        getLeafCertificate(client->endpoint.serverCertificate);

    /* Instantiate the SecurityPolicy context with the remote certificate */
    res = UA_SecureChannel_setSecurityPolicy(&client->channel, sp, &appInstCert);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Cannot instantiate the SecurityPolicy %S "
                     "with the supplied server certificate", sp->policyUri);
        return res;
    }

    /* Set the SecurityMode. Replace INVALID with NONE as a workaround for
     * misconfigured endpoints. */
    UA_MessageSecurityMode securityMode = client->endpoint.securityMode;
    if(securityMode == UA_MESSAGESECURITYMODE_INVALID)
        securityMode = UA_MESSAGESECURITYMODE_NONE;
    res = UA_SecureChannel_setSecurityMode(&client->channel, securityMode);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Client configuration uses mismatching "
                     "MessageSecurityMode==%u for SecurityPolicy %S",
                     securityMode, sp->policyUri);
    }
    return res;
}

static void
connectActivity(UA_Client *client) {
    UA_LOCK_ASSERT(&client->clientMutex);
    UA_LOG_TRACE(client->config.logging, UA_LOGCATEGORY_CLIENT,
                 "Client connect iterate");

    /* Could not connect with an error that canot be recovered from */
    if(client->connectStatus != UA_STATUSCODE_GOOD)
        return;

    /* Already connected */
    if(client->sessionState == UA_SESSIONSTATE_ACTIVATED)
        return;

    /* Switch on the SecureChannel state */
    switch(client->channel.state) {
        /* Nothing to do if the connection has not opened fully */
    case UA_SECURECHANNELSTATE_CONNECTING:
    case UA_SECURECHANNELSTATE_REVERSE_CONNECTED:
    case UA_SECURECHANNELSTATE_CLOSING:
    case UA_SECURECHANNELSTATE_HEL_SENT:
    case UA_SECURECHANNELSTATE_OPN_SENT:
        return;

        /* Send HEL */
    case UA_SECURECHANNELSTATE_CONNECTED:
        setConnectStatus(client, sendHELMessage(client));
        return;

        /* ACK receieved. Send OPN. */
    case UA_SECURECHANNELSTATE_ACK_RECEIVED:
        setConnectStatus(client, sendOPNAsync(client, false)); /* Send OPN */
        return;

        /* The channel is open -> continue with the Session handling */
    case UA_SECURECHANNELSTATE_OPEN:
        break;

        /* The connection is closed. Reset the SecureChannel and open a new TCP
         * connection */
    case UA_SECURECHANNELSTATE_CLOSED:
        if(client->config.noReconnect)
            setConnectStatus(client, UA_STATUSCODE_BADNOTCONNECTED);
        else
            initConnect(client); /* Sets the connectStatus internally */
        return;

        /* These states should never occur for the client */
    default:
        setConnectStatus(client, UA_STATUSCODE_BADINTERNALERROR);
        return;
    }

    /* <-- The SecureChannel is open --> */

    /* Ongoing handshake -> Waiting for a response */
    if(client->endpointsHandshake || client->findServersHandshake ||
       client->namespacesHandshake)
        return;

    /* Call FindServers to see if we should reconnect with another EndpointUrl.
     * This needs to be done before GetEndpoints, as the set of returned
     * endpoints may depend on the EndpointUrl used during the initial HEL/ACK
     * handshake. */
    if(client->discoveryUrl.length == 0) {
        setConnectStatus(client, requestFindServers(client));
        return;
    }

    /* GetEndpoints to identify the remote side and/or reset the SecureChannel
     * with encryption */
    if(endpointUnconfigured(&client->endpoint)) {
        setConnectStatus(client, requestGetEndpoints(client));
        return;
    }

    /* Have the final SecureChannel but no session */
    if(client->config.noSession)
        return;

    /* Create and Activate the Session */
    switch(client->sessionState) {
        /* Send a CreateSessionRequest */
    case UA_SESSIONSTATE_CLOSED:
        setConnectStatus(client, createSessionAsync(client));
        return;

        /* Activate the Session */
    case UA_SESSIONSTATE_CREATED:
        setConnectStatus(client, activateSessionAsync(client));
        return;

    case UA_SESSIONSTATE_CREATE_REQUESTED:
    case UA_SESSIONSTATE_ACTIVATE_REQUESTED:
    case UA_SESSIONSTATE_ACTIVATED:
    case UA_SESSIONSTATE_CLOSING:
        return; /* Nothing to do */

        /* These states should never occur for the client */
    default:
        setConnectStatus(client, UA_STATUSCODE_BADINTERNALERROR);
        break;
    }
}

/* Verify the OPN response. Note that the client knows the remote server
 * certificate before opening the SecureChannel (from the EndpointDescription).
 *
 * The server certificate is used to initialize the SecureChannel/SecurityPolicy
 * before connecting in initSecurityPolicy. The certificate from the endpoint is
 * checked to be the same used in the AsymHeader. */
static UA_StatusCode
verifyClientSecureChannelHeader(void *application, UA_SecureChannel *channel,
                                const UA_AsymmetricAlgorithmSecurityHeader *asymHeader) {
    UA_Client *client = (UA_Client*)application;
    const UA_SecurityPolicy *sp = channel->securityPolicy;
    UA_assert(sp != NULL);

    /* Check the SecurityPolicyUri if it is defined. If the SecurityMode is not
     * None, then the SecurityPolicyUri must be defined. For None we allow an
     * empty SecurityPolicyUri to support all (historical) server behaviors. */
    if((asymHeader->securityPolicyUri.length > 0 ||
        channel->securityMode != UA_MESSAGESECURITYMODE_NONE) &&
       !UA_String_equal(&sp->policyUri, &asymHeader->securityPolicyUri)) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "The server uses a different SecurityPolicy than "
                     "the SecureChannel/Endpoint configured in the client");
        return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
    }

    /* In initSecurityPolicy we already verified
     * client->endpoint.serverCertificate and loaded it into the channel context
     * of the SecurityPolicy.
     *
     * If the securityPolicyUri is None (== SecurityMode is None), the server
     * shall ignore the ApplicationInstanceCertificate. Otherwise compare that
     * the certificate in OPN is the same as in the endpoint.
     *
     * Both the clientCertificate of this request and of the endpoint may
     * contain a partial or a complete certificate chain. The compareCertificate
     * function will compare the first certificate of each chain. The end
     * certificate shall be located first in the chain according to the OPC UA
     * specification Part 6 (1.04), chapter 6.2.3.*/
    UA_StatusCode res;
    if(channel->securityMode != UA_MESSAGESECURITYMODE_NONE) {
        void *cc = channel->channelContext;
        res = sp->compareCertificate(sp, cc, &asymHeader->senderCertificate);
        if(res != UA_STATUSCODE_GOOD) {
            UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                         "The server certificate in the OPN message is "
                         "different from the EndpointDescription");
            return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
        }
    }

    /* Verify the certificate the server assumes on our end */
    res = sp->compareCertThumbprint(sp, &asymHeader->receiverCertificateThumbprint);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "The client certificate thumprint in the OPN response "
                     "is incorrect");
        return res;
    }

    return UA_STATUSCODE_GOOD;
}

/* The local ApplicationUri has to match the certificates of the
 * SecurityPolicies */
static void
verifyClientApplicationUri(const UA_Client *client) {
#if UA_LOGLEVEL <= 400
    const UA_ClientConfig *cc = &client->config;
    for(size_t i = 0; i < cc->securityPoliciesSize; i++) {
        UA_SecurityPolicy *sp = &cc->securityPolicies[i];
        if(sp->policyType == UA_SECURITYPOLICYTYPE_NONE &&
           !sp->localCertificate.data)
            continue;
        UA_StatusCode retval =
            UA_CertificateUtils_verifyApplicationUri(&sp->localCertificate,
                                &cc->clientDescription.applicationUri);
        if(retval != UA_STATUSCODE_GOOD) {
            UA_LOG_WARNING(cc->logging, UA_LOGCATEGORY_CLIENT,
                           "The ApplicationUri %S in the client's ApplicationDescription "
                           "does not match the URI specified in the certificate "
                           "for the SecurityPolicy %S",
                           cc->clientDescription.applicationUri, sp->policyUri);
        }
    }
#endif
}

static void
delayedNetworkCallback(void *application, void *context);

static void
__Client_networkCallback(UA_ConnectionManager *cm, uintptr_t connectionId,
                         void *application, void **connectionContext,
                         UA_ConnectionState state, const UA_KeyValueMap *params,
                         UA_ByteString msg) {
    /* Take the client lock */
    UA_Client *client = (UA_Client*)application;
    lockClient(client);

    UA_LOG_TRACE(client->config.logging, UA_LOGCATEGORY_CLIENT, "Client network callback");

    /* A new connection with no context pointer attached */
    if(!*connectionContext) {
        /* Inconsistent SecureChannel state. Has to be fresh for a new
         * connection. */
        if(client->channel.state != UA_SECURECHANNELSTATE_CLOSED &&
           client->channel.state != UA_SECURECHANNELSTATE_REVERSE_LISTENING) {
            UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                         "Cannot open a connection, the SecureChannel is already used");
            setConnectStatus(client, UA_STATUSCODE_BADINTERNALERROR);
            notifyClientState(client);
            unlockClient(client);
            return;
        }

        /* Initialize the client connection and attach to the EventLoop connection */
        client->channel.connectionManager = cm;
        client->channel.connectionId = connectionId;
        *connectionContext = &client->channel;
    }

    /* The connection is closing in the EventLoop. This is the last callback
     * from that connection. Clean up the SecureChannel in the client. */
    if(state == UA_CONNECTIONSTATE_CLOSING) {
        UA_LOG_INFO_CHANNEL(client->config.logging, &client->channel,
                            "SecureChannel closed");

        /* Set to closing (could be done already in UA_SecureChannel_shutdown).
         * This impacts the handling of cancelled requests below. */
        UA_SecureChannelState oldState = client->channel.state;
        client->channel.state = UA_SECURECHANNELSTATE_CLOSING;

        /* Set the Session to CREATED if it was ACTIVATED */
        if(client->sessionState == UA_SESSIONSTATE_ACTIVATED)
            client->sessionState = UA_SESSIONSTATE_CREATED;

        /* Delete outstanding async services - the RequestId is no longer valid. Do
         * this after setting the Session state. Otherwise we send out new Publish
         * Requests immediately. */
        __Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSECURECHANNELCLOSED);

        /* Clean up the channel and set the status to CLOSED */
        UA_SecureChannel_clear(&client->channel);

        /* The connection closed before it actually opened. Since we are
         * connecting asynchronously, this happens when the TCP connection
         * fails. Try to fall back on the initial EndpointUrl. */
        if(oldState == UA_SECURECHANNELSTATE_CONNECTING &&
           client->connectStatus == UA_STATUSCODE_GOOD)
            setConnectStatus(client, fallbackEndpointUrl(client));

        /* Try to reconnect. Duplicate the code instead of continue_connect to
         * pacify compiler warnings. */
        /* goto continue_connect; */
        if(!isFullyConnected(client))
            connectActivity(client);
        notifyClientState(client);
        unlockClient(client);
        return;
    }

    /* Update the SecureChannel state */
    if(UA_LIKELY(state == UA_CONNECTIONSTATE_ESTABLISHED)) {
        /* The connection is now open on the TCP level. Set the SecureChannel
         * state to reflect this. Otherwise later consistency checks for the
         * received messages fail. */
        if(client->channel.state < UA_SECURECHANNELSTATE_CONNECTED)
            client->channel.state = UA_SECURECHANNELSTATE_CONNECTED;
    } else /* state == UA_CONNECTIONSTATE_OPENING */ {
        /* The connection was opened on our end only. Waiting for the TCP handshake
         * to complete. */
        client->channel.state = UA_SECURECHANNELSTATE_CONNECTING;
    }

    UA_EventLoop *el = client->config.eventLoop;
    UA_DateTime nowMonotonic = el->dateTime_nowMonotonic(el);

    /* Received a message. Process the message with the SecureChannel. */
    UA_StatusCode res = UA_SecureChannel_loadBuffer(&client->channel, msg);
    while(UA_LIKELY(res == UA_STATUSCODE_GOOD)) {
        UA_MessageType messageType;
        UA_UInt32 requestId = 0;
        UA_ByteString payload = UA_BYTESTRING_NULL;
        UA_Boolean copied = false;
        res = UA_SecureChannel_getCompleteMessage(&client->channel, &messageType, &requestId,
                                                  &payload, &copied, nowMonotonic);
        if(res != UA_STATUSCODE_GOOD || payload.length == 0)
            break;
        res = processServiceResponse(client, &client->channel,
                                     messageType, requestId, &payload);
        if(copied)
            UA_ByteString_clear(&payload);

        /* Abort after synchronous processing of a message.
         * Add a delayed callback to process the remaining buffer ASAP. */
        if(res == UA_STATUSCODE_GOODCOMPLETESASYNCHRONOUSLY) {
            if(client->channel.unprocessed.length > client->channel.unprocessedOffset &&
               client->channel.unprocessedDelayed.callback == NULL) {
                client->channel.unprocessedDelayed.callback = delayedNetworkCallback;
                client->channel.unprocessedDelayed.application = client;
                client->channel.unprocessedDelayed.context = &client->channel;
                el->addDelayedCallback(el, &client->channel.unprocessedDelayed);
            }
            res = UA_STATUSCODE_GOOD;
            break;
        }
    }
    res |= UA_SecureChannel_persistBuffer(&client->channel);

    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Processing the message returned the error code %s",
                     UA_StatusCode_name(res));

        /* If processing the buffer fails before the SecureChannel has opened,
         * then the client cannot recover. Set the connectStatus to reflect
         * this. The application is notified when the socket has closed. */
        if(client->channel.state != UA_SECURECHANNELSTATE_OPEN)
            setConnectStatus(client, res);

        /* Close the SecureChannel, but don't notify the client right away.
         * Return immediately. notifyClientState will be called in the next
         * callback from the ConnectionManager when the connection closes with a
         * StatusCode.
         *
         * If the connectStatus is still good (the SecureChannel was fully
         * opened before), then a reconnect is attempted. */
        closeSecureChannel(client);
        unlockClient(client);
        return;
    }

    /* continue_connect: */
    /* Trigger the next action from our end to fully open up the connection */
    if(!isFullyConnected(client))
        connectActivity(client);
    notifyClientState(client);
    unlockClient(client);
}

static void
delayedNetworkCallback(void *application, void *context) {
    UA_Client *client = (UA_Client*)application;
    client->channel.unprocessedDelayed.callback = NULL;
    if(client->channel.state >= UA_SECURECHANNELSTATE_CONNECTING)
        __Client_networkCallback(client->channel.connectionManager,
                                 client->channel.connectionId,
                                 client, &context,
                                 UA_CONNECTIONSTATE_ESTABLISHED,
                                 &UA_KEYVALUEMAP_NULL, UA_BYTESTRING_NULL);
}

/* Initialize a TCP connection. Writes the result to client->connectStatus. */
static void
initConnect(UA_Client *client) {
    UA_LOCK_ASSERT(&client->clientMutex);
    if(client->channel.state != UA_SECURECHANNELSTATE_CLOSED) {
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                       "Client connection already initiated");
        return;
    }

    UA_StatusCode res;

    /* An exact endpoint was configured. Use it. */
    if(!endpointUnconfigured(&client->config.endpoint)) {
        UA_EndpointDescription_clear(&client->endpoint);
        res = UA_EndpointDescription_copy(&client->config.endpoint, &client->endpoint);
        if(res != UA_STATUSCODE_GOOD) {
            setConnectStatus(client, res);
            return;
        }
    }

    /* Start the EventLoop if not already started */
    setConnectStatus(client, __UA_Client_startup(client));
    if(client->connectStatus != UA_STATUSCODE_GOOD)
        return;

    /* Consistency check the client's own ApplicationUri.
     * Problems are only logged. */
    verifyClientApplicationUri(client);

    /* Initialize the SecureChannel */
    UA_SecureChannel_clear(&client->channel);
    client->channel.config = client->config.localConnectionConfig;
    client->channel.processOPNHeader = verifyClientSecureChannelHeader;
    client->channel.processOPNHeaderApplication = client;

    /* Initialize the SecurityPolicy */
    setConnectStatus(client, initSecurityPolicy(client));
    if(client->connectStatus != UA_STATUSCODE_GOOD)
        return;

    /* Extract hostname and port from the URL */
    UA_String hostname = UA_STRING_NULL;
    UA_String path = UA_STRING_NULL;
    UA_UInt16 port = 4840;

    res = UA_parseEndpointUrl(&client->config.endpointUrl, &hostname, &port, &path);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_NETWORK,
                       "Endpoint URL is invalid: %S", client->config.endpointUrl);
        setConnectStatus(client, res);
        return;
    }

    /* Initialize the TCP connection */
    UA_String tcpString = UA_STRING("tcp");
    for(UA_EventSource *es = client->config.eventLoop->eventSources;
        es != NULL; es = es->next) {
        /* Is this a usable connection manager? */
        if(es->eventSourceType != UA_EVENTSOURCETYPE_CONNECTIONMANAGER)
            continue;
        UA_ConnectionManager *cm = (UA_ConnectionManager*)es;
        if(!UA_String_equal(&tcpString, &cm->protocol))
            continue;

        /* Set up the parameters */
        UA_KeyValuePair params[3];
        params[0].key = UA_QUALIFIEDNAME(0, "port");
        UA_Variant_setScalar(&params[0].value, &port, &UA_TYPES[UA_TYPES_UINT16]);
        params[1].key = UA_QUALIFIEDNAME(0, "address");
        UA_Variant_setScalar(&params[1].value, &hostname, &UA_TYPES[UA_TYPES_STRING]);
        params[2].key = UA_QUALIFIEDNAME(0, "reuse");
        UA_Variant_setScalar(&params[2].value, &client->config.tcpReuseAddr,
                             &UA_TYPES[UA_TYPES_BOOLEAN]);

        UA_KeyValueMap paramMap;
        paramMap.map = params;
        paramMap.mapSize = 3;

        /* Open the client TCP connection */
        res = cm->openConnection(cm, &paramMap, client, NULL, __Client_networkCallback);
        if(res == UA_STATUSCODE_GOOD)
            break;
    }

    /* The channel has not opened */
    if(client->channel.state == UA_SECURECHANNELSTATE_CLOSED)
        res = UA_STATUSCODE_BADINTERNALERROR;

    /* Opening the TCP connection failed */
    if(res != UA_STATUSCODE_GOOD || client->connectStatus != UA_STATUSCODE_GOOD) {
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                       "Could not open a TCP connection to %S",
                       client->config.endpointUrl);
        setConnectStatus(client, UA_STATUSCODE_BADCONNECTIONCLOSED);
    }
}

void
connectSync(UA_Client *client) {
    UA_LOCK_ASSERT(&client->clientMutex);

    /* Initialize the connection */
    initConnect(client);
    notifyClientState(client);
    if(client->connectStatus != UA_STATUSCODE_GOOD)
        return;

    /* EventLoop is started. Otherwise initConnect would have failed. */
    UA_EventLoop *el = client->config.eventLoop;
    UA_assert(el);

    UA_DateTime now = el->dateTime_nowMonotonic(el);
    UA_DateTime maxDate = now + ((UA_DateTime)client->config.timeout * UA_DATETIME_MSEC);

    /* Run the EventLoop until connected, connect fail or timeout. Continue
     * to iterate when the channel is in CLOSING state so that the pending
     * close callback is processed and the channel fully transitions to CLOSED
     * before returning to the caller. */
    while((client->connectStatus == UA_STATUSCODE_GOOD && !isFullyConnected(client)) ||
          client->channel.state == UA_SECURECHANNELSTATE_CLOSING) {
        /* Timeout -> abort */
        now = el->dateTime_nowMonotonic(el);
        if(maxDate < now) {
            UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                         "The connection has timed out before it could be fully opened");
            setConnectStatus(client, UA_STATUSCODE_BADTIMEOUT);
            /* Continue to run. The loop continues while the channel is
             * CLOSING so the close callback is processed. */
        }

        /* Drop into the EventLoop */
        UA_StatusCode res = el->run(el, (UA_UInt32)((maxDate - now) / UA_DATETIME_MSEC));
        if(res != UA_STATUSCODE_GOOD)
            setConnectStatus(client, res);
    }
}

UA_StatusCode
connectInternal(UA_Client *client, UA_Boolean async) {
    UA_LOCK_ASSERT(&client->clientMutex);

    /* Reset the connectStatus. This should be the only place where we can
     * recover from a bad connectStatus. */
    client->connectStatus = UA_STATUSCODE_GOOD;

    if(async)
        initConnect(client);
    else
        connectSync(client);
    notifyClientState(client);
    return client->connectStatus;
}

UA_StatusCode
connectSecureChannel(UA_Client *client, const char *endpointUrl) {
    UA_LOCK_ASSERT(&client->clientMutex);

    UA_ClientConfig *cc = UA_Client_getConfig(client);
    cc->noSession = true;
    UA_String_clear(&cc->endpointUrl);
    cc->endpointUrl = UA_STRING_ALLOC(endpointUrl);
    return connectInternal(client, false);
}

UA_StatusCode
__UA_Client_connect(UA_Client *client, UA_Boolean async, const char *endpointUrl) {
    lockClient(client);

    UA_ClientConfig *cc = UA_Client_getConfig(client);
    if(endpointUrl) {
        UA_String_clear(&cc->endpointUrl);
        cc->endpointUrl = UA_STRING_ALLOC(endpointUrl);
    }

    connectInternal(client, async);

    unlockClient(client);
    return client->connectStatus;
}

static UA_StatusCode
activateSessionSync(UA_Client *client) {
    UA_LOCK_ASSERT(&client->clientMutex);

    /* EventLoop is started. Otherwise activateSessionAsync would have failed. */
    UA_EventLoop *el = client->config.eventLoop;
    UA_assert(el);

    UA_DateTime now = el->dateTime_nowMonotonic(el);
    UA_DateTime maxDate = now + ((UA_DateTime)client->config.timeout * UA_DATETIME_MSEC);

    /* Try to activate */
    UA_StatusCode res = activateSessionAsync(client);
    if(res != UA_STATUSCODE_GOOD)
        return res;

    /* Continue iterating while the session is being activated or the
     * channel is draining (CLOSING) after a timeout. */
    while((client->sessionState != UA_SESSIONSTATE_ACTIVATED &&
          client->connectStatus == UA_STATUSCODE_GOOD) ||
          client->channel.state == UA_SECURECHANNELSTATE_CLOSING) {
        /* Timeout -> abort */
        now = el->dateTime_nowMonotonic(el);
        if(maxDate < now) {
            UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                         "The connection has timed out before it could be fully opened");
            setConnectStatus(client, UA_STATUSCODE_BADTIMEOUT);
            /* Continue to run. The loop continues while the channel is
             * CLOSING so the close callback is processed. */
        }

        /* Drop into the EventLoop */
        res = el->run(el, (UA_UInt32)((maxDate - now) / UA_DATETIME_MSEC));
        if(res != UA_STATUSCODE_GOOD)
            setConnectStatus(client, res);
    }

    return client->connectStatus;
}

UA_StatusCode
UA_Client_activateCurrentSession(UA_Client *client) {
    lockClient(client);
    UA_StatusCode res = activateSessionSync(client);
    notifyClientState(client);
    unlockClient(client);
    return res != UA_STATUSCODE_GOOD ? res : client->connectStatus;
}

UA_StatusCode
UA_Client_activateCurrentSessionAsync(UA_Client *client) {
    lockClient(client);
    UA_StatusCode res = activateSessionAsync(client);
    notifyClientState(client);
    unlockClient(client);
    return res != UA_STATUSCODE_GOOD ? res : client->connectStatus;
}

UA_StatusCode
UA_Client_getSessionAuthenticationToken(UA_Client *client,
                                        UA_NodeId *authenticationToken,
                                        UA_ByteString *serverNonce) {
    lockClient(client);
    if(client->sessionState != UA_SESSIONSTATE_CREATED &&
       client->sessionState != UA_SESSIONSTATE_ACTIVATED) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "There is no current session");
        unlockClient(client);
        return UA_STATUSCODE_BADSESSIONCLOSED;
    }

    UA_StatusCode res =
        UA_NodeId_copy(&client->authenticationToken, authenticationToken);
    res |= UA_ByteString_copy(&client->serverSessionNonce, serverNonce);
    unlockClient(client);
    return res;
}

static UA_StatusCode
switchSession(UA_Client *client,
              const UA_NodeId authenticationToken,
              const UA_ByteString serverNonce) {
    /* Check that there is no pending session in the client */
    if(client->sessionState != UA_SESSIONSTATE_CLOSED) {
        UA_LOG_ERROR(client->config.logging, UA_LOGCATEGORY_CLIENT,
                     "Cannot activate a session with a different AuthenticationToken "
                     "when the client already has a Session.");
        return UA_STATUSCODE_BADINTERNALERROR;
    }

    /* Replace token and nonce */
    UA_NodeId_clear(&client->authenticationToken);
    UA_ByteString_clear(&client->serverSessionNonce);
    UA_StatusCode res = UA_NodeId_copy(&authenticationToken,
                                       &client->authenticationToken);
    res |= UA_ByteString_copy(&serverNonce, &client->serverSessionNonce);
    if(res != UA_STATUSCODE_GOOD)
        return res;

    /* Notify that we have now a created session */
    client->sessionState = UA_SESSIONSTATE_CREATED;
    notifyClientState(client);

    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_Client_activateSession(UA_Client *client,
                          const UA_NodeId authenticationToken,
                          const UA_ByteString serverNonce) {
    lockClient(client);
    UA_StatusCode res = switchSession(client, authenticationToken, serverNonce);
    if(res != UA_STATUSCODE_GOOD) {
        unlockClient(client);
        return res;
    }
    res = activateSessionSync(client);
    notifyClientState(client);
    unlockClient(client);
    return res != UA_STATUSCODE_GOOD ? res : client->connectStatus;
}

UA_StatusCode
UA_Client_activateSessionAsync(UA_Client *client,
                               const UA_NodeId authenticationToken,
                               const UA_ByteString serverNonce) {
    lockClient(client);
    UA_StatusCode res = switchSession(client, authenticationToken, serverNonce);
    if(res != UA_STATUSCODE_GOOD) {
        unlockClient(client);
        return res;
    }
    res = activateSessionAsync(client);
    notifyClientState(client);
    unlockClient(client);
    return res != UA_STATUSCODE_GOOD ? res : client->connectStatus;
}

static void
disconnectListenSockets(UA_Client *client) {
    UA_ConnectionManager *cm = client->reverseConnectionCM;
    for(size_t i = 0; i < 16; i++) {
        if(client->reverseConnectionIds[i] != 0)
            cm->closeConnection(cm, client->reverseConnectionIds[i]);
    }
}

/* ConnectionContext meaning:
 * - NULL: New listen connection
 * - &client->channel: Established active socket to a server
 * - &client->reverseConnectionIds[*] == connectionId: Established listen socket
 * - &client->reverseConnectionIds[*] != connectionId: New active socket */
static void
__Client_reverseConnectCallback(UA_ConnectionManager *cm, uintptr_t connectionId,
                                void *application, void **connectionContext,
                                UA_ConnectionState state, const UA_KeyValueMap *params,
                                UA_ByteString msg) {
    UA_Client *client = (UA_Client*)application;
    lockClient(client);

    if(!*connectionContext) {
        /* Store the new listen connection */
        size_t i = 0;
        for(; i < 16; i++) {
            if(client->reverseConnectionIds[i] == 0) {
                client->reverseConnectionIds[i] = connectionId;
                client->reverseConnectionCM = cm;
                *connectionContext = &client->reverseConnectionIds[i];
                if(client->channel.state == UA_SECURECHANNELSTATE_CLOSED)
                    client->channel.state = UA_SECURECHANNELSTATE_REVERSE_LISTENING;
                break;
            }
        }
        /* All slots are full, close */
        if(i == 16) {
            cm->closeConnection(cm, connectionId);
            unlockClient(client);
            return;
        }
    } else if(*connectionContext == &client->channel ||
              *(uintptr_t*)*connectionContext != connectionId) {
        /* Active socket */

        /* New active socket */
        if(*connectionContext != &client->channel) {
            /* The client already has an active connection */
            if(client->channel.connectionId) {
                cm->closeConnection(cm, connectionId);
                unlockClient(client);
                return;
            }

            /* Set the connection the SecureChannel */
            client->channel.connectionId = connectionId;
            client->channel.connectionManager = cm;
            *connectionContext = &client->channel;

            /* Don't keep the listen sockets when an active connection is open */
            disconnectListenSockets(client);

            /* Set the channel state. The notification callback is called within
             * __Client_reverseConnectCallback. */
            if(client->channel.state == UA_SECURECHANNELSTATE_REVERSE_LISTENING)
                client->channel.state = UA_SECURECHANNELSTATE_REVERSE_CONNECTED;
        }

        /* Handle the active connection in the normal network callback */
        unlockClient(client);
        __Client_networkCallback(cm, connectionId, application,
                                 connectionContext, state, params, msg);
        return;
    }

    /* Close the listen socket. Was this the last one? */
    if(state == UA_CONNECTIONSTATE_CLOSING) {
        UA_Byte count = 0;
        for(size_t i = 0; i < 16; i++) {
            if(client->reverseConnectionIds[i] == connectionId)
                client->reverseConnectionIds[i] = 0;
            if(client->reverseConnectionIds[i] != 0)
                count++;
        }
        /* The last connection was closed */
        if(count == 0 && client->channel.connectionId == 0)
            client->channel.state = UA_SECURECHANNELSTATE_CLOSED;
    }

    notifyClientState(client);
    unlockClient(client);
}

UA_StatusCode
UA_Client_startListeningForReverseConnect(UA_Client *client,
                                          const UA_String *listenHostnames,
                                          size_t listenHostnamesLength,
                                          UA_UInt16 port) {
    lockClient(client);

    if(client->channel.state != UA_SECURECHANNELSTATE_CLOSED) {
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                       "Unable to listen for reverse connect while the client "
                       "is connected or already listening");
        unlockClient(client);
        return UA_STATUSCODE_BADINVALIDSTATE;
    }

    const UA_String tcpString = UA_STRING_STATIC("tcp");
    UA_StatusCode res = UA_STATUSCODE_BADINTERNALERROR;

    client->connectStatus = UA_STATUSCODE_GOOD;
    client->channel.renewState = UA_SECURECHANNELRENEWSTATE_NORMAL;

    UA_SecureChannel_init(&client->channel);
    client->channel.config = client->config.localConnectionConfig;
    client->channel.processOPNHeader = verifyClientSecureChannelHeader;
    client->channel.processOPNHeaderApplication = client;
    client->channel.connectionId = 0;

    setConnectStatus(client, initSecurityPolicy(client));
    if(client->connectStatus != UA_STATUSCODE_GOOD)
        return client->connectStatus;

    UA_EventLoop *el = client->config.eventLoop;
    if(!el) {
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                       "No EventLoop configured");
        unlockClient(client);
        return UA_STATUSCODE_BADINTERNALERROR;
    }

    if(el->state != UA_EVENTLOOPSTATE_STARTED) {
        res = el->start(el);
        UA_CHECK_STATUS(res, unlockClient(client); return res);
    }

    UA_ConnectionManager *cm = NULL;
    for(UA_EventSource *es = el->eventSources; es != NULL; es = es->next) {
        if(es->eventSourceType != UA_EVENTSOURCETYPE_CONNECTIONMANAGER)
            continue;
        cm = (UA_ConnectionManager*)es;
        if(UA_String_equal(&tcpString, &cm->protocol))
            break;
        cm = NULL;
    }

    if(!cm) {
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                       "Could not find a TCP connection manager, unable to "
                       "listen for reverse connect");
        unlockClient(client);
        return UA_STATUSCODE_BADINTERNALERROR;
    }

    client->channel.connectionManager = cm;

    UA_KeyValuePair params[4];
    bool booleanTrue = true;
    params[0].key = UA_QUALIFIEDNAME(0, "port");
    UA_Variant_setScalar(&params[0].value, &port,
                         &UA_TYPES[UA_TYPES_UINT16]);
    params[1].key = UA_QUALIFIEDNAME(0, "address");
    UA_Variant_setArray(&params[1].value, (void *)(uintptr_t)listenHostnames,
            listenHostnamesLength, &UA_TYPES[UA_TYPES_STRING]);
    params[2].key = UA_QUALIFIEDNAME(0, "listen");
    UA_Variant_setScalar(&params[2].value, &booleanTrue,
                         &UA_TYPES[UA_TYPES_BOOLEAN]);
    params[3].key = UA_QUALIFIEDNAME(0, "reuse");
    UA_Variant_setScalar(&params[3].value, &client->config.tcpReuseAddr,
                         &UA_TYPES[UA_TYPES_BOOLEAN]);

    UA_KeyValueMap paramMap;
    paramMap.map = params;
    paramMap.mapSize = 4;

    res = cm->openConnection(cm, &paramMap, client, NULL,
                             __Client_reverseConnectCallback);

    /* Opening the TCP connection failed */
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_WARNING(client->config.logging, UA_LOGCATEGORY_CLIENT,
                       "Failed to open a listening TCP socket for "
                       "reverse connect");
        res = UA_STATUSCODE_BADCONNECTIONCLOSED;
    }

    unlockClient(client);
    return res;
}

/************************/
/* Close the Connection */
/************************/

void
closeSecureChannel(UA_Client *client) {
    /* If we close SecureChannel when the Session is still active, set to
     * created. Otherwise the Session would remain active until the connection
     * callback is called for the closing connection. */
    if(client->sessionState == UA_SESSIONSTATE_ACTIVATED)
        client->sessionState = UA_SESSIONSTATE_CREATED;

    /* Prevent recursion */
    if(client->channel.state == UA_SECURECHANNELSTATE_CLOSING ||
       client->channel.state == UA_SECURECHANNELSTATE_CLOSED)
        return;

    UA_LOG_DEBUG_CHANNEL(client->config.logging, &client->channel,
                         "Closing the channel");

    disconnectListenSockets(client);

    /* Send CLO if the SecureChannel is open */
    if(client->channel.state == UA_SECURECHANNELSTATE_OPEN) {
        UA_LOG_DEBUG_CHANNEL(client->config.logging, &client->channel,
                             "Sending the CLO message");

        UA_EventLoop *el = client->config.eventLoop;

        /* Manually set up the header (otherwise done in sendRequest) */
        UA_CloseSecureChannelRequest request;
        UA_CloseSecureChannelRequest_init(&request);
        request.requestHeader.requestHandle = ++client->requestHandle;
        request.requestHeader.timestamp = el->dateTime_now(el);
        request.requestHeader.timeoutHint = client->config.timeout;
        request.requestHeader.authenticationToken = client->authenticationToken;
        UA_SecureChannel_sendCLO(&client->channel, ++client->requestId, &request);
    }

    /* The connection is eventually closed in the next callback from the
     * ConnectionManager with the appropriate status code. Don't set the
     * connection closed right away! */
    UA_SecureChannel_shutdown(&client->channel, UA_SHUTDOWNREASON_CLOSE);
}

static void
sendCloseSession(UA_Client *client) {
    UA_CloseSessionRequest request;
    UA_CloseSessionRequest_init(&request);
    request.deleteSubscriptions = true;
    UA_CloseSessionResponse response;
    __Client_Service(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
                        &response, &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE]);
    UA_CloseSessionRequest_clear(&request);
    UA_CloseSessionResponse_clear(&response);

    /* Set after sending the message to prevent immediate reoping during the
     * service call */
    client->sessionState = UA_SESSIONSTATE_CLOSING;
}

void
cleanupSession(UA_Client *client) {
    UA_NodeId_clear(&client->sessionId);
    UA_NodeId_clear(&client->authenticationToken);
    client->requestHandle = 0;

#ifdef UA_ENABLE_SUBSCRIPTIONS
    /* We need to clean up the subscriptions */
    __Client_Subscriptions_clear(client);
#endif

    /* Delete outstanding async services */
    __Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSESSIONCLOSED);

#ifdef UA_ENABLE_SUBSCRIPTIONS
    client->currentlyOutStandingPublishRequests = 0;
#endif

    client->sessionState = UA_SESSIONSTATE_CLOSED;

    /* Clean the latest server's ephemeral public key */
    UA_ByteString_clear(&client->serverEphemeralPubKey);
    if(client->utpSp && client->utpSpContext) {
        client->utpSp->deleteChannelContext(client->utpSp, client->utpSpContext);
        client->utpSp = NULL;
        client->utpSpContext = NULL;
    }
}

static void
disconnectSecureChannel(UA_Client *client, UA_Boolean sync) {
    /* Clean the DiscoveryUrl and endpoint description when the connection is
     * explicitly closed */
    UA_String_clear(&client->discoveryUrl);
    UA_EndpointDescription_clear(&client->endpoint);

    /* Close the SecureChannel */
    closeSecureChannel(client);

    /* Manually set the status to closed to prevent an automatic reconnection.
     * Notify the client at the end. */
    if(client->connectStatus == UA_STATUSCODE_GOOD)
        client->connectStatus = UA_STATUSCODE_BADCONNECTIONCLOSED;

    /* In the synchronous case, loop until the client has actually closed. */
    UA_EventLoop *el = client->config.eventLoop;
    if(sync && el &&
       el->state != UA_EVENTLOOPSTATE_FRESH &&
       el->state != UA_EVENTLOOPSTATE_STOPPED) {
        while(client->channel.state != UA_SECURECHANNELSTATE_CLOSED) {
            UA_StatusCode runStatus = el->run(el, 100);
            if(runStatus != UA_STATUSCODE_GOOD) {
                UA_LOG_DEBUG(client->config.logging, UA_LOGCATEGORY_CLIENT,
                             "EventLoop run returned %s during synchronous disconnect, "
                             "stopping wait loop", UA_StatusCode_name(runStatus));
                break;
            }
        }
    }

    notifyClientState(client);
}

UA_StatusCode
UA_Client_disconnectSecureChannel(UA_Client *client) {
    lockClient(client);
    disconnectSecureChannel(client, true);
    unlockClient(client);
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_Client_disconnectSecureChannelAsync(UA_Client *client) {
    lockClient(client);
    disconnectSecureChannel(client, false);
    unlockClient(client);
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_Client_disconnect(UA_Client *client) {
    lockClient(client);
    if(client->sessionState == UA_SESSIONSTATE_ACTIVATED)
        sendCloseSession(client);
    cleanupSession(client);
    disconnectSecureChannel(client, true);
    unlockClient(client);
    return UA_STATUSCODE_GOOD;
}

static void
closeSessionCallback(UA_Client *client, void *userdata,
                     UA_UInt32 requestId, void *response) {
    lockClient(client);
    cleanupSession(client);
    disconnectSecureChannel(client, false);
    notifyClientState(client);
    unlockClient(client);
}

UA_StatusCode
UA_Client_disconnectAsync(UA_Client *client) {
    lockClient(client);

    if(client->sessionState == UA_SESSIONSTATE_CLOSED ||
       client->sessionState == UA_SESSIONSTATE_CLOSING) {
        disconnectSecureChannel(client, false);
        notifyClientState(client);
        unlockClient(client);
        return UA_STATUSCODE_GOOD;
    }

    /* Set before sending the message to prevent recursion */
    client->sessionState = UA_SESSIONSTATE_CLOSING;

    UA_CloseSessionRequest request;
    UA_CloseSessionRequest_init(&request);
    request.deleteSubscriptions = true;
    UA_StatusCode res =
        __Client_AsyncService(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
                              (UA_ClientAsyncServiceCallback)closeSessionCallback,
                              &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE], NULL, NULL);
    if(res != UA_STATUSCODE_GOOD) {
        /* Sending the close request failed. Continue to close the connection
         * anyway. */
        cleanupSession(client);
        disconnectSecureChannel(client, false);
    }

    notifyClientState(client);
    unlockClient(client);
    return res;
}