summaryrefslogtreecommitdiffstats
path: root/wiretap/cllog.c
blob: 3ca4b333760ea26f4e0088ba691f166bd0dfaeaa (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
/* cllog.c
 *
 * Wiretap Library
 * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

/*
 * Reads log files from CLX000 CAN loggers from CSS Electronics:
 *
 *    https://canlogger.csselectronics.com/clx000-docs/cl1000/log/index.html
 *    https://canlogger.csselectronics.com/clx000-docs/cl2000/log/index.html
 *
 * Based on the cCLLog.c, cCLLog.h, and wtap-cllog.c source files from
 * the WS_v2.4-Plugin_v7.1.zip version of the CSS Electronics plugin at
 *
 *    https://canlogger.csselectronics.com/downloads.php?q=wireshark
 *
 * with the files combined into one source file, modernized to
 * fit into an up-to-date version of Wireshark, and cleaned up
 * not to, for example, do seeks by rewinding and reading to
 * get to the seek target.
 *
 * It could probably use some further cleanup.
 */

#include "config.h"

#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#include <wsutil/str_util.h>
#include <wsutil/strtoi.h>

#include "wtap-int.h"
#include "file_wrappers.h"

/***********************************************************************************************************************
 * Public definitions
 **********************************************************************************************************************/
#define MAX_LOG_LINE_FIELDS 7 /*( seqNo, timestamp, lost, SE, ID, length, data) */
/***********************************************************************************************************************
 * Public type declarations
 **********************************************************************************************************************/
/* Time stamp structure type (sec since start + ms resolution) */
typedef struct { time_t epoch; uint16_t ms; } cCLLog_timeStamp_t;

 /* Message type */
typedef enum
{
    msg_rx_standard_e = 0,
    msg_rx_extended_e = 1,
    msg_tx_standard_e = 7,
    msg_tx_extended_e = 8,
} cCLLog_messageType_t;

/* Typedef CAN-bus message type */
typedef struct
{
    cCLLog_timeStamp_t timestamp;
    uint32_t lost;
    cCLLog_messageType_t msgType;
    uint32_t id;
    uint8_t length;
    uint8_t data[ 8 ];
} cCLLog_message_t;

/* Silent-mode*/
typedef enum { silent_disabled_e = 0, silent_enabled_e } cCLLog_silentMode_t;

/* Cyclic-mode*/
typedef enum { cyclic_disabled_e = 0, cyclic_enabled_e } cCLLog_cyclicMode_t;

/* Logger type */
typedef enum { type_CL1000_e = 0, type_CL2000_e, type_CL3000_e } cCLLog_loggerType_t;

typedef char * (*CLLog_gets_t)(char *s, int size, void *stream);
typedef int (*CLLog_rewind_t)(void *stream);

typedef struct cLLog_private cCLLog_logFileInfo_t;

/* Type used to parse a field in a log line */
typedef bool (*parseFieldFunc_t)(cCLLog_logFileInfo_t *pInfo, char *pField, cCLLog_message_t *pLogEntry, int *err, char **err_info);

/* Log file information */
struct cLLog_private
{
    uint32_t firstLogRow;
    cCLLog_loggerType_t loggerType;
    char hwrev[5];
    char fwrev[5];
    char id[20];
    uint32_t sessionNo;
    uint32_t splitNo;
    cCLLog_timeStamp_t logStartTime;
    char logStartTimeString[ 20 ];
    char separator;
    uint8_t timeFormat;
    char timeSeparator;
    char timeSeparatorMs;
    char dateSeparator;
    char dateAndTimeSeparator;
    uint32_t bitRate;
    cCLLog_silentMode_t silentMode;
    cCLLog_cyclicMode_t cyclicMode;

    parseFieldFunc_t parseFieldFunc[ MAX_LOG_LINE_FIELDS ];

    /* First log time stamp as relative offset */
    cCLLog_timeStamp_t firstTimeStampAbs;
};

/***********************************************************************************************************************
 * Private definitions
 **********************************************************************************************************************/
#define HEADER_LINE_PARSE_MAPPING_LENGTH array_length(headerLineParseMapping)
#define MAX_LOG_LINE_LENGTH 200
#define TIME_STAMP_STRING_MAX_LENGTH ( sizeof( "YYYY/MM/DDThh:mm:ss.kkk" ) )
#define TIME_STAMP_STRING_STRIPPED_MAX_LENGTH ( sizeof( "YYYYMMDDhhmmsskkk" ) )

/***********************************************************************************************************************
 * Private type definitions
 **********************************************************************************************************************/
/* Function type to parse a single log file line */
typedef bool (*parseFunc_t)(cCLLog_logFileInfo_t *pInfo, char *pLine, int *err, char **err_info);

/* Structure of the header parse mapping. A match string is paired with a parse function */
typedef struct
{
    const char *pMatchString;
    parseFunc_t parseFunc;
} headerLineParseMapping_t;

/***********************************************************************************************************************
 * Private function declarations
 **********************************************************************************************************************/
static bool parseColumnHeaderFields( cCLLog_logFileInfo_t *pInfo, char *pColLine );
static uint8_t stripTimeStamp( const cCLLog_logFileInfo_t *pInfo, char *pTimeStampString );

/* Parse header lines functions */
static bool parseLogFileHeaderLine_type(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_hwrev(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_fwrev(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_id(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_sessionNo(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_splitNo(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_time(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_valueSeparator(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_timeFormat(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_timeSeparator(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_timeSeparatorMs(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_dateSeparator(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_timeAndDateSeparator(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_bitRate(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_silentMode(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
static bool parseLogFileHeaderLine_cyclicMode(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info);
/***********************************************************************************************************************
 * Private variable definitions
 **********************************************************************************************************************/

/* Array of header line match strings and associated parse functions */
static const headerLineParseMapping_t headerLineParseMapping[] =
{
    { .pMatchString = "Logger type: ", .parseFunc = parseLogFileHeaderLine_type},
    { .pMatchString = "HW rev: ", .parseFunc = parseLogFileHeaderLine_hwrev },
    { .pMatchString = "FW rev: ", .parseFunc = parseLogFileHeaderLine_fwrev },
    { .pMatchString = "Logger ID: ", .parseFunc = parseLogFileHeaderLine_id},
    { .pMatchString = "Session No.: ", .parseFunc = parseLogFileHeaderLine_sessionNo},
    { .pMatchString = "Split No.: ", .parseFunc = parseLogFileHeaderLine_splitNo},
    { .pMatchString = "Time: ", .parseFunc = parseLogFileHeaderLine_time},
    { .pMatchString = "Value separator: ", .parseFunc = parseLogFileHeaderLine_valueSeparator},
    { .pMatchString = "Time format: ", .parseFunc = parseLogFileHeaderLine_timeFormat},
    { .pMatchString = "Time separator: ", .parseFunc = parseLogFileHeaderLine_timeSeparator},
    { .pMatchString = "Time separator ms: ", .parseFunc = parseLogFileHeaderLine_timeSeparatorMs},
    { .pMatchString = "Date separator: ", .parseFunc = parseLogFileHeaderLine_dateSeparator},
    { .pMatchString = "Time and date separator: ", .parseFunc = parseLogFileHeaderLine_timeAndDateSeparator},
    { .pMatchString = "Bit-rate: ", .parseFunc = parseLogFileHeaderLine_bitRate},
    { .pMatchString = "Silent mode: ", .parseFunc = parseLogFileHeaderLine_silentMode},
    { .pMatchString = "Cyclic mode: ", .parseFunc = parseLogFileHeaderLine_cyclicMode},
};

/*
 * Do a string copy to a buffer of a specified length.
 * If the string will fit, return true.
 * If the string won't fit, return false.
 */
static bool
checked_strcpy(char *dest, size_t destlen, const char *src)
{
    size_t srclen;

    srclen = strlen(src) + 1; // count the trailing '\0'
    if (srclen > destlen)
        return false;
    memcpy(dest, src, srclen);
    return true;
}

/* TODO: Does not support separators set to numbers (will remove part of the time stamp also */
/* TODO: Does not support time stamps without ms, as given in the header */
/* TODO: Alot of copying slows down the parsing */
static bool parseFieldTS(cCLLog_logFileInfo_t *pInfo, char *pField, cCLLog_message_t *pLogEntry, int *err, char **err_info)
{
    struct tm tm;
    int ms;

    /* Copy the string to not modify the original */
    char timeStampCopy[TIME_STAMP_STRING_MAX_LENGTH];
    if (!checked_strcpy(timeStampCopy, sizeof timeStampCopy, pField))
    {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup("cllog: time stamp is too long");
        return false;
    }

    /* Copy the header time stamp string to not modify the original */
    char timeStampHeaderCopy[TIME_STAMP_STRING_MAX_LENGTH];
    if (!checked_strcpy(timeStampHeaderCopy, sizeof timeStampHeaderCopy, pInfo->logStartTimeString))
    {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup("cllog: header time stamp too long");
        return false;
    }

    /* Strip the delimiters from the time strings */
    uint8_t msgTimeStrippedLen = stripTimeStamp(pInfo, timeStampCopy);
    if (msgTimeStrippedLen > TIME_STAMP_STRING_STRIPPED_MAX_LENGTH - 1) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup("cllog: time stamp incorrectly formatted");
        return false;
    }

    uint8_t headerTimeStrippedLen = stripTimeStamp(pInfo, timeStampHeaderCopy);
    if (headerTimeStrippedLen > TIME_STAMP_STRING_STRIPPED_MAX_LENGTH - 1) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup("cllog: header time stamp incorrectly formatted");
        return false;
    }

    /* Set time string (YYYYMMDDhhmmsskkk) to the epoch */
    char timeStampStringFull[TIME_STAMP_STRING_STRIPPED_MAX_LENGTH] = "19700101000000000";

    /* Copy the header time to the template */
    memcpy(timeStampStringFull, timeStampHeaderCopy, headerTimeStrippedLen);

    /* Copy the stripped timestamp into the full template */
    memcpy(&timeStampStringFull[TIME_STAMP_STRING_STRIPPED_MAX_LENGTH - 1 - msgTimeStrippedLen], timeStampCopy, msgTimeStrippedLen);
    timeStampStringFull[TIME_STAMP_STRING_STRIPPED_MAX_LENGTH - 1] = '\0';

    memset(&tm, 0, sizeof tm);

    /* YYYYMMDDThhmmss */
    sscanf(timeStampStringFull, "%4u%2u%2u%2u%2u%2u%3d",
            &tm.tm_year,
            &tm.tm_mon,
            &tm.tm_mday,
            &tm.tm_hour,
            &tm.tm_min,
            &tm.tm_sec,
            &ms
            );
    tm.tm_mon -= 1;
    tm.tm_year -= 1900;

    /* To Epoch (mktime converts to epoch from local (!!!) timezone) */
    pLogEntry->timestamp.epoch = mktime(&tm);
    pLogEntry->timestamp.ms = ms;

    /* Is first time stamp ? */
    if (pInfo->firstTimeStampAbs.epoch == 0 && pInfo->firstTimeStampAbs.ms == 0)
    {
        pInfo->firstTimeStampAbs.epoch = pLogEntry->timestamp.epoch;
        pInfo->firstTimeStampAbs.ms = pLogEntry->timestamp.ms;
    }

    return true;
}

static bool parseFieldLost(cCLLog_logFileInfo_t *pInfo _U_, char *pField, cCLLog_message_t *pLogEntry, int *err, char **err_info)
{
    uint32_t lost;

    if (!ws_strtou32(pField, NULL, &lost)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup_printf("cllog: lost packet count value is not valid");
        return false;
    }
    pLogEntry->lost = lost;
    return true;
}

static bool parseFieldMsgType(cCLLog_logFileInfo_t *pInfo _U_, char *pField, cCLLog_message_t *pLogEntry, int *err, char **err_info)
{
     switch (pField[0])
    {
        case '0':
            pLogEntry->msgType = msg_rx_standard_e;
            return true;
        case '1':
            pLogEntry->msgType = msg_rx_extended_e;
            return true;
        case '8':
            pLogEntry->msgType = msg_tx_standard_e;
            return true;
        case '9':
            pLogEntry->msgType = msg_tx_extended_e;
            return true;
        default:
            *err = WTAP_ERR_BAD_FILE;
            *err_info = g_strdup("cllog: unknown message type");
            return false;
    }
}

static bool parseFieldID(cCLLog_logFileInfo_t *pInfo _U_, char *pField, cCLLog_message_t *pLogEntry, int *err, char **err_info)
{
    uint32_t id;

    if (!ws_hexstrtou32(pField, NULL, &id)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup_printf("cllog: ID value is not valid");
        return false;
    }
    pLogEntry->id = id;
    return true;
}

static bool parseFieldLength(cCLLog_logFileInfo_t *pInfo _U_, char *pField, cCLLog_message_t *pLogEntry, int *err, char **err_info)
{
    uint32_t length;

    if (!ws_strtou32(pField, NULL, &length)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup_printf("cllog: length value is not valid");
        return false;
    }
    pLogEntry->length = length;
    return true;
}

static bool parseFieldData(cCLLog_logFileInfo_t *pInfo _U_, char *pField, cCLLog_message_t *pLogEntry, int *err, char **err_info)
{
    char *pFieldStart = pField;

    /* Set data length in case length field is not set explicitly in the log file */
    pLogEntry->length = 0;

    /* Loop all data bytes */
    for (unsigned int dataByte = 0; dataByte < 8; dataByte++)
    {
        int hexdigit;
        uint8_t data;

        if (*pFieldStart == '\n' || *pFieldStart == '\r')
        {
            break;
        }

        hexdigit = ws_xton(*pFieldStart);
        if (hexdigit < 0) {
            *err = WTAP_ERR_BAD_FILE;
            *err_info = g_strdup_printf("cllog: packet byte value is not valid");
            return false;
        }
        data = (uint8_t)hexdigit << 4U;
        pFieldStart++;
        hexdigit = ws_xton(*pFieldStart);
        if (hexdigit < 0) {
            *err = WTAP_ERR_BAD_FILE;
            *err_info = g_strdup("cllog: packet byte value is not valid");
            return false;
        }
        data = data | (uint8_t)hexdigit;
        pFieldStart++;
        pLogEntry->data[dataByte] = data;

        pLogEntry->length++;
    }
    return true;
}

static bool parseLogLine(cCLLog_logFileInfo_t *pInfo, char *pLine, cCLLog_message_t *pLogEntry, int *err, char **err_info)
{
    char *pFieldStart = pLine;

    /* Loop all fields in log line */
    for (unsigned int fieldNo = 0, finalField = 0; fieldNo < MAX_LOG_LINE_FIELDS && finalField == 0; fieldNo++)
    {
        /* Find field end by separator */
        char *pFieldEnd = strchr(pFieldStart, pInfo->separator);

        /* If final field, then EOL marks the end of the field */
        if (pFieldEnd == NULL)
        {
            pFieldEnd = strchr(pFieldStart, '\n');
            finalField = 1;
        }

        /* Replace separator with string termination */
        *pFieldEnd = '\0';

        /* Is parse function assigned to field? */
        if (pInfo->parseFieldFunc[fieldNo] != NULL)
        {
            /* Parse field */
            if (!pInfo->parseFieldFunc[fieldNo](pInfo, pFieldStart, pLogEntry, err, err_info))
            {
                return false;
            }
        }

        /* Skip over the separator */
        pFieldStart = pFieldEnd + 1;
    }
    return true;
}

/***********************************************************************************************************************
 * parseColumnHeaderFields
 *
 * Parse the column fields and determine which fields are present and the position of the fields
 *
 * @param[ in ]         pInfo           Pointer to the CLLog object
 * @param[ in ]         pColLine        The column line
 **********************************************************************************************************************/
static bool parseColumnHeaderFields( cCLLog_logFileInfo_t *pInfo, char *pColLine )
{
    bool resultFlag = false;

    /* Initialise field start */
    char *pFieldStart = pColLine;

    /* Loop all fields in line */
    for ( uint8_t fieldNo = 0, finalField = 0 ; fieldNo < MAX_LOG_LINE_FIELDS && finalField == 0 ; fieldNo++ )
    {
        /* Find field end */
        char *pFieldEnd = strchr( pFieldStart, pInfo->separator );

        /* If final field, then EOL marks the end of the field */
        if( pFieldEnd == NULL )
        {
            pFieldEnd = strchr( pFieldStart, '\n' );
            finalField = 1;
        }

        /* Replace separator with string termination */
        *pFieldEnd = '\0';

        /* Set field number */
        if( strcmp( pFieldStart, "Timestamp" ) == 0 )  { pInfo->parseFieldFunc[ fieldNo ] = parseFieldTS; resultFlag = true; }
        if( strcmp( pFieldStart, "Lost" ) == 0 )       { pInfo->parseFieldFunc[ fieldNo ] = parseFieldLost; resultFlag = true; }
        if( strcmp( pFieldStart, "Type" ) == 0 )       { pInfo->parseFieldFunc[ fieldNo ] = parseFieldMsgType; resultFlag = true; }
        if( strcmp( pFieldStart, "ID" ) == 0 )         { pInfo->parseFieldFunc[ fieldNo ] = parseFieldID; resultFlag = true; }
        if( strcmp( pFieldStart, "Length" ) == 0 )     { pInfo->parseFieldFunc[ fieldNo ] = parseFieldLength; resultFlag = true; }
        if( strcmp( pFieldStart, "Data" ) == 0 )       { pInfo->parseFieldFunc[ fieldNo ] = parseFieldData; resultFlag = true; }

        /* Set start of next field to end of previous + 1 */
        pFieldStart = pFieldEnd + 1;
    }

    return resultFlag;
}

/***********************************************************************************************************************
 * stripTimeStamp
 *
 * Strips a time stamp string for any delimiters
 **********************************************************************************************************************/
static uint8_t stripTimeStamp( const cCLLog_logFileInfo_t *pInfo, char *pTimeStampString )
{
    uint8_t strippedLength = 0U;

    /* Char by char, strip the delimiters from the time stamp string */
    size_t timeStampStringLen = strlen( pTimeStampString );
    for (size_t i = 0U; i < timeStampStringLen; i++ )
    {
        /* Get char */
        char charTmp = pTimeStampString[i];

        /* If delimiter, skip */
        if( charTmp == pInfo->separator ){ continue; }
        if( charTmp == pInfo->timeSeparator ){ continue; }
        if( charTmp == pInfo->timeSeparatorMs ){ continue; }
        if( charTmp == pInfo->dateSeparator ){ continue; }
        if( charTmp == pInfo->dateAndTimeSeparator ){ continue; }

        /* Not a delimiter, keep char */
        pTimeStampString[ strippedLength++ ] = charTmp;
    }
    pTimeStampString[ strippedLength ] = '\0';

    return strippedLength;
}

static bool parseString(const char *pFieldValue, char *valuep, size_t valueSize, char *fieldName, int *err, char **err_info)
{
    if (!checked_strcpy(valuep, valueSize, pFieldValue))
    {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup_printf("cllog: %s is too long",
                                     fieldName);
        return false;
    }
    return true;
}

static bool parseUnsigned(const char *pFieldValue, uint32_t *valuep, char *fieldName, int *err, char **err_info)
{
    uint32_t value;

    if (!ws_strtou32(pFieldValue, NULL, &value)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup_printf("cllog: %s value is not valid",
                                     fieldName);
        return false;
    }
    *valuep = value;
    return true;
}

static bool parseSeparator(const char *pFieldValue, char *separatorp, char *fieldName, int *err, char **err_info)
{
    char separator = '\0';

    /* Separator field is if set e.g. ";" - that is 3 chars. Else it is "" */
    if (strlen( pFieldValue) == 3)
    {
        if (pFieldValue[0] != '"' || !g_ascii_isprint(pFieldValue[1]) ||
            pFieldValue[2] != '"')
        {
            *err = WTAP_ERR_BAD_FILE;
            *err_info = ws_strdup_printf("cllog: %s separator is not valid",
                                         fieldName);
            return false;
        }
        separator = pFieldValue[1];
    }
    *separatorp = separator;
    return true;
}

static bool parseBoolean(const char *pFieldValue, bool *value, char *fieldName, int *err, char **err_info)
{
    if (strcmp(pFieldValue, "true") == 0)
    {
        *value = true;
    }
    else if (strcmp(pFieldValue, "false") == 0)
    {
        *value = false;
    }
    else
    {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup_printf("cllog: %s value is not valid",
                                     fieldName);
        return false;
    }
    return true;
}

static bool parseLogFileHeaderLine_type(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    if (strcmp(pFieldValue, "CANLogger1000") == 0 )
    {
        pInfo->loggerType = type_CL1000_e;
    }
    else if (strcmp(pFieldValue, "CANLogger2000") == 0)
    {
        pInfo->loggerType = type_CL2000_e;
    }
    else if (strcmp(pFieldValue, "CANLogger3000") == 0 )
    {
        pInfo->loggerType = type_CL3000_e;
    }
    else
    {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup("cllog: logger type value is not valid");
        return false;
    }
    return true;
}

static bool parseLogFileHeaderLine_hwrev(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseString(pFieldValue, pInfo->hwrev, sizeof pInfo->hwrev, "hardware revision", err, err_info);
}

static bool parseLogFileHeaderLine_fwrev(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseString(pFieldValue, pInfo->fwrev, sizeof pInfo->fwrev, "firmware revision", err, err_info);
}

static bool parseLogFileHeaderLine_id(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseString(pFieldValue, pInfo->id, sizeof pInfo->id, "ID", err, err_info);
}

static bool parseLogFileHeaderLine_sessionNo(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseUnsigned(pFieldValue, &pInfo->sessionNo, "session number", err, err_info);
}

static bool parseLogFileHeaderLine_splitNo(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseUnsigned(pFieldValue, &pInfo->splitNo, "split number", err, err_info);
}

static bool parseLogFileHeaderLine_time(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    struct tm tm;

    memset(&tm, 0, sizeof tm);
    /* YYYYMMDDThhmmss */
    sscanf(pFieldValue,
           "%4u%2u%2uT%2u%2u%2u",
           &tm.tm_year,
           &tm.tm_mon,
           &tm.tm_mday,
           &tm.tm_hour,
           &tm.tm_min,
           &tm.tm_sec);
    tm.tm_mon -= 1;
    tm.tm_year -= 1900;

    /* To Epoch ( mktime converts to epoch from local (!!!) timezone )*/
    pInfo->logStartTime.epoch = mktime(&tm);
    pInfo->logStartTime.ms = 0;

    if (!checked_strcpy(pInfo->logStartTimeString, sizeof pInfo->logStartTimeString, pFieldValue))
    {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup("cllog: time is too long");
        return false;
    }
    return true;
}

static bool parseLogFileHeaderLine_valueSeparator(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseSeparator(pFieldValue, &pInfo->separator, "value", err, err_info);
}

static bool parseLogFileHeaderLine_timeFormat(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    uint32_t format;

    if (!ws_strtou32(pFieldValue, NULL, &format))
    {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup("cllog: time format value is not valid");
        return false;
    }
    if (format > 6)
    {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = g_strdup("cllog: time format value is not valid");
        return false;
    }
    pInfo->timeFormat = (uint8_t)format;
    return true;
}

static bool parseLogFileHeaderLine_timeSeparator(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseSeparator(pFieldValue, &pInfo->timeSeparator, "time", err, err_info);
}

static bool parseLogFileHeaderLine_timeSeparatorMs(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseSeparator(pFieldValue, &pInfo->timeSeparatorMs, "time millisecond", err, err_info);
}

static bool parseLogFileHeaderLine_dateSeparator(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseSeparator(pFieldValue, &pInfo->dateSeparator, "date", err, err_info);
}

static bool parseLogFileHeaderLine_timeAndDateSeparator(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseSeparator(pFieldValue, &pInfo->dateAndTimeSeparator, "date and time", err, err_info);
}

static bool parseLogFileHeaderLine_bitRate(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    return parseUnsigned(pFieldValue, &pInfo->bitRate, "bit rate", err, err_info);
}

static bool parseLogFileHeaderLine_silentMode(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    bool silentMode;

    if (!parseBoolean(pFieldValue, &silentMode, "silent mode", err, err_info))
    {
        return false;
    }

    if (silentMode)
    {
        pInfo->silentMode = silent_enabled_e;
    }
    else
    {
        pInfo->silentMode = silent_disabled_e;
    }
    return true;
}

static bool parseLogFileHeaderLine_cyclicMode(cCLLog_logFileInfo_t *pInfo, char *pFieldValue, int *err, char **err_info)
{
    bool cyclicMode;

    if (!parseBoolean(pFieldValue, &cyclicMode, "silent mode", err, err_info))
    {
        return false;
    }

    if (cyclicMode)
    {
        pInfo->cyclicMode = cyclic_enabled_e;
    }
    else
    {
        pInfo->cyclicMode = cyclic_disabled_e;
    }
    return true;
}

/*

         c:\development\wireshark\plugins\wimaxmacphy\cCLLog.c(248): warning C4
       477: 'sscanf' : format string '%i' requires an argument of type 'int *',
        but variadic argument 1 has type 'uint8_t *'
         c:\development\wireshark\plugins\wimaxmacphy\cCLLog.c(274): warning C4
       477: 'sscanf' : format string '%i' requires an argument of type 'int *',
        but variadic argument 1 has type 'uint8_t *'
         c:\development\wireshark\plugins\wimaxmacphy\cCLLog.c(288): warning C4
       477: 'sscanf' : format string '%2x' requires an argument of type 'unsign
       ed int *', but variadic argument 1 has type 'uint8_t *


*/

#include "cllog.h"

static int cllog_file_type_subtype = -1;

#define CAN_EFF_MASK 0x1FFFFFFF /* extended frame format (EFF) */
#define CAN_SFF_MASK 0x000007FF /* standard frame format (SFF) */

static bool
cllog_read_common(wtap *wth, FILE_T fh, wtap_rec *rec, Buffer *buf, int *err, char **err_info _U_)
{
    cCLLog_logFileInfo_t *clLog = (cCLLog_logFileInfo_t *) wth->priv;
    char line[MAX_LOG_LINE_LENGTH];
    cCLLog_message_t logEntry;
    uint8_t *can_data;

    /* Read a line */
    if (file_gets(line, sizeof(line), fh) == NULL)
    {
        /* EOF or error. */
        *err = file_error(wth->fh, err_info);
        return false;
    }

    /* Default the log entry structure */
    memset(&logEntry, 0, sizeof(logEntry));

    /* Parse the line */
    if (!parseLogLine(clLog, line, &logEntry, err, err_info))
    {
        return false;
    }

    rec->rec_type = REC_TYPE_PACKET;
    rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
    rec->presence_flags = WTAP_HAS_TS;

    rec->ts.secs = logEntry.timestamp.epoch;
    rec->ts.nsecs = logEntry.timestamp.ms * 1000U * 1000U;

    rec->rec_header.packet_header.caplen = 8 + logEntry.length;
    rec->rec_header.packet_header.len = 8 + logEntry.length;

    if (logEntry.msgType == msg_tx_standard_e || logEntry.msgType == msg_tx_extended_e)
    {
        wtap_block_add_uint32_option(rec->block, OPT_PKT_FLAGS, PACK_FLAGS_DIRECTION_OUTBOUND);
    }
    else if (logEntry.msgType == msg_rx_standard_e || logEntry.msgType == msg_rx_extended_e)
    {
        wtap_block_add_uint32_option(rec->block, OPT_PKT_FLAGS, PACK_FLAGS_DIRECTION_INBOUND);
    }

    ws_buffer_assure_space(buf, rec->rec_header.packet_header.caplen);
    can_data = ws_buffer_start_ptr(buf);

    can_data[0] = (logEntry.id >> 24);
    can_data[1] = (logEntry.id >> 16);
    can_data[2] = (logEntry.id >>  8);
    can_data[3] = (logEntry.id >>  0);
    can_data[4] = logEntry.length;
    can_data[5] = 0;
    can_data[6] = 0;
    can_data[7] = 0;

    if (logEntry.msgType == msg_tx_extended_e || logEntry.msgType == msg_rx_extended_e || (logEntry.id & CAN_EFF_MASK) > CAN_SFF_MASK)
        can_data[0] |= 0x80;

    memcpy(&can_data[8], logEntry.data, logEntry.length);
    return true;
}

static bool
cllog_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err, char **err_info, int64_t *data_offset)
{
    *data_offset = file_tell(wth->fh);

    return cllog_read_common(wth, wth->fh, rec, buf, err, err_info);
}

static bool
cllog_seek_read(wtap *wth, int64_t seek_off, wtap_rec *rec, Buffer *buf, int *err, char **err_info)
{
    if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
        return false;

    return cllog_read_common(wth, wth->random_fh, rec, buf, err, err_info);
}

wtap_open_return_val
cllog_open(wtap *wth, int *err, char **err_info _U_)
{
    cCLLog_logFileInfo_t *clLog;
    char line[ MAX_LOG_LINE_LENGTH ];

    clLog = g_new0(cCLLog_logFileInfo_t, 1);

    /* Initialize the header information */
    clLog->loggerType = 0;
    clLog->hwrev[0] = '\0';
    clLog->fwrev[0] = '\0';
    clLog->id[0] = '\0';
    clLog->sessionNo = 0;
    clLog->splitNo = 0;
    clLog->logStartTime.epoch = 0;
    clLog->logStartTime.ms = 0;
    clLog->logStartTimeString[0] = '\0';
    clLog->separator = '\0';
    clLog->timeFormat = 0;
    clLog->timeSeparator = '\0';
    clLog->timeSeparatorMs = '\0';
    clLog->dateSeparator = '\0';
    clLog->dateAndTimeSeparator = '\0';
    clLog->bitRate = 0;
    clLog->silentMode = 0;
    clLog->cyclicMode = 0;

    /* Set parse function pointers */
    memset(clLog->parseFieldFunc, 0, sizeof( clLog->parseFieldFunc));

    /*
     * We're at the beginning of the file; read each line and
     * parse it.
     */
    while (file_gets(line, sizeof(line), wth->fh) != NULL)
    {
        char *linep;

        if (*err != 0)
        {
            if (*err == WTAP_ERR_SHORT_READ)
            {
                /* Incomplete header, so not ours. */
                g_free(clLog);
                return WTAP_OPEN_NOT_MINE;
            }
            else
            {
                /* I/O error. */
                g_free(clLog);
                return WTAP_OPEN_ERROR;
            }
        }

        linep = line;

        /* Break on end of header */
        if (linep[0] != '#')
        {
            break;
        }

        /*
         * Skip the comment character and white space following it.
         */
        linep++;
        while (*linep == ' ' || *linep == '\t')
            linep++;

        if (*linep == '\0')
        {
            /*
             * Skip over empty comment lines.
             * XXX - should we treat that as an indication of an
             * invalid file?
             */
            continue;
        }

        /*
         * Look for the handler for this particular header line.
         */
        for (unsigned int i = 0U; i < HEADER_LINE_PARSE_MAPPING_LENGTH; i++)
        {
            const headerLineParseMapping_t *pHeaderMapping = &headerLineParseMapping[i];
            size_t matchStringLen = strlen(pHeaderMapping->pMatchString);

            if (strncmp(linep, pHeaderMapping->pMatchString, matchStringLen) == 0 &&
                 pHeaderMapping->parseFunc != NULL)
            {
                /*
                 * This matches this header value.
                 * Skip past the tag.
                 */
                linep += matchStringLen;

                /* Replace any newline chars with end of line */
                for (char *pChar = linep; ; pChar++)
                {
                    if (*pChar == '\n' || *pChar == '\r' || *pChar == '\0')
                    {
                        *pChar = '\0';
                        break;
                    }
                }

                /*
                 * Call the handler.
                 */
                if (!pHeaderMapping->parseFunc(clLog, linep, err, err_info))
                {
                    /*
                     * XXX - should this file be rejected as not
                     * one of ours?  Given the line looks like
                     * a comment that begins with a valid header
                     * field tag, it may be likely to be one of
                     * ours.
                     */
                    g_free(clLog);
                    return WTAP_OPEN_ERROR;
                }
            }
        }
    }

    /*
     * We've read the first line after the header, so it's the column
     * header line. Parse it.
     */
    if (!parseColumnHeaderFields(clLog, line))
    {
        g_free(clLog);
        return WTAP_OPEN_NOT_MINE;
    }

    wth->priv = clLog;

    wth->file_type_subtype = cllog_file_type_subtype;
    wth->file_encap = WTAP_ENCAP_SOCKETCAN;
    wth->snapshot_length = 0;

    wth->subtype_read = cllog_read;
    wth->subtype_seek_read = cllog_seek_read;
    wth->file_tsprec = WTAP_TSPREC_MSEC;

    return WTAP_OPEN_MINE;
}

/* Options for packet blocks. */
static const struct supported_option_type packet_block_options_supported[] = {
    { OPT_PKT_FLAGS, ONE_OPTION_SUPPORTED },
};

static const struct supported_block_type cllog_blocks_supported[] = {
    /*
     * We support packet blocks, with only the flags option supported.
     */
    { WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, OPTION_TYPES_SUPPORTED(packet_block_options_supported) }
};

static const struct file_type_subtype_info cllog_info = {
    "CSS Electronics CLX000 CAN log", "cllog", "txt", NULL,
    false, BLOCKS_SUPPORTED(cllog_blocks_supported),
    NULL, NULL, NULL
};

void
register_canlogger(void)
{
    cllog_file_type_subtype = wtap_register_file_type_subtype(&cllog_info);
}