aboutsummaryrefslogtreecommitdiffstats
path: root/vnfs/VES5.0/evel/evel-library/code/evel_library/evel_event_mgr.c
blob: 4fb195c162a386e0e6fa4a51b0486e2abe39fdf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
/*************************************************************************//**
 *
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 *
 * Unless otherwise specified, all software contained herein is
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 ****************************************************************************/

/**************************************************************************//**
 * @file
 * Event Manager
 *
 * Simple event manager that is responsible for taking events (Heartbeats,
 * Faults and Measurements) from the ring-buffer and posting them to the API.
 *
 ****************************************************************************/

#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <pthread.h>

#include <curl/curl.h>

#include "evel.h"
#include "evel_internal.h"
#include "ring_buffer.h"
#include "evel_throttle.h"

/**************************************************************************//**
 * How long we're prepared to wait for the API service to respond in
 * seconds.
 *****************************************************************************/
static const int EVEL_API_TIMEOUT = 10;

/*****************************************************************************/
/* Prototypes of locally scoped functions.                                   */
/*****************************************************************************/
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp);
static void * event_handler(void *arg);
static bool evel_handle_response_tokens(const MEMORY_CHUNK * const chunk,
                                        const jsmntok_t * const json_tokens,
                                        const int num_tokens,
                                        MEMORY_CHUNK * const post);
static bool evel_tokens_match_command_list(const MEMORY_CHUNK * const chunk,
                                           const jsmntok_t * const json_token,
                                           const int num_tokens);
static bool evel_token_equals_string(const MEMORY_CHUNK * const chunk,
                                     const jsmntok_t * const json_token,
                                     const char * check_string);
static void * event_multi_handler(void * arg __attribute__ ((unused)));

/**************************************************************************//**
 * Buffers for error strings from libcurl.
 *****************************************************************************/
static char curl_err_string[CURL_ERROR_SIZE] = "<NULL>";
static char curl_err_string2[CURL_ERROR_SIZE] = "<NULL>";

/**************************************************************************//**
 * Handle for the API into libcurl.
 *****************************************************************************/
static CURL * curl_handle = NULL;
static CURL * curl_handle2 = NULL;
static CURLM * multi_handle = NULL;
int curr_global_handles = 0;
int activmode = -1;

/**************************************************************************//**
 * Special headers that we send.
 *****************************************************************************/
static struct curl_slist * hdr_chunk = NULL;
static struct curl_slist * hdr_chunk2 = NULL;

/**************************************************************************//**
 * Message queue for sending events to the API.
 *****************************************************************************/
static ring_buffer event_buffer;

/**************************************************************************//**
 * Single pending priority post, which can be generated as a result of a
 * response to an event.  Currently only used to respond to a commandList.
 *****************************************************************************/
static MEMORY_CHUNK priority_post;

/**************************************************************************//**
 * The thread which is responsible for handling events off of the ring-buffer
 * and posting them to the Event Handler API.
 *****************************************************************************/
static pthread_t evt_handler_thread;

/**************************************************************************//**
 * Variable to convey to the event handler thread what the foreground wants it
 * to do.
 *****************************************************************************/
static EVT_HANDLER_STATE evt_handler_state = EVT_HANDLER_UNINITIALIZED;

/**************************************************************************//**
 * The configured API URL for event and throttling.
 *****************************************************************************/
static char * evel_event_api_url;
static char * evel_throt_api_url;
static char * evel_batch_api_url;

static char * evel_bevent_api_url;
static char * evel_bthrot_api_url;
static char * evel_bbatch_api_url;


/**************************************************************************//**
 * Initialize the event handler.
 *
 * Primarily responsible for getting CURL ready for use.
 *
 * @param[in] event_api_url
 *                      The URL where the Vendor Event Listener API is expected
 *                      to be.
 * @param[in] throt_api_url
 *                      The URL where the Throttling API is expected to be.
 * @param[in] source_ip  Source IP of VES Agent
 * @param[in] ring_buf_size     Initial size of ring buffer
 * @param[in] secure     Whether Using http or https
 * @param[in] cert_file_path  Path to Client Certificate file
 * @param[in] key_file_path   Path to Client key file
 * @param[in] ca_info         Path to CA info file
 * @param[in] ca_file_path    Path to CA file 
 * @param[in] verify_peer     Using peer verification or not 0 or 1
 * @param[in] verify_host     Using host verification or not 0 or 1
 * @param[in] username  The username for the Basic Authentication of requests.
 * @param[in] password  The password for the Basic Authentication of requests.
 * @param     verbosity 0 for normal operation, positive values for chattier
 *                        logs.
 *****************************************************************************/
