Statistics
| Branch: | Revision:

chunker-player / chunker_player / http.c @ a2da678c

History | View | Annotate | Download (2.22 KB)

1
// based on curl/examples/{simple,getinmemory,ftpget}.c
2

    
3
#include <string.h>
4
#include <stdlib.h>
5
#include <stdio.h>
6
#include <curl/curl.h>
7

    
8
//see http://curl.haxx.se/libcurl/c/getinmemory.html
9
//char *http_get(char *uri, char*fname);
10

    
11
/*
12
 * This is an example showing how to get a single file from an FTP/HTTP server.
13
 * It delays the actual destination file creation until the first write
14
 * callback so that it won't create an empty file in case the remote file
15
 * doesn't exist or something else fails.
16
 */
17

    
18
struct FtpFile {
19
  const char *filename;
20
  FILE *stream;
21
};
22

    
23
static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
24
{
25
  struct FtpFile *out=(struct FtpFile *)stream;
26
  if(out && !out->stream) {
27
    /* open file for writing */
28
    out->stream=fopen(out->filename, "wb");
29
    if(!out->stream)
30
      return -1; /* failure, can't open file to write */
31
  }
32
  return fwrite(buffer, size, nmemb, out->stream);
33
}
34

    
35
int http_get2file(char *uri, char *fname)
36
{
37
  CURL *curl;
38
  CURLcode res;
39
  struct FtpFile ftpfile={
40
    fname, /* name to store the file as if succesful */
41
    NULL
42
  };
43

    
44
  if (strncmp(fname, "~/", 2) == 0) {        /* curl can't handle ~ in the filename */
45
    char *fname2;
46
    char *home = getenv("HOME");
47
    if (!home) return -1;
48

    
49
    fname2 = malloc(strlen(home) + strlen(fname));
50
    if (!fname2) return -1;
51

    
52
    strcpy(fname2, home);
53
    strcpy(fname2 + strlen(home), fname+1);
54
    ftpfile.filename = fname2;
55
  }
56

    
57
  curl_global_init(CURL_GLOBAL_DEFAULT);
58

    
59
  curl = curl_easy_init();
60
  if(curl) {
61
    curl_easy_setopt(curl, CURLOPT_URL,uri);
62
    /* Define our callback to get called when there's data to be written */
63
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
64
    /* Set a pointer to our struct to pass to the callback */
65
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
66

    
67
    /* Switch on full protocol/debug output */
68
    //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
69

    
70
    res = curl_easy_perform(curl);
71

    
72
    /* always cleanup */
73
    curl_easy_cleanup(curl);
74

    
75
    if(CURLE_OK != res) {
76
      /* we failed */
77
      fprintf(stderr, "curl told us %d\n", res);
78
      return -1;
79
    }
80
  }
81

    
82
  if(ftpfile.stream)
83
    fclose(ftpfile.stream); /* close the local file */
84

    
85
  curl_global_cleanup();
86

    
87
  return 0;
88
}