src/config.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Sat, 13 Dec 2008 15:40:22 +0100
changeset 12 213c3d4abc66
parent 11 a769385a59c6
child 13 d3554afaa768
permissions -rw-r--r--
A simple garbage collector fills the memory leaks... committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 *  $Id: config.c 51 2008-01-10 00:19:39Z mbroeker $
 * $URL: http://localhost/svn/c/mcbot/trunk/src/config.c $
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <config.h>

const
char *CONFIG_OPTIONS[] = {
    "NICK", "PASSWORD", "SERVER", "PORT",
    "CHANNEL", "TOPIC", NULL
};

int config (UC * uc, char *fname)
{
    FILE *f;
    char buffer[513];
    char **line;
    char *token;
    char *value;
    int i = 0;

    if ((f = fopen (fname, "r")) == NULL)
        return -1;

    while (CONFIG_OPTIONS[i] != NULL)
        i++;

    line = calloc ((size_t) (i + 1), sizeof (char *));

    /*
     * We can easily provide default values ...
     */
    uc->nick = uc->pass = uc->server = uc->channel = uc->topic = NULL;
    uc->port = 6667;

    while (!feof (f)) {
        *buffer = '\0';
        (void)fgets (buffer, 512, f);
        token = buffer;

        while (*token == '\t')  /* Eat trailing tabs */
            token++;
        while (*token == ' ')   /* Eat trailing whitespaces */
            token++;

        token = strtok (token, ":");

        if (token != NULL) {
            value = strtok (NULL, "\n");
            i = 0;
            while (CONFIG_OPTIONS[i] != NULL) {
                if (!strcmp (CONFIG_OPTIONS[i], token)) {
                    if (value)
                        line[i] = strdup (value);
                }
                i++;
            }
        }
    }

    if (fclose (f) != 0)
        return -1;

    i = 0;
    while (CONFIG_OPTIONS[i] != NULL) {
        if (line[i] != NULL)
            switch (i) {
            case 0:            /* NICK */
                uc->nick = strdup (line[i]);
                free (line[i]);
                break;
            case 1:            /* PASSWORD */
                uc->pass = strdup (line[i]);
                free (line[i]);
                break;
            case 2:            /* SERVER */
                uc->server = strdup (line[i]);
                free (line[i]);
                break;
            case 3:            /* PORT */
                uc->port = atoi (line[i]);
                free (line[i]);
                break;
            case 4:            /* CHANNEL */
                uc->channel = strdup (line[i]);
                free (line[i]);
                break;
            case 5:            /* TOPIC */
                uc->topic = strdup (line[i]);
                free (line[i]);
                break;
            }
        i++;
    }

    if (line != NULL)
        free (line);

    if (!(uc->nick && uc->pass && uc->server && uc->channel))
        return -2;

    return 0;
}