Import of IN-GS source
[infodrom/cgilib] / cgi.c
1 /*
2     cgi.c - Ein paar Routinen fuer die Programmierung von CGI-Programmen
3     Copyright (c) 1996  Martin Schulze <joey@office.individual.net>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include "cgi.h"
24
25 c_var *cgiParseVar (char *binding)
26 {
27   c_var *result;
28   char *ip;
29
30   if ((ip = (char *)index(binding, '=')) == NULL)
31     return NULL;
32   if (((result = (c_var *)malloc(sizeof(c_var))) == NULL)
33       ||((result->name = (char *)malloc(ip - binding +1)) == NULL)
34       ||((result->value = (char *)malloc(strlen(ip))) == NULL))
35     return NULL;
36
37   bzero(result->name,sizeof(result->name));
38   bzero(result->value,sizeof(result->value));
39   strncpy (result->name, binding, ip++ - binding);
40   strcpy (result->value, ip);
41
42   return result;
43 }
44
45 c_var **cgiParseInput ()
46 {
47   int length;
48   char *line;
49   char frag[50];
50   int numargs;
51   char *cp, *ip;
52   c_var **result;
53   int i;
54
55   if (!getenv("CONTENT_LENGTH"))
56     return NULL;
57   length = atoi(getenv("CONTENT_LENGTH"));
58   if ((line = (char *)malloc (length+2)) == NULL)
59     return NULL;
60
61   fgets(line, length+1, stdin);
62
63   /* line contains all values stored like okz=0923&plz=23 */
64   for (numargs=1,cp=line; *cp; cp++)
65     if (*cp == '&') numargs++;
66   if ((result = (c_var **)malloc((numargs * sizeof(c_var *))+1)) == NULL)
67     return NULL;
68
69   cp = line;
70   i=0;
71   while ((ip = (char *)index(cp, '&')) != NULL) {
72     bzero (frag, sizeof(frag));
73     strncpy (frag, cp, ip - cp);
74     result[i++] = cgiParseVar(frag);
75     cp = ++ip;
76   }
77   result[i++] = cgiParseVar(cp);
78   result[i] = NULL;
79
80 /*
81   for (i=0;result[i]; i++)
82     printf ("%s=%s<br>\n", result[i]->name,result[i]->value);
83 */
84
85   return result;
86 }
87
88 char *cgiGetValue(c_var **parms, const char *var)
89 {
90   int i;
91
92   if (parms)
93     for (i=0;parms[i]; i++)
94       if (!strcmp(var,parms[i]->name))
95         return parms[i]->value;
96   return NULL;
97 }