File:  [ELWIX - Embedded LightWeight unIX -] / libaitwww / src / aitwww.c
Revision 1.6: download - view: text, annotated - select for diffs - revision graph
Wed Sep 14 15:12:22 2016 UTC (7 years, 8 months ago) by misho
Branches: MAIN
CVS tags: www3_4, WWW3_3, HEAD
version 3.3

/*************************************************************************
* (C) 2012 AITNET ltd - Sofia/Bulgaria - <misho@aitnet.org>
*  by Michael Pounov <misho@elwix.org>
*
* $Author: misho $
* $Id: aitwww.c,v 1.6 2016/09/14 15:12:22 misho Exp $
*
**************************************************************************
The ELWIX and AITNET software is distributed under the following
terms:

All of the documentation and software included in the ELWIX and AITNET
Releases is copyrighted by ELWIX - Sofia/Bulgaria <info@elwix.org>

Copyright 2004 - 2016
	by Michael Pounov <misho@elwix.org>.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
This product includes software developed by Michael Pounov <misho@elwix.org>
ELWIX - Embedded LightWeight unIX and its contributors.
4. Neither the name of AITNET nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY AITNET AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
#include "global.h"
#include "mime.h"


#pragma GCC visibility push(hidden)

int www_Errno;
char www_Error[STRSIZ];

#pragma GCC visibility pop

// www_GetErrno() Get error code of last operation
int
www_GetErrno()
{
	return www_Errno;
}

// www_GetError() Get error text of last operation
const char *
www_GetError()
{
	return www_Error;
}

// www_SetErr() Set error to variables for internal use!!!
void
www_SetErr(int eno, char *estr, ...)
{
	va_list lst;

	www_Errno = eno;
	memset(www_Error, 0, sizeof www_Errno);
	va_start(lst, estr);
	vsnprintf(www_Error, sizeof www_Errno, estr, lst);
	va_end(lst);
}

/* -------------------------------------------------------------- */

/*
 * www_initCGI() - Init CGI program
 *
 * return: NULL error or allocated cgi session
 */
cgi_t *
www_initCGI(void)
{
	char *s, *str;
	int ctlen, rlen;
	register int i;
	cgi_t *cgi = NULL;

	str = getenv("REQUEST_METHOD");
	if (!str) {
		www_SetErr(EFAULT, "Request method not found");
		return NULL;
	}
	if (!strcmp(str, "GET") || !strcmp(str, "HEAD")) {
		/* GET | HEAD */
		str = getenv("QUERY_STRING");
		if (!str) {
			www_SetErr(EFAULT, "Query string not found");
			return NULL;
		}
		cgi = www_parseQuery(str);
	} else if (!strcmp(str, "POST")) {
		/* POST */
		str = getenv("CONTENT_LENGTH");
		if (!str) {
			www_SetErr(EFAULT, "Content length not found");
			return NULL;
		} else
			ctlen = strtol(str, NULL, 0);

		s = getenv("CONTENT_TYPE");
		if (!s) {
			www_SetErr(EFAULT, "Content type not found");
			return NULL;
		}
		if (www_cmp(s, "multipart/form-data") && 
				www_cmp(s, "application/x-www-form-urlencoded")) {
			www_SetErr(EFAULT, "MIME parts are broken");
			return NULL;
		}

		/* allocated space for post data */
		str = e_malloc(ctlen + 1);
		if (!str) {
			www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
			return NULL;
		} else
			memset(str, 0, ctlen + 1);
		for (i = 0; i < ctlen && (rlen = 
					read(STDIN_FILENO, (void*) str + i, ctlen - i)) > 0; i += rlen);
		str[ctlen] = 0;

		if (!www_cmp(s, "application/x-www-form-urlencoded"))
			cgi = www_parseQuery(str);
		else if (!www_cmp(s, "multipart/form-data"))
			cgi = www_parseMultiPart(str, ctlen, s);

		e_free(str);
	} else {
		/* Unknown method */
		www_SetErr(EFAULT, "Unknown request method");
		return NULL;
	}

	return cgi;
}

/*
 * www_closeCGI() - Close and free all CGI resources
 *
 * @cgi = Inited cgi session
 * return: none
 */
