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"
54 static gboolean check_file_first_line(FILE* f, gchar *patterns[])
62 memset(buf, 0, sizeof(buf));
65 nr = fread(buf, 1, sizeof(buf) - 1, f);
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);
139 file_list_mutex = g_mutex_new();
142 static gboolean lock_file(const char *fn)
144 gboolean locked = FALSE;
145 g_mutex_lock(file_list_mutex);
146 if (g_list_find_custom(file_list, fn, (GCompareFunc)g_strcmp0) == NULL)
148 // The filename is not yet locked
149 file_list = g_list_append(file_list, (gpointer)fn),
152 g_mutex_unlock(file_list_mutex);
156 static void unlock_file(const char *fn)
158 g_mutex_lock(file_list_mutex);
159 file_list = g_list_remove(file_list, (gconstpointer)fn);
160 g_mutex_unlock(file_list_mutex);
164 static void uncompress_zip ( gchar *name )
166 GError *error = NULL;
169 if ((mf = g_mapped_file_new ( name, FALSE, &error )) == NULL) {
170 g_critical(_("Couldn't map file %s: %s"), name, error->message);
174 gchar *file_contents = g_mapped_file_get_contents ( mf );
176 void *unzip_mem = NULL;
179 if ((unzip_mem = unzip_file (file_contents, &ucsize)) == NULL) {
180 g_mapped_file_unref ( mf );
184 // This overwrires any previous file contents
185 if ( ! g_file_set_contents ( name, unzip_mem, ucsize, &error ) ) {
186 g_critical ( "Couldn't write file '%s', because of %s", name, error->message );
187 g_error_free ( error );
192 * a_try_decompress_file:
193 * @name: The potentially compressed filename
195 * Perform magic to decide how which type of decompression to attempt
197 void a_try_decompress_file (gchar *name)
200 magic_t myt = magic_open ( MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME );
201 gboolean zip = FALSE;
202 gboolean bzip2 = FALSE;
205 // We have to 'package' the magic database ourselves :(
206 // --> %PROGRAM FILES%\Viking\magic.mgc
207 magic_load ( myt, "magic.mgc" );
209 // Use system default
210 magic_load ( myt, NULL );
212 const char* magic = magic_file (myt, name);
213 g_debug ("%s: magic output: %s", __FUNCTION__, magic );
215 if ( g_strcmp0 (magic, "application/zip; charset=binary") == 0 )
218 if ( g_strcmp0 (magic, "application/x-bzip2; charset=binary") == 0 )
224 if ( !(zip || bzip2) )
228 uncompress_zip ( name );
231 gchar* bz2_name = uncompress_bzip2 ( name );
233 g_rename ( bz2_name, name );
240 static DownloadResult_t download( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *options, gboolean ftp, void *handle)
245 gboolean failure = FALSE;
246 DownloadFileOptions file_options = {0, NULL, NULL};
249 if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
251 if (options == NULL || (!options->check_file_server_time &&
252 !options->use_etag)) {
253 /* Nothing to do as file already exists and we don't want to check server */
254 return DOWNLOAD_NOT_REQUIRED;
257 time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
258 /* Get the modified time of this file */
261 time_t file_time = buf.st_mtime;
262 if ( (time(NULL) - file_time) < tile_age ) {
263 /* File cache is too recent, so return */
264 return DOWNLOAD_NOT_REQUIRED;
267 if (options->check_file_server_time) {
268 file_options.time_condition = file_time;
270 if (options->use_etag) {
271 gchar *etag_filename = g_strdup_printf("%s.etag", fn);
272 gsize etag_length = 0;
273 g_file_get_contents (etag_filename, &(file_options.etag), &etag_length, NULL);
274 g_free (etag_filename);
275 etag_filename = NULL;
277 /* check if etag is short enough */
278 if (etag_length > 100) {
279 g_free(file_options.etag);
280 file_options.etag = NULL;
283 /* TODO: should check that etag is a valid string */
287 gchar *dir = g_path_get_dirname ( fn );
288 g_mkdir_with_parents ( dir , 0777 );
292 tmpfilename = g_strdup_printf("%s.tmp", fn);
293 if (!lock_file ( tmpfilename ) )
295 g_debug("%s: Couldn't take lock on temporary file \"%s\"\n", __FUNCTION__, tmpfilename);
296 g_free ( tmpfilename );
297 if (options->use_etag)
298 g_free ( file_options.etag );
299 return DOWNLOAD_FILE_WRITE_ERROR;
301 f = g_fopen ( tmpfilename, "w+b" ); /* truncate file and open it */
303 g_warning("Couldn't open temporary file \"%s\": %s", tmpfilename, g_strerror(errno));
304 g_free ( tmpfilename );
305 if (options->use_etag)
306 g_free ( file_options.etag );
307 return DOWNLOAD_FILE_WRITE_ERROR;
310 /* Call the backend function */
311 ret = curl_download_get_url ( hostname, uri, f, options, ftp, &file_options, handle );
313 DownloadResult_t result = DOWNLOAD_SUCCESS;
315 if (ret != CURL_DOWNLOAD_NO_ERROR && ret != CURL_DOWNLOAD_NO_NEWER_FILE) {
316 g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
318 result = DOWNLOAD_HTTP_ERROR;
321 if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
322 g_debug("%s: file content checking failed", __FUNCTION__);
324 result = DOWNLOAD_CONTENT_ERROR;
332 g_warning(_("Download error: %s"), fn);
333 g_remove ( tmpfilename );
334 unlock_file ( tmpfilename );
335 g_free ( tmpfilename );
336 if (options->use_etag) {
337 g_free ( file_options.etag );
338 g_free ( file_options.new_etag );
343 if ( options->convert_file )
344 options->convert_file ( tmpfilename );
346 if (options->use_etag) {
347 if (file_options.new_etag) {
348 /* server returned an etag value */
349 gchar *etag_filename = g_strdup_printf("%s.etag", fn);
350 g_file_set_contents (etag_filename, file_options.new_etag, -1, NULL);
351 g_free (etag_filename);
352 etag_filename = NULL;
356 if (ret == CURL_DOWNLOAD_NO_NEWER_FILE) {
357 g_remove ( tmpfilename );
358 #if GLIB_CHECK_VERSION(2,18,0)
359 g_utime ( fn, NULL ); /* update mtime of local copy */
361 utimes ( fn, NULL ); /* update mtime of local copy */
364 /* move completely-downloaded file to permanent location */
365 if ( g_rename ( tmpfilename, fn ) )
366 g_warning ("%s: file rename failed [%s] to [%s]", __FUNCTION__, tmpfilename, fn );
368 unlock_file ( tmpfilename );
369 g_free ( tmpfilename );
371 if (options->use_etag) {
372 g_free ( file_options.etag );
373 g_free ( file_options.new_etag );
375 return DOWNLOAD_SUCCESS;
379 * uri: like "/uri.html?whatever"
380 * only reason for the "wrapper" is so we can do redirects.
382 DownloadResult_t a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
384 return download ( hostname, uri, fn, opt, FALSE, handle );
387 DownloadResult_t a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
389 return download ( hostname, uri, fn, opt, TRUE, handle );
392 void * a_download_handle_init ()
394 return curl_download_handle_init ();
397 void a_download_handle_cleanup ( void *handle )
399 curl_download_handle_cleanup ( handle );
403 * a_download_url_to_tmp_file:
404 * @uri: The URI (Uniform Resource Identifier)
405 * @options: Download options (maybe NULL)
407 * returns name of the temporary file created - NULL if unsuccessful
408 * this string needs to be freed once used
409 * the file needs to be removed once used
411 gchar *a_download_uri_to_tmp_file ( const gchar *uri, DownloadMapOptions *options )
417 if ( (tmp_fd = g_file_open_tmp ("viking-download.XXXXXX", &tmpname, NULL)) == -1 ) {
418 g_critical (_("couldn't open temp file"));
422 tmp_file = fdopen(tmp_fd, "r+");
424 if ( curl_download_uri ( uri, tmp_file, options, NULL, NULL ) ) {
427 g_remove ( tmpname );