EVEL_ERR_CODES event_handler_initialize(const char * const event_api_url,
                                        const char * const bakup_api_url,
                                        const char * const throt_api_url,
                                        const char * const source_ip,
                                        const char * const source_ip_bakup,
                                        int ring_buf_size,
                                        int secure,
                                        int activitymode,
                                        const char * const cert_file_path,
                                        const char * const key_file_path,
                                        const char * const ca_info,
                                        const char * const ca_file_path,
                                        long verify_peer,
                                        long verify_host,
                                        const char * const username,
                                        const char * const password,
                                        const char * const username2,
                                        const char * const password2,
                                        int verbosity)
{
  int rc = EVEL_SUCCESS;
  CURLcode curl_rc = CURLE_OK;
  char batch_api_url[EVEL_MAX_URL_LEN + 1] = {0};
  char local_address[64];

  EVEL_ENTER();

  /***************************************************************************/
  /* Check assumptions.                                                      */
  /***************************************************************************/
  assert(event_api_url != NULL);
  assert(throt_api_url != NULL);
  assert(username != NULL);
  assert(password != NULL);
  if( bakup_api_url != NULL )
  {
    assert(username2 != NULL);
    assert(password2 != NULL);
  }


  /***************************************************************************/
  /* Store the API URLs.                                                     */
  /***************************************************************************/
  evel_event_api_url = strdup(event_api_url);
  assert(evel_event_api_url != NULL);
  sprintf(batch_api_url,"%s/eventBatch",event_api_url);
  evel_batch_api_url = strdup(batch_api_url);
  assert(evel_batch_api_url != NULL);
  evel_throt_api_url = strdup(throt_api_url);
  assert(evel_throt_api_url != NULL);
  curr_global_handles = 1;

  if( bakup_api_url != NULL )
  {
    evel_bevent_api_url = strdup(bakup_api_url);
    assert(evel_bevent_api_url != NULL);
    sprintf(batch_api_url,"%s/eventBatch",event_api_url);
    evel_bbatch_api_url = strdup(batch_api_url);
    assert(evel_bbatch_api_url != NULL);
    evel_bthrot_api_url = strdup(throt_api_url);
    assert(evel_bthrot_api_url != NULL);
    curr_global_handles = 2;
  }


  curl_version_info_data *d = curl_version_info(CURLVERSION_NOW);
  /* compare with the 24 bit hex number in 8 bit fields */
  if(d->version_num >= 0x072100) {
     /* this is libcurl 7.33.0 or later */
     EVEL_INFO("7.33 or later Curl version %x.",d->version_num);
  }
  else {
     EVEL_INFO("Old Curl version.");
  }
  /***************************************************************************/
  /* Start the CURL library. Note that this initialization is not threadsafe */
  /* which imposes a constraint that the EVEL library is initialized before  */
  /* any threads are started.                                                */
  /***************************************************************************/
  curl_rc = curl_global_init(CURL_GLOBAL_SSL);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL. Error code=%d", curl_rc);
    goto exit_label;
  }

  /***************************************************************************/
  /* Get a curl handle which we'll use for all of our output.                */
  /***************************************************************************/
  curl_handle = curl_easy_init();
  if (curl_handle == NULL)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to get libCURL handle");
    goto exit_label;
  }

  if( bakup_api_url != NULL )
  {
     curl_handle2 = curl_easy_init();
     if (curl_handle2 == NULL)
     {
       rc = EVEL_CURL_LIBRARY_FAIL;
       log_error_state("Failed to get backup libCURL handle");
       goto exit_label;
     }
  }
  /***************************************************************************/
  /* Prime the library to give friendly error codes.                         */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_ERRORBUFFER,
                             curl_err_string);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to provide friendly errors. "
                    "Error code=%d", curl_rc);
    goto exit_label;
  }

  if( bakup_api_url != NULL )
  {
    curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_ERRORBUFFER,
                             curl_err_string2);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL2 to provide friendly errors. "
                    "Error code=%d", curl_rc);
      goto exit_label;
    }
  }


  /***************************************************************************/
  /* If running in verbose mode generate more output.                        */
  /***************************************************************************/
  if (verbosity > 0)
  {
    curl_rc = curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL to be verbose. "
                      "Error code=%d", curl_rc);
      goto exit_label;
    }
  if( bakup_api_url != NULL )
  {
    curl_rc = curl_easy_setopt(curl_handle2, CURLOPT_VERBOSE, 1L);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL to be verbose. "
                      "Error code=%d", curl_rc);
      goto exit_label;
    }
   }

  }



  /***************************************************************************/
  /* Set the URL for the API.                                                */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, event_api_url);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  EVEL_INFO("Initializing CURL to send events to: %s", event_api_url);

  if( bakup_api_url != NULL )
  {
    curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_URL,
                             bakup_api_url);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
      goto exit_label;
    }
  }


  /***************************************************************************/
  /* send all data to this function.                                         */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_WRITEFUNCTION,
                             evel_write_callback);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with the write callback. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  if( bakup_api_url != NULL )
  {
    curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_WRITEFUNCTION,
                             evel_write_callback);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
      goto exit_label;
    }
  }



  /***************************************************************************/
  /* configure local ip address if provided */
  /* Default ip if NULL */
  /***************************************************************************/
  if( source_ip != NULL )
  {
    snprintf(local_address,sizeof(local_address),source_ip);
    if( local_address[0] != '\0' )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_INTERFACE,
                             local_address);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the local address. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
    }
  }
  if( source_ip_bakup != NULL )
  {
    snprintf(local_address,sizeof(local_address),source_ip_bakup);
    if( local_address[0] != '\0' )
    {
      curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_INTERFACE,
                             local_address);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize bakup libCURL with the local address. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
        goto exit_label;
      }
    }
  }

  /***************************************************************************/
  /* configure SSL options for HTTPS transfers */
  /***************************************************************************/
  if( secure )
  {
    if( cert_file_path != NULL )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_SSLCERT,
                             cert_file_path);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the client cert. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
  if( bakup_api_url != NULL )
  {
      curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_SSLCERT,
                             cert_file_path);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the client cert. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
  }
    }

    if( key_file_path != NULL )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_SSLKEY,
                             key_file_path);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the client key. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
  if( bakup_api_url != NULL )
  {
      curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_SSLKEY,
                             key_file_path);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the client key. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
  }
    }

    if( ca_info != NULL )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_CAINFO,
                             ca_info);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the CA cert file. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
  if( bakup_api_url != NULL )
  {
      curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_CAINFO,
                             ca_info);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the CA cert file. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
  }
    }

    if( ca_file_path != NULL )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_CAPATH,
                             ca_file_path);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the CA cert path. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
  if( bakup_api_url != NULL )
  {
      curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_CAPATH,
                             ca_file_path);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the CA cert path. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
  }
    }

      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_SSL_VERIFYPEER,
                             verify_peer);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with SSL Server verification. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_SSL_VERIFYHOST,
                             verify_host);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with Client host verification. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }

     if( bakup_api_url != NULL )
     {
      curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_SSL_VERIFYPEER,
                             verify_peer);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with SSL Server verification. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
      curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_SSL_VERIFYHOST,
                             verify_host);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with Client host verification. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
     }
  }



  /***************************************************************************/
  /* some servers don't like requests that are made without a user-agent     */
  /* field, so we provide one.                                               */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_USERAGENT,
                             "libcurl-agent/1.0");
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  if( bakup_api_url != NULL )
  {
    curl_rc = curl_easy_setopt(curl_handle2,
                             CURLOPT_USERAGENT,
                             "libcurl-agent/1.0");
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
      goto exit_label;
    }
  }


  /***************************************************************************/
  /* Specify that we are going to POST data.                                 */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_POST, 1L);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  if( bakup_api_url != NULL )
  {
    curl_rc = curl_easy_setopt(curl_handle2,CURLOPT_POST, 1L);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
      goto exit_label;
    }
  }


  /***************************************************************************/
  /* we want to use our own read function.                                   */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, read_callback);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to upload using read "
                    "function. Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  if( bakup_api_url != NULL )
  {
    curl_rc = curl_easy_setopt(curl_handle2,CURLOPT_READFUNCTION, read_callback);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
      goto exit_label;
    }
  }


  /***************************************************************************/
  /* All of our events are JSON encoded.  We also suppress the               */
  /* Expect: 100-continue   header that we would otherwise get since it      */
  /* confuses some servers.                                                  */
  /*                                                                         */
  /* @TODO: do AT&T want this behavior?                                      */
  /***************************************************************************/
  hdr_chunk = curl_slist_append(hdr_chunk, "Content-type: application/json");
  hdr_chunk = curl_slist_append(hdr_chunk, "Expect:");

  /***************************************************************************/
  /* set our custom set of headers.                                         */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, hdr_chunk);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to use custom headers. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  if( bakup_api_url != NULL )
  {
    hdr_chunk2 = curl_slist_append(hdr_chunk2, "Content-type: application/json");
    hdr_chunk2 = curl_slist_append(hdr_chunk2, "Expect:");
    curl_rc = curl_easy_setopt(curl_handle2,CURLOPT_HTTPHEADER, hdr_chunk2);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
      goto exit_label;
    }
  }



  /***************************************************************************/
  /* Set the timeout for the operation.                                      */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_TIMEOUT,
                             EVEL_API_TIMEOUT);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL for API timeout. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  if( bakup_api_url != NULL )
  {
    curl_rc = curl_easy_setopt(curl_handle2,CURLOPT_TIMEOUT, EVEL_API_TIMEOUT);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
      goto exit_label;
    }
  }


  /***************************************************************************/
  /* Set that we want Basic authentication with username:password Base-64    */
  /* encoded for the operation.                                              */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL for Basic Authentication. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_USERNAME, username);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with username. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_PASSWORD, password);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with password. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

  if( bakup_api_url != NULL )
  {
  curl_rc = curl_easy_setopt(curl_handle2, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL for Basic Authentication. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
    goto exit_label;
  }
  curl_rc = curl_easy_setopt(curl_handle2, CURLOPT_USERNAME, username2);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with username. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
    goto exit_label;
  }
  curl_rc = curl_easy_setopt(curl_handle2, CURLOPT_PASSWORD, password2);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with password. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
    goto exit_label;
  }

     multi_handle = curl_multi_init();;
     if (multi_handle == NULL)
     {
       rc = EVEL_CURL_LIBRARY_FAIL;
       log_error_state("Failed to get libCURL Multi handle");
       goto exit_label;
     }
     activmode = activitymode;

  }


  /***************************************************************************/
  /* Initialize a message ring-buffer to be used between the foreground and  */
  /* the thread which sends the messages.  This can't fail.                  */
  /***************************************************************************/
  if( ring_buf_size < EVEL_EVENT_BUFFER_DEPTH )
  {
    log_error_state("Warning: Failed to initialize Ring buffer size to %d. ",
                    ring_buf_size);
    goto exit_label;
  }
  ring_buffer_initialize(&event_buffer, EVEL_EVENT_BUFFER_DEPTH);

  /***************************************************************************/
  /* Initialize the priority post buffer to empty.                           */
  /***************************************************************************/
  priority_post.memory = NULL;

