Terminate a freshly allocated string as well.
[infodrom/cgilib] / cgi.c
diff --git a/cgi.c b/cgi.c
index 59546df..e390b37 100644 (file)
--- a/cgi.c
+++ b/cgi.c
 #include <cgi.h>
 #include "aux.h"
 
+#ifndef HAVE_STRNDUP
+char *strndup(const char *s, size_t n);
+#endif
+
 char *cgiHeaderString = NULL;
 char *cgiType = NULL;
 
@@ -46,8 +50,11 @@ int cgiSetHeader (const char *name, const char *value)
     for (cp=name;*cp && *cp!=' ' && *cp!='\r' && *cp!='\n' && *cp!=':';cp++);
     for (vp=value;*vp && *vp!='\r' && *vp!='\n';vp++);
 
+    if (cp-name == 0 || vp-value == 0)
+       return 0;
+
     if (cgiHeaderString) {
-       len = (strlen (cgiHeaderString) + cp-name + vp-value + 5) * sizeof (char);
+       len = (strlen (cgiHeaderString) + cp-name + vp-value + 4) * sizeof (char);
        if ((pivot = (char *)realloc (cgiHeaderString,len)) == NULL)
            return 0;
        cgiHeaderString = pivot;
@@ -57,7 +64,10 @@ int cgiSetHeader (const char *name, const char *value)
        if ((cgiHeaderString = (char *)malloc (len)) == NULL)
            return 0;
        pivot = cgiHeaderString;
+       *pivot = '\0';
     }
+    memset(pivot+1, 0, (cp-name + vp-value + 4));
+
     strncpy (pivot, name, cp-name);
     strncat (pivot, ": ", 2);
     strncat (pivot, value, vp-value);
@@ -663,7 +673,23 @@ s_cgi *cgiInit()
     if (res)
        res->cookies = cgiReadCookies ();
     else
-       return NULL;
+       {
+           /* In some cases, we might have no other CGI results.
+              But we still have cookies! */
+           s_cookie **cookies;
+           cookies = cgiReadCookies();
+           if (cookies) {
+               /* We need to create a s_cgi structure. */
+               if ((res = (s_cgi *)malloc (sizeof (s_cgi))) == NULL)
+                   return NULL;
+               res->vars = NULL;
+               res->cookies = cookies;
+               res->files = NULL;
+               
+           } else {
+               return NULL;
+           }
+       }
 
     if (!res->vars && !res->cookies && !res->files) {
        free (res);
@@ -841,6 +867,18 @@ void cgiFree (s_cgi *parms)
     }
 }
 
+#ifndef HAVE_STRNDUP
+char *strndup(const char *s, size_t n) {
+    char *fnval;
+
+    if ((fnval = (char *)malloc (n + 1)) == NULL)
+       return NULL;
+    strncpy(fnval, s, n);
+    fnval[n] = '\0';
+    return fnval;
+}
+#endif
+
 /*
  * Local variables:
  *  c-indent-level: 4