void
www_closeCGI(cgi_t ** __restrict cgi)
{
	struct tagCGI *t;

	if (!cgi || !*cgi)
		return;

	while ((t = SLIST_FIRST(*cgi))) {
		ait_freeVar(&t->cgi_name);
		ait_freeVar(&t->cgi_value);

		SLIST_REMOVE_HEAD(*cgi, cgi_node);
		e_free(t);
	}

	e_free(*cgi);
	*cgi = NULL;
}

/*
 * www_parseQuery() - Parse CGI query string
 *
 * @str = String
 * return: NULL error or allocated cgi session
 */
cgi_t *
www_parseQuery(const char *str)
{
	char *base, *wrk;
	cgi_t *cgi;
	struct tagCGI *t, *old = NULL;

	if (!str) {
		www_SetErr(EINVAL, "String is NULL");
		return NULL;
	}

	cgi = e_malloc(sizeof(cgi_t));
	if (!cgi) {
		www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
		return NULL;
	} else {
		memset(cgi, 0, sizeof(cgi_t));
		SLIST_INIT(cgi);
	}

	base = wrk = e_strdup(str);

	while (*wrk) {
		t = e_malloc(sizeof(struct tagCGI));
		if (!t) {
			www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
			www_closeCGI(&cgi);
			return NULL;
		} else
			memset(t, 0, sizeof(struct tagCGI));

		t->cgi_name = www_getpair(&wrk, "=");
		www_unescape(AIT_GET_STR(t->cgi_name));

		t->cgi_value = www_getpair(&wrk, "&;");
		www_unescape(AIT_GET_STR(t->cgi_value));

		if (!old)
			SLIST_INSERT_HEAD(cgi, t, cgi_node);
		else
			SLIST_INSERT_AFTER(old, t, cgi_node);
		old = t;
	}

	e_free(base);
	return cgi;
}

/*
 * www_getValue() - Get Value from CGI session
 *
 * @cgi = Inited cgi session
 * @name = Name of cgi variable
 * return: NULL not found or !=NULL value
 */
const char *
www_getValue(cgi_t * __restrict cgi, const char *name)
{
	struct tagCGI *t;

	if (!cgi || !name) {
		www_SetErr(EINVAL, "Invalid argument(s)");
		return NULL;
	}

	SLIST_FOREACH(t, cgi, cgi_node)
		if (t->cgi_name && !strcmp(name, AIT_GET_STR(t->cgi_name)))
			return AIT_GET_STR(t->cgi_value);

	return NULL;
}

/*
 * www_addValue() - Add new or update if exists CGI variable
 *
 * @cgi = Inited cgi session
 * @name = Name of cgi variable
 * @value = Value of cgi variable
 * return: -1 error, 0 add new one or 1 updated variable
 */
int
www_addValue(cgi_t * __restrict cgi, const char *name, const char *value)
{
	struct tagCGI *t, *tmp;

	if (!cgi || !name) {
		www_SetErr(EINVAL, "Invalid argument(s)");
		return -1;
	}

	/* search for update */
	SLIST_FOREACH_SAFE(t, cgi, cgi_node, tmp) {
		if (t->cgi_name && !strcmp(name, AIT_GET_STR(t->cgi_name))) {
			AIT_FREE_VAL(t->cgi_value);
			AIT_SET_STR(t->cgi_value, value);
			/* update */
			return 1;
		}
		/* save last cgi pair */
		if (!tmp)
			break;
	}

	/* add new one */
	tmp = e_malloc(sizeof(struct tagCGI));
	if (!tmp) {
		www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
		return -1;
	} else
		memset(tmp, 0, sizeof(struct tagCGI));

	tmp->cgi_name = ait_allocVar();
	if (!tmp->cgi_name) {
		www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
		e_free(tmp);
		return -1;
	} else
		AIT_SET_STR(tmp->cgi_name, name);
	tmp->cgi_value = ait_allocVar();
	if (!tmp->cgi_name) {
		www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
		ait_freeVar(&tmp->cgi_name);
		e_free(tmp);
		return -1;
	} else
		AIT_SET_STR(tmp->cgi_value, value);

	if (!t)
		SLIST_INSERT_HEAD(cgi, tmp, cgi_node);
	else
		SLIST_INSERT_AFTER(t, tmp, cgi_node);
	return 0;
}

