+gchar *curl_download_user_agent = NULL;
+
+/*
+ * Even if writing to FILE* is supported by libcurl by default,
+ * it seems that it is non-portable (win32 DLL specific).
+ *
+ * So, we provide our own trivial CURLOPT_WRITEFUNCTION.
+ */
+static size_t curl_write_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
+{
+ return fwrite(ptr, size, nmemb, stream);
+}
+
+static size_t curl_get_etag_func(char *ptr, size_t size, size_t nmemb, void *stream)
+{
+#define ETAG_KEYWORD "ETag: "
+#define ETAG_LEN (sizeof(ETAG_KEYWORD)-1)
+ gchar **etag = stream;
+ size_t len = size*nmemb;
+ char *str = g_strstr_len((const char*)ptr, len, ETAG_KEYWORD);
+ if (str) {
+ char *etag_str = str + ETAG_LEN;
+ char *end_str = g_strstr_len(etag_str, len - ETAG_LEN, "\r\n");
+ if (etag_str && end_str) {
+ *etag = g_strndup(etag_str, end_str - etag_str);
+ g_debug("%s: ETAG found: %s", __FUNCTION__, *etag);
+ }
+ }
+ return nmemb;
+}
+
+static int curl_progress_func(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
+{
+ return a_background_testcancel(NULL);
+}
+
+static gchar *get_cookie_file(gboolean init)
+{
+ static gchar *cookie_file = NULL;
+
+ // Wipe any previous cookies set on startup (for some reason??)
+ // Startup is single threaded so don't care about mutexes
+ if (init) {
+ static gchar *cookie_fn = "cookies.txt";
+ const gchar *viking_dir = a_get_viking_dir();
+ cookie_file = g_build_filename(viking_dir, cookie_fn, NULL);
+ g_unlink(cookie_file);
+ return NULL;
+ }
+
+ return(cookie_file);
+}
+
+/* This should to be called from main() to make sure thread safe */
+void curl_download_init()
+{
+ curl_global_init(CURL_GLOBAL_ALL);
+ get_cookie_file(TRUE);
+ curl_download_user_agent = g_strdup_printf ("%s/%s %s", PACKAGE, VERSION, curl_version());
+}
+
+/* This should to be called from main() to make sure thread safe */
+void curl_download_uninit()
+{
+ curl_global_cleanup();
+}
+
+int curl_download_uri ( const char *uri, FILE *f, DownloadMapOptions *options, DownloadFileOptions *file_options, void *handle )