exit_label:
  EVEL_EXIT();

  return(rc);
}

/**************************************************************************//**
 * Run the event handler.
 *
 * Spawns the thread responsible for handling events and sending them to the
 * API.
 *
 *  @return Status code.
 *  @retval ::EVEL_SUCCESS if everything OK.
 *  @retval One of ::EVEL_ERR_CODES if there was a problem.
 *****************************************************************************/
EVEL_ERR_CODES event_handler_run()
{
  EVEL_ERR_CODES rc = EVEL_SUCCESS;
  int pthread_rc = 0;

  EVEL_ENTER();

  /***************************************************************************/
  /* Start the event handler thread.                                         */
  /***************************************************************************/
  evt_handler_state = EVT_HANDLER_INACTIVE;
  if( curr_global_handles <= 1 )
      pthread_rc = pthread_create(&evt_handler_thread, NULL, event_handler, NULL);
  else
      pthread_rc = pthread_create(&evt_handler_thread, NULL, event_multi_handler, NULL);

  if (pthread_rc != 0)
  {
    rc = EVEL_PTHREAD_LIBRARY_FAIL;
    log_error_state("Failed to start event handler thread. "
                    "Error code=%d", pthread_rc);
  }

  EVEL_EXIT()
  return rc;
}

/**************************************************************************//**
 * Terminate the event handler.
 *
 * Shuts down the event handler thread in as clean a way as possible. Sets the
 * global exit flag and then signals the thread to interrupt it since it's
 * most likely waiting on the ring-buffer.
 *
 * Having achieved an orderly shutdown of the event handler thread, clean up
 * the cURL library's resources cleanly.
 *
 *  @return Status code.
 *  @retval ::EVEL_SUCCESS if everything OK.
 *  @retval One of ::EVEL_ERR_CODES if there was a problem.
 *****************************************************************************/
EVEL_ERR_CODES event_handler_terminate()
{
  EVEL_ERR_CODES rc = EVEL_SUCCESS;

  EVEL_ENTER();
  EVENT_INTERNAL *event = NULL;

  /***************************************************************************/
  /* Make sure that we were initialized before trying to terminate the       */
  /* event handler thread.                                                   */
  /***************************************************************************/
  if (evt_handler_state != EVT_HANDLER_UNINITIALIZED)
  {
    /*************************************************************************/
    /* Make sure that the event handler knows it's time to die.              */
    /*************************************************************************/
    event = evel_new_internal_event(EVT_CMD_TERMINATE,"EVELinternal","EVELid");
    if (event == NULL)
    {
      /***********************************************************************/
      /* We failed to get an event, but we don't bail out - we will just     */
      /* clean up what we can and continue on our way, since we're exiting   */
      /* anyway.                                                             */
      /***********************************************************************/
      EVEL_ERROR("Failed to get internal event - perform dirty exit instead!");
    }
    else
    {
      /***********************************************************************/
      /* Post the event then wait for the Event Handler to exit.  Set the    */
      /* global command, too, in case the ring-buffer is full.               */
      /***********************************************************************/
      EVEL_DEBUG("Sending event to Event Hander to request it to exit.");
      evt_handler_state = EVT_HANDLER_REQUEST_TERMINATE;
      evel_post_event((EVENT_HEADER *) event);
      pthread_join(evt_handler_thread, NULL);
      EVEL_DEBUG("Event Handler thread has exited.");
    }
  }
  else
  {
    EVEL_DEBUG("Event handler was not initialized, so no need to kill it");
  }

  /***************************************************************************/
  /* Clean-up the cURL library.                                              */
  /***************************************************************************/
  if (multi_handle != NULL)
  {
     curl_multi_cleanup(multi_handle);
  }
  if (curl_handle != NULL)
  {
    curl_easy_cleanup(curl_handle);
    curl_handle = NULL;
  }
  if (curl_handle2 != NULL)
  {
    curl_easy_cleanup(curl_handle2);
    curl_handle2 = NULL;
  }
  if (hdr_chunk != NULL)
  {
    curl_slist_free_all(hdr_chunk);
    hdr_chunk = NULL;
  }
  if (hdr_chunk2 != NULL)
  {
    curl_slist_free_all(hdr_chunk2);
    hdr_chunk2 = NULL;
  }


  /***************************************************************************/
  /* Free off the stored API URL strings.                                    */
  /***************************************************************************/
  if (evel_event_api_url != NULL)
  {
    free(evel_event_api_url);
    evel_event_api_url = NULL;
  }
  if (evel_batch_api_url != NULL)
  {
    free(evel_batch_api_url);
    evel_batch_api_url = NULL;
  }
  if (evel_throt_api_url != NULL)
  {
    free(evel_throt_api_url);
    evel_throt_api_url = NULL;
  }

  EVEL_EXIT();
  return rc;
}

/**************************************************************************//**
 * Post an event.
 *
 * @note  So far as the caller is concerned, successfully posting the event
 * relinquishes all responsibility for the event - the library will take care
 * of freeing the event in due course.

 * @param event   The event to be posted.
 *
 * @returns Status code
 * @retval  EVEL_SUCCESS On success
 * @retval  "One of ::EVEL_ERR_CODES" On failure.
 *****************************************************************************/