/*
 * www_delPair() - Delete CGI variable from session
 *
 * @cgi = Inited cgi session
 * @name = Name of cgi variable
 * return: -1 error, 0 not found or 1 deleted ok
 */
int
www_delPair(cgi_t * __restrict cgi, const char *name)
{
	struct tagCGI *t, *tmp;

	if (!cgi || !name) {
		www_SetErr(EINVAL, "Invalid argument(s)");
		return -1;
	}

	/* search for delete */
	SLIST_FOREACH_SAFE(t, cgi, cgi_node, tmp)
		if (t->cgi_name && !strcmp(name, AIT_GET_STR(t->cgi_name))) {
			SLIST_REMOVE(cgi, t, tagCGI, cgi_node);

			ait_freeVar(&t->cgi_name);
			ait_freeVar(&t->cgi_value);
			e_free(t);
			return 1;
		}

	return 0;
}

/*
 * www_listPairs() - Walk over CGI session variables
 *
 * @cgi = Cgi session
 * @func = If !=NULL call function for each element
 * @arg = Optional argument pass through callback
 * return: -1 error or >-1 number of elements
 */
int
www_listPairs(cgi_t * __restrict cgi, list_cb_t func, void *arg)
{
	register int ret = 0;
	struct tagCGI *t;

	if (!cgi) {
		www_SetErr(EINVAL, "Invalid CGI session argument");
		return -1;
	}

	SLIST_FOREACH(t, cgi, cgi_node) {
		ret++;

		if (func)
			func(t, arg);
	}

	return ret;
}

/*
 * www_header() - Output initial html header
 *
 * @output = file handle
 * return: <1 error or >0 writed bytes
 */
int
www_header(FILE *output)
{
	FILE *f = output ? output : stdout;

	return fputs("Content-type: text/html\n\n", f);
}

static ait_val_t *
quotStr(const char *str, const char **end)
{
	char *e;
	int n, len = 0;
	register int i;
	ait_val_t *s;

	/* get str w/o " */
	if (*str != '"') {
		n = strspn(str, "!#$%&'*+-.0123456789?ABCDEFGHIJKLMNOPQRSTUVWXYZ"
				"^_`abcdefghijklmnopqrstuvwxyz{|}~");
		s = ait_allocVar();
		if (!s) {
			www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
			return NULL;
		} else {
			AIT_SET_STRSIZ(s, n + 1);
			strlcpy(AIT_GET_STR(s), str, AIT_LEN(s));
			*end = str + n;
			return s;
		}
	} else
		str++;
	/* get quoted string */
	if (!(e = strchr(str, '"')))
		return NULL;
	else
		len = e - str;

	s = ait_allocVar();
	if (!s) {
		www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
		return NULL;
	} else {
		AIT_SET_STRSIZ(s, len + 1);
		e = AIT_GET_STR(s);
	}

	for (i = 0; i < len; i++, str++) {
		if (*str == '\\' || *str == '\n')
			e[i] = *++str;
		else if (*str == '"')
			break;
		else
			e[i] = *str;
	}
	e[i] = 0;

	*end = ++str;
	return s;
}

static struct tagCGI *
addAttr(const char **ct)
{
	struct tagCGI *a;
	const char *c;
	char *eq;

	if (!*ct || !(c = strchr(*ct, ';')))
		return NULL;
	else
		c++;
	while (isspace((int) *c))
		c++;

	if (!(eq = strchr(c, '=')))
		return NULL;

	a = e_malloc(sizeof(struct tagCGI));
	if (!a) {
		www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
		return NULL;
	}
	a->cgi_name = ait_allocVar();
	if (!a->cgi_name) {
		www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
		e_free(a);
		return NULL;
	}

	*eq++ = 0;
	AIT_SET_STR(a->cgi_name, c);
	a->cgi_value = quotStr(eq, &c);
	if (!a->cgi_value) {
		ait_freeVar(&a->cgi_name);
		e_free(a);
		return NULL;
	}

	*ct = c;
	return a;
}

