]> git.street.me.uk Git - andy/viking.git/blame - src/download.c
SF BugsZZ#123: Fix bzip2 decompression on Windows.
[andy/viking.git] / src / download.c
CommitLineData
a3697549 1/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
85611cd9
GB
2/*
3 * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
4 *
5 * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
a482007a 6 * Copyright (C) 2007, Guilhem Bonnefille <guilhem.bonnefille@gmail.com>
a3697549 7 * Copyright (C) 2013, Rob Norris <rw_norris@hotmail.com>
85611cd9
GB
8 *
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.
13 *
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.
18 *
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
22 *
23 */
24
3292ba8b
GB
25#ifdef HAVE_CONFIG_H
26#include "config.h"
27#endif
28
932f8f22 29#include <stdio.h>
6e78a423 30#include <ctype.h>
6a4a29aa 31#include <errno.h>
6e78a423 32#include <string.h>
7de36baf 33#ifdef HAVE_SYS_TYPES_H
6a4a29aa 34#include <sys/types.h>
7de36baf
GB
35#endif
36#ifdef HAVE_UTIME_H
6a4a29aa 37#include <utime.h>
7de36baf 38#endif
f83131b9
MA
39#include <glib.h>
40#include <glib/gstdio.h>
4c77d5e0 41#include <glib/gi18n.h>
932f8f22 42
a3697549
RN
43#ifdef HAVE_MAGIC_H
44#include <magic.h>
45#endif
46#include "compression.h"
6a4a29aa 47
85611cd9 48#include "download.h"
3292ba8b 49
3292ba8b 50#include "curl_download.h"
6693f5f9
GB
51#include "preferences.h"
52#include "globals.h"
fc6640a9 53#include "vik_compat.h"
85611cd9 54
388cf5a4 55static gboolean check_file_first_line(FILE* f, gchar *patterns[])
6e78a423 56{
533bbf34
MA
57 gchar **s;
58 gchar *bp;
6e78a423 59 fpos_t pos;
533bbf34 60 gchar buf[33];
6e78a423 61 size_t nr;
6e78a423 62
c44594ee 63 memset(buf, 0, sizeof(buf));
6e78a423
QT
64 fgetpos(f, &pos);
65 rewind(f);
66 nr = fread(buf, 1, sizeof(buf) - 1, f);
67 fsetpos(f, &pos);
68 for (bp = buf; (bp < (buf + sizeof(buf) - 1)) && (nr > (bp - buf)); bp++) {
69 if (!(isspace(*bp)))
70 break;
71 }
72 if ((bp >= (buf + sizeof(buf) -1)) || ((bp - buf) >= nr))
1ac37c09 73 return FALSE;
388cf5a4 74 for (s = patterns; *s; s++) {
1918a993 75 if (strncasecmp(*s, bp, strlen(*s)) == 0)
1ac37c09 76 return TRUE;
6e78a423 77 }
1ac37c09
GB
78 return FALSE;
79}
80
388cf5a4
GB
81gboolean a_check_html_file(FILE* f)
82{
83 gchar * html_str[] = {
84 "<html",
85 "<!DOCTYPE html",
86 "<head",
87 "<title",
88 NULL
89 };
90
91 return check_file_first_line(f, html_str);
92}
93
1ac37c09
GB
94gboolean a_check_map_file(FILE* f)
95{
388cf5a4 96 /* FIXME no more true since a_check_kml_file */
1ac37c09 97 return !a_check_html_file(f);
6e78a423
QT
98}
99
ae941b4c
HMJ
100gboolean a_check_kml_file(FILE* f)
101{
388cf5a4 102 gchar * kml_str[] = {
ae941b4c
HMJ
103 "<?xml",
104 NULL
105 };
106
388cf5a4 107 return check_file_first_line(f, kml_str);
ae941b4c
HMJ
108}
109
4b992365
GB
110static GList *file_list = NULL;
111static GMutex *file_list_mutex = NULL;
112
6693f5f9 113/* spin button scales */
32dfea86
RN
114static VikLayerParamScale params_scales[] = {
115 {1, 365, 1, 0}, /* download_tile_age */
6693f5f9
GB
116};
117
32dfea86
RN
118static VikLayerParamData convert_to_display ( VikLayerParamData value )
119{
120 // From seconds into days
121 return VIK_LPD_UINT ( value.u / 86400 );
122}
123
124static VikLayerParamData convert_to_internal ( VikLayerParamData value )
125{
126 // From days into seconds
127 return VIK_LPD_UINT ( 86400 * value.u );
128}
129
6693f5f9 130static VikLayerParam prefs[] = {
32dfea86 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, &params_scales[0], NULL, NULL, NULL, convert_to_display, convert_to_internal },
6693f5f9
GB
132};
133
4b992365
GB
134void a_download_init (void)
135{
6693f5f9 136 VikLayerParamData tmp;
32dfea86 137 tmp.u = VIK_CONFIG_DEFAULT_TILE_AGE / 86400; // Now in days
6693f5f9 138 a_preferences_register(prefs, tmp, VIKING_PREFERENCES_GROUP_KEY);
fc6640a9 139 file_list_mutex = vik_mutex_new();
e3da2277 140}
6693f5f9 141
e3da2277
RN
142void a_download_uninit (void)
143{
144 vik_mutex_free(file_list_mutex);
4b992365
GB
145}
146
147static gboolean lock_file(const char *fn)
148{
149 gboolean locked = FALSE;
150 g_mutex_lock(file_list_mutex);
2894744e 151 if (g_list_find_custom(file_list, fn, (GCompareFunc)g_strcmp0) == NULL)
4b992365
GB
152 {
153 // The filename is not yet locked
154 file_list = g_list_append(file_list, (gpointer)fn),
155 locked = TRUE;
156 }
157 g_mutex_unlock(file_list_mutex);
158 return locked;
159}
160
161static void unlock_file(const char *fn)
162{
163 g_mutex_lock(file_list_mutex);
164 file_list = g_list_remove(file_list, (gconstpointer)fn);
165 g_mutex_unlock(file_list_mutex);
166}
167
feef2120
RN
168/**
169 * Unzip a file - replacing the file with the unzipped contents of the self
170 */
a3697549
RN
171static void uncompress_zip ( gchar *name )
172{
173 GError *error = NULL;
174 GMappedFile *mf;
175
176 if ((mf = g_mapped_file_new ( name, FALSE, &error )) == NULL) {
177 g_critical(_("Couldn't map file %s: %s"), name, error->message);
178 g_error_free(error);
179 return;
180 }
181 gchar *file_contents = g_mapped_file_get_contents ( mf );
182
183 void *unzip_mem = NULL;
184 gulong ucsize;
185
186 if ((unzip_mem = unzip_file (file_contents, &ucsize)) == NULL) {
187 g_mapped_file_unref ( mf );
188 return;
189 }
190
feef2120 191 // This overwrites any previous file contents
a3697549
RN
192 if ( ! g_file_set_contents ( name, unzip_mem, ucsize, &error ) ) {
193 g_critical ( "Couldn't write file '%s', because of %s", name, error->message );
194 g_error_free ( error );
195 }
196}
197
198/**
199 * a_try_decompress_file:
200 * @name: The potentially compressed filename
201 *
202 * Perform magic to decide how which type of decompression to attempt
203 */
204void a_try_decompress_file (gchar *name)
205{
206#ifdef HAVE_MAGIC_H
207 magic_t myt = magic_open ( MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME );
208 gboolean zip = FALSE;
209 gboolean bzip2 = FALSE;
210 if ( myt ) {
9702385a
RN
211#ifdef WINDOWS
212 // We have to 'package' the magic database ourselves :(
213 // --> %PROGRAM FILES%\Viking\magic.mgc
214 magic_load ( myt, "magic.mgc" );
215#else
216 // Use system default
a3697549 217 magic_load ( myt, NULL );
9702385a 218#endif
a3697549
RN
219 const char* magic = magic_file (myt, name);
220 g_debug ("%s: magic output: %s", __FUNCTION__, magic );
221
222 if ( g_strcmp0 (magic, "application/zip; charset=binary") == 0 )
223 zip = TRUE;
224
225 if ( g_strcmp0 (magic, "application/x-bzip2; charset=binary") == 0 )
226 bzip2 = TRUE;
227
228 magic_close ( myt );
229 }
230
231 if ( !(zip || bzip2) )
232 return;
233
234 if ( zip ) {
235 uncompress_zip ( name );
236 }
237 else if ( bzip2 ) {
238 gchar* bz2_name = uncompress_bzip2 ( name );
239 g_remove ( name );
240 g_rename ( bz2_name, name );
241 }
242
243 return;
244#endif
245}
246
4e815e90 247static DownloadResult_t download( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *options, gboolean ftp, void *handle)
932f8f22
GB
248{
249 FILE *f;
250 int ret;
533bbf34 251 gchar *tmpfilename;
1ac37c09 252 gboolean failure = FALSE;
ab716260 253 DownloadFileOptions file_options = {0, NULL, NULL};
932f8f22
GB
254
255 /* Check file */
45acf79e 256 if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
932f8f22 257 {
8853eed9
JJ
258 if (options == NULL || (!options->check_file_server_time &&
259 !options->use_etag)) {
260 /* Nothing to do as file already exists and we don't want to check server */
4e815e90 261 return DOWNLOAD_NOT_REQUIRED;
6a4a29aa 262 }
8853eed9 263
57ecf9cb
JJ
264 time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
265 /* Get the modified time of this file */
266 struct stat buf;
267 g_stat ( fn, &buf );
268 time_t file_time = buf.st_mtime;
269 if ( (time(NULL) - file_time) < tile_age ) {
270 /* File cache is too recent, so return */
4e815e90 271 return DOWNLOAD_NOT_REQUIRED;
57ecf9cb
JJ
272 }
273
8853eed9 274 if (options->check_file_server_time) {
57ecf9cb 275 file_options.time_condition = file_time;
6a4a29aa 276 }
55246377 277 if (options->use_etag) {
f91cc826 278 gchar *etag_filename = g_strdup_printf("%s.etag", fn);
9137c580 279 gsize etag_length = 0;
f91cc826 280 g_file_get_contents (etag_filename, &(file_options.etag), &etag_length, NULL);
9137c580
GB
281 g_free (etag_filename);
282 etag_filename = NULL;
f91cc826
JJ
283
284 /* check if etag is short enough */
9137c580 285 if (etag_length > 100) {
f91cc826 286 g_free(file_options.etag);
9137c580
GB
287 file_options.etag = NULL;
288 }
f91cc826
JJ
289
290 /* TODO: should check that etag is a valid string */
55246377 291 }
f91cc826 292
932f8f22 293 } else {
a1618d62
MA
294 gchar *dir = g_path_get_dirname ( fn );
295 g_mkdir_with_parents ( dir , 0777 );
296 g_free ( dir );
3335ae4e
EB
297 }
298
299 tmpfilename = g_strdup_printf("%s.tmp", fn);
4b992365
GB
300 if (!lock_file ( tmpfilename ) )
301 {
302 g_debug("%s: Couldn't take lock on temporary file \"%s\"\n", __FUNCTION__, tmpfilename);
303 g_free ( tmpfilename );
9137c580
GB
304 if (options->use_etag)
305 g_free ( file_options.etag );
4e815e90 306 return DOWNLOAD_FILE_WRITE_ERROR;
4b992365
GB
307 }
308 f = g_fopen ( tmpfilename, "w+b" ); /* truncate file and open it */
3335ae4e 309 if ( ! f ) {
4b992365 310 g_warning("Couldn't open temporary file \"%s\": %s", tmpfilename, g_strerror(errno));
3335ae4e 311 g_free ( tmpfilename );
9137c580
GB
312 if (options->use_etag)
313 g_free ( file_options.etag );
4e815e90 314 return DOWNLOAD_FILE_WRITE_ERROR;
932f8f22
GB
315 }
316
317 /* Call the backend function */
9a021e4f 318 ret = curl_download_get_url ( hostname, uri, f, options, ftp, &file_options, handle );
6a4a29aa 319
4e815e90
RN
320 DownloadResult_t result = DOWNLOAD_SUCCESS;
321
322 if (ret != CURL_DOWNLOAD_NO_ERROR && ret != CURL_DOWNLOAD_NO_NEWER_FILE) {
1ac37c09
GB
323 g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
324 failure = TRUE;
4e815e90 325 result = DOWNLOAD_HTTP_ERROR;
1ac37c09
GB
326 }
327
328 if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
329 g_debug("%s: file content checking failed", __FUNCTION__);
330 failure = TRUE;
4e815e90 331 result = DOWNLOAD_CONTENT_ERROR;
1ac37c09 332 }
932f8f22 333
1ec35593
MA
334 fclose ( f );
335 f = NULL;
336
1ac37c09 337 if (failure)
932f8f22 338 {
4258f4e2 339 g_warning(_("Download error: %s"), fn);
8c060406 340 g_remove ( tmpfilename );
4b992365 341 unlock_file ( tmpfilename );
3335ae4e 342 g_free ( tmpfilename );
55246377
JJ
343 if (options->use_etag) {
344 g_free ( file_options.etag );
345 g_free ( file_options.new_etag );
346 }
4e815e90 347 return result;
932f8f22
GB
348 }
349
a3697549
RN
350 if ( options->convert_file )
351 options->convert_file ( tmpfilename );
352
55246377
JJ
353 if (options->use_etag) {
354 if (file_options.new_etag) {
355 /* server returned an etag value */
f91cc826
JJ
356 gchar *etag_filename = g_strdup_printf("%s.etag", fn);
357 g_file_set_contents (etag_filename, file_options.new_etag, -1, NULL);
9137c580
GB
358 g_free (etag_filename);
359 etag_filename = NULL;
55246377
JJ
360 }
361 }
362
4e815e90 363 if (ret == CURL_DOWNLOAD_NO_NEWER_FILE) {
6a4a29aa 364 g_remove ( tmpfilename );
7de36baf
GB
365#if GLIB_CHECK_VERSION(2,18,0)
366 g_utime ( fn, NULL ); /* update mtime of local copy */
367#else
d4939f80 368 utimes ( fn, NULL ); /* update mtime of local copy */
7de36baf 369#endif
4945e425 370 } else {
4bdc96fc
RN
371 /* move completely-downloaded file to permanent location */
372 if ( g_rename ( tmpfilename, fn ) )
373 g_warning ("%s: file rename failed [%s] to [%s]", __FUNCTION__, tmpfilename, fn );
4945e425 374 }
4b992365 375 unlock_file ( tmpfilename );
6a4a29aa 376 g_free ( tmpfilename );
1ec35593 377
55246377
JJ
378 if (options->use_etag) {
379 g_free ( file_options.etag );
380 g_free ( file_options.new_etag );
381 }
4e815e90 382 return DOWNLOAD_SUCCESS;
932f8f22
GB
383}
384
4e815e90
RN
385/**
386 * uri: like "/uri.html?whatever"
387 * only reason for the "wrapper" is so we can do redirects.
388 */
389DownloadResult_t a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
85611cd9 390{
825413ba 391 return download ( hostname, uri, fn, opt, FALSE, handle );
0c1044e9
EB
392}
393
4e815e90 394DownloadResult_t a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
0c1044e9 395{
825413ba
SW
396 return download ( hostname, uri, fn, opt, TRUE, handle );
397}
398
399void * a_download_handle_init ()
400{
401 return curl_download_handle_init ();
402}
403
404void a_download_handle_cleanup ( void *handle )
405{
406 curl_download_handle_cleanup ( handle );
85611cd9 407}
e09b94fe
RN
408
409/**
410 * a_download_url_to_tmp_file:
411 * @uri: The URI (Uniform Resource Identifier)
412 * @options: Download options (maybe NULL)
413 *
414 * returns name of the temporary file created - NULL if unsuccessful
415 * this string needs to be freed once used
416 * the file needs to be removed once used
417 */
418gchar *a_download_uri_to_tmp_file ( const gchar *uri, DownloadMapOptions *options )
419{
420 FILE *tmp_file;
421 int tmp_fd;
422 gchar *tmpname;
423
424 if ( (tmp_fd = g_file_open_tmp ("viking-download.XXXXXX", &tmpname, NULL)) == -1 ) {
425 g_critical (_("couldn't open temp file"));
426 return NULL;
427 }
428
429 tmp_file = fdopen(tmp_fd, "r+");
86b25a6c
RN
430 if ( !tmp_file )
431 return NULL;
e09b94fe
RN
432
433 if ( curl_download_uri ( uri, tmp_file, options, NULL, NULL ) ) {
434 // error
435 fclose ( tmp_file );
436 g_remove ( tmpname );
437 g_free ( tmpname );
438 return NULL;
439 }
440 fclose ( tmp_file );
441
442 return tmpname;
443}