EVEL_ERR_CODES evel_post_event(EVENT_HEADER * event)
{
  int rc = EVEL_SUCCESS;

  EVEL_ENTER();

  /***************************************************************************/
  /* Check preconditions.                                                    */
  /***************************************************************************/
  assert(event != NULL);

  /***************************************************************************/
  /* We need to make sure that we are either initializing or running         */
  /* normally before writing the event into the buffer so that we can        */
  /* guarantee that the ring-buffer empties  properly on exit.               */
  /***************************************************************************/
  if ((evt_handler_state == EVT_HANDLER_ACTIVE) ||
      (evt_handler_state == EVT_HANDLER_INACTIVE) ||
      (evt_handler_state == EVT_HANDLER_REQUEST_TERMINATE))
  {
    if (ring_buffer_write(&event_buffer, event) == 0)
    {
      log_error_state("Failed to write event to buffer - event dropped!");
      rc = EVEL_EVENT_BUFFER_FULL;
      evel_free_event(event);
    }
  }
  else
  {
    /*************************************************************************/
    /* System is not in active operation, so reject the event.               */
    /*************************************************************************/
    log_error_state("Event Handler system not active - event dropped!");
    rc = EVEL_EVENT_HANDLER_INACTIVE;
    evel_free_event(event);
  }

  EVEL_EXIT();
  return (rc);
}

/**************************************************************************//**
 * Post an event to the Vendor Event Listener API.
 *
 * @returns Status code
 * @retval  EVEL_SUCCESS On success
 * @retval  "One of ::EVEL_ERR_CODES" On failure.
 *****************************************************************************/
static EVEL_ERR_CODES evel_post_api(char * msg, size_t size)
{
  int rc = EVEL_SUCCESS;
  CURLcode curl_rc = CURLE_OK;
  MEMORY_CHUNK rx_chunk;
  MEMORY_CHUNK tx_chunk;
  int http_response_code = 0;

  EVEL_ENTER();

  /***************************************************************************/
  /* Create the memory chunk to be used for the response to the post.  The   */
  /* will be realloced.                                                      */
  /***************************************************************************/
  rx_chunk.memory = malloc(1);
  assert(rx_chunk.memory != NULL);
  rx_chunk.size = 0;

  /***************************************************************************/
  /* Create the memory chunk to be sent as the body of the post.             */
  /***************************************************************************/
  tx_chunk.memory = msg;
  tx_chunk.size = size;
  EVEL_DEBUG("Sending chunk of size %d", tx_chunk.size);

  /***************************************************************************/
  /* Point to the data to be received.                                       */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &rx_chunk);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  EVEL_DEBUG("Initialized data to receive");

  /***************************************************************************/
  /* Pointer to pass to our read function                                    */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_READDATA, &tx_chunk);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to set upload data for libCURL to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  EVEL_DEBUG("Initialized data to send");

  /***************************************************************************/
  /* Size of the data to transmit.                                           */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_POSTFIELDSIZE,
                             tx_chunk.size);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to set length of upload data for libCURL to "
                    "upload.  Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  EVEL_DEBUG("Initialized length of data to send");

  /***************************************************************************/
  /* Now run off and do what you've been told!                               */
  /***************************************************************************/
  curl_rc = curl_easy_perform(curl_handle);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to transfer an event to Vendor Event Listener! "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    EVEL_ERROR("Dropped event: %s", msg);
    goto exit_label;
  }

  /***************************************************************************/
  /* See what response we got - any 2XX response is good.                    */
  /***************************************************************************/
  curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &http_response_code);
  EVEL_DEBUG("HTTP response code: %d", http_response_code);
  if ((http_response_code / 100) == 2)
  {
    /*************************************************************************/
    /* If the server responded with data it may be interesting but not a     */
    /* problem.                                                              */
    /*************************************************************************/
    if ((rx_chunk.size > 0) && (rx_chunk.memory != NULL))
    {
      EVEL_DEBUG("Server returned data = %d (%s)",
                 rx_chunk.size,
                 rx_chunk.memory);

      /***********************************************************************/
      /* If this is a response to priority post, then we're not interested.  */
      /***********************************************************************/
      if (priority_post.memory != NULL)
      {
        EVEL_ERROR("Ignoring priority post response");
      }
      else
      {
        evel_handle_event_response(&rx_chunk, &priority_post);
      }
    }
  }
  else
  {
    EVEL_ERROR("Unexpected HTTP response code: %d with data size %d (%s)",
                http_response_code,
                rx_chunk.size,
                rx_chunk.size > 0 ? rx_chunk.memory : "NONE");
    EVEL_ERROR("Potentially dropped event: %s", msg);
  }

exit_label:
  free(rx_chunk.memory);
  EVEL_EXIT();
  return(rc);
}

/**************************************************************************//**
 * Callback function to provide data to send.
 *
 * Copy data into the supplied buffer, read_callback::ptr, checking size
 * limits.
 *
 * @returns   Number of bytes placed into read_callback::ptr. 0 for EOF.
 *****************************************************************************/
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
{
  size_t rtn = 0;
  size_t bytes_to_write = 0;
  MEMORY_CHUNK *tx_chunk = (MEMORY_CHUNK *)userp;

  EVEL_ENTER();

  bytes_to_write = min(size*nmemb, tx_chunk->size);

  if (bytes_to_write > 0)
  {
    EVEL_DEBUG("Going to try to write %d bytes", bytes_to_write);
    strncpy((char *)ptr, tx_chunk->memory, bytes_to_write);
    tx_chunk->memory += bytes_to_write;
    tx_chunk->size -= bytes_to_write;
    rtn = bytes_to_write;
  }
  else
  {
    EVEL_DEBUG("Reached EOF");
  }

  EVEL_EXIT();
  return rtn;
}

/**************************************************************************//**
 * Callback function to provide returned data.
 *
 * Copy data into the supplied buffer, write_callback::ptr, checking size
 * limits.
 *
 * @returns   Number of bytes placed into write_callback::ptr. 0 for EOF.
 *****************************************************************************/
size_t evel_write_callback(void *contents,
                             size_t size,
                             size_t nmemb,
                             void *userp)
{
  size_t realsize = size * nmemb;
  MEMORY_CHUNK * rx_chunk = (MEMORY_CHUNK *)userp;

  EVEL_ENTER();

  EVEL_DEBUG("Called with %d chunks of %d size = %d", nmemb, size, realsize);
  EVEL_DEBUG("rx chunk size is %d", rx_chunk->size);

  rx_chunk->memory = realloc(rx_chunk->memory, rx_chunk->size + realsize + 1);
  if(rx_chunk->memory == NULL) {
    /* out of memory! */
    printf("not enough memory (realloc returned NULL)\n");
    return 0;
  }

  memcpy(&(rx_chunk->memory[rx_chunk->size]), contents, realsize);
  rx_chunk->size += realsize;
  rx_chunk->memory[rx_chunk->size] = 0;

  EVEL_DEBUG("Rx data: %s", rx_chunk->memory);
  EVEL_DEBUG("Returning: %d", realsize);

  EVEL_EXIT();
  return realsize;
}


