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
/**
 *    @file  csv.c
 *   @brief  https://www.rfc-editor.org/rfc/rfc4180
 *
 *  <+DETAILED+>
 *
 *  @author  François Cerbelle (Fanfan), francois@cerbelle.net
 *
 *  @internal
 *       Created:  29/10/2024
 *      Revision:  none
 * Last modified:  2024-12-05 20:17
 *      Compiler:  gcc
 *  Organization:  Cerbelle.net
 *     Copyright:  Copyright (c) 2024, François Cerbelle
 *
 *  This source code is released for free distribution under the terms of the
 *  GNU General Public License as published by the Free Software Foundation.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "csv.h"

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

static unsigned short int _csv_firstfield = 1;

void csv_addline(FILE* reportfile) {
    fprintf(reportfile,"\r\n");
    _csv_firstfield = 1;
}

void csv_addfield(FILE* reportfile, const char* value) {
    char* csv = txt2csv(value);
    if (_csv_firstfield) {
        fprintf(reportfile,"%s",csv);
        _csv_firstfield = 0;
    } else
        fprintf(reportfile,",%s",csv);
    free(csv);
}

/* RFC4180 compliant CSV parser, with LF only tolerance when CRLF expected */
/* https://www.rfc-editor.org/rfc/rfc4180 */
static char* _csvtok_csv=NULL;
char* csvtok(char* source) {
    size_t csv_idx=0;
    size_t txt_idx=0;
    char* csvtok_txt = NULL;
    unsigned short int quoted = 0;

    if (NULL!=source)
        _csvtok_csv = source;

    if (_csvtok_csv[0]==0)
        return NULL;

    if (NULL==(csvtok_txt = malloc(strlen(_csvtok_csv)+1))) {
        perror("csvtok csvtok_txt malloc");
        exit(EXIT_FAILURE);
    }
    csvtok_txt[0]=0;

    while (_csvtok_csv[csv_idx]) {
        if (!quoted) {
            if (_csvtok_csv[csv_idx]==',') {
                if ((_csvtok_csv[csv_idx+1]==0)||
                        (_csvtok_csv[csv_idx+1]=='\n')|| /* Unix style tolerance */
                        ((_csvtok_csv[csv_idx+1]=='\r')&&(_csvtok_csv[csv_idx+2]=='\n'))) {
                    fprintf(stderr,"RFC4180 forbids comma at the end of record %s at %zu.\n",
                            _csvtok_csv,csv_idx);
                    free(csvtok_txt);
                    _csvtok_csv=NULL;
                    return NULL;
                } else
                    break;
            } else if ((_csvtok_csv[csv_idx]=='\n')||
                       ((_csvtok_csv[csv_idx]=='\r')&&(_csvtok_csv[csv_idx+1]=='\n')))
                break;
            else if (_csvtok_csv[csv_idx]=='"') {
                if (csv_idx==0) {
                    quoted = 1;
                    csv_idx++;
                    continue;
                } else {
                    fprintf(stderr,"doublequote in a non quoted value %s at %zu.\n",
                            _csvtok_csv,csv_idx);
                    free(csvtok_txt);
                    _csvtok_csv=NULL;
                    return NULL;
                }
            }
        } else { /* Quoted */
            if (_csvtok_csv[csv_idx]=='"') {
                if (_csvtok_csv[csv_idx+1]=='"') {
                    /* Skip escaping doublequote and let the copy occur */
                    csv_idx++;
                } else if ((_csvtok_csv[csv_idx+1]=='0')||
                           (_csvtok_csv[csv_idx+1]==',')||
                           (_csvtok_csv[csv_idx+1]=='\n')||
                           ((_csvtok_csv[csv_idx+1]=='\r')&&(_csvtok_csv[csv_idx+2]=='\n'))) {
                    quoted = 0;
                    csv_idx++;
                    break;
                } else {
                    fprintf(stderr,"doublequote should be at the end of field or escaping another doublequote in %s at %zu.\n",
                            _csvtok_csv,csv_idx);
                    free(csvtok_txt);
                    _csvtok_csv=NULL;
                    return NULL;
                }
            }
        }
        csvtok_txt[txt_idx++]=_csvtok_csv[csv_idx++];
    }

    /* Close csvtok_txt */
    csvtok_txt[txt_idx]=0;
    if (quoted) {
        fprintf(stderr,"Missing end-of-field doublequote %s\n",csvtok_txt);
        free(csvtok_txt);
        _csvtok_csv=NULL;
        return NULL;
    } else if (_csvtok_csv[csv_idx]==',') /* Next char after end of field should be 0/,/CRLF */
        csv_idx++;
    else if (_csvtok_csv[csv_idx]=='\n')
        csv_idx+=1;
    else if ((_csvtok_csv[csv_idx]=='\r')&&(_csvtok_csv[csv_idx+1]=='\n'))
        csv_idx+=2;
    else if (_csvtok_csv[csv_idx]!=0) {
        fprintf(stderr,"Parsing error after %s\n",csvtok_txt);
        free(csvtok_txt);
        _csvtok_csv=NULL;
        return NULL;
    }
    _csvtok_csv += csv_idx;
    /* Shrink overallocated string */
    if (NULL==(csvtok_txt=realloc(csvtok_txt,strlen(csvtok_txt)+1))) {<--- Common realloc mistake: 'csvtok_txt' nulled but not freed upon failure
        fprintf(stderr,"ERROR: csvtok Trimming CSV token\n");
        free(csvtok_txt);
        return NULL;
    }
    return csvtok_txt;
}

/* RFC4180 compliant text to CSV encoder */
/* https://www.rfc-editor.org/rfc/rfc4180 */
char* txt2csv(const char* text) {
    char* csv;
    size_t text_idx;
    size_t csv_idx;
    unsigned short int need_quotes=0;

    {
        /* Check if quotes are needed and how many doublequotes are in the
         * source text to allocate output buffer. This text iteration could be
         * avoided but would imply to overallocate for the worst case scenario
         * and to reallocate at the end with the potentially needed surrounding
         * quotes */
        size_t extra_chars = 0;
        for (text_idx=0; text[text_idx]; text_idx++) {
            if ( (text[text_idx]==',')|| (text[text_idx]=='\r')|| (text[text_idx]=='\n'))
                need_quotes = 1;
            if (text[text_idx]=='"') {
                need_quotes = 1;
                extra_chars++;
            }
        }
        /* Allocate the right output buffer size */
        if (NULL==(csv=malloc(strlen(text)+(need_quotes?2:0)+extra_chars+1))) {
            perror("txt2csv malloc");
            return NULL;
        }
    }

    text_idx = 0;
    csv_idx = 0;

    /* If quotes are needed add a starting doublequote */
    if (need_quotes)
        csv[csv_idx++] = '"';

    /* Copy each source char to the destination buffer */
    while (text[text_idx]) {
        /* With a doublequote before if the char to copy is a doublequote */
        if (text[text_idx]=='"')
            csv[csv_idx++] = '"';
        csv[csv_idx++] = text[text_idx++];
    }

    /* If quotes are needed add a closing doublequote */
    if (need_quotes)
        csv[csv_idx++] = '"';

    /* Properly end the C string */
    csv[csv_idx] = 0;

    return csv;
}
/* vim: set tw=80: */