http.c
author Tero Marttila <terom@fixme.fi>
Fri, 06 Jun 2008 16:05:26 +0300
changeset 10 9daa832ab9c4
child 12 43297144f196
permissions -rw-r--r--
separate http query argument parsing into a new http module, and clean up unused headers from web_main.c

committer: Tero Marttila <terom@fixme.fi>
#include <sys/queue.h>
#include <string.h>
#include <stdlib.h>

#include <event2/event_struct.h>

#include "http.h"
#include "common.h"

int http_qarg_parse (struct evhttp_request *request, struct http_qarg *qarg_spec) {
    // our return code
    int error_flag = 0;

#define ERROR(msg, ...) do { error("http_qarg_parse: " msg, __VA_ARGS__); error_flag = -1; goto error; } while (0)
    
    // get the uri from the request
    const char *uri = evhttp_request_get_uri(request);
    
    // the keyval list that we get from evhttp_parse_query
    struct evkeyval *qarg;
    struct evkeyvalq qargs;
    
    // parse the uri into a list
    evhttp_parse_query(uri, &qargs);
    
    // iterate over the list of given query arugments
    TAILQ_FOREACH(qarg, &qargs, next) {
        struct http_qarg *qarg_info;
        
        // match them against our http_qarg structs
        for (qarg_info = qarg_spec; qarg_info->hqa_type != QARG_END; qarg_info++) {
            if (strcmp(qarg->key, qarg_info->hqa_key) == 0) {
                // found a match
                
                // extract a value from the qarg
                char *cptr = NULL;
                signed long int int_val;

                switch (qarg_info->hqa_type) {
                    case QARG_UINT :
                        int_val = strtol(qarg->value, &cptr, 10);

                        if (*qarg->value == '\0' || *cptr != '\0' || int_val < 0)
                            ERROR("Invalid QARG_UINT: %s: %s -> %d", qarg->key, qarg->value, int_val);

                        *((unsigned long int *) qarg_info->hqa_addr) = (unsigned long int) int_val;

                        break;
                    
                    case QARG_INVALID :
                        ERROR("QARG_INVALID: %s: %s", qarg->key, qarg->value);

                    default :
                        err_exit("http_qarg_parse: Invalid qarg_info->hqa_type: %d", qarg_info->hqa_type);
                }
            }
        }
    }

#undef ERROR    
error:    

    // clean up the qargs (badly named functions :< )
    evhttp_clear_headers(&qargs);
    
    return error_flag;
}