/**************************************************************************//**
 * Post an event to the Vendor Event Listener API.
 *
 * @returns Status code
 * @retval  EVEL_SUCCESS On success
 * @retval  "One of ::EVEL_ERR_CODES" On failure.
 *****************************************************************************/
static EVEL_ERR_CODES evel_postmulti_message(char *msg, size_t size, int *still,
                CURL *handle, CURL *bhandle, int numhandles )
{
  int rc = EVEL_SUCCESS;
  CURLcode curl_rc = CURLE_OK;
  MEMORY_CHUNK rx_chunk[2];
  MEMORY_CHUNK tx_chunk[2];
  int http_response_code = 0, i;

  EVEL_ENTER();

  EVEL_INFO("Sending :%s: %d\n",msg, numhandles);

  /***************************************************************************/
  /* Create the memory chunk to be used for the response to the post.  The   */
  /* will be realloced.                                                      */
  /***************************************************************************/
for (i=0;i<numhandles;i++)
{
  rx_chunk[i].memory = malloc(1);
  assert(rx_chunk[i].memory != NULL);
  rx_chunk[i].size = 0;

  /***************************************************************************/
  /* Create the memory chunk to be sent as the body of the post.             */
  /***************************************************************************/
  tx_chunk[i].memory = msg;
  tx_chunk[i].size = size;
  EVEL_DEBUG("Sending chunk of size %d", tx_chunk[i].size);
}

  /***************************************************************************/
  /* Point to the data to be received.                                       */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(handle, CURLOPT_WRITEDATA, &rx_chunk[0]);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL rx to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

  /***************************************************************************/
  /* Pointer to pass to our read function                                    */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(handle, CURLOPT_READDATA, &tx_chunk[0]);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to set upload data for libCURL tx to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  /***************************************************************************/
  /* Size of the data to transmit.                                           */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(handle,
                             CURLOPT_POSTFIELDSIZE,
                             tx_chunk[0].size);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to set length of upload data for libCURL to "
                    "upload.  Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

if(numhandles == 2)
{

  /***************************************************************************/
  /* Point to the data to be received.                                       */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(bhandle, CURLOPT_WRITEDATA, &rx_chunk[1]);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL2 rx to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
    goto exit_label;
  }

  /***************************************************************************/
  /* Pointer to pass to our read function                                    */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(bhandle, CURLOPT_READDATA, &tx_chunk[1]);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to set upload data for libCURL2 tx to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string2);
    goto exit_label;
  }
  /***************************************************************************/
  /* Size of the data to transmit.                                           */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(bhandle,
                             CURLOPT_POSTFIELDSIZE,
                             tx_chunk[1].size);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to set length of upload data for libCURL2 to "
                    "upload.  Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

}

  /***************************************************************************/
  /* Now run off and do what you've been told!                               */
  /***************************************************************************/
  curl_rc = curl_multi_perform(multi_handle, still);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to transfer an multi event to Vendor Event Listener! "
                    "Error code=%d (%s)", curl_rc, curl_multi_strerror(curl_rc
));
    EVEL_ERROR("Dropped event: %s", msg);
    goto exit_label;
  }

  /***************************************************************************/
  /* See what response we got - any 2XX response is good.                    */
  /***************************************************************************/

exit_label:
 for (i=0;i<numhandles;i++)
    free(rx_chunk[i].memory);
  EVEL_EXIT();

  return(rc);
}


/**************************************************************************//**
 * Event Multi Post Handler.
 *
 * Watch for messages coming on the internal queue and send them to the
 * listener.
 *
 * param[in]  jsonmsg  json message to be sent.
 * param[in]  size     size of json message
 * param[in]  currhandle Primary handle
 * param[in]  url1     pimary url
 * param[in]  bakkhandle  Backup handle
 * param[in]  url2     secondary url
 *****************************************************************************/
static int evel_post_multiapi(char *jsonmsg, size_t size,CURL *currhandle, char *url1,
                                   CURL *bakkhandle, char *url2)
{
      int rc = EVEL_SUCCESS;
      CURLcode curl_rc = 0;
      int nhandles = 1;
      int still_running,i;
      CURLMsg *msg; /* for picking up messages with the transfer status */ 
      int msgs_left; /* how many messages are left */

      /***************************************************************************/
      /* Set the URL for the API.                                                */
      /***************************************************************************/
      curl_rc = curl_easy_setopt(currhandle, CURLOPT_URL, url1);
      if (curl_rc != CURLE_OK )
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the multi API URL. "
                    "%s Error code=%d (%s)", url1, curl_rc, curl_err_string);
      }

      if( url2 != NULL && activmode == 1 )
      {
        curl_rc = curl_easy_setopt(bakkhandle, CURLOPT_URL, url2);
        if (curl_rc != CURLE_OK)
        {
           rc = EVEL_CURL_LIBRARY_FAIL;
           log_error_state("Failed to initialize libCURL with the API URL. "
                    "%s Error code=%d (%s)", url2, curl_rc, curl_err_string2);
        }
        nhandles = 2;
      }

      /* we start some action by calling perform right away */
      curl_multi_add_handle(multi_handle, currhandle);
      if(nhandles==2){
        curl_multi_add_handle(multi_handle, bakkhandle);
      }

      /* we start some action by calling perform right away */
      curl_multi_perform(multi_handle, &still_running);

  do {
    struct timeval timeout;
    int rc; /* select() return code */ 
    CURLMcode mc; /* curl_multi_fdset() return code */ 
 
    fd_set fdread;
    fd_set fdwrite;
    fd_set fdexcep;
    int maxfd = -1;
 
    long curl_timeo = -1;
 
    FD_ZERO(&fdread);
    FD_ZERO(&fdwrite);
    FD_ZERO(&fdexcep);
 
    /* set a suitable timeout to play around with */ 
    timeout.tv_sec = 1;
    timeout.tv_usec = 0;
 
    curl_multi_timeout(multi_handle, &curl_timeo);
    if(curl_timeo >= 0) {
      timeout.tv_sec = curl_timeo / 1000;
      if(timeout.tv_sec > 1)
        timeout.tv_sec = 1;
      else
        timeout.tv_usec = (curl_timeo % 1000) * 1000;
    }
 
    /* get file descriptors from the transfers */ 
    mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
 
    if(mc != CURLM_OK) {
      EVEL_ERROR("curl_multi_fdset() failed, code %d.\n", mc);
      break;
    }
 
    /* On success the value of maxfd is guaranteed to be >= -1. We call
       select(maxfd + 1, ...); specially in case of (maxfd == -1) there are
       no fds ready yet so we call select(0, ...) --or Sleep() on Windows--
       to sleep 100ms, which is the minimum suggested value in the
       curl_multi_fdset() doc. */ 
 
    if(maxfd == -1) {
#ifdef _WIN32
      Sleep(100);
      rc = 0;
#else
      /* Portable sleep for platforms other than Windows. */ 
      struct timeval wait = { 0, 300000 }; /* 250ms */ 
      rc = select(0, NULL, NULL, NULL, &wait);
#endif
    }
    else {
      /* Note that on some platforms 'timeout' may be modified by select().
         If you need access to the original value save a copy beforehand. */ 
      rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);
    }
 
    switch(rc) {
    case -1:
      /* select error */ 
      break;
    case 0: /* timeout */ 
    default: /* action */ 
      //curl_multi_perform(multi_handle, &still_running);
      evel_postmulti_message(jsonmsg, size, &still_running, currhandle, bakkhandle, nhandles);
    }
  } while(still_running);
 
  /* See how the transfers went */ 
  while((msg = curl_multi_info_read(multi_handle, &msgs_left))) {
    if(msg->msg == CURLMSG_DONE) {
      int idx, found = 0;
      EVEL_DEBUG("Transfer status - %s\n", curl_multi_strerror(msg->data.result));

      /* Find out which handle this message is about */ 
      for(idx = 0; idx<nhandles; idx++) {
        if (msg->easy_handle == currhandle) break;
        else if(msg->easy_handle == bakkhandle) break;
      }
 
      switch(idx) {
      case 0:
        curl_rc = msg->data.result;
        break;
      case 1:
        curl_rc = msg->data.result;
        break;
      }
    }
  }

  /* we start some action by calling perform right away */
  curl_multi_remove_handle(multi_handle, currhandle);
  if(nhandles==2){
        curl_multi_remove_handle(multi_handle, bakkhandle);
  }

  EVEL_DEBUG("Transfer completed with status %s\n", curl_multi_strerror(curl_rc));
  if( curl_rc == 0 || curl_rc == 55 )
     return EVEL_SUCCESS;
  else
     return EVEL_CURL_LIBRARY_FAIL;

}
/**************************************************************************//**
 * Event Handler.
 *
 * Watch for messages coming on the internal queue and send them to the
 * listener.
 *
 * param[in]  arg  Argument - unused.
 *****************************************************************************/
