1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
3 * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
5 * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
6 * Copyright (C) 2007, Guilhem Bonnefille <guilhem.bonnefille@gmail.com>
7 * Copyright (C) 2013, Rob Norris <rw_norris@hotmail.com>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 #ifdef HAVE_SYS_TYPES_H
34 #include <sys/types.h>
40 #include <glib/gstdio.h>
41 #include <glib/gi18n.h>
46 #include "compression.h"
50 #include "curl_download.h"
51 #include "preferences.h"
53 #include "vik_compat.h"
55 static gboolean check_file_first_line(FILE* f, gchar *patterns[])
63 memset(buf, 0, sizeof(buf));
66 nr = fread(buf, 1, sizeof(buf) - 1, f);
68 for (bp = buf; (bp < (buf + sizeof(buf) - 1)) && (nr > (bp - buf)); bp++) {
72 if ((bp >= (buf + sizeof(buf) -1)) || ((bp - buf) >= nr))
74 for (s = patterns; *s; s++) {
75 if (strncasecmp(*s, bp, strlen(*s)) == 0)
81 gboolean a_check_html_file(FILE* f)
83 gchar * html_str[] = {
91 return check_file_first_line(f, html_str);
94 gboolean a_check_map_file(FILE* f)
96 /* FIXME no more true since a_check_kml_file */
97 return !a_check_html_file(f);
100 gboolean a_check_kml_file(FILE* f)
102 gchar * kml_str[] = {
107 return check_file_first_line(f, kml_str);
110 static GList *file_list = NULL;
111 static GMutex *file_list_mutex = NULL;
113 /* spin button scales */
114 static VikLayerParamScale params_scales[] = {
115 {1, 365, 1, 0}, /* download_tile_age */
118 static VikLayerParamData convert_to_display ( VikLayerParamData value )
120 // From seconds into days
121 return VIK_LPD_UINT ( value.u / 86400 );
124 static VikLayerParamData convert_to_internal ( VikLayerParamData value )
126 // From days into seconds
127 return VIK_LPD_UINT ( 86400 * value.u );
130 static VikLayerParam prefs[] = {
131 { VIK_LAYER_NUM_TYPES, VIKING_PREFERENCES_NAMESPACE "download_tile_age", VIK_LAYER_PARAM_UINT, VIK_LAYER_GROUP_NONE, N_("Tile age (days):"), VIK_LAYER_WIDGET_SPINBUTTON, ¶ms_scales[0], NULL, NULL, NULL, convert_to_display, convert_to_internal },
134 void a_download_init (void)
136 VikLayerParamData tmp;
137 tmp.u = VIK_CONFIG_DEFAULT_TILE_AGE / 86400; // Now in days
138 a_preferences_register(prefs, tmp, VIKING_PREFERENCES_GROUP_KEY);
139 file_list_mutex = vik_mutex_new();
143 static gboolean lock_file(const char *fn)
145 gboolean locked = FALSE;
146 g_mutex_lock(file_list_mutex);
147 if (g_list_find_custom(file_list, fn, (GCompareFunc)g_strcmp0) == NULL)
149 // The filename is not yet locked
150 file_list = g_list_append(file_list, (gpointer)fn),
153 g_mutex_unlock(file_list_mutex);
157 static void unlock_file(const char *fn)
159 g_mutex_lock(file_list_mutex);
160 file_list = g_list_remove(file_list, (gconstpointer)fn);
161 g_mutex_unlock(file_list_mutex);
165 static void uncompress_zip ( gchar *name )
167 GError *error = NULL;
170 if ((mf = g_mapped_file_new ( name, FALSE, &error )) == NULL) {
171 g_critical(_("Couldn't map file %s: %s"), name, error->message);
175 gchar *file_contents = g_mapped_file_get_contents ( mf );
177 void *unzip_mem = NULL;
180 if ((unzip_mem = unzip_file (file_contents, &ucsize)) == NULL) {
181 g_mapped_file_unref ( mf );
185 // This overwrires any previous file contents
186 if ( ! g_file_set_contents ( name, unzip_mem, ucsize, &error ) ) {
187 g_critical ( "Couldn't write file '%s', because of %s", name, error->message );
188 g_error_free ( error );
193 * a_try_decompress_file:
194 * @name: The potentially compressed filename
196 * Perform magic to decide how which type of decompression to attempt
198 void a_try_decompress_file (gchar *name)
201 magic_t myt = magic_open ( MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME );
202 gboolean zip = FALSE;
203 gboolean bzip2 = FALSE;
206 // We have to 'package' the magic database ourselves :(
207 // --> %PROGRAM FILES%\Viking\magic.mgc
208 magic_load ( myt, "magic.mgc" );
210 // Use system default
211 magic_load ( myt, NULL );
213 const char* magic = magic_file (myt, name);
214 g_debug ("%s: magic output: %s", __FUNCTION__, magic );
216 if ( g_strcmp0 (magic, "application/zip; charset=binary") == 0 )
219 if ( g_strcmp0 (magic, "application/x-bzip2; charset=binary") == 0 )
225 if ( !(zip || bzip2) )
229 uncompress_zip ( name );
232 gchar* bz2_name = uncompress_bzip2 ( name );
234 g_rename ( bz2_name, name );
241 static DownloadResult_t download( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *options, gboolean ftp, void *handle)
246 gboolean failure = FALSE;
247 DownloadFileOptions file_options = {0, NULL, NULL};
250 if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
252 if (options == NULL || (!options->check_file_server_time &&
253 !options->use_etag)) {
254 /* Nothing to do as file already exists and we don't want to check server */
255 return DOWNLOAD_NOT_REQUIRED;
258 time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
259 /* Get the modified time of this file */
262 time_t file_time = buf.st_mtime;
263 if ( (time(NULL) - file_time) < tile_age ) {
264 /* File cache is too recent, so return */
265 return DOWNLOAD_NOT_REQUIRED;
268 if (options->check_file_server_time) {
269 file_options.time_condition = file_time;
271 if (options->use_etag) {
272 gchar *etag_filename = g_strdup_printf("%s.etag", fn);
273 gsize etag_length = 0;
274 g_file_get_contents (etag_filename, &(file_options.etag), &etag_length, NULL);
275 g_free (etag_filename);
276 etag_filename = NULL;
278 /* check if etag is short enough */
279 if (etag_length > 100) {
280 g_free(file_options.etag);
281 file_options.etag = NULL;
284 /* TODO: should check that etag is a valid string */
288 gchar *dir = g_path_get_dirname ( fn );
289 g_mkdir_with_parents ( dir , 0777 );
293 tmpfilename = g_strdup_printf("%s.tmp", fn);
294 if (!lock_file ( tmpfilename ) )
296 g_debug("%s: Couldn't take lock on temporary file \"%s\"\n", __FUNCTION__, tmpfilename);
297 g_free ( tmpfilename );
298 if (options->use_etag)
299 g_free ( file_options.etag );
300 return DOWNLOAD_FILE_WRITE_ERROR;
302 f = g_fopen ( tmpfilename, "w+b" ); /* truncate file and open it */
304 g_warning("Couldn't open temporary file \"%s\": %s", tmpfilename, g_strerror(errno));
305 g_free ( tmpfilename );
306 if (options->use_etag)
307 g_free ( file_options.etag );
308 return DOWNLOAD_FILE_WRITE_ERROR;
311 /* Call the backend function */
312 ret = curl_download_get_url ( hostname, uri, f, options, ftp, &file_options, handle );
314 DownloadResult_t result = DOWNLOAD_SUCCESS;
316 if (ret != CURL_DOWNLOAD_NO_ERROR && ret != CURL_DOWNLOAD_NO_NEWER_FILE) {
317 g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
319 result = DOWNLOAD_HTTP_ERROR;
322 if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
323 g_debug("%s: file content checking failed", __FUNCTION__);
325 result = DOWNLOAD_CONTENT_ERROR;
333 g_warning(_("Download error: %s"), fn);
334 g_remove ( tmpfilename );
335 unlock_file ( tmpfilename );
336 g_free ( tmpfilename );
337 if (options->use_etag) {
338 g_free ( file_options.etag );
339 g_free ( file_options.new_etag );
344 if ( options->convert_file )
345 options->convert_file ( tmpfilename );
347 if (options->use_etag) {
348 if (file_options.new_etag) {
349 /* server returned an etag value */
350 gchar *etag_filename = g_strdup_printf("%s.etag", fn);
351 g_file_set_contents (etag_filename, file_options.new_etag, -1, NULL);
352 g_free (etag_filename);
353 etag_filename = NULL;
357 if (ret == CURL_DOWNLOAD_NO_NEWER_FILE) {
358 g_remove ( tmpfilename );
359 #if GLIB_CHECK_VERSION(2,18,0)
360 g_utime ( fn, NULL ); /* update mtime of local copy */
362 utimes ( fn, NULL ); /* update mtime of local copy */
365 /* move completely-downloaded file to permanent location */
366 if ( g_rename ( tmpfilename, fn ) )
367 g_warning ("%s: file rename failed [%s] to [%s]", __FUNCTION__, tmpfilename, fn );
369 unlock_file ( tmpfilename );
370 g_free ( tmpfilename );
372 if (options->use_etag) {
373 g_free ( file_options.etag );
374 g_free ( file_options.new_etag );
376 return DOWNLOAD_SUCCESS;
380 * uri: like "/uri.html?whatever"
381 * only reason for the "wrapper" is so we can do redirects.
383 DownloadResult_t a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
385 return download ( hostname, uri, fn, opt, FALSE, handle );
388 DownloadResult_t a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
390 return download ( hostname, uri, fn, opt, TRUE, handle );
393 void * a_download_handle_init ()
395 return curl_download_handle_init ();
398 void a_download_handle_cleanup ( void *handle )
400 curl_download_handle_cleanup ( handle );
404 * a_download_url_to_tmp_file:
405 * @uri: The URI (Uniform Resource Identifier)
406 * @options: Download options (maybe NULL)
408 * returns name of the temporary file created - NULL if unsuccessful
409 * this string needs to be freed once used
410 * the file needs to be removed once used
412 gchar *a_download_uri_to_tmp_file ( const gchar *uri, DownloadMapOptions *options )
418 if ( (tmp_fd = g_file_open_tmp ("viking-download.XXXXXX", &tmpname, NULL)) == -1 ) {
419 g_critical (_("couldn't open temp file"));
423 tmp_file = fdopen(tmp_fd, "r+");
425 if ( curl_download_uri ( uri, tmp_file, options, NULL, NULL ) ) {
428 g_remove ( tmpname );