e54895cfaed21a781d447c6f48a2a6c6a2a5b890
[infodrom/cgilib] / aux.c
1 /*
2     aux.c - Auxilliary code for CGI library
3     Copyright (C) 2007 by Martin Schulze <joey@infodrom.org>
4      
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9     
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14     
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software 
17     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 */
19
20 #include <stdlib.h>
21 #include <string.h>
22
23 char *cgiEscape (char *string)
24 {
25     char *cp, *np;
26     char *buf;
27     size_t len;
28
29     for (cp=string, len=0; *cp; cp++) {
30         switch (*cp) {
31         case '&':
32             len+=5;
33             break;
34         case '<':
35         case '>':
36             len+=4;
37             break;
38         default:
39             len++;
40             break;
41         }
42     }
43
44     if (len == strlen(string))
45         return strdup(string);
46
47     if ((buf = (char *)malloc(len+1)) == NULL)
48         return NULL;
49
50     for (cp=string, np=buf; *cp; cp++) {
51         switch (*cp) {
52         case '&':
53             *np++ = '&';
54             *np++ = 'a';
55             *np++ = 'm';
56             *np++ = 'p';
57             *np++ = ';';
58             break;
59         case '<':
60             *np++ = '&';
61             *np++ = 'l';
62             *np++ = 't';
63             *np++ = ';';
64             break;
65         case '>':
66             *np++ = '&';
67             *np++ = 'g';
68             *np++ = 't';
69             *np++ = ';';
70             break;
71         default:
72             *np++ = *cp;
73             break;
74         }
75     }
76     *np = '\0';
77
78     return buf;
79 }
80
81 /*
82  * Local variables:
83  *  c-indent-level: 4
84  *  c-basic-offset: 4
85  *  tab-width: 8
86  * End:
87  */