/*
 * www_parseMultiPart() - Parse Multi part POST CGI query string
 *
 * @str = String
 * @ctlen = Content length
 * @ct = Content type
 * return: NULL error or allocated cgi session
 */
cgi_t *
www_parseMultiPart(const char *str, int ctlen, const char *ct)
{
	cgi_t *cgi, *attr;
	mime_t *mime = NULL;
	struct tagMIME *m;
	struct tagCGI *t, *old = NULL;
	const char *s;
	int len;
	ait_val_t *v;

	if (!str) {
		www_SetErr(EINVAL, "String is NULL");
		return NULL;
	}

	cgi = e_malloc(sizeof(cgi_t));
	if (!cgi) {
		www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
		return NULL;
	} else {
		memset(cgi, 0, sizeof(cgi_t));
		SLIST_INIT(cgi);
	}

	/* parse MIME messages */
	attr = www_parseAttributes(&ct);
	if (!attr) {
		www_closeCGI(&cgi);
		return NULL;
	}
	v = www_getAttribute(attr, "boundary");
	mime = mime_parseMultiPart(str, ctlen, AIT_GET_STR(v), NULL);
	www_freeAttributes(&attr);
	if (!mime) {
		www_closeCGI(&cgi);
		return NULL;
	}

	SLIST_FOREACH(m, mime, mime_node) {
		s = mime_getValue(m, "content-disposition");
		attr = www_parseAttributes(&s);
		if (!www_getAttribute(attr, "name")) {
			www_freeAttributes(&attr);
			continue;
		}

		t = e_malloc(sizeof(struct tagCGI));
		if (!t) {
			www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
			mime_close(&mime);
			www_closeCGI(&cgi);
			return NULL;
		} else
			memset(t, 0, sizeof(struct tagCGI));

		AIT_COPY_VAL(t->cgi_name, www_getAttribute(attr, "name"));
		len = mime_calcRawSize(m);
		t->cgi_value = ait_allocVar();
		if (!t->cgi_value) {
			www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
			ait_freeVar(&t->cgi_name);
			e_free(t);
			mime_close(&mime);
			www_closeCGI(&cgi);
			return NULL;
		} else {
			AIT_SET_STRSIZ(t->cgi_value, len + 1);
			len = mime_getRawData(m, AIT_GET_STR(t->cgi_value), AIT_LEN(t->cgi_value));
		}

		www_freeAttributes(&attr);

		if (!old)
			SLIST_INSERT_HEAD(cgi, t, cgi_node);
		else
			SLIST_INSERT_AFTER(old, t, cgi_node);
		old = t;
	}

	mime_close(&mime);
	return cgi;
}

/*
 * www_parseAttributes() - Parse attributes
 *
 * @ct = Content type
 * return: NULL error or !=NULL attributes
 */
cgi_t *
www_parseAttributes(const char **ct)
{
	struct tagCGI *t, *old = NULL;
	cgi_t *attr = NULL;

	if (!ct) {
		www_SetErr(EINVAL, "String is NULL");
		return NULL;
	}

	attr = e_malloc(sizeof(cgi_t));
	if (!attr) {
		www_SetErr(elwix_GetErrno(), "%s", elwix_GetError());
		return NULL;
	} else {
		memset(attr, 0, sizeof(cgi_t));
		SLIST_INIT(attr);
	}

	/* get mime attributes */
	while ((t = addAttr(ct))) {
		if (!old)
			SLIST_INSERT_HEAD(attr, t, cgi_node);
		else
			SLIST_INSERT_AFTER(old, t, cgi_node);
		old = t;
	}

	return attr;
}

/*
 * www_getAttribute() - Get Attribute from attribute session
 *
 * @cgi = Inited attribute session
 * @name = Name of attribute variable
 * return: NULL not found or !=NULL value
 */
ait_val_t *
www_getAttribute(cgi_t * __restrict cgi, const char *name)
{
	struct tagCGI *t;

	if (!cgi || !name) {
		www_SetErr(EINVAL, "Invalid argument(s)");
		return NULL;
	}

	SLIST_FOREACH(t, cgi, cgi_node)
		if (t->cgi_name && !strcmp(name, AIT_GET_STR(t->cgi_name)))
			return t->cgi_value;

	return NULL;
}


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>