/**
 * @file load-url.c
 * @brief File loading helper functions
 */

/* $Progeny$
 *
 * Copyright 2003 Hewlett-Packard Company
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include "config.h"

#ifndef HAVE_LIBCURL

#include <assert.h>
#include <expat.h>

#include <discover/load-url.h>

#ifdef HAVE_ZLIB
#include <zlib.h>
#define stdio_file gzFile
#define fopen gzopen
#define STDIO_READ fread
#define fclose gzclose
#else
#include <stdio.h>
typedef FILE *stdio_file;
#define STDIO_READ(f, buf, len) fread(buf, 1, len, f)
#endif

#include <string.h>

int
_discover_load_url(const char *url, XML_Parser parser)
{
    const char *file_path;
    stdio_file url_file;
    char buf[4096];
    char *tmp;
    size_t len;
    int parse_result;

    assert(url != NULL);

    if (strncmp(url, "file:", 5))
        return 0;

    /* We have three accepted formats for the url: file://host/path,
     * file:///path, and file://path.  The third is not actually
     * legal, but curl allows it to refer to a file in the current
     * directory.  Since we use that format in the test suite, we need
     * to support it here.
     *
     * For file://host/path and file:///path, the strchr call takes us
     * directly to the correct absolute path.  For file://path, url +
     * 7 is just "path" so we use that relative path. */
    file_path = strchr(url + 7, '/');
    if (!file_path) {
        file_path = url + 7;
    }

    if (*file_path == '\0')
        return 0;

    url_file = fopen(file_path, "r");
    if (url_file == NULL)
        return 0;

    do
    {
        len = STDIO_READ(url_file, buf, sizeof(buf));
        if (len > 0)
            parse_result = XML_Parse(parser, buf, len, 0);
    } while ((len > 0) && (parse_result != 0));

    fclose(url_file);

    return (parse_result != 0);
}

#endif
