summaryrefslogtreecommitdiff
path: root/src/libical/icalparser.c
blob: ebb10970a42e7393998c773e7935b8d1e4b72fad (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
/*======================================================================
 FILE: icalparser.c
 CREATOR: eric 04 August 1999

 (C) COPYRIGHT 2000, Eric Busboom <eric@civicknowledge.com>

 This library is free software; you can redistribute it and/or modify
 it under the terms of either:

    The LGPL as published by the Free Software Foundation, version
    2.1, available at: https://www.gnu.org/licenses/lgpl-2.1.html

 Or:

    The Mozilla Public License Version 2.0. You may obtain a copy of
    the License at https://www.mozilla.org/MPL/

 This library is free software; you can redistribute it and/or modify
 it under the terms of either:

    The LGPL as published by the Free Software Foundation, version
    2.1, available at: https://www.gnu.org/licenses/lgpl-2.1.html

 Or:

    The Mozilla Public License Version 2.0. You may obtain a copy of
    the License at https://www.mozilla.org/MPL/

  The Initial Developer of the Original Code is Eric Busboom
 ======================================================================*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "icalparser.h"
#include "icalerror.h"
#include "icalmemory.h"
#include "icalvalue.h"
#include "icalproperty_p.h"

#include <ctype.h>
#include <stddef.h>     /* for ptrdiff_t */
#include <stdlib.h>

#define TMP_BUF_SIZE 80
#define MAXIMUM_ALLOWED_PARAMETERS 100
#define MAXIMUM_ALLOWED_MULTIPLE_VALUES 500

struct icalparser_impl
{
    int buffer_full;    /* flag indicates that temp is smaller that
                           data being read into it */
    int continuation_line;      /* last line read was a continuation line */
    size_t tmp_buf_size;
    char temp[TMP_BUF_SIZE];
    icalcomponent *root_component;
    int version;
    int level;
    int lineno;
    icalparser_state state;
    pvl_list components;

    void *line_gen_data;
};

/*
 * New version of strstrip() that does not move the pointer.
 */
static void strstriplt(char *buf)
{
    size_t len;
    int a;

    if (buf == NULL) {
        return;
    }
    if (buf[0] == 0) {
        return;
    }
    len = strlen(buf);
    /* the casts to unsigned char below are to work around isspace asserts
       on Windows due to non-ascii characters becoming negative */
    while ((buf[0] != 0) && (isspace((unsigned char)buf[len - 1]))) {
        buf[--len] = 0;
    }
    if (buf[0] == 0) {
        return;
    }
    a = 0;
    while ((buf[0] != 0) && (isspace((unsigned char)buf[a]))) {
        a++;
    }
    if (a > 0) {
        memmove(buf, &buf[a], len - a + 1);
    }
}

icalparser *icalparser_new(void)
{
    struct icalparser_impl *impl = 0;

    if ((impl = (struct icalparser_impl *)malloc(sizeof(struct icalparser_impl))) == 0) {
        icalerror_set_errno(ICAL_NEWFAILED_ERROR);
        return 0;
    }

    impl->root_component = 0;
    impl->components = pvl_newlist();
    impl->level = 0;
    impl->state = ICALPARSER_SUCCESS;
    impl->tmp_buf_size = TMP_BUF_SIZE;
    impl->buffer_full = 0;
    impl->continuation_line = 0;
    impl->lineno = 0;
    memset(impl->temp, 0, TMP_BUF_SIZE);

    return (icalparser *) impl;
}

void icalparser_free(icalparser *parser)
{
    icalcomponent *c;

    if (parser->root_component != 0) {
        icalcomponent_free(parser->root_component);
    }

    while ((c = pvl_pop(parser->components)) != 0) {
        icalcomponent_free(c);
    }

    pvl_free(parser->components);

    free(parser);
}

void icalparser_set_gen_data(icalparser *parser, void *data)
{
    parser->line_gen_data = data;
}

icalvalue *icalvalue_new_From_string_with_error(icalvalue_kind kind,
                                                char *str, icalproperty ** error);

static char *parser_get_next_char(char c, char *str, int qm)
{
    int quote_mode = 0;
    char *p = str;
    char next_char = *p;
    char prev_char = 0;
    unsigned int cnt = 0;

    while ((cnt < TMP_BUF_SIZE) && (next_char != '\0')) {
        cnt++;
        if ((prev_char != '\0') && (prev_char != '\\')) {
            if (qm == 1 && next_char == '"') {
                /* Encountered a quote, toggle quote mode */
                quote_mode = !quote_mode;
            } else if (quote_mode == 0 && next_char == c) {
                /* Found a matching character out of quote mode, return it */
                return p;
            }
        }

        /* Save the previous character so we can check if it's a backslash in the next iteration */
        prev_char = next_char;
        next_char = *(++p);
    }

    return 0;
}

/** Makes a new tmp buffer out of a substring. */
static char *make_segment(char *start, char *end)
{
    char *buf, *tmp;
    ptrdiff_t size = (ptrdiff_t)(end - start);
    ptrdiff_t cnt = 0;

    buf = icalmemory_new_buffer((size_t)(size + 1));
    strncpy(buf, start, size);
    *(buf + size) = 0;

    tmp = (buf + size);
    while ((cnt < size) && (tmp >= buf) && ((*tmp == '\0') || iswspace((wint_t)*tmp))) {
        cnt++;
        *tmp = 0;
        tmp--;
    }

    return buf;
}

static char *parser_get_prop_name(char *line, char **end)
{
    char *p;
    char *v;
    char *str;

    p = parser_get_next_char(';', line, 1);
    v = parser_get_next_char(':', line, 1);
    if (p == 0 && v == 0) {
        return 0;
    }

    /* There is no ';' or, it is after the ';' that marks the beginning of
       the value */
    if (v != 0 && (p == 0 || p > v)) {
        str = make_segment(line, v);
        *end = v + 1;
    } else {
        str = make_segment(line, p);
        *end = p + 1;
    }

    return str;
}

/** Decode parameter value per RFC6868 */
static void parser_decode_param_value(char *value)
{
    char *in, *out;

    for (in = out = value; *in; in++, out++) {
        if (*in == '^' && strspn(in+1, "n^'")) {
            switch (*++in) {
            case 'n':
                *out = '\n';
                break;

            case '^':
                *out = '^';
                break;

            case '\'':
                *out = '"';
                break;
            }
        } else {
            *out = *in;
        }
    }

    while (*out) *out++ = '\0';
}

static int parser_get_param_name_stack(char *line, char *name, size_t name_length,
                                       char *value, size_t value_length)
{
    char *next, *end_quote;
    size_t requested_name_length, requested_value_length;

    /* The name is everything up to the equals sign */
    next = parser_get_next_char('=', line, 1);

    if (next == 0) {
        return 0;
    }

    requested_name_length = (ptrdiff_t)(next - line);

    /* Figure out what range of line contains the value (everything after the equals sign) */
    next++;

    if (next[0] == '"') {
        /* Dequote the value */
        next++;

        end_quote = (*next == '"') ? next : parser_get_next_char('"', next, 0);

        if (end_quote == 0) {
            return 0;
        }

        requested_value_length = (ptrdiff_t)(end_quote - next);
    } else {
        requested_value_length = strlen(next);
    }

    /* There's not enough room in the name or value inputs, we need to fall back
       to parser_get_param_name_heap and use heap-allocated strings */
    if (requested_name_length >= name_length - 1 || requested_value_length >= value_length - 1) {
        return 0;
    }

    strncpy(name, line, requested_name_length);
    name[requested_name_length] = 0;

    strncpy(value, next, requested_value_length);
    value[requested_value_length] = 0;

    parser_decode_param_value(value);

    return 1;
}

static char *parser_get_param_name_heap(char *line, char **end)
{
    /* This is similar to parser_get_param_name_stack except it returns heap
       objects in the return value and the end parameter. This is used in case
       the name or value is longer than the stack-allocated string.
    */
    char *next;
    char *str;

    next = parser_get_next_char('=', line, 1);

    if (next == 0) {
        return 0;
    }

    str = make_segment(line, next);
    *end = next + 1;
    if (**end == '"') {
        *end = *end + 1;
        next = (**end == '"') ? *end : parser_get_next_char('"', *end, 0);
        if (next == 0) {
            free(str);
            *end = NULL;
            return 0;
        }

        *end = make_segment(*end, next);
    } else {
        *end = make_segment(*end, *end + strlen(*end));
    }

    parser_decode_param_value(*end);

    return str;
}

#if 0
/*keep for historical sake*/
static char *parser_get_next_paramvalue(char *line, char **end)
{
    char *next;
    char *str;

    next = parser_get_next_char(',', line, 1);

    if (next == 0) {
        next = (char *)(size_t) line + (size_t) strlen(line);
    }

    if (next == line) {
        return 0;
    } else {
        str = make_segment(line, next);
        *end = next + 1;
        return str;
    }
}

#endif

static char *icalparser_get_value(char *line, char **end, icalvalue_kind kind)
{
    char *str;
    size_t length = strlen(line);

    _unused(kind);

    if (length == 0) {
        return 0;
    }

    *end = line + length;
    str = make_segment(line, *end);

    return str;
}

/**
   A property may have multiple values, if the values are separated by
   commas in the content line. This routine will look for the next
   comma after line and will set the next place to start searching in
   end. */

static char *parser_get_next_value(char *line, char **end, icalvalue_kind kind)
{
    char *next = 0;
    char *p;
    char *str;
    size_t length = strlen(line);
    int quoted = 0;

    if (line[0] == '\"' && line[length - 1] == '\"') {
        /* This line is quoted, don't split into multiple values */
        quoted = 1;
    }

    p = line;
    while (!quoted) {

        next = parser_get_next_char(',', p, 1);

        /* Unfortunately, RFC2445 allowed that for the RECUR value, COMMA
           could both separate digits in a list, and it could separate
           multiple recurrence specifications. This is not a friendly
           part of the spec and was deprecated in RFC5545. The following
           weirdness tries to distinguish the two uses. It is probably a HACK */

        if (kind == ICAL_RECUR_VALUE) {
            if (next != 0 && (*end + length) > next + 5 && strncmp(next, "FREQ", 4) == 0) {
                /* The COMMA was followed by 'FREQ', is it a real separator */
                /* Fall through */
            } else if (next != 0) {
                /* Not real, get the next COMMA */
                p = next + 1;
                next = 0;
                continue;
            }
        }
        /* ignore all commas for query and x values. select dtstart, dtend etc ... */
        else if (kind == ICAL_QUERY_VALUE || kind == ICAL_X_VALUE) {
            if (next != 0) {
                p = next + 1;
                continue;
            } else {
                break;
            }
        }

        /* If the comma is preceded by a '\', then it is a literal and
           not a value separator */

        if ((next != 0 && *(next - 1) == '\\') || (next != 0 && *(next - 3) == '\\')
            )
            /*second clause for '/' is on prev line. HACK may be out of bounds */
        {
            p = next + 1;
        } else {
            break;
        }
    }

    if (next == 0) {
        next = (char *)(size_t) line + length;
        *end = next;
    } else {
        *end = next + 1;
    }

    if (next == line) {
        return 0;
    }

    str = make_segment(line, next);
    return str;
}

static char *parser_get_next_parameter(char *line, char **end)
{
    char *next;
    char *v;
    char *str;

    v = parser_get_next_char(':', line, 1);
    next = parser_get_next_char(';', line, 1);

    /* There is no ';' or, it is after the ':' that marks the beginning of
       the value */

    if (next == 0 || next > v) {
        next = parser_get_next_char(':', line, 1);
    }

    if (next != 0) {
        str = make_segment(line, next);
        *end = next + 1;
        return str;
    } else {
        *end = line;
        return 0;
    }
}

char *icalparser_get_line(icalparser *parser,
                          icalparser_line_gen_func line_gen_func)
{
    char *line;
    char *line_p;
    size_t buf_size = parser->tmp_buf_size;

    line_p = line = icalmemory_new_buffer(buf_size);
    line[0] = '\0';

    /* Read lines by calling line_gen_func and putting the data into
       parser->temp. If the line is a continuation line ( begins with a
       space after a newline ) then append the data onto line and read
       again. Otherwise, exit the loop. */

    while (1) {

        /* The first part of the loop deals with the temp buffer,
           which was read on he last pass through the loop. The
           routine is split like this because it has to read lone line
           ahead to determine if a line is a continuation line. */

        /* The tmp buffer is not clear, so transfer the data in it to the
           output. This may be left over from a previous call */
        if (parser->temp[0] != '\0') {

            /* If the last position in the temp buffer is occupied,
               mark the buffer as full. The means we will do another
               read later, because the line is not finished */
            if (parser->temp[parser->tmp_buf_size - 1] == 0 &&
                parser->temp[parser->tmp_buf_size - 2] != '\n' &&
                parser->temp[parser->tmp_buf_size - 2] != 0) {
                parser->buffer_full = 1;
            } else {
                parser->buffer_full = 0;
            }

            /* Copy the temp to the output and clear the temp buffer. */
            if (parser->continuation_line == 1) {
                /* back up the pointer to erase the continuation characters */
                parser->continuation_line = 0;
                line_p--;

                if (*(line_p - 1) == '\r') {
                    line_p--;
                }

                /* copy one space up to eliminate the leading space */
                icalmemory_append_string(&line, &line_p, &buf_size, parser->temp + 1);

            } else {
                icalmemory_append_string(&line, &line_p, &buf_size, parser->temp);
            }

            parser->temp[0] = '\0';
        }

        parser->temp[parser->tmp_buf_size - 1] = 1;     /* Mark end of buffer */

        /****** Here is where the routine gets string data ******************/
        if ((*line_gen_func) (parser->temp, parser->tmp_buf_size, parser->line_gen_data)
            == 0) {     /* Get more data */

            /* If the first position is clear, it means we didn't get
               any more data from the last call to line_ge_func */
            if (parser->temp[0] == '\0') {

                if (line[0] != '\0') {
                    /* There is data in the output, so fall trhough and process it */
                    break;
                } else {
                    /* No data in output; return and signal that there
                       is no more input */
                    free(line);
                    return 0;
                }
            }
        }

        /* If the output line ends in a '\n' and the temp buffer
           begins with a ' ' or tab, then the buffer holds a continuation
           line, so keep reading.  RFC 5545, section 3.1 */

        if (line_p > line + 1 && *(line_p - 1) == '\n'
            && (parser->temp[0] == ' ' || parser->temp[0] == '\t')) {

            parser->continuation_line = 1;

        } else if (parser->buffer_full == 1) {

            /* The buffer was filled on the last read, so read again */

        } else {

            /* Looks like the end of this content line, so break */
            break;
        }
    }

    /* Erase the final newline and/or carriage return */
    if (line_p > line + 1 && *(line_p - 1) == '\n') {
        *(line_p - 1) = '\0';
        if (*(line_p - 2) == '\r') {
            *(line_p - 2) = '\0';
        }

    } else {
        *(line_p) = '\0';
    }

    while ((*line_p == '\0' || iswspace((wint_t) * line_p)) && line_p > line) {
        *line_p = '\0';
        line_p--;
    }

    return line;
}

static void insert_error(icalcomponent *comp, const char *text,
                         const char *message, icalparameter_xlicerrortype type)
{
    char temp[1024];

    if (text == 0) {
        snprintf(temp, 1024, "%s:", message);
    } else {
        snprintf(temp, 1024, "%s: %s", message, text);
    }

    icalcomponent_add_property(
        comp,
        icalproperty_vanew_xlicerror(temp, icalparameter_new_xlicerrortype(type), 0));
}

static int line_is_blank(char *line)
{
    int i = 0;

    for (i = 0; *(line + i) != 0; i++) {
        char c = *(line + i);

        if (c != ' ' && c != '\n' && c != '\t') {
            return 0;
        }
    }

    return 1;
}

icalcomponent *icalparser_parse(icalparser *parser,
                                icalparser_line_gen_func line_gen_func)
{
    char *line;
    icalcomponent *c = 0;
    icalcomponent *root = 0;
    icalerrorstate es = icalerror_get_error_state(ICAL_MALFORMEDDATA_ERROR);
    int cont;

    icalerror_check_arg_rz((parser != 0), "parser");

    icalerror_set_error_state(ICAL_MALFORMEDDATA_ERROR, ICAL_ERROR_NONFATAL);

    do {
        line = icalparser_get_line(parser, line_gen_func);

        if ((c = icalparser_add_line(parser, line)) != 0) {

            if (icalcomponent_get_parent(c) != 0) {
                /* This is bad news... assert? */
            }

            assert(parser->root_component == 0);
            assert(pvl_count(parser->components) == 0);

            if (root == 0) {
                /* Just one component */
                root = c;
            } else if (icalcomponent_isa(root) != ICAL_XROOT_COMPONENT) {
                /*Got a second component, so move the two components under
                   an XROOT container */
                icalcomponent *tempc = icalcomponent_new(ICAL_XROOT_COMPONENT);

                icalcomponent_add_component(tempc, root);
                icalcomponent_add_component(tempc, c);
                root = tempc;
            } else if (icalcomponent_isa(root) == ICAL_XROOT_COMPONENT) {
                /* Already have an XROOT container, so add the component
                   to it */
                icalcomponent_add_component(root, c);

            } else {
                /* Badness */
                assert(0);
            }

            c = 0;
        }
        cont = 0;
        if (line != 0) {
            icalmemory_free_buffer(line);
            cont = 1;
        }
    } while (cont);

    icalerror_set_error_state(ICAL_MALFORMEDDATA_ERROR, es);

    return root;
}

icalcomponent *icalparser_add_line(icalparser *parser, char *line)
{
    char *str;
    char *end;
    int pcount = 0;
    int vcount = 0;
    icalproperty *prop;
    icalproperty_kind prop_kind;
    icalvalue *value;
    icalvalue_kind value_kind = ICAL_NO_VALUE;

    icalerror_check_arg_rz((parser != 0), "parser");

    if (line == 0) {
        parser->state = ICALPARSER_ERROR;
        return 0;
    }

    if (line_is_blank(line) == 1) {
        return 0;
    }

    /* Begin by getting the property name at the start of the line. The
       property name may end up being "BEGIN" or "END" in which case it
       is not really a property, but the marker for the start or end of
       a component */

    end = 0;
    str = parser_get_prop_name(line, &end);

    if (str == 0 || *str == '\0') {
        /* Could not get a property name */
        icalcomponent *tail = pvl_data(pvl_tail(parser->components));

        if (tail) {
            insert_error(
                tail, line,
                "Got a data line, but could not find a property name or component begin tag",
                ICAL_XLICERRORTYPE_COMPONENTPARSEERROR);
        }
        tail = 0;
        parser->state = ICALPARSER_ERROR;
        icalmemory_free_buffer(str);
        str = NULL;
        return 0;
    }

    /**********************************************************************
     * Handle begin and end of components
     **********************************************************************/
    /* If the property name is BEGIN or END, we are actually
       starting or ending a new component */

    if (strcasecmp(str, "BEGIN") == 0) {
        icalcomponent *c;
        icalcomponent_kind comp_kind;

        parser->level++;
        icalmemory_free_buffer(str);
        str = parser_get_next_value(end, &end, value_kind);

        comp_kind = icalenum_string_to_component_kind(str);

        c = icalcomponent_new(comp_kind);

        if (c == 0) {
            c = icalcomponent_new(ICAL_XLICINVALID_COMPONENT);
            insert_error(c, str, "Parse error in component name",
                         ICAL_XLICERRORTYPE_COMPONENTPARSEERROR);
        }

        pvl_push(parser->components, c);

        parser->state = ICALPARSER_BEGIN_COMP;

        icalmemory_free_buffer(str);
        str = NULL;
        return 0;

    } else if (strcasecmp(str, "END") == 0) {
        icalcomponent *tail;

        parser->level--;
        icalmemory_free_buffer(str);
        str = parser_get_next_value(end, &end, value_kind);

        /* Pop last component off of list and add it to the second-to-last */
        parser->root_component = pvl_pop(parser->components);

        tail = pvl_data(pvl_tail(parser->components));

        if (tail != 0) {
            icalcomponent_add_component(tail, parser->root_component);
        }

        tail = 0;
        icalmemory_free_buffer(str);
        str = NULL;

        if (parser->level < 0) {
            // Encountered an END before any BEGIN, this must be invalid data
            icalerror_warn("Encountered END before BEGIN");

            parser->state = ICALPARSER_ERROR;
            parser->level = 0;
            return 0;
        } else if (parser->level == 0) {
            /* Return the component if we are back to the 0th level */
            icalcomponent *rtrn;

            if (pvl_count(parser->components) != 0) {
                /* There are still components on the stack -- this means
                   that one of them did not have a proper "END" */
                pvl_push(parser->components, parser->root_component);
                (void)icalparser_clean(parser); /* may reset parser->root_component */
            }

            assert(pvl_count(parser->components) == 0);

            parser->state = ICALPARSER_SUCCESS;
            rtrn = parser->root_component;
            parser->root_component = 0;
            return rtrn;

        } else {
            parser->state = ICALPARSER_END_COMP;
            return 0;
        }
    }

    /* There is no point in continuing if we have not seen a
       component yet */

    if (pvl_data(pvl_tail(parser->components)) == 0) {
        parser->state = ICALPARSER_ERROR;
        icalmemory_free_buffer(str);
        str = NULL;
        return 0;
    }

    /**********************************************************************
     * Handle property names
     **********************************************************************/

    /* At this point, the property name really is a property name,
       (Not a component name) so make a new property and add it to
       the component */

    prop_kind = icalproperty_string_to_kind(str);

    prop = icalproperty_new(prop_kind);

    if (prop != 0) {
        icalcomponent *tail = pvl_data(pvl_tail(parser->components));

        if (prop_kind == ICAL_X_PROPERTY) {
            icalproperty_set_x_name(prop, str);
        }

        icalcomponent_add_property(tail, prop);

        /* Set the value kind for the default for this type of
           property. This may be re-set by a VALUE parameter */
        value_kind = icalproperty_kind_to_value_kind(icalproperty_isa(prop));

    } else {
        icalcomponent *tail = pvl_data(pvl_tail(parser->components));

        insert_error(tail, str, "Parse error in property name",
                     ICAL_XLICERRORTYPE_PROPERTYPARSEERROR);

        tail = 0;
        parser->state = ICALPARSER_ERROR;
        icalmemory_free_buffer(str);
        str = NULL;
        return 0;
    }

    icalmemory_free_buffer(str);
    str = NULL;

    /**********************************************************************
     * Handle parameter values
     **********************************************************************/

    /* Now, add any parameters to the last property */

    while (pcount < MAXIMUM_ALLOWED_PARAMETERS) {
        if (*(end - 1) == ':') {
            /* if the last separator was a ":" and the value is a
               URL, icalparser_get_next_parameter will find the
               ':' in the URL, so better break now. */
            break;
        }

        icalmemory_free_buffer(str);
        str = parser_get_next_parameter(end, &end);
        strstriplt(str);
        if (str != 0) {
            char *name_heap = 0;
            char *pvalue_heap = 0;
            char name_stack[TMP_BUF_SIZE];
            char pvalue_stack[TMP_BUF_SIZE];
            char *name = name_stack;
            char *pvalue = pvalue_stack;

            icalparameter *param = 0;
            icalparameter_kind kind;
            icalcomponent *tail = pvl_data(pvl_tail(parser->components));

            if (!parser_get_param_name_stack(str, name_stack, sizeof(name_stack),
                                             pvalue_stack, sizeof(pvalue_stack))) {
                name_heap = parser_get_param_name_heap(str, &pvalue_heap);

                name = name_heap;
                pvalue = pvalue_heap;

                if (name_heap == 0) {
                    /* 'tail' defined above */
                    insert_error(tail, str, "Can't parse parameter name",
                                 ICAL_XLICERRORTYPE_PARAMETERNAMEPARSEERROR);
                    tail = 0;
                    break;
                }
            }

            kind = icalparameter_string_to_kind(name);

            if (kind == ICAL_X_PARAMETER) {
                param = icalparameter_new(ICAL_X_PARAMETER);
                if (param != 0) {
                    icalparameter_set_xname(param, name);
                    icalparameter_set_xvalue(param, pvalue);
                }
            } else if (kind == ICAL_IANA_PARAMETER) {
                ical_unknown_token_handling tokHandlingSetting =
                    ical_get_unknown_token_handling_setting();
                if (tokHandlingSetting == ICAL_DISCARD_TOKEN) {
                    if (name_heap) {
                        icalmemory_free_buffer(name_heap);
                        name_heap = 0;
                    }
                    if (pvalue_heap) {
                        icalmemory_free_buffer(pvalue_heap);
                        pvalue_heap = 0;
                    }
                    continue;
                }

                param = icalparameter_new(ICAL_IANA_PARAMETER);

                if (param != 0) {
                    icalparameter_set_xname(param, name);
                    icalparameter_set_xvalue(param, pvalue);
                }
            } else if (kind == ICAL_TZID_PARAMETER && *(end - 1) != ';') {
                /*
                   Special case handling for TZID to work around invalid incoming data.
                   For example, Google Calendar will send back stuff like this:
                   DTSTART;TZID=GMT+05:30:20120904T020000

                   In this case we read to the next semicolon or the last colon rather
                   than the first colon.  This way the TZID will become GMT+05:30 rather
                   than trying to parse the date-time as 30:20120904T020000.

                   This also handles properties that look like this:
                   DTSTART;TZID=GMT+05:30;VALUE=DATE-TIME:20120904T020000
                 */
                char *lastColon = 0;
                char *nextColon = end;
                char *nextSemicolon = parser_get_next_char(';', end, 1);

                /* Find the last colon in the line */
                do {
                    nextColon = parser_get_next_char(':', nextColon, 1);

                    if (nextColon) {
                        lastColon = nextColon;
                    }
                } while (nextColon);

                if (lastColon && nextSemicolon && nextSemicolon < lastColon) {
                    /*
                       Ensures that we don't read past a semicolon

                       Handles the following line:
                       DTSTART;TZID=GMT+05:30;VALUE=DATE-TIME:20120904T020000
                     */
                    lastColon = nextSemicolon;
                }

                /*
                   Rebuild str so that it includes everything up to the next semicolon
                   or the last colon. So given the above example, str will go from
                   "TZID=GMT+05" to "TZID=GMT+05:30"
                 */
                if (lastColon && *(lastColon + 1) != 0) {
                    char *strStart = line + strlen(name) + 2;

                    end = lastColon + 1;

                    icalmemory_free_buffer(str);
                    str = make_segment(strStart, end - 1);
                }

                /* Reparse the parameter name and value with the new segment */
                if (!parser_get_param_name_stack(str, name_stack, sizeof(name_stack),
                                                 pvalue_stack, sizeof(pvalue_stack))) {
                    if (pvalue_heap) {
                        icalmemory_free_buffer(pvalue_heap);
                        pvalue_heap = 0;
                        pvalue = 0;
                    }
                    if (name_heap) {
                        icalmemory_free_buffer(name_heap);
                        name = 0;
                    }
                    name_heap = parser_get_param_name_heap(str, &pvalue_heap);
                    pvalue = pvalue_heap;
                }
                param = icalparameter_new_from_value_string(kind, pvalue);
            } else if (kind != ICAL_NO_PARAMETER) {
                param = icalparameter_new_from_value_string(kind, pvalue);
            } else {
                /* Error. Failed to parse the parameter */
                /* 'tail' defined above */

                /* Change for mozilla */
                /* have the option of being flexible towards unsupported parameters */
#if ICAL_ERRORS_ARE_FATAL == 1
                insert_error(tail, str, "Can't parse parameter name",
                             ICAL_XLICERRORTYPE_PARAMETERNAMEPARSEERROR);
                tail = 0;
                parser->state = ICALPARSER_ERROR;
                if (pvalue_heap) {
                    icalmemory_free_buffer(pvalue_heap);
                    pvalue = 0;
                }
                if (name_heap) {
                    icalmemory_free_buffer(name_heap);
                    name = 0;
                }
                icalmemory_free_buffer(str);
                str = NULL;
                return 0;
#else
                if (name_heap) {
                    icalmemory_free_buffer(name_heap);
                    name_heap = 0;
                }
                if (pvalue_heap) {
                    icalmemory_free_buffer(pvalue_heap);
                    pvalue_heap = 0;
                }
                icalmemory_free_buffer(str);
                str = NULL;
                continue;
#endif
            }

            if (pvalue_heap) {
                icalmemory_free_buffer(pvalue_heap);
                pvalue_heap = 0;
            }

            if (name_heap) {
                icalmemory_free_buffer(name_heap);
                name_heap = 0;
            }

            if (param == 0) {
                /* 'tail' defined above */
                insert_error(tail, str, "Can't parse parameter value",
                             ICAL_XLICERRORTYPE_PARAMETERVALUEPARSEERROR);

                tail = 0;
                parser->state = ICALPARSER_ERROR;

                icalmemory_free_buffer(str);
                str = NULL;

                continue;
            }

            /* If it is a VALUE parameter, set the kind of value */
            if (icalparameter_isa(param) == ICAL_VALUE_PARAMETER) {
                value_kind =
                    (icalvalue_kind)icalparameter_value_to_value_kind(
                        icalparameter_get_value(param));

                if (!icalproperty_value_kind_is_valid(prop_kind, value_kind)) {

                    /* Ooops, invalid VALUE parameter, so reset the value_kind */

                    const char *err_str = "Invalid VALUE type for property";
                    const char *prop_str = icalproperty_kind_to_string(prop_kind);
                    size_t tmp_buf_len = strlen(err_str) + strlen(prop_str) + 2;
                    char *tmp_buf = icalmemory_tmp_buffer(tmp_buf_len);
                    snprintf(tmp_buf, tmp_buf_len, "%s %s", err_str, prop_str);

                    insert_error(tail, str, tmp_buf,
                                 ICAL_XLICERRORTYPE_PARAMETERVALUEPARSEERROR);

                    value_kind = icalproperty_kind_to_value_kind(prop_kind);

                    icalparameter_free(param);
                    tail = 0;
                    parser->state = ICALPARSER_ERROR;

                    icalmemory_free_buffer(str);
                    str = NULL;
                    pcount++;
                    continue;
                }
            }

            /* Everything is OK, so add the parameter */
            icalproperty_add_parameter(prop, param);
            tail = 0;
            icalmemory_free_buffer(str);
            str = NULL;
            pcount++;

        } else {
            /* str is NULL */
            break;
        }

    }   /* while(1) */

    /**********************************************************************
     * Handle values
     **********************************************************************/

    /* Look for values. If there are ',' characters in the values,
       then there are multiple values, so clone the current
       parameter and add one part of the value to each clone */

    vcount = 0;
    while (vcount < MAXIMUM_ALLOWED_MULTIPLE_VALUES) {
        /* Only some properties can have multiple values. This list was taken
           from rfc5545. Also added the x-properties, because the spec actually
           says that commas should be escaped. For x-properties, other apps may
           depend on that behaviour
         */
        icalmemory_free_buffer(str);
        str = NULL;

        if (icalproperty_value_kind_is_multivalued(prop_kind, &value_kind)) {
            str = parser_get_next_value(end, &end, value_kind);
        } else {
            str = icalparser_get_value(end, &end, value_kind);
        }
        strstriplt(str);

        if (str != 0) {

            if (vcount > 0) {
                /* Actually, only clone after the second value */
                icalproperty *clone = icalproperty_new_clone(prop);
                icalcomponent *tail = pvl_data(pvl_tail(parser->components));

                icalcomponent_add_property(tail, clone);
                prop = clone;
                tail = 0;
            }

            value = icalvalue_new_from_string(value_kind, str);

            /* Don't add properties without value */
            if (value == 0) {
                char temp[200]; /* HACK */

                icalproperty_kind prop_kind = icalproperty_isa(prop);
                icalcomponent *tail = pvl_data(pvl_tail(parser->components));

                snprintf(temp, sizeof(temp),
                         "Can't parse as %s value in %s property. Removing entire property",
                         icalvalue_kind_to_string(value_kind),
                         icalproperty_kind_to_string(prop_kind));

                insert_error(tail, str, temp, ICAL_XLICERRORTYPE_VALUEPARSEERROR);

                /* Remove the troublesome property */
                icalcomponent_remove_property(tail, prop);
                icalproperty_free(prop);
                prop = 0;
                tail = 0;
                parser->state = ICALPARSER_ERROR;

                icalmemory_free_buffer(str);
                str = NULL;
                return 0;

            } else {
                vcount++;
                icalproperty_set_value(prop, value);
            }
            icalmemory_free_buffer(str);
            str = NULL;

        } else {
#if ICAL_ALLOW_EMPTY_PROPERTIES
            /* Don't replace empty properties with an error.
               Set an empty length string (not null) as the value instead */
            if (vcount == 0) {
                icalproperty_set_value(prop, icalvalue_new(ICAL_NO_VALUE));
            }

            break;
#else
            if (vcount == 0) {
                char temp[200]; /* HACK */

                icalproperty_kind prop_kind = icalproperty_isa(prop);
                icalcomponent *tail = pvl_data(pvl_tail(parser->components));

                snprintf(temp, sizeof(temp), "No value for %s property. Removing entire property",
                         icalproperty_kind_to_string(prop_kind));

                insert_error(tail, str, temp, ICAL_XLICERRORTYPE_VALUEPARSEERROR);

                /* Remove the troublesome property */
                icalcomponent_remove_property(tail, prop);
                icalproperty_free(prop);
                prop = 0;
                tail = 0;
                parser->state = ICALPARSER_ERROR;
                return 0;
            } else {

                break;
            }
#endif
        }
    }

    /****************************************************************
     * End of component parsing.
     *****************************************************************/

    if (pvl_data(pvl_tail(parser->components)) == 0 && parser->level == 0) {
        /* HACK. Does this clause ever get executed? */
        parser->state = ICALPARSER_SUCCESS;
        assert(0);
        return parser->root_component;
    } else {
        parser->state = ICALPARSER_IN_PROGRESS;
        return 0;
    }
}

icalparser_state icalparser_get_state(icalparser *parser)
{
    return parser->state;
}

icalcomponent *icalparser_clean(icalparser *parser)
{
    icalcomponent *tail;

    icalerror_check_arg_rz((parser != 0), "parser");

    /* We won't get a clean exit if some components did not have an
       "END" tag. Clear off any component that may be left in the list */

    while ((tail = pvl_data(pvl_tail(parser->components))) != 0) {

        insert_error(tail, " ",
                     "Missing END tag for this component. Closing component at end of input.",
                     ICAL_XLICERRORTYPE_COMPONENTPARSEERROR);

        parser->root_component = pvl_pop(parser->components);
        tail = pvl_data(pvl_tail(parser->components));

        if (tail != 0 && parser->root_component != NULL) {
            if (icalcomponent_get_parent(parser->root_component) != 0) {
                icalerror_warn(
                    "icalparser_clean is trying to attach a component for the second time");
            } else {
                icalcomponent_add_component(tail, parser->root_component);
            }
        }
    }

    return parser->root_component;
}

struct slg_data
{
    const char *pos;
    const char *str;
};

char *icalparser_string_line_generator(char *out, size_t buf_size, void *d)
{
    int replace_cr = 0;
    char *n;
    size_t size;
    struct slg_data *data = (struct slg_data *)d;

    if (data->pos == 0) {
        data->pos = data->str;

        /* Skip the UTF-8 marker at the beginning of the string */
        if (((unsigned char) data->pos[0]) == 0xEF &&
            ((unsigned char) data->pos[1]) == 0xBB &&
            ((unsigned char) data->pos[2]) == 0xBF) {
            data->pos += 3;
        }
    }

    /* If the pointer is at the end of the string, we are done */
    if (*(data->pos) == 0) {
        return 0;
    }

    n = strchr(data->pos, '\n');

    if (n == 0) {
        n = strchr(data->pos, '\r'); /* support malformed input with only CR and no LF
                                        (e.g. from Kerio Connect Server) */
        if(n == 0) {
            size = strlen(data->pos);
        } else {
            n++; /* include CR in output - will be replaced by LF later on */
            replace_cr = 1;
            size = (size_t) (ptrdiff_t) (n - data->pos);
        }
    } else {
        n++;    /* include newline in output */
        size = (size_t) (ptrdiff_t) (n - data->pos);
    }

    if (size > buf_size - 1) {
        size = buf_size - 1;
    }

    strncpy(out, data->pos, size);

    if(replace_cr) {
        *(out + size - 1) = '\n';
    }
    *(out + size) = '\0';

    data->pos += size;

    return out;
}

icalcomponent *icalparser_parse_string(const char *str)
{
    icalcomponent *c;
    struct slg_data d;
    icalparser *p;

    icalerrorstate es = icalerror_get_error_state(ICAL_MALFORMEDDATA_ERROR);

    d.pos = 0;
    d.str = str;

    p = icalparser_new();
    icalparser_set_gen_data(p, &d);

    icalerror_set_error_state(ICAL_MALFORMEDDATA_ERROR, ICAL_ERROR_NONFATAL);

    c = icalparser_parse(p, icalparser_string_line_generator);

    icalerror_set_error_state(ICAL_MALFORMEDDATA_ERROR, es);

    icalparser_free(p);

    return c;
}