Imported Upstream version 2.7
[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 #include "os_regex_internal.h"
17
18
19 /** char **OS_StrBreak(char match, char *str, int size) v0.2
20  * Split a string into multiples pieces, divided by a char "match".
21  * Returns a NULL terminated array on success or NULL on error.
22  */
23 char **OS_StrBreak(char match, char *str, int size)
24 {
25     int count = 0;
26     int i = 0;
27
28     char *tmp_str = str;
29
30     char **ret;
31
32     /* We can't do anything if str is null or size <= 0 */
33     if((str == NULL)||(size <= 0))
34         return(NULL);
35
36     ret = (char **)calloc(size+1, sizeof(char *));
37
38     if(ret == NULL)
39     {
40         /* Memory error. Should provice a better way to detect it */
41         return(NULL);
42     }
43
44     /* Allocating memory to null */
45     while(i <= size)
46     {
47         ret[i] = NULL;
48         i++;
49     }
50     i = 0;
51
52     /* */
53     while(*str != '\0')
54     {
55         i++;
56         if((count < size-1)&&(*str == match))
57         {
58             ret[count] = (char *)calloc(i,sizeof(char));
59
60             if(ret[count] == NULL)
61             {
62                 goto error;
63             }
64
65             /* Copying the string */
66             ret[count][i-1] = '\0';
67             strncpy(ret[count],tmp_str,i-1);
68
69             tmp_str = ++str;
70             count++;
71             i=0;
72
73             continue;
74         }
75         str++;
76     } /* leave from here when *str == \0 */
77
78
79     /* Just do it if count < size */
80     if(count < size)
81     {
82         ret[count] = (char *)calloc(i+1,sizeof(char));
83
84         if(ret[count] == NULL)
85         {
86             goto error;
87         }
88
89         /* Copying the string */
90         ret[count][i] = '\0';
91         strncpy(ret[count],tmp_str,i);
92
93         count++;
94
95         /* Making sure it is null terminated */
96         ret[count] = NULL;
97
98         return(ret);
99     }
100
101     /* We shouldn't get to this point
102      * Just let "error" handle that
103      */
104
105     error:
106         i = 0;
107
108         /* Deallocating the memory whe can */
109         while(i < count)
110         {
111             free(ret[i]);
112             i++;
113         }
114
115         free(ret);
116         return(NULL);
117
118 }
119
120 /* EOF */