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

Last change on this file since 4748 was 4748, checked in by Jean-Yves Lamoureux, 9 years ago
  • Added copyright notices
File size: 2.0 KB
Line 
1/*
2 *  Gaycko        Text mode web browser
3 *  Copyright (c) 2011 Jean-Yves Lamoureux <jylam@lnxscene.org>
4 *                All Rights Reserved
5 *
6 *  This library is free software. It comes without any warranty, to
7 *  the extent permitted by applicable law. You can redistribute it
8 *  and/or modify it under the terms of the Do What The Fuck You Want
9 *  To Public License, Version 2, as published by Sam Hocevar. See
10 *  http://sam.zoy.org/wtfpl/COPYING for more details.
11 */
12#include "http.h"
13#include <stdlib.h>
14#include <string.h>
15
16        static size_t
17http_callback(void *ptr, size_t size, size_t nmemb, void *user)
18{
19        size_t realsize = size * nmemb;
20        gHttp *mem = (gHttp *)user;
21
22        mem->data = realloc(mem->data, mem->size + realsize + 1);
23
24        if (mem->data == NULL) {
25                /* out of memory! */
26                printf("not enough memory (realloc returned NULL)\n");
27                exit(EXIT_FAILURE);
28        }
29
30        memcpy(&(mem->data[mem->size]), ptr, realsize);
31        mem->size += realsize;
32        mem->data[mem->size] = 0;
33
34        return realsize;
35}
36
37gHttp *http_open(char* url) {
38        gHttp *ret = malloc(sizeof(gHttp));
39        ret->data = malloc(1024);
40        ret->size = 0;
41
42        curl_global_init(CURL_GLOBAL_ALL);
43        ret->curl_handle = curl_easy_init();
44
45        /* specify URL to get */
46        curl_easy_setopt(ret->curl_handle, CURLOPT_URL, url);
47
48        /* send all data to this function  */
49        curl_easy_setopt(ret->curl_handle, CURLOPT_WRITEFUNCTION, http_callback);
50
51        /* we pass our 'chunk' struct to the callback function */
52        curl_easy_setopt(ret->curl_handle, CURLOPT_WRITEDATA, (void *)ret);
53
54        /* some servers don't like requests that are made without a user-agent
55           field, so we provide one */
56        curl_easy_setopt(ret->curl_handle, CURLOPT_USERAGENT, "Gaycko/0.1");
57        curl_easy_setopt(ret->curl_handle, CURLOPT_AUTOREFERER, 1);
58        curl_easy_setopt(ret->curl_handle, CURLOPT_FOLLOWLOCATION, 1);
59
60
61        /* get it! */
62        curl_easy_perform(ret->curl_handle);
63
64        /* cleanup curl stuff */
65        curl_easy_cleanup(ret->curl_handle);
66
67        return ret;
68}
69
70void   http_close(gHttp *f) {
71        if(!f) return;
72
73        memset(f->data, 0, f->size);
74        free(f->data);
75        f->size = 0;
76
77        curl_global_cleanup();
78}
Note: See TracBrowser for help on using the repository browser.