forked from CESNET/ipfixcol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unirec.c
1470 lines (1291 loc) · 52.1 KB
/
unirec.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* \file unirec.c
* \author Petr Velan <[email protected]>
* \author Erik Sabik <[email protected]>
* \brief Plugin for converting IPFIX data to UniRec format
*
* Copyright (C) 2015 CESNET, z.s.p.o.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of the Company nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* ALTERNATIVELY, provided that this notice is retained in full, this
* product may be distributed under the terms of the GNU General Public
* License (GPL) version 2 or later, in which case the provisions
* of the GPL apply INSTEAD OF those given above.
*
* This software is provided ``as is, and any express or implied
* warranties, including, but not limited to, the implied warranties of
* merchantability and fitness for a particular purpose are disclaimed.
* In no event shall the company or contributors be liable for any
* direct, indirect, incidental, special, exemplary, or consequential
* damages (including, but not limited to, procurement of substitute
* goods or services; loss of use, data, or profits; or business
* interruption) however caused and on any theory of liability, whether
* in contract, strict liability, or tort (including negligence or
* otherwise) arising in any way out of the use of this software, even
* if advised of the possibility of such damage.
*
*/
#include <ipfixcol.h>
#include <stdio.h>
#include <string.h>
#include <endian.h>
#include <time.h>
#include <errno.h>
#include <libxml/parser.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <libtrap/trap.h>
#include "config.h"
#include "unirec.h"
/* API version constant */
IPFIXCOL_API_VERSION;
// Global variables
uint8_t INIT_COUNT = 0; // Number of running instances of plugin
/* NEEDED FOR DEBUG CODE */
#include <arpa/inet.h>
#include <sys/time.h>
uint32_t DEBUG_PRINT = 0;
uint32_t DEBUG_PRINT2 = 0;
time_t curr_time;
time_t prev_time;
time_t step_time = 3;
uint32_t DEBUG_TIME_RECORD = 0;
/* some auxiliary functions for extracting data of exact length */
#define read8(ptr) (*((uint8_t *) (ptr)))
#define read16(ptr) (*((uint16_t *) (ptr)))
#define read32(ptr) (*((uint32_t *) (ptr)))
#define read64(ptr) (*((uint64_t *) (ptr)))
/** Identifier to MSG_* macros */
static char *msg_module = "unirec";
// Struct with information about module
trap_module_info_t module_info = {
"ipfixcol UniRec plugin", // Module name
// Module description
"This is both Nemea module and ipfixcol plugin. It converts IPFIX records"
"to UniRec format for Nemea.\n"
"Interfaces:\n"
" Inputs: 0\n"
" Outputs: 1\n",
0, // Number of input interfaces
1, // Number of output interfaces
};
// Possible UniRec data types
const char *unirec_data_types_str[] = {
"string", /*UR_TYPE_STRING*/
"bytes", /*UR_TYPE_BYTES*/
"char", /*UR_TYPE_CHAR*/
"uint8", /*UR_TYPE_UINT8*/
"int8", /*UR_TYPE_INT8*/
"uint16", /*UR_TYPE_UINT16*/
"int16", /*UR_TYPE_INT16*/
"uint32", /*UR_TYPE_UINT32*/
"int32", /*UR_TYPE_INT32*/
"uint64", /*UR_TYPE_UINT64*/
"int64", /*UR_TYPE_INT64*/
"float", /*UR_TYPE_FLOAT*/
"double", /*UR_TYPE_DOUBLE*/
"ipaddr", /*UR_TYPE_IP*/
"time", /*UR_TYPE_TIME*/
};
/**
* \brief Works as memcpy but converts common data sizes to host byteorder
*
* @param dst Destination buffer
* @param src Source buffer
* @param length Data length
*/
static void data_copy(char *dst, char *src, uint16_t length)
{
switch (length) {
case (1):
*dst = read8(src);
break;
case (2):
*(uint16_t *) dst = ntohs(read16(src));
break;
case (4):
*(uint32_t *) dst = ntohl(read32(src));
break;
case (8):
*(uint64_t *) dst = be64toh(read64(src));
break;
case (16):
*(uint64_t *) dst = be64toh(read64(src));
dst += 16;
*(uint64_t *) dst = be64toh(read64(src+16));
break;
default:
memcpy(dst, src, length);
break;
}
}
/**
* \brief Add `ODID` to every port in Trap interface specification
*
* @param conf Pointer to storage plugin structure
* @param ODID ODID from current exporter
*/
static void update_ifc_spec(unirec_config *conf, uint32_t ODID)
{
char *state;
char *port, *limit;
char buff[32];
char ibuff[32];
uint16_t port_num;
int ifc_count = conf->ifc_count;
for (int i = 0; i < ifc_count; i++) {
memset(ibuff, 0, 32);
memset(buff, 0, 32);
state = NULL;
strncpy(ibuff, conf->ifc_spec.params[i], 30);
port = strtok_r(ibuff, ",", &state);
limit = strtok_r(NULL, ",", &state);
port_num = atoi(port) + ODID;
sprintf(buff, "%u,", port_num);
strncat(&(buff[strlen(buff)]), limit, 10);
if (strlen(conf->ifc_spec.params[i]) < strlen(buff)) {
conf->ifc_spec.params[i] = realloc(conf->ifc_spec.params[i], strlen(buff) + 1);
}
memcpy(conf->ifc_spec.params[i], buff, strlen(buff));
}
}
/**
* \brief Initialize Trap with updated interface specification
*
* @param conf Pointer to storage plugin structure
* @return 1 on success, 0 otherwise
*/
static int init_trap_ifc(unirec_config *conf)
{
MSG_DEBUG(msg_module, "Initializing TRAP (%u)...\n", conf->odid);
if ((conf->trap_ctx_ptr = trap_ctx_init(&module_info, conf->ifc_spec)) == NULL) {
MSG_ERROR(msg_module, "Error in TRAP initialization: (%i) %s\n",
trap_last_error, trap_last_error_msg);
printf("Error in TRAP initialization: (%i) %s\n",
trap_last_error, trap_last_error_msg);
return 0;
}
MSG_DEBUG(msg_module, "OK\n");
for (int i = 0; i < conf->ifc_count; i++) {
MSG_INFO(msg_module, "Setting interface %u buffer %s\n", i, conf->ifc_buff_switch[i] ? "ON" : "OFF");
trap_ctx_ifcctl(conf->trap_ctx_ptr, TRAPIFC_OUTPUT, i, TRAPCTL_BUFFERSWITCH, conf->ifc_buff_switch[i]);
MSG_INFO(msg_module, "Setting interface %u autoflush to %llu us\n", i, conf->ifc_buff_timeout[i]);
trap_ctx_ifcctl(conf->trap_ctx_ptr, TRAPIFC_OUTPUT, i, TRAPCTL_AUTOFLUSH_TIMEOUT, conf->ifc_buff_timeout[i]);
MSG_INFO(msg_module, "Setting interface %u timeout to %llu us\n", i, conf->ifc[i].timeout);
trap_ctx_ifcctl(conf->trap_ctx_ptr, TRAPIFC_OUTPUT, i, TRAPCTL_SETTIMEOUT, (int) conf->ifc[i].timeout);
//set output format
if (conf->ifc[i].unirec_data_format != NULL) {
trap_ctx_set_data_fmt(conf->trap_ctx_ptr, i, TRAP_FMT_UNIREC, conf->ifc[i].unirec_data_format);
}
}
return 1;
}
/**
* \brief Return an UniRec field that matches given IPFIX element
*
* @param element Element to match
* @param ht Hash table containing UniRec fields to search
* @param ipfix_id Ipfix element id to fill.
* @param en_id Enterprise id to fill.
* @return return matching UniRec filed or NULL
*/
static unirecField *match_field(template_ie *element, fht_table_t *ht, uint16_t *ipfix_id, uint32_t *en_id)
{
uint16_t id;
uint32_t en;
uint64_t ht_key;
unirecField **tmp;
id = element->ie.id;
if (id >> 15) {
en = (element+1)->enterprise_number;
id = id & 0x7FFF;
} else {
en = 0;
}
*ipfix_id = id;
*en_id = en;
ht_key = (((uint64_t)en) << 32) | ((uint32_t)id);
tmp = fht_get_data(ht, &ht_key);
return tmp == NULL ? NULL : *tmp;
}
/**
* \brief Get data from data record
*
* Uses conf->unirecFields to store values from this record
*
* \param[in] data_record IPFIX data record
* \param[in] template corresponding template
* \param[out] conf structure containing necessary information for converting ipfix to unirec
* \return length of the data record
*/
static uint16_t process_record(char *data_record, struct ipfix_template *template, unirec_config *conf)
{
if (!template) {
/* We don't have template for this data set */
MSG_WARNING(msg_module, "No template for the data set\n");
return 0;
}
if (!conf) {
/* Configuration not given */
MSG_WARNING(msg_module, "No configuration given to process_record\n");
return 0;
}
uint16_t offset = 0;
uint16_t index, count;
uint16_t length, size_length;
unirecField *matchField;
uint16_t ipfix_id;
uint32_t en_id;
uint64_t sec, msec, frac;
// Fill ODID (link bit field) in all ifc where it is included
// Only do this if using ODID MANAGER method
if (conf->ODID_get_method == ODID_MANAGER_METHOD) {
for (int i = 0; i < conf->ifc_count; i++) {
if (conf->LBF_field->included_ar[i]) {
*(uint64_t*)(conf->ifc[i].buffer + conf->LBF_field->offset_ar[i]) = 1LLU << (conf->odid - 1);
}
}
}
/* Go over all fields */
for (count = index = 0; count < template->field_count; count++, index++) {
matchField = match_field(&template->fields[index], conf->ht_fields, &ipfix_id, &en_id);
length = template->fields[index].ie.length;
size_length = 0;
/* Handle variable length */
if (length == VAR_IE_LENGTH) {
/* Variable length */
length = read8(data_record+offset);
size_length = 1;
if (length == 255) {
length = ntohs(read16(data_record+offset+size_length));
size_length = 3;
}
}
/* Copy the element value on match */
if (matchField) {
// Determine if it is static or dynamic element
// If static, copy to all Unirec ifcs whose are using this element
// Else if dynamic, copy ptr to this element to `matchField->value` for futher use
if (matchField->size != -1) {
// Static element
for (int i = 0; i < conf->ifc_count; i++) {
// For every interface
if (matchField->included_ar[i]) {
// If element is present in current interface
// Copy special elements in special way
switch (matchField->type) {
case UNIREC_FIELD_IP:
if ((en_id == 0 && (ipfix_id == 8 || ipfix_id == 12)) ||
(en_id == 39499 && ipfix_id == 40)) {
// IPv4 or INVEA_SIP_RTP_IPV4
// Put IPv4 into 128 bits in a special way (see ipaddr.h in Nemea-UniRec for details)
*(uint64_t*)(conf->ifc[i].buffer + matchField->offset_ar[i]) = 0;
*(uint32_t*)(conf->ifc[i].buffer + matchField->offset_ar[i] + 8) = *(uint32_t*)(data_record + offset + size_length);
*(uint32_t*)(conf->ifc[i].buffer + matchField->offset_ar[i] + 12) = 0xffffffff;
} else {
// IPv6 or INVEA_SIP_RTP_IPV6
memcpy(conf->ifc[i].buffer + matchField->offset_ar[i], data_record + offset + size_length, length);
}
break;
case UNIREC_FIELD_PACKET:
// PACKET SIZE IS DIFFERENT FOR DIFFERENT EXPORTER!!!
if (template->fields[index].ie.length == 4) {
*(uint32_t*)(conf->ifc[i].buffer + matchField->offset_ar[i]) = ntohl(*(uint32_t*)(data_record + offset + size_length));
}
else if (template->fields[index].ie.length == 8) {
*(uint32_t*)(conf->ifc[i].buffer + matchField->offset_ar[i]) = ntohl(*(uint32_t*)(data_record + offset + size_length + 4));
} else {
*(uint32_t*)(conf->ifc[i].buffer + matchField->offset_ar[i]) = 0xFFFFFFFF;
}
break;
case UNIREC_FIELD_TS:
// Handle Time variables
msec = be64toh(*(uint64_t*)(data_record + offset + size_length));
sec = msec / 1000;
frac = ((msec % 1000) * 0x4189374BC6A7EFULL) >> 32;
*(uint64_t*)(conf->ifc[i].buffer + matchField->offset_ar[i]) = (sec<<32) | frac;
break;
case UNIREC_FIELD_DBF:
// Handle DIR_BIT_FIELD
*(uint8_t*)(conf->ifc[i].buffer + matchField->offset_ar[i]) = ((*(uint16_t*)(data_record + offset + size_length)) >> 8) & 0x1;
break;
case UNIREC_FIELD_LBF:
// Handle LINK_BIT_FIELD, is BIG ENDIAN but we are using only LSB
// Only do this if ODID JOINFLOWS method
if (conf->ODID_get_method == ODID_JOINFLOWS_METHOD) {
*(uint64_t*)(conf->ifc[i].buffer + matchField->offset_ar[i]) = 1LLU << ((*(uint8_t*)(data_record + offset + size_length + 3)) - 1);
}
break;
default:
// Check length of ipfix element and if it is larger than unirec element, then saturate unirec element
if (matchField->size >= length) {
data_copy( (conf->ifc[i].buffer) + matchField->offset_ar[i], // Offset to Unirec buffer for current ifc
(data_record + offset + size_length), // Offset to data in Ipfix message
length); // Size of element
} else {
// set maximum value to unirec element
memset( (conf->ifc[i].buffer) + matchField->offset_ar[i],
0xFF,
matchField->size);
}
}
// if required, add required-filled count
conf->ifc[i].requiredFilled += matchField->required_ar[i];
}
}
} else {
// Dynamic element
matchField->valueSize = length;
matchField->value = (void*) (data_record + offset + size_length);
matchField->valueFilled = 1;
// Fill required count for Unirec where this element is required
for (int i = 0; i < conf->ifc_count; i++) {
// For every interface
if (matchField->included_ar[i]) {
// If element is present in current ifc
conf->ifc[i].requiredFilled += matchField->required_ar[i];
}
}
}
}
/* Skip enterprise element number if necessary*/
if (template->fields[index].ie.id >> 15) {
index++;
}
/* Skip the length of the value */
offset += length + size_length;
}
return offset;
}
/**
* \brief Copy dynamic fields to output buffer
*
* \param[in] conf Pointer to interface config structure
*/
static void process_dynamic(ifc_config *conf)
{
conf->bufferOffset = conf->bufferStaticSize;
// Cycle throu all fields
for (int i = 0; i < conf->dynCount; i++) {
// Saturate dynamic field size
size_t size = conf->dynAr[i]->valueSize > MAX_DYNAMIC_FIELD_SIZE ? MAX_DYNAMIC_FIELD_SIZE : conf->dynAr[i]->valueSize;
// Store end offset of dynamic value to Unirec buffer
*(uint16_t*)(conf->buffer + conf->dynAr[i]->offset_ar[conf->number]) = (uint16_t)conf->bufferDynSize;
// Store size of dynamic value to Unirec buffer
*(uint16_t*)(conf->buffer + conf->dynAr[i]->offset_ar[conf->number] + 2) = (uint16_t)size;
// If dynamic field was filled, copy it to Unirec buffer
if (conf->dynAr[i]->valueFilled) {
memcpy( conf->buffer + conf->bufferOffset,
conf->dynAr[i]->value,
size);
conf->bufferOffset += size;
conf->bufferDynSize += size;
conf->dynAr[i]->valueFilled = 0;
conf->dynAr[i]->valueSize = 0;
}
}
}
/**
* \brief Process all data sets in IPFIX message
*
* \param[in] ipfix_msg IPFIX message
* \param[in] conf Pointer to interface config structure
* \return 0 on success, -1 otherwise
*/
static int process_data_sets(const struct ipfix_message *ipfix_msg, unirec_config *conf)
{
uint16_t data_index = 0;
struct ipfix_data_set *data_set;
char *data_record;
struct ipfix_template *template;
uint32_t offset;
uint16_t min_record_length, ret = 0;
int i;
// ********** Store ODID *************
uint32_t ODID = ntohl(ipfix_msg->pkt_header->observation_domain_id);
// Fill ODID
conf->odid = (uint16_t) ODID;
// ***********************************
data_set = ipfix_msg->data_couple[data_index].data_set;
while (data_set) {
template = ipfix_msg->data_couple[data_index].data_template;
/* Skip datasets with missing templates */
if (template == NULL) {
/* Process next set */
data_set = ipfix_msg->data_couple[++data_index].data_set;
continue;
}
min_record_length = template->data_length;
offset = 4; /* Size of the header */
if (min_record_length & 0x8000) {
/* Record contains fields with variable length */
min_record_length = min_record_length & 0x7fff; /* size of the fields, variable fields excluded */
}
while ((int) ntohs(data_set->header.length) - (int) offset - (int) min_record_length >= 0) {
data_record = (((char *) data_set) + offset);
// Process data record only once
ret = process_record(data_record, template, conf);
// Check that the record was processes successfuly
if (ret == 0) {
return -1;
}
//Fill dynamic fields for every UniRec record and send it
for (i = 0; i < conf->ifc_count; i++) {
// Check if we have all required fields
if (conf->ifc[i].requiredCount == conf->ifc[i].requiredFilled) {
// Fill dynamic fields if there are ones
if (conf->ifc[i].dynamic) {
process_dynamic(&(conf->ifc[i]));
}
// Send record
trap_ctx_send( conf->trap_ctx_ptr,
conf->ifc[i].number,
conf->ifc[i].buffer,
conf->ifc[i].bufferStaticSize + conf->ifc[i].bufferDynSize);
// conf->ifc[i].timeout); // Timeout is set by IFCCTL
} else {
// Set default values for dynamic fields
for (int j = 0; j < conf->ifc[i].dynCount; j++) {
conf->ifc[i].dynAr[j]->valueFilled = 0;
conf->ifc[i].dynAr[j]->valueSize = 0;
}
}
// Clear static fields
memset(conf->ifc[i].buffer, 0, conf->ifc[i].bufferStaticSize);
conf->ifc[i].requiredFilled = 0;
conf->ifc[i].bufferDynSize = 0;
}
offset += ret;
}
/* Process next set */
data_set = ipfix_msg->data_couple[++data_index].data_set;
}
return 0;
}
/**
* \brief Destroys and frees an unirecField structure
*
* @param field Field to destroy
*/
static void destroy_field(unirecField *field)
{
/* Free field name */
free(field->name);
free(field->included_ar);
free(field->required_ar);
free(field->offset_ar);
if (field->size > 0) {
free(field->value);
}
/* Free field */
free(field);
}
/**
* \brief Destroy UniRec fields list
*
* @param fields Field list to destroy
*/
static void destroy_fields(unirecField *fields)
{
unirecField *tmp;
while (fields != NULL) {
/* Save last position */
tmp = fields;
/* Move pointer */
fields = fields->next;
/* Free field */
destroy_field(tmp);
}
}
/**
* \brief Creates IPFIX id from string
*
* @param ipfixToken String in eXXidYY format, where XX is enterprise number and YY is element ID
* @return Returns id that is used to compare field against IPFIX template
*/
static ipfixElement ipfix_from_string(char *ipfixToken)
{
ipfixElement element;
char *endptr;
element.en = strtol(ipfixToken + 1, &endptr, 10);
element.id = strtol(endptr + 2, (char **) NULL, 10);
return element;
}
static int8_t checkUnirecType(const char *type)
{
int i;
for (i = 0; i < UNIREC_DATA_TYPES_COUNT; i++) {
if (strcmp(type, unirec_data_types_str[i]) == 0) {
return i;
}
}
return -1;
}
/**
* \brief Convert ipfix element id to unirec type for faster processing ipfix messages
* \param ipfix_el Ipfix element structure.
* \return One value from enum `unirecFieldEnum`.
*/
static int8_t getUnirecFieldTypeFromIpfixId(ipfixElement ipfix_el)
{
uint16_t id = ipfix_el.id;
uint32_t en = ipfix_el.en;
if ((en == 0 && (id == 8 || id == 12)) ||
(en == 39499 && id== 40) ||
(en == 0 && (id == 27 || id == 28)) ||
(en == 39499 && id == 41)) {
// IP or INVEA_SIP_RTP_IP
return UNIREC_FIELD_IP;
} else if (en == 0 && id == 2) {
// Packets
return UNIREC_FIELD_PACKET;
} else if (en == 0 && (id == 152 || id == 153)) {
// Timestamps
return UNIREC_FIELD_TS;
} else if (en == 0 && id == 10) {
// DIR_BIT_FIELD
return UNIREC_FIELD_DBF;
} else if (en == 0 && id == 405) {
// LINK_BIT_FIELD
return UNIREC_FIELD_LBF;
} else {
// Other
return UNIREC_FIELD_OTHER;
}
}
/**
* \brief Loads all available elements from configuration file
* @return List of UniRec elements on success, NULL otherwise
*/
static unirecField *load_elements()
{
FILE *uef = NULL;
char *line;
size_t lineSize = 100;
ssize_t res;
char *token, *state; /* Variables for strtok */
unirecField *fields = NULL, *currentField = NULL;
/* Open the file */
uef = fopen(UNIREC_ELEMENTS_FILE, "r");
if (uef == NULL) {
MSG_ERROR(msg_module, "Cannot load UniRec configuration file (\"%s\")", UNIREC_ELEMENTS_FILE);
return NULL;
}
/* Init buffer */
line = malloc(lineSize);
/* Process all lines */
while (1) {
/* Read one line */
res = getline(&line, &lineSize, uef);
if (res <= 0) {
break;
}
/* Exclude comments */
if (line[0] == '#') continue;
/* Create new element structure, make space for ipfixElCount ipfix elements and NULL */
currentField = malloc(sizeof(unirecField));
currentField->name = NULL;
currentField->value = NULL;
currentField->offset_ar = NULL;
currentField->required_ar = NULL;
currentField->included_ar = NULL;
/* Read individual tokens */
int position = 0;
for (token = strtok_r(line, " \t", &state); token != NULL; token = strtok_r(NULL, " \t", &state), position++) {
switch (position) {
case 0:
currentField->name = strdup(token);
break;
case 1:
currentField->unirec_type = checkUnirecType(token);
if (currentField->unirec_type < 0) {
MSG_ERROR(msg_module, "Unknown UniRec data type \"%s\" of field \"%s\"", token, currentField->name);
fclose(uef);
free(line);
return NULL;
}
break;
case 2:
currentField->size = atoi(token);
break;
case 3: {
/* Split the string */
char *ipfixToken, *ipfixState; /* Variables for strtok */
int ipfixPosition = 0;
currentField->ipfixCount = 0;
for (ipfixToken = strtok_r(token, ",", &ipfixState);
ipfixToken != NULL;
ipfixToken = strtok_r(NULL, ",", &ipfixState), ipfixPosition++) {
/* Enlarge the element if necessary */
if (ipfixPosition > 0) {
currentField = realloc(currentField, sizeof(unirecField) + (ipfixPosition) * sizeof(uint64_t));
}
/* Store the ipfix element id */
currentField->ipfix[ipfixPosition] = ipfix_from_string(ipfixToken);
currentField->ipfixCount++;
/* Fill in Unirec field type based on ipfix element id */
currentField->type = getUnirecFieldTypeFromIpfixId(currentField->ipfix[ipfixPosition]);
}
break;
} // case 2 end
} // switch end
}
/* Check that all necessary data was provided */
if (position < 3) {
if (currentField->name) {
free(currentField->name);
}
free(currentField);
continue;
}
currentField->next = fields;
fields = currentField;
}
fclose(uef);
free(line);
return fields;
}
/**
* \brief Update field's length and ipfix elements from configuration fields list
*
* @param currentField Field to update
* @param confFields Field list loaded from configuration
* @param dynamic Flag is set to 1 if current element is dynamic, 0 otherwise
* @return Returns 0 on success
*/
static int update_field(unirecField **currentField, unirecField *confFields, int *dynamic)
{
unirecField *tmp;
int updated = 0;
*dynamic = 0; // Assume there is no dynamic field, if there is then change this variable to 1
/* Look for specified element */
for (tmp = confFields; tmp != NULL; tmp = tmp->next) {
if (strcmp((*currentField)->name, tmp->name) == 0) {
(*currentField)->size = tmp->size;
(*currentField)->ipfixCount = 0;
(*currentField)->type = tmp->type;
(*currentField)->unirec_type = tmp->unirec_type;
if (tmp->size == -1) {
// If it is dynamic field, set dynamic to 1
*dynamic = 1;
}
/* Copy IPFIX element identifiers */
int i;
for (i = 0; i < tmp->ipfixCount; i++) {
/* Realloc when there is more than one element */
if (i > 0) {
(*currentField) = realloc((*currentField), sizeof(unirecField) + i * sizeof(uint64_t));
}
(*currentField)->ipfix[i] = tmp->ipfix[i];
(*currentField)->ipfixCount++;
}
/* Set updated flag */
updated = 1;
}
}
/* Return 0 on success */
return 1 - updated;
}
/**
* \brief Parse format of unirec template for every interface specified in startup.xml.
* \param[in] conf Pointer to interface config structure
* @return Returns 0 on success
*/
static int parse_format(unirec_config *conf_plugin)
{
char *token, *state; /* Variables for strtok */
unirecField *lastField, *currentField, *confFields;
int ret;
ifc_config *conf;
int dynamic;
uint16_t field_offset;
uint32_t fields_count = 0;
/* Load elements from configuration file */
confFields = load_elements();
for (int c = 0; c < conf_plugin->ifc_count; c++) {
conf = &conf_plugin->ifc[c];
conf->dynamic = 0;
conf->dynCount = 0;
field_offset = 0;
lastField = NULL;
currentField = NULL;
if (conf->format == NULL) {
return -1;
}
// Allocate memory for dynamic fields array
conf->dynAr = malloc(sizeof(unirecField*) * INIT_DYNAMIC_ARR_SIZE);
conf->dynArAlloc = INIT_DYNAMIC_ARR_SIZE;
char *unirec_data_format = NULL, *unirec_data_format_move = NULL, *unirec_data_format_new = NULL;
int unirec_data_format_len = UNIREC_DEFAULT_LENGTH_OF_DATA_FORMAT, unirec_data_format_act_len = 0;
unirec_data_format = (char*) calloc (sizeof(char), unirec_data_format_len);
if (unirec_data_format == NULL) {
return -1;
}
unirec_data_format_move = unirec_data_format;
// Allocate memory for output data buffer
conf->buffer = malloc(INIT_OUTPUT_BUFFER_SIZE);
if (conf->buffer == NULL) {
return -1;
}
conf->bufferAllocSize = INIT_OUTPUT_BUFFER_SIZE;
memset(conf->buffer, 0, conf->bufferAllocSize);
// Used for static size overflow check
conf->bufferSize = conf->bufferAllocSize;
// ****** Split string to tokens ******
for (token = strtok_r(conf->format, ",", &state); token != NULL; token = strtok_r(NULL, ",", &state)) {
// Add it to config array if it is not there yet
lastField = conf_plugin->fields;
// Check if field is already present in fields list or if it is new field
while (1) {
// Try to find field in field list
if (lastField != NULL && strcmp(lastField->name, token[0] == '?' ? token + 1 : token) == 0) {
// Element is already present in config array so we do not need to add it
// but we need to adjust required_ar and included_ar and offset_ar
if (token[0] == '?') {
lastField->required_ar[c] = 0;
} else {
lastField->required_ar[c] = 1;
// Do not count DIRECTION_FLAGS as required value because it is always present
// Do not count LINK_BIT_FIELD as required value because it is always present (only in manager method)
// *These two fields are filled in specific way and they dont have to have required flag
if ((strcmp(token, "DIRECTION_FLAGS") == 0) ||
(strcmp(token, "LINK_BIT_FIELD") == 0 && conf_plugin->ODID_get_method == ODID_MANAGER_METHOD)) {
; // NOP (this way the condition is writed in nicer way)
} else {
conf->requiredCount++;
}
}
lastField->included_ar[c] = 1;
lastField->offset_ar[c] = field_offset;
if (lastField->size == -1) {
// Dynamic field
field_offset += 4; // 2B is size of offset of the end of dynamic field in unirec record + 2B is size of length.
conf->bufferStaticSize += 4; // same as above
// Add last field to dynAr and update dynamic field counter
conf->dynAr[conf->dynCount] = lastField;
conf->dynCount++;
if (conf->dynCount >= conf->dynArAlloc) {
conf->dynArAlloc += INIT_DYNAMIC_ARR_SIZE;
conf->dynAr = realloc(conf->dynAr, sizeof(unirecField*) * conf->dynArAlloc);
}
// Update output buffer for new dynamic value
conf->bufferAllocSize += MAX_DYNAMIC_FIELD_SIZE;
conf->buffer = realloc(conf->buffer, conf->bufferAllocSize);
} else {
conf->bufferStaticSize += lastField->size;
field_offset += lastField->size;
// Update output buffer size if needed
if (conf->bufferSize <= conf->bufferStaticSize) {
conf->bufferAllocSize += INIT_OUTPUT_BUFFER_SIZE;
conf->buffer = realloc(conf->buffer, conf->bufferAllocSize);
conf->bufferSize += INIT_OUTPUT_BUFFER_SIZE;
}
}
// Append field to UniRec output data format
unirec_data_format_act_len += strlen(unirec_data_types_str[lastField->unirec_type]) + strlen(lastField->name) + 2;
if (unirec_data_format_act_len >= unirec_data_format_len) {
unirec_data_format_len *= 2;
unirec_data_format_new = (char*) realloc (unirec_data_format, sizeof(char) * unirec_data_format_len);
if (unirec_data_format_new == NULL) {
free(unirec_data_format);
return -1;
}
unirec_data_format_move = unirec_data_format_new + (unirec_data_format_move - unirec_data_format);
unirec_data_format = unirec_data_format_new;
}
sprintf(unirec_data_format_move, "%s %s,", unirec_data_types_str[lastField->unirec_type], lastField->name);
unirec_data_format_move += strlen(unirec_data_format_move);
break;
}
// If it is very first field or it was not found in fields list, then create it and add it to fields list
if (lastField == NULL || lastField->next == NULL) {
/* Create new field element */
currentField = malloc(sizeof(unirecField));
currentField->required_ar = malloc(sizeof(uint8_t) * conf_plugin->ifc_count);
currentField->included_ar = malloc(sizeof(uint8_t) * conf_plugin->ifc_count);
currentField->offset_ar = malloc(sizeof(uint16_t) * conf_plugin->ifc_count);
memset(currentField->required_ar, 0, conf_plugin->ifc_count);
memset(currentField->included_ar, 0, conf_plugin->ifc_count);
memset(currentField->offset_ar, 0, 2 * conf_plugin->ifc_count); // 2Bytes * ifc count
/* Init values used for iteration */
currentField->next = NULL;
currentField->nextIfc = NULL;
currentField->value = NULL;
currentField->valueSize = 0;
currentField->valueFilled = 0;
currentField->ipfixCount = 0;
currentField->included_ar[c] = 1;
currentField->offset_ar[c] = field_offset;
/* Fill name and required values */
if (token[0] == '?') {
currentField->required = 0;
currentField->name = strdup(token + 1);
currentField->required_ar[c] = 0;
} else {
conf->requiredCount++;
currentField->required = 1;
currentField->name = strdup(token);
currentField->required_ar[c] = 1;
}
/* Handle special fields */
if (strcmp(currentField->name, "DIRECTION_FLAGS") == 0) {
conf->requiredCount--; // Is required but it is always present
currentField->size = 1;
currentField->value = malloc(1);
currentField->valueSize = 1;
currentField->ipfixCount = 1; // Only for compatibility with other elements
currentField->ipfix[0].id = 0; // when comparing
currentField->ipfix[0].en = 0; //
} else
if ((strcmp(currentField->name, "LINK_BIT_FIELD") == 0) &&
(conf_plugin->ODID_get_method = ODID_MANAGER_METHOD)) {
// Only in ODID manager method
conf_plugin->LBF_field = currentField;
conf->requiredCount--; // Is required but it is always present
currentField->size = 8;
currentField->value = malloc(8);
currentField->valueSize = 8;
currentField->unirec_type = 9; // uint64
currentField->ipfixCount = 1; // Only for compatibility with other elements
currentField->ipfix[0].id = 0; // when comparing
currentField->ipfix[0].en = 0; //
} else {
/* Fill values from configuration file */
ret = update_field(¤tField, confFields, &dynamic);
if (ret) {
MSG_ERROR(msg_module, "Field \"%s\" is not present in UniRec configuration file", currentField->name);
destroy_field(currentField);
destroy_fields(confFields);
return 1;
}
conf->dynamic |= dynamic; // Set dynamic field flag on interface
}
// Update offset of current field
currentField->offset_ar[c] = field_offset;