Imported Upstream version 2.7
[ossec-hids.git] / src / shared / string_op.c
1 /* @(#) $Id: ./src/shared/string_op.c, 2011/11/01 dcid Exp $
2  */
3
4 /* Copyright (C) 2009 Trend Micro Inc.
5  * All rights reserved.
6  *
7  * This program is a free software; you can redistribute it
8  * and/or modify it under the terms of the GNU General Public
9  * License (version 2) as published by the FSF - Free Software
10  * Foundation
11  *
12  * License details at the LICENSE file included with OSSEC or
13  * online at: http://www.ossec.net/en/licensing.html
14  */
15
16
17 #include "shared.h"
18 #include "string.h"
19
20 /** os_trimcrlf
21  * Trims the cr and/or LF from the last positions of a string
22  */
23 void os_trimcrlf(char *str)
24 {
25     int len;
26
27     len=strlen(str);
28     len--;
29
30     while (str[len]=='\n' || str[len]=='\r')
31     {
32        str[len]='\0';
33        len--;
34     }
35 }
36
37 /* Remove offending char (e.g., double quotes) from source */
38 char *os_strip_char(char *source, char remove) {
39     char *clean;
40     char *iterator = source;
41     int length = 0;
42     int i;
43
44     // Figure out how much memory to allocate
45     for( ; *iterator; iterator++ ) {
46         if ( *iterator != remove ) {
47             length++;
48         }
49     }
50
51     // Allocate the memory
52     if( (clean = malloc( length + 1 )) == NULL ) {
53         // Return NULL
54         return NULL;
55     }
56     memset(clean, '\0', length + 1);
57
58     // Remove the characters
59     iterator=source;
60     for( i=0; *iterator; iterator++ ) {
61         if ( *iterator != remove ) {
62             clean[i] = *iterator;
63             i++;
64         }
65     }
66
67     return clean;
68 }
69
70 /* Do a substring */
71 int os_substr(char *dest, const char *src, int position, int length) {
72     dest[0]='\0';
73
74     if( length <= 0  ) {
75         // Unsupported negative length string
76         return -3;
77     }
78     if( src == NULL ) {
79         return -2;
80     }
81     if( position >= strlen(src) ) {
82         return -1;
83     }
84
85     strncat(dest, (src + position), length);
86     // Return Success
87     return 0;
88 }
89
90
91 /* EOF */