source: gaycko/trunk/src/io/http.c @ 4730

Last change on this file since 4730 was 4730, checked in by Jean-Yves Lamoureux, 9 years ago
  • Don't crash on unknow/weird/hippy tags
File size: 1.6 KB
Line 
1#include "http.h"
2#include <stdlib.h>
3#include <string.h>
4
5        static size_t
6http_callback(void *ptr, size_t size, size_t nmemb, void *user)
7{
8        size_t realsize = size * nmemb;
9        gHttp *mem = (gHttp *)user;
10
11        mem->data = realloc(mem->data, mem->size + realsize + 1);
12
13        if (mem->data == NULL) {
14                /* out of memory! */
15                printf("not enough memory (realloc returned NULL)\n");
16                exit(EXIT_FAILURE);
17        }
18
19        memcpy(&(mem->data[mem->size]), ptr, realsize);
20        mem->size += realsize;
21        mem->data[mem->size] = 0;
22
23        return realsize;
24}
25
26gHttp *http_open(char* url) {
27        gHttp *ret = malloc(sizeof(gHttp));
28        ret->data = malloc(1024);
29        ret->size = 0;
30
31        curl_global_init(CURL_GLOBAL_ALL);
32        ret->curl_handle = curl_easy_init();
33
34        /* specify URL to get */
35        curl_easy_setopt(ret->curl_handle, CURLOPT_URL, url);
36
37        /* send all data to this function  */
38        curl_easy_setopt(ret->curl_handle, CURLOPT_WRITEFUNCTION, http_callback);
39
40        /* we pass our 'chunk' struct to the callback function */
41        curl_easy_setopt(ret->curl_handle, CURLOPT_WRITEDATA, (void *)ret);
42
43        /* some servers don't like requests that are made without a user-agent
44           field, so we provide one */
45        curl_easy_setopt(ret->curl_handle, CURLOPT_USERAGENT, "Gaycko/0.1");
46        curl_easy_setopt(ret->curl_handle, CURLOPT_AUTOREFERER, 1);
47        curl_easy_setopt(ret->curl_handle, CURLOPT_FOLLOWLOCATION, 1);
48
49
50        /* get it! */
51        curl_easy_perform(ret->curl_handle);
52
53        /* cleanup curl stuff */
54        curl_easy_cleanup(ret->curl_handle);
55
56        return ret;
57}
58
59void   http_close(gHttp *f) {
60        if(!f) return;
61
62        memset(f->data, 0, f->size);
63        free(f->data);
64        f->size = 0;
65
66        curl_global_cleanup();
67}
Note: See TracBrowser for help on using the repository browser.