aboutsummaryrefslogtreecommitdiff
path: root/src/fetch.c
blob: 3b156af2e9cf2a1e14ecd70bd19812299c97fd1e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#include "fetch.h"

#include <curl/curl.h>
#include <curl/multi.h>
#include <libxml/parser.h>
#include <string.h>

#include "log.h"
#include "parse.h"

#define REQUEST_TIMEOUT_MS (30 * 1000)

static size_t write_data(void* data, size_t size, size_t count, void* file) {
  // as data comes in, push it directly into the XML parser
  size_t length = size * count;
  xmlParserCtxtPtr* parser = (xmlParserCtxtPtr*)file;
  if (*parser == NULL) {
    LOG_DEBUG("Initializing a document parser");

    // if this is the first time this is being called, create the parser
    *parser =
        xmlCreatePushParserCtxt(NULL, NULL, (char*)data, (int)length, NULL);
  } else {
    xmlParseChunk(*parser, (char*)data, (int)length, 0);
  }

  LOG_DEBUG("Received %zu bytes", count);

  return length;
}

static void init_request(CURLM* curlm, rss_config_t* config, int uri_index) {
  char* uri = config->uris[uri_index];

  CURL* curl = NULL;
  if ((curl = curl_easy_init()) == NULL) {
    LOG_ERROR("Failed to create CURL object for URI \"%s\"", uri);
    return;
  }

  LOG_DEBUG("Fetching document from %s", uri);

  xmlParserCtxtPtr* parser = malloc(sizeof(xmlParserCtxtPtr));
  *parser = NULL;

  curl_easy_setopt(curl, CURLOPT_URL, uri);
  curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, parser);
  curl_easy_setopt(curl, CURLOPT_PRIVATE, parser);
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, config->useragent);

#ifdef DEBUG
  curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
#endif

  curl_multi_add_handle(curlm, curl);
}

static int parse_response_document(post_item_t** posts, xmlDocPtr doc,
                                   rss_config_t* config, const char* url,
                                   int total) {
  int doc_post_count = 0;
  post_item_t* doc_posts = parse_posts_from_doc(doc, &doc_post_count, config);

  if (doc_posts != NULL) {
    if (doc_post_count > 0) {
      LOG_DEBUG("Found %d syndicated entries", doc_post_count);
      post_item_t* expanded =
          realloc(*posts, (total + doc_post_count) * sizeof(post_item_t));
      if (expanded == NULL) {
        LOG_ERROR("Ran out of memory while fetching posts from %s", url);
        return 0;
      }

      memcpy(&expanded[total], doc_posts, doc_post_count * sizeof(post_item_t));
      *posts = expanded;
    }

    // only free the temporary buffer, not the post items themselves; the
    // string pointers on the post structure need to remain valid after this
    // point
    free(doc_posts);
  }

  return doc_post_count;
}

static void wait_until_finished(CURLM* curlm) {
  int running = 0;
  curl_multi_perform(curlm, &running);

  do {
    int numfds = 0;
    int result = curl_multi_wait(curlm, NULL, 0, REQUEST_TIMEOUT_MS, &numfds);
    if (result != CURLM_OK) {
      LOG_ERROR("An error occurred while waiting for a request to complete: %s",
                curl_multi_strerror(result));
      break;
    }

    curl_multi_perform(curlm, &running);
  } while (running);
}

static bool ensure_response_success_code(CURL* curl) {
  int status_code = 0;
  curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status_code);

  if (status_code != 200) {
    char* url = NULL;
    curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
    if (url != NULL) {
      LOG_ERROR("Received HTTP error code %d from %s", status_code, url);
    }

    curl_easy_cleanup(curl);
    false;
  }

  return true;
}

static bool ensure_curl_success(CURLMsg* msg, CURL* curl) {
  if (msg->data.result != CURLE_OK) {
    char* url = NULL;
    curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
    if (url != NULL) {
      LOG_ERROR("Received CURL error code %d while fetching %s",
                msg->data.result, url);
    } else {
      LOG_ERROR("Received CURL error code %ds", msg->data.result);
    }

    return false;
  }

  return true;
}

static void append_posts_from_parser(CURL* curl, int* total,
                                     rss_config_t* config,
                                     post_item_t** posts) {
  xmlParserCtxtPtr* parser;
  curl_easy_getinfo(curl, CURLINFO_PRIVATE, &parser);
  if (parser != NULL) {
    if (*parser != NULL) {
      // terminate the parser
      xmlParseChunk(*parser, NULL, 0, 1);
      xmlDocPtr doc = (*parser)->myDoc;
      xmlFreeParserCtxt(*parser);

      char* url = NULL;
      curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
      *total += parse_response_document(posts, doc, config, url, *total);

      xmlFreeDoc(doc);
    }

    free(parser);
  }
}

post_item_t* fetch_posts(rss_config_t* config, int* count) {
  post_item_t* posts = NULL;
  *count = 0;

  CURLM* curlm = curl_multi_init();

  for (int i = 0; i < config->uri_count; ++i) {
    init_request(curlm, config, i);
  }

  wait_until_finished(curlm);

  CURLMsg* msg;
  int msgs_left = 0;
  while ((msg = curl_multi_info_read(curlm, &msgs_left))) {
    if (msg->msg != CURLMSG_DONE) {
      // log error
      continue;
    }

    CURL* curl = msg->easy_handle;

    curl_multi_remove_handle(curlm, curl);

    if (!ensure_curl_success(msg, curl)) {
      continue;
    }

    if (!ensure_response_success_code(curl)) {
      continue;
    }

    append_posts_from_parser(curl, count, config, &posts);

    curl_easy_cleanup(curl);
  }

  curl_multi_cleanup(curlm);

  return posts;
}

void init_fetch(void) {
  LOG_DEBUG("Initializing CURL globally");

  curl_global_init(CURL_GLOBAL_DEFAULT);
}

/*
 * Cleans up global resources used for fetching data from URLs
 */
void cleanup_fetch(void) {
  LOG_DEBUG("Cleaning up CURL global resources");
  curl_global_cleanup();
}