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>
43 #include "file_magic.h"
44 #include "compression.h"
47 #include "curl_download.h"
48 #include "preferences.h"
50 #include "vik_compat.h"
52 static gboolean check_file_first_line(FILE* f, gchar *patterns[])
60 memset(buf, 0, sizeof(buf));
61 if ( !fgetpos(f, &pos) )
64 nr = fread(buf, 1, sizeof(buf) - 1, f);
65 if ( !fgetpos(f, &pos) )
67 for (bp = buf; (bp < (buf + sizeof(buf) - 1)) && (nr > (bp - buf)); bp++) {
71 if ((bp >= (buf + sizeof(buf) -1)) || ((bp - buf) >= nr))
73 for (s = patterns; *s; s++) {
74 if (strncasecmp(*s, bp, strlen(*s)) == 0)
80 gboolean a_check_html_file(FILE* f)
82 gchar * html_str[] = {
90 return check_file_first_line(f, html_str);
93 gboolean a_check_map_file(FILE* f)
95 /* FIXME no more true since a_check_kml_file */
96 return !a_check_html_file(f);
99 gboolean a_check_kml_file(FILE* f)
101 gchar * kml_str[] = {
106 return check_file_first_line(f, kml_str);
109 static GList *file_list = NULL;
110 static GMutex *file_list_mutex = NULL;
112 /* spin button scales */
113 static VikLayerParamScale params_scales[] = {
114 {1, 365, 1, 0}, /* download_tile_age */
117 static VikLayerParamData convert_to_display ( VikLayerParamData value )
119 // From seconds into days
120 return VIK_LPD_UINT ( value.u / 86400 );
123 static VikLayerParamData convert_to_internal ( VikLayerParamData value )
125 // From days into seconds
126 return VIK_LPD_UINT ( 86400 * value.u );
129 static VikLayerParam prefs[] = {
130 { 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 },
133 void a_download_init (void)
135 VikLayerParamData tmp;
136 tmp.u = VIK_CONFIG_DEFAULT_TILE_AGE / 86400; // Now in days
137 a_preferences_register(prefs, tmp, VIKING_PREFERENCES_GROUP_KEY);
138 file_list_mutex = vik_mutex_new();
141 void a_download_uninit (void)
143 vik_mutex_free(file_list_mutex);
146 static gboolean lock_file(const char *fn)
148 gboolean locked = FALSE;
149 g_mutex_lock(file_list_mutex);
150 if (g_list_find_custom(file_list, fn, (GCompareFunc)g_strcmp0) == NULL)
152 // The filename is not yet locked
153 file_list = g_list_append(file_list, (gpointer)fn),
156 g_mutex_unlock(file_list_mutex);
160 static void unlock_file(const char *fn)
162 g_mutex_lock(file_list_mutex);
163 file_list = g_list_remove(file_list, (gconstpointer)fn);
164 g_mutex_unlock(file_list_mutex);
168 * Unzip a file - replacing the file with the unzipped contents of the self
170 static void uncompress_zip ( gchar *name )
172 GError *error = NULL;
175 if ((mf = g_mapped_file_new ( name, FALSE, &error )) == NULL) {
176 g_critical(_("Couldn't map file %s: %s"), name, error->message);
180 gchar *file_contents = g_mapped_file_get_contents ( mf );
182 void *unzip_mem = NULL;
185 if ((unzip_mem = unzip_file (file_contents, &ucsize)) == NULL) {
186 g_mapped_file_unref ( mf );
190 // This overwrites any previous file contents
191 if ( ! g_file_set_contents ( name, unzip_mem, ucsize, &error ) ) {
192 g_critical ( "Couldn't write file '%s', because of %s", name, error->message );
193 g_error_free ( error );
198 * a_try_decompress_file:
199 * @name: The potentially compressed filename
201 * Perform magic to decide how which type of decompression to attempt
203 void a_try_decompress_file (gchar *name)
205 if ( file_magic_check (name, "application/zip", ".zip") ) {
206 uncompress_zip ( name );
208 else if ( file_magic_check (name, "application/x-bzip2", ".bz2") ) {
209 gchar* bz2_name = uncompress_bzip2 ( name );
211 if ( g_remove ( name ) )
212 g_critical ("%s: remove file failed [%s]", __FUNCTION__, name );
213 if ( g_rename (bz2_name, name) )
214 g_critical ("%s: file rename failed [%s] to [%s]", __FUNCTION__, bz2_name, name );
220 #define VIKING_ETAG_XATTR "xattr::viking.etag"
222 static gboolean get_etag_xattr(const char *fn, CurlDownloadOptions *cdo)
224 gboolean result = FALSE;
228 file = g_file_new_for_path(fn);
229 fileinfo = g_file_query_info(file, VIKING_ETAG_XATTR, G_FILE_QUERY_INFO_NONE, NULL, NULL);
231 const char *etag = g_file_info_get_attribute_string(fileinfo, VIKING_ETAG_XATTR);
233 cdo->etag = g_strdup(etag);
234 result = !!cdo->etag;
236 g_object_unref(fileinfo);
238 g_object_unref(file);
241 g_debug("%s: Get etag (xattr) from %s: %s", __FUNCTION__, fn, cdo->etag);
246 static gboolean get_etag_file(const char *fn, CurlDownloadOptions *cdo)
248 gboolean result = FALSE;
249 gchar *etag_filename;
251 etag_filename = g_strdup_printf("%s.etag", fn);
253 result = g_file_get_contents(etag_filename, &cdo->etag, NULL, NULL);
254 g_free(etag_filename);
258 g_debug("%s: Get etag (file) from %s: %s", __FUNCTION__, fn, cdo->etag);
263 static void get_etag(const char *fn, CurlDownloadOptions *cdo)
265 /* first try to get etag from xattr, then fall back to plain file */
266 if (!get_etag_xattr(fn, cdo) && !get_etag_file(fn, cdo)) {
267 g_debug("%s: Failed to get etag from %s", __FUNCTION__, fn);
271 /* check if etag is short enough */
272 if (strlen(cdo->etag) > 100) {
277 /* TODO: should check that etag is a valid string */
280 static gboolean set_etag_xattr(const char *fn, CurlDownloadOptions *cdo)
282 gboolean result = FALSE;
285 file = g_file_new_for_path(fn);
286 result = g_file_set_attribute_string(file, VIKING_ETAG_XATTR, cdo->new_etag, G_FILE_QUERY_INFO_NONE, NULL, NULL);
287 g_object_unref(file);
290 g_debug("%s: Set etag (xattr) on %s: %s", __FUNCTION__, fn, cdo->new_etag);
295 static gboolean set_etag_file(const char *fn, CurlDownloadOptions *cdo)
297 gboolean result = FALSE;
298 gchar *etag_filename;
300 etag_filename = g_strdup_printf("%s.etag", fn);
302 result = g_file_set_contents(etag_filename, cdo->new_etag, -1, NULL);
303 g_free(etag_filename);
307 g_debug("%s: Set etag (file) on %s: %s", __FUNCTION__, fn, cdo->new_etag);
312 static void set_etag(const char *fn, const char *fntmp, CurlDownloadOptions *cdo)
314 /* first try to store etag in extended attribute, then fall back to plain file */
315 if (!set_etag_xattr(fntmp, cdo) && !set_etag_file(fn, cdo)) {
316 g_debug("%s: Failed to set etag on %s", __FUNCTION__, fn);
320 static DownloadResult_t download( const char *hostname, const char *uri, const char *fn, DownloadFileOptions *options, gboolean ftp, void *handle)
324 gboolean failure = FALSE;
325 CurlDownloadOptions cdo = {0, NULL, NULL};
328 if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
330 if (options == NULL || (!options->check_file_server_time &&
331 !options->use_etag)) {
332 /* Nothing to do as file already exists and we don't want to check server */
333 return DOWNLOAD_NOT_REQUIRED;
336 time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
337 /* Get the modified time of this file */
339 (void)g_stat ( fn, &buf );
340 time_t file_time = buf.st_mtime;
341 if ( (time(NULL) - file_time) < tile_age ) {
342 /* File cache is too recent, so return */
343 return DOWNLOAD_NOT_REQUIRED;
346 if (options != NULL && options->check_file_server_time) {
347 cdo.time_condition = file_time;
349 if (options != NULL && options->use_etag) {
354 gchar *dir = g_path_get_dirname ( fn );
355 if ( g_mkdir_with_parents ( dir , 0777 ) != 0)
356 g_warning ("%s: Failed to mkdir %s", __FUNCTION__, dir );
360 // Early test for valid hostname & uri to avoid unnecessary tmp file
361 if ( !hostname && !uri ) {
362 g_warning ( "%s: Parameter error - neither hostname nor uri defined", __FUNCTION__ );
363 return DOWNLOAD_PARAMETERS_ERROR;
366 tmpfilename = g_strdup_printf("%s.tmp", fn);
367 if (!lock_file ( tmpfilename ) )
369 g_debug("%s: Couldn't take lock on temporary file \"%s\"\n", __FUNCTION__, tmpfilename);
370 g_free ( tmpfilename );
371 if (options->use_etag)
373 return DOWNLOAD_FILE_WRITE_ERROR;
375 f = g_fopen ( tmpfilename, "w+b" ); /* truncate file and open it */
377 g_warning("Couldn't open temporary file \"%s\": %s", tmpfilename, g_strerror(errno));
378 g_free ( tmpfilename );
379 if (options->use_etag)
381 return DOWNLOAD_FILE_WRITE_ERROR;
384 /* Call the backend function */
385 CURL_download_t ret = curl_download_get_url ( hostname, uri, f, options, ftp, &cdo, handle );
387 DownloadResult_t result = DOWNLOAD_SUCCESS;
389 if (ret != CURL_DOWNLOAD_NO_ERROR && ret != CURL_DOWNLOAD_NO_NEWER_FILE) {
390 g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
392 result = DOWNLOAD_HTTP_ERROR;
395 if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
396 g_debug("%s: file content checking failed", __FUNCTION__);
398 result = DOWNLOAD_CONTENT_ERROR;
406 g_warning(_("Download error: %s"), fn);
407 if ( g_remove ( tmpfilename ) != 0 )
408 g_warning( ("Failed to remove: %s"), tmpfilename);
409 unlock_file ( tmpfilename );
410 g_free ( tmpfilename );
411 if ( options != NULL && options->use_etag ) {
413 g_free ( cdo.new_etag );
418 if (ret == CURL_DOWNLOAD_NO_NEWER_FILE) {
419 (void)g_remove ( tmpfilename );
420 // update mtime of local copy
421 // Not security critical, thus potential Time of Check Time of Use race condition is not bad
423 if ( g_utime ( fn, NULL ) != 0 )
424 g_warning ( "%s couldn't set time on: %s", __FUNCTION__, fn );
426 if ( options != NULL && options->convert_file )
427 options->convert_file ( tmpfilename );
429 if ( options != NULL && options->use_etag ) {
430 if ( cdo.new_etag ) {
431 /* server returned an etag value */
432 set_etag(fn, tmpfilename, &cdo);
436 /* move completely-downloaded file to permanent location */
437 if ( g_rename ( tmpfilename, fn ) )
438 g_warning ("%s: file rename failed [%s] to [%s]", __FUNCTION__, tmpfilename, fn );
440 unlock_file ( tmpfilename );
441 g_free ( tmpfilename );
443 if ( options != NULL && options->use_etag ) {
445 g_free ( cdo.new_etag );
447 return DOWNLOAD_SUCCESS;
451 * uri: like "/uri.html?whatever"
452 * only reason for the "wrapper" is so we can do redirects.
454 DownloadResult_t a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadFileOptions *opt, void *handle )
456 return download ( hostname, uri, fn, opt, FALSE, handle );
459 DownloadResult_t a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadFileOptions *opt, void *handle )
461 return download ( hostname, uri, fn, opt, TRUE, handle );
464 void * a_download_handle_init ()
466 return curl_download_handle_init ();
469 void a_download_handle_cleanup ( void *handle )
471 curl_download_handle_cleanup ( handle );
475 * a_download_url_to_tmp_file:
476 * @uri: The URI (Uniform Resource Identifier)
477 * @options: Download options (maybe NULL)
479 * returns name of the temporary file created - NULL if unsuccessful
480 * this string needs to be freed once used
481 * the file needs to be removed once used
483 gchar *a_download_uri_to_tmp_file ( const gchar *uri, DownloadFileOptions *options )
489 if ( (tmp_fd = g_file_open_tmp ("viking-download.XXXXXX", &tmpname, NULL)) == -1 ) {
490 g_critical (_("couldn't open temp file"));
494 tmp_file = fdopen(tmp_fd, "r+");
498 if ( curl_download_uri ( uri, tmp_file, options, NULL, NULL ) ) {
501 (void)g_remove ( tmpname );