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