static void * event_multi_handler(void * arg __attribute__ ((unused)))
{
  int old_type = 0;
  EVENT_HEADER * msg = NULL;
  EVENT_INTERNAL * internal_msg = NULL;
  int json_size = 0;
  char json_body[EVEL_MAX_JSON_BODY];
  int rc = EVEL_SUCCESS;
  CURLcode curl_rc;
  CURL *currhandler = NULL;
  CURL *bakhandler = NULL;
  char *send_url = NULL;
  char *send_url2 = NULL;

  EVEL_INFO("Event multi handler thread started");

  /***************************************************************************/
  /* Set this thread to be cancellable immediately.                          */
  /***************************************************************************/
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_type);

  /***************************************************************************/
  /* Set the handler as active, defending against weird situations like      */
  /* immediately shutting down after initializing the library so the         */
  /* handler never gets started up properly.                                 */
  /***************************************************************************/
  if (evt_handler_state == EVT_HANDLER_INACTIVE)
  {
    evt_handler_state = EVT_HANDLER_ACTIVE;
  }
  else
  {
    EVEL_ERROR("Event Handler State was not INACTIVE at start-up - "
               "Handler will exit immediately!");
  }

  currhandler = curl_handle;
  while (evt_handler_state == EVT_HANDLER_ACTIVE)
  {
    /*************************************************************************/
    /* Wait for a message to be received.                                    */
    /*************************************************************************/
    msg = ring_buffer_read(&event_buffer);

    /*************************************************************************/
    /* Internal events get special treatment while regular events get posted */
    /* to the far side.                                                      */
    /*************************************************************************/
    if (msg->event_domain == EVEL_DOMAIN_BATCH )
    {
      EVEL_DEBUG("Batch event received");

      /***********************************************************************/
      /* Encode the event in JSON.                                           */
      /***********************************************************************/
      json_size = evel_json_encode_batch_event(json_body, EVEL_MAX_JSON_BODY, msg);

      /***************************************************************************/
      /* Set the URL for the API.                                                */
      /***************************************************************************/
      if( currhandler == curl_handle){
         send_url = evel_batch_api_url;
         send_url2 = evel_bbatch_api_url;
         bakhandler = curl_handle2;
      } else if(currhandler == curl_handle2) {
         send_url = evel_bbatch_api_url;
         send_url2 = evel_batch_api_url;
         bakhandler = curl_handle;
      }

      /***********************************************************************/
      /* Send the JSON across the API.                                       */
      /***********************************************************************/
      EVEL_DEBUG("Sending Batch JSON of size %d is: %s", json_size, json_body);
      rc = evel_post_multiapi(json_body, json_size, currhandler, send_url, bakhandler, send_url2);
      if (rc != EVEL_SUCCESS)
      {
        EVEL_ERROR("Failed to transfer the data to %s. Error code=%d", send_url, rc);
        EVEL_INFO("Switched Collector ...");
        if( currhandler == curl_handle){
	  currhandler = curl_handle2;
          bakhandler = curl_handle;
        } else if(currhandler == curl_handle2) {
	  currhandler = curl_handle;
          bakhandler = curl_handle2;
        }
        rc = evel_post_multiapi(json_body, json_size, currhandler, send_url2, bakhandler,send_url);
        if (rc != EVEL_SUCCESS)
           EVEL_ERROR("Failed to transfer the data to failover %s. Error code=%d", send_url2, rc);
      }
    }
    else if (msg->event_domain != EVEL_DOMAIN_INTERNAL )
    {
      EVEL_DEBUG("External event received");

      /***********************************************************************/
      /* Encode the event in JSON.                                           */
      /***********************************************************************/
      json_size = evel_json_encode_event(json_body, EVEL_MAX_JSON_BODY, msg);

      /***************************************************************************/
      /* Set the URL for the API.                                                */
      /***************************************************************************/
      if( currhandler == curl_handle){
         send_url = evel_event_api_url;
         send_url2 = evel_bevent_api_url;
         bakhandler = curl_handle2;
      } else if(currhandler == curl_handle2) {
         send_url = evel_bevent_api_url;
         send_url2 = evel_event_api_url;
         bakhandler = curl_handle;
      }

      /***********************************************************************/
      /* Send the JSON across the API.                                       */
      /***********************************************************************/
      EVEL_DEBUG("Sending Batch JSON of size %d is: %s", json_size, json_body);
      rc = evel_post_multiapi(json_body, json_size, currhandler, send_url, bakhandler, send_url2);
      if (rc != EVEL_SUCCESS)
      {
        EVEL_ERROR("Failed to transfer the data to %s. Error code=%d", send_url, rc);
        EVEL_INFO("Switched Collector ...");
        if( currhandler == curl_handle){
          currhandler = curl_handle2;
          bakhandler = curl_handle;
        } else if(currhandler == curl_handle2) {
          currhandler = curl_handle;
          bakhandler = curl_handle2;
        }
        rc = evel_post_multiapi(json_body, json_size, currhandler, send_url2, bakhandler,send_url);
        if (rc != EVEL_SUCCESS)
           EVEL_ERROR("Failed to transfer the data to failover %s. Error code=%d", send_url2, rc);
      }

    }
    else
    {
      EVEL_DEBUG("Internal event received");
      internal_msg = (EVENT_INTERNAL *) msg;
      assert(internal_msg->command == EVT_CMD_TERMINATE);
      evt_handler_state = EVT_HANDLER_TERMINATING;
    }

    /*************************************************************************/
    /* We are responsible for freeing the memory.                            */
    /*************************************************************************/
    evel_free_event(msg);
    msg = NULL;

    /*************************************************************************/
    /* There may be a single priority post to be sent.                       */
    /*************************************************************************/
    if (priority_post.memory != NULL)
    {
      EVEL_DEBUG("Priority Post");

      /***********************************************************************/
      /* Set the URL for the throttling API.                                 */
      /***********************************************************************/
      curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_throt_api_url);
      if (curl_rc != CURLE_OK)
      {
        /*********************************************************************/
        /* This is only likely to happen with CURLE_OUT_OF_MEMORY, in which  */
        /* case we carry on regardless.                                      */
        /*********************************************************************/
        EVEL_ERROR("Failed to set throttling URL. Error code=%d", rc);
      }
      else
      {
        rc = evel_post_api(priority_post.memory, priority_post.size);
        if (rc != EVEL_SUCCESS)
        {
          EVEL_ERROR("Failed to transfer priority post. Error code=%d", rc);
        }
      }

      /***********************************************************************/
      /* Reinstate the URL for the event API.                                */
      /***********************************************************************/
      curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_event_api_url);
      if (curl_rc != CURLE_OK)
      {
        /*********************************************************************/
        /* This is only likely to happen with CURLE_OUT_OF_MEMORY, in which  */
        /* case we carry on regardless.                                      */
        /*********************************************************************/
        EVEL_ERROR("Failed to reinstate events URL. Error code=%d", rc);
      }

      /***********************************************************************/
      /* We are responsible for freeing the memory.                          */
      /***********************************************************************/
      free(priority_post.memory);
      priority_post.memory = NULL;
    }
  }

  /***************************************************************************/
  /* The event handler is now exiting. The ring-buffer could contain events  */
  /* which have not been processed, so deplete those.  Because we've been    */
  /* asked to exit we can be confident that the foreground will have stopped */
  /* sending events in so we know that this process will conclude!           */
  /***************************************************************************/
  evt_handler_state = EVT_HANDLER_TERMINATING;
  while (!ring_buffer_is_empty(&event_buffer))
  {
    EVEL_DEBUG("Reading event from buffer");
    msg = ring_buffer_read(&event_buffer);
    evel_free_event(msg);
  }
  evt_handler_state = EVT_HANDLER_TERMINATED;
  EVEL_INFO("Event handler thread stopped");

  return (NULL);
}


/**************************************************************************//**
 * Event Handler.
 *
 * Watch for messages coming on the internal queue and send them to the
 * listener.
 *
 * param[in]  arg  Argument - unused.
 *****************************************************************************/
static void * event_handler(void * arg __attribute__ ((unused)))
{
  int old_type = 0;
  EVENT_HEADER * msg = NULL;
  EVENT_INTERNAL * internal_msg = NULL;
  int json_size = 0;
  char json_body[EVEL_MAX_JSON_BODY];
  int rc = EVEL_SUCCESS;
  CURLcode curl_rc;

  EVEL_INFO("Event handler thread started");

  /***************************************************************************/
  /* Set this thread to be cancellable immediately.                          */
  /***************************************************************************/
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_type);

  /***************************************************************************/
  /* Set the handler as active, defending against weird situations like      */
  /* immediately shutting down after initializing the library so the         */
  /* handler never gets started up properly.                                 */
  /***************************************************************************/
  if (evt_handler_state == EVT_HANDLER_INACTIVE)
  {
    evt_handler_state = EVT_HANDLER_ACTIVE;
  }
  else
  {
    EVEL_ERROR("Event Handler State was not INACTIVE at start-up - "
               "Handler will exit immediately!");
  }

  while (evt_handler_state == EVT_HANDLER_ACTIVE)
  {
    /*************************************************************************/
    /* Wait for a message to be received.                                    */
    /*************************************************************************/
    EVEL_DEBUG("Event handler getting any messages");
    msg = ring_buffer_read(&event_buffer);

    /*************************************************************************/
    /* Internal events get special treatment while regular events get posted */
    /* to the far side.                                                      */
    /*************************************************************************/
    if (msg->event_domain == EVEL_DOMAIN_BATCH )
    {
      EVEL_DEBUG("Batch event received");

      /***********************************************************************/
      /* Encode the event in JSON.                                           */
      /***********************************************************************/
      json_size = evel_json_encode_batch_event(json_body, EVEL_MAX_JSON_BODY, msg);

      /***************************************************************************/
      /* Set the URL for the API.                                                */
      /***************************************************************************/
      curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_batch_api_url);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the Batch API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
      }

      /***********************************************************************/
      /* Send the JSON across the API.                                       */
      /***********************************************************************/
      EVEL_DEBUG("Sending Batch JSON of size %d is: %s", json_size, json_body);
      rc = evel_post_api(json_body, json_size);
      if (rc != EVEL_SUCCESS)
      {
        EVEL_ERROR("Failed to transfer the data %s. Error code=%d", evel_batch_api_url, rc);
      }
    }
    else if (msg->event_domain != EVEL_DOMAIN_INTERNAL )
    {
      EVEL_DEBUG("External event received");

      /***********************************************************************/
      /* Encode the event in JSON.                                           */
      /***********************************************************************/
      json_size = evel_json_encode_event(json_body, EVEL_MAX_JSON_BODY, msg);

      /***************************************************************************/
      /* Set the URL for the API.                                                */
      /***************************************************************************/
      curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_event_api_url);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
      }

      /***********************************************************************/
      /* Send the JSON across the API.                                       */
      /***********************************************************************/
      EVEL_DEBUG("Sending JSON of size %d is: %s", json_size, json_body);
      rc = evel_post_api(json_body, json_size);
      if (rc != EVEL_SUCCESS)
      {
        EVEL_ERROR("Failed to transfer the data %s. Error code=%d",evel_event_api_url, rc);
      }
    }
    else
    {
      EVEL_DEBUG("Internal event received");
      internal_msg = (EVENT_INTERNAL *) msg;
      assert(internal_msg->command == EVT_CMD_TERMINATE);
      evt_handler_state = EVT_HANDLER_TERMINATING;
    }

    /*************************************************************************/
    /* We are responsible for freeing the memory.                            */
    /*************************************************************************/
    evel_free_event(msg);
    msg = NULL;

    /*************************************************************************/
    /* There may be a single priority post to be sent.                       */
    /*************************************************************************/
    if (priority_post.memory != NULL)
    {
      EVEL_DEBUG("Priority Post");

      /***********************************************************************/
      /* Set the URL for the throttling API.                                 */
      /***********************************************************************/
      curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_throt_api_url);
      if (curl_rc != CURLE_OK)
      {
        /*********************************************************************/
        /* This is only likely to happen with CURLE_OUT_OF_MEMORY, in which  */
        /* case we carry on regardless.                                      */
        /*********************************************************************/
        EVEL_ERROR("Failed to set throttling URL. Error code=%d", rc);
      }
      else
      {
        rc = evel_post_api(priority_post.memory, priority_post.size);
        if (rc != EVEL_SUCCESS)
        {
          EVEL_ERROR("Failed to transfer priority post. Error code=%d", rc);
        }
      }

      /***********************************************************************/
      /* Reinstate the URL for the event API.                                */
      /***********************************************************************/
      curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_event_api_url);
      if (curl_rc != CURLE_OK)
      {
        /*********************************************************************/
        /* This is only likely to happen with CURLE_OUT_OF_MEMORY, in which  */
        /* case we carry on regardless.                                      */
        /*********************************************************************/
        EVEL_ERROR("Failed to reinstate events URL. Error code=%d", rc);
      }

      /***********************************************************************/
      /* We are responsible for freeing the memory.                          */
      /***********************************************************************/
      free(priority_post.memory);
      priority_post.memory = NULL;
    }
  }

  /***************************************************************************/
  /* The event handler is now exiting. The ring-buffer could contain events  */
  /* which have not been processed, so deplete those.  Because we've been    */
  /* asked to exit we can be confident that the foreground will have stopped */
  /* sending events in so we know that this process will conclude!           */
  /***************************************************************************/
  evt_handler_state = EVT_HANDLER_TERMINATING;
  while (!ring_buffer_is_empty(&event_buffer))
  {
    EVEL_DEBUG("Reading event from buffer");
    msg = ring_buffer_read(&event_buffer);
    evel_free_event(msg);
  }
  evt_handler_state = EVT_HANDLER_TERMINATED;
  EVEL_INFO("Event handler thread stopped");

  return (NULL);
}

/**************************************************************************//**
 * Handle a JSON response from the listener, contained in a ::MEMORY_CHUNK.
 *
 * Tokenize the response, and decode any tokens found.
 *
 * @param chunk         The memory chunk containing the response.
 * @param post          The memory chunk in which to place any resulting POST.
 *****************************************************************************/
void evel_handle_event_response(const MEMORY_CHUNK * const chunk,
                                MEMORY_CHUNK * const post)
{
  jsmn_parser json_parser;
  jsmntok_t json_tokens[EVEL_MAX_RESPONSE_TOKENS];
  int num_tokens = 0;

  EVEL_ENTER();

  /***************************************************************************/
  /* Check preconditions.                                                    */
  /***************************************************************************/
  assert(chunk != NULL);
  assert(priority_post.memory == NULL);

  EVEL_DEBUG("Response size = %d", chunk->size);
  EVEL_DEBUG("Response = %s", chunk->memory);

  /***************************************************************************/
  /* Initialize the parser and tokenize the response.                        */
  /***************************************************************************/
  jsmn_init(&json_parser);
  num_tokens = jsmn_parse(&json_parser,
                          chunk->memory,
                          chunk->size,
                          json_tokens,
                          EVEL_MAX_RESPONSE_TOKENS);

  if (num_tokens < 0)
  {
    EVEL_ERROR("Failed to parse JSON response.  "
               "Error code=%d", num_tokens);
  }
  else if (num_tokens == 0)
  {
    EVEL_DEBUG("No tokens found in JSON response");
  }
  else
  {
    //EVEL_DEBUG("Decode JSON response tokens");
    //if (!evel_handle_response_tokens(chunk, json_tokens, num_tokens, post))
    //{
    //  EVEL_ERROR("Failed to handle JSON response.");
    //}
  }

  EVEL_EXIT();
}

/**************************************************************************//**
 * Handle a JSON response from the listener, as a list of tokens from JSMN.
 *
 * @param chunk         Memory chunk containing the JSON buffer.
 * @param json_tokens   Array of tokens to handle.
 * @param num_tokens    The number of tokens to handle.
 * @param post          The memory chunk in which to place any resulting POST.
 * @return true if we handled the response, false otherwise.
 *****************************************************************************/
bool evel_handle_response_tokens(const MEMORY_CHUNK * const chunk,
                                 const jsmntok_t * const json_tokens,
                                 const int num_tokens,
                                 MEMORY_CHUNK * const post)
{
  bool json_ok = false;

  EVEL_ENTER();

  /***************************************************************************/
  /* Check preconditions.                                                    */
  /***************************************************************************/
  assert(chunk != NULL);
  assert(json_tokens != NULL);
  assert(num_tokens < EVEL_MAX_RESPONSE_TOKENS);

  /***************************************************************************/
  /* Peek at the tokens to decide what the response it, then call the        */
  /* appropriate handler to handle it.  There is only one handler at this    */
  /* point.                                                                  */
  /***************************************************************************/
  if (evel_tokens_match_command_list(chunk, json_tokens, num_tokens))
  {
    json_ok = evel_handle_command_list(chunk, json_tokens, num_tokens, post);
  }

  EVEL_EXIT();

  return json_ok;
}

/**************************************************************************//**
 * Determine whether a list of tokens looks like a "commandList" response.
 *
 * @param chunk         Memory chunk containing the JSON buffer.
 * @param json_tokens   Token to check.
 * @param num_tokens    The number of tokens to handle.
 * @return true if the tokens look like a "commandList" match, or false.
 *****************************************************************************/
bool evel_tokens_match_command_list(const MEMORY_CHUNK * const chunk,
                                    const jsmntok_t * const json_tokens,
                                    const int num_tokens)
{
  bool result = false;

  EVEL_ENTER();

  /***************************************************************************/
  /* Make some checks on the basic layout of the commandList.                */
  /***************************************************************************/
  if ((num_tokens > 3) &&
      (json_tokens[0].type == JSMN_OBJECT) &&
      (json_tokens[1].type == JSMN_STRING) &&
      (json_tokens[2].type == JSMN_ARRAY) &&
      (evel_token_equals_string(chunk, &json_tokens[1], "commandList")))
  {
    result = true;
  }

  EVEL_EXIT();

  return result;
}

/**************************************************************************//**
 * Check that a string token matches a given input string.
 *
 * @param chunk         Memory chunk containing the JSON buffer.
 * @param json_token    Token to check.
 * @param check_string  String to check it against.
 * @return true if the strings match, or false.
 *****************************************************************************/
bool evel_token_equals_string(const MEMORY_CHUNK * const chunk,
                              const jsmntok_t * json_token,
                              const char * check_string)
{
  bool result = false;

  EVEL_ENTER();

  const int token_length = json_token->end - json_token->start;
  const char * const token_string = chunk->memory + json_token->start;

  if (token_length == (int)strlen(check_string))
  {
    result = (strncmp(token_string, check_string, token_length) == 0);
  }

  EVEL_EXIT();

  return result;
}