new upstream release (3.3.0); modify package compatibility for Stretch
[ossec-hids.git] / src / os_regex / os_regex_strbreak.c
1 /* Copyright (C) 2009 Trend Micro Inc.
2  * All right reserved.
3  *
4  * This program is a free software; you can redistribute it
5  * and/or modify it under the terms of the GNU General Public
6  * License (version 2) as published by the FSF - Free Software
7  * Foundation
8  */
9
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13
14 #include "os_regex.h"
15 #include "os_regex_internal.h"
16
17
18 /* Split a string into multiples pieces, divided by a char "match".
19  * Returns a NULL terminated array on success or NULL on error.
20  */
21 char **OS_StrBreak(char match, const char *str, size_t size)
22 {
23     size_t count = 0;
24     size_t i = 0;
25     const char *tmp_str = str;
26     char **ret;
27
28     /* We can't do anything if str is null */
29     if (str == NULL) {
30         return (NULL);
31     }
32
33     ret = (char **)calloc(size + 1, sizeof(char *));
34
35     if (ret == NULL) {
36         /* Memory error. Should provide a better way to detect it */
37         return (NULL);
38     }
39
40     /* Allocate memory to null */
41     while (i <= size) {
42         ret[i] = NULL;
43         i++;
44     }
45     i = 0;
46
47     while (*str != '\0') {
48         i++;
49         if ((count < size - 1) && (*str == match)) {
50             ret[count] = (char *)calloc(i, sizeof(char));
51
52             if (ret[count] == NULL) {
53                 goto error;
54             }
55
56             /* Copy the string */
57             ret[count][i - 1] = '\0';
58             strncpy(ret[count], tmp_str, i - 1);
59
60             tmp_str = ++str;
61             count++;
62             i = 0;
63
64             continue;
65         }
66         str++;
67     } /* leave from here when *str == \0 */
68
69
70     /* Just do it if count < size */
71     if (count < size) {
72         ret[count] = (char *)calloc(i + 1, sizeof(char));
73
74         if (ret[count] == NULL) {
75             goto error;
76         }
77
78         /* Copy the string */
79         ret[count][i] = '\0';
80         strncpy(ret[count], tmp_str, i);
81
82         count++;
83
84         /* Make sure it is null terminated */
85         ret[count] = NULL;
86
87         return (ret);
88     }
89
90     /* We shouldn't get to this point
91      * Just let "error" handle that
92      */
93
94 error:
95     i = 0;
96
97     while (i < count) {
98         free(ret[i]);
99         i++;
100     }
101
102     free(ret);
103     return (NULL);
104
105 }
106