]> git.street.me.uk Git - andy/viking.git/blame - src/download.c
[QA] Consistent usage of g_stat() GStatBuf parameter type
[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));
fd437981
RN
64 if ( !fgetpos(f, &pos) )
65 return FALSE;
6e78a423
QT
66 rewind(f);
67 nr = fread(buf, 1, sizeof(buf) - 1, f);
fd437981
RN
68 if ( !fgetpos(f, &pos) )
69 return FALSE;
6e78a423
QT
70 for (bp = buf; (bp < (buf + sizeof(buf) - 1)) && (nr > (bp - buf)); bp++) {
71 if (!(isspace(*bp)))
72 break;
73 }
74 if ((bp >= (buf + sizeof(buf) -1)) || ((bp - buf) >= nr))
1ac37c09 75 return FALSE;
388cf5a4 76 for (s = patterns; *s; s++) {
1918a993 77 if (strncasecmp(*s, bp, strlen(*s)) == 0)
1ac37c09 78 return TRUE;
6e78a423 79 }
1ac37c09
GB
80 return FALSE;
81}
82
388cf5a4
GB
83gboolean a_check_html_file(FILE* f)
84{
85 gchar * html_str[] = {
86 "<html",
87 "<!DOCTYPE html",
88 "<head",
89 "<title",
90 NULL
91 };
92
93 return check_file_first_line(f, html_str);
94}
95
1ac37c09
GB
96gboolean a_check_map_file(FILE* f)
97{
388cf5a4 98 /* FIXME no more true since a_check_kml_file */
1ac37c09 99 return !a_check_html_file(f);
6e78a423
QT
100}
101
ae941b4c
HMJ
102gboolean a_check_kml_file(FILE* f)
103{
388cf5a4 104 gchar * kml_str[] = {
ae941b4c
HMJ
105 "<?xml",
106 NULL
107 };
108
388cf5a4 109 return check_file_first_line(f, kml_str);
ae941b4c
HMJ
110}
111
4b992365
GB
112static GList *file_list = NULL;
113static GMutex *file_list_mutex = NULL;
114
6693f5f9 115/* spin button scales */
32dfea86
RN
116static VikLayerParamScale params_scales[] = {
117 {1, 365, 1, 0}, /* download_tile_age */
6693f5f9
GB
118};
119
32dfea86
RN
120static VikLayerParamData convert_to_display ( VikLayerParamData value )
121{
122 // From seconds into days
123 return VIK_LPD_UINT ( value.u / 86400 );
124}
125
126static VikLayerParamData convert_to_internal ( VikLayerParamData value )
127{
128 // From days into seconds
129 return VIK_LPD_UINT ( 86400 * value.u );
130}
131
6693f5f9 132static VikLayerParam prefs[] = {
32dfea86 133 { 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
134};
135
4b992365
GB
136void a_download_init (void)
137{
6693f5f9 138 VikLayerParamData tmp;
32dfea86 139 tmp.u = VIK_CONFIG_DEFAULT_TILE_AGE / 86400; // Now in days
6693f5f9 140 a_preferences_register(prefs, tmp, VIKING_PREFERENCES_GROUP_KEY);
fc6640a9 141 file_list_mutex = vik_mutex_new();
e3da2277 142}
6693f5f9 143
e3da2277
RN
144void a_download_uninit (void)
145{
146 vik_mutex_free(file_list_mutex);
4b992365
GB
147}
148
149static gboolean lock_file(const char *fn)
150{
151 gboolean locked = FALSE;
152 g_mutex_lock(file_list_mutex);
2894744e 153 if (g_list_find_custom(file_list, fn, (GCompareFunc)g_strcmp0) == NULL)
4b992365
GB
154 {
155 // The filename is not yet locked
156 file_list = g_list_append(file_list, (gpointer)fn),
157 locked = TRUE;
158 }
159 g_mutex_unlock(file_list_mutex);
160 return locked;
161}
162
163static void unlock_file(const char *fn)
164{
165 g_mutex_lock(file_list_mutex);
166 file_list = g_list_remove(file_list, (gconstpointer)fn);
167 g_mutex_unlock(file_list_mutex);
168}
169
feef2120
RN
170/**
171 * Unzip a file - replacing the file with the unzipped contents of the self
172 */
a3697549
RN
173static void uncompress_zip ( gchar *name )
174{
175 GError *error = NULL;
176 GMappedFile *mf;
177
178 if ((mf = g_mapped_file_new ( name, FALSE, &error )) == NULL) {
179 g_critical(_("Couldn't map file %s: %s"), name, error->message);
180 g_error_free(error);
181 return;
182 }
183 gchar *file_contents = g_mapped_file_get_contents ( mf );
184
185 void *unzip_mem = NULL;
186 gulong ucsize;
187
188 if ((unzip_mem = unzip_file (file_contents, &ucsize)) == NULL) {
189 g_mapped_file_unref ( mf );
190 return;
191 }
192
feef2120 193 // This overwrites any previous file contents
a3697549
RN
194 if ( ! g_file_set_contents ( name, unzip_mem, ucsize, &error ) ) {
195 g_critical ( "Couldn't write file '%s', because of %s", name, error->message );
196 g_error_free ( error );
197 }
198}
199
200/**
201 * a_try_decompress_file:
202 * @name: The potentially compressed filename
203 *
204 * Perform magic to decide how which type of decompression to attempt
205 */
206void a_try_decompress_file (gchar *name)
207{
208#ifdef HAVE_MAGIC_H
ef9f0fcc
RN
209#ifdef MAGIC_VERSION
210 // Or magic_version() if available - probably need libmagic 5.18 or so
211 // (can't determine exactly which version the versioning became available)
212 g_debug ("%s: magic version: %d", __FUNCTION__, MAGIC_VERSION );
213#endif
a3697549
RN
214 magic_t myt = magic_open ( MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME );
215 gboolean zip = FALSE;
216 gboolean bzip2 = FALSE;
217 if ( myt ) {
9702385a
RN
218#ifdef WINDOWS
219 // We have to 'package' the magic database ourselves :(
220 // --> %PROGRAM FILES%\Viking\magic.mgc
ef9f0fcc 221 int ml = magic_load ( myt, ".\\magic.mgc" );
9702385a
RN
222#else
223 // Use system default
ef9f0fcc 224 int ml = magic_load ( myt, NULL );
9702385a 225#endif
ef9f0fcc
RN
226 if ( ml == 0 ) {
227 const char* magic = magic_file (myt, name);
228 g_debug ("%s: magic output: %s", __FUNCTION__, magic );
229
efa54543 230 if ( g_ascii_strncasecmp(magic, "application/zip", 15) == 0 )
ef9f0fcc
RN
231 zip = TRUE;
232
efa54543 233 if ( g_ascii_strncasecmp(magic, "application/x-bzip2", 19) == 0 )
ef9f0fcc
RN
234 bzip2 = TRUE;
235 }
236 else {
237 g_critical ("%s: magic load database failure", __FUNCTION__ );
238 }
a3697549
RN
239
240 magic_close ( myt );
241 }
242
243 if ( !(zip || bzip2) )
244 return;
245
246 if ( zip ) {
247 uncompress_zip ( name );
248 }
249 else if ( bzip2 ) {
250 gchar* bz2_name = uncompress_bzip2 ( name );
7184955f
RN
251 if ( bz2_name ) {
252 if ( g_remove ( name ) )
253 g_critical ("%s: remove file failed [%s]", __FUNCTION__, name );
254 if ( g_rename (bz2_name, name) )
255 g_critical ("%s: file rename failed [%s] to [%s]", __FUNCTION__, bz2_name, name );
256 }
a3697549
RN
257 }
258
259 return;
260#endif
261}
262
fed82438
SW
263#define VIKING_ETAG_XATTR "xattr::viking.etag"
264
686baff0 265static gboolean get_etag_xattr(const char *fn, CurlDownloadOptions *cdo)
fed82438
SW
266{
267 gboolean result = FALSE;
268 GFileInfo *fileinfo;
269 GFile *file;
270
271 file = g_file_new_for_path(fn);
272 fileinfo = g_file_query_info(file, VIKING_ETAG_XATTR, G_FILE_QUERY_INFO_NONE, NULL, NULL);
273 if (fileinfo) {
274 const char *etag = g_file_info_get_attribute_string(fileinfo, VIKING_ETAG_XATTR);
275 if (etag) {
686baff0
RN
276 cdo->etag = g_strdup(etag);
277 result = !!cdo->etag;
fed82438
SW
278 }
279 g_object_unref(fileinfo);
280 }
281 g_object_unref(file);
282
283 if (result)
686baff0 284 g_debug("%s: Get etag (xattr) from %s: %s", __FUNCTION__, fn, cdo->etag);
fed82438
SW
285
286 return result;
287}
288
686baff0 289static gboolean get_etag_file(const char *fn, CurlDownloadOptions *cdo)
fed82438
SW
290{
291 gboolean result = FALSE;
292 gchar *etag_filename;
293
294 etag_filename = g_strdup_printf("%s.etag", fn);
295 if (etag_filename) {
686baff0 296 result = g_file_get_contents(etag_filename, &cdo->etag, NULL, NULL);
fed82438
SW
297 g_free(etag_filename);
298 }
299
300 if (result)
686baff0 301 g_debug("%s: Get etag (file) from %s: %s", __FUNCTION__, fn, cdo->etag);
fed82438
SW
302
303 return result;
304}
305
686baff0 306static void get_etag(const char *fn, CurlDownloadOptions *cdo)
fed82438
SW
307{
308 /* first try to get etag from xattr, then fall back to plain file */
686baff0 309 if (!get_etag_xattr(fn, cdo) && !get_etag_file(fn, cdo)) {
fed82438
SW
310 g_debug("%s: Failed to get etag from %s", __FUNCTION__, fn);
311 return;
312 }
313
314 /* check if etag is short enough */
686baff0
RN
315 if (strlen(cdo->etag) > 100) {
316 g_free(cdo->etag);
317 cdo->etag = NULL;
fed82438
SW
318 }
319
320 /* TODO: should check that etag is a valid string */
321}
322
686baff0 323static gboolean set_etag_xattr(const char *fn, CurlDownloadOptions *cdo)
fed82438
SW
324{
325 gboolean result = FALSE;
326 GFile *file;
327
328 file = g_file_new_for_path(fn);
686baff0 329 result = g_file_set_attribute_string(file, VIKING_ETAG_XATTR, cdo->new_etag, G_FILE_QUERY_INFO_NONE, NULL, NULL);
fed82438
SW
330 g_object_unref(file);
331
332 if (result)
686baff0 333 g_debug("%s: Set etag (xattr) on %s: %s", __FUNCTION__, fn, cdo->new_etag);
fed82438
SW
334
335 return result;
336}
337
686baff0 338static gboolean set_etag_file(const char *fn, CurlDownloadOptions *cdo)
fed82438
SW
339{
340 gboolean result = FALSE;
341 gchar *etag_filename;
342
343 etag_filename = g_strdup_printf("%s.etag", fn);
344 if (etag_filename) {
686baff0 345 result = g_file_set_contents(etag_filename, cdo->new_etag, -1, NULL);
fed82438
SW
346 g_free(etag_filename);
347 }
348
349 if (result)
686baff0 350 g_debug("%s: Set etag (file) on %s: %s", __FUNCTION__, fn, cdo->new_etag);
fed82438
SW
351
352 return result;
353}
354
686baff0 355static void set_etag(const char *fn, const char *fntmp, CurlDownloadOptions *cdo)
fed82438
SW
356{
357 /* first try to store etag in extended attribute, then fall back to plain file */
686baff0 358 if (!set_etag_xattr(fntmp, cdo) && !set_etag_file(fn, cdo)) {
fed82438
SW
359 g_debug("%s: Failed to set etag on %s", __FUNCTION__, fn);
360 }
361}
362
686baff0 363static DownloadResult_t download( const char *hostname, const char *uri, const char *fn, DownloadFileOptions *options, gboolean ftp, void *handle)
932f8f22
GB
364{
365 FILE *f;
366 int ret;
533bbf34 367 gchar *tmpfilename;
1ac37c09 368 gboolean failure = FALSE;
686baff0 369 CurlDownloadOptions cdo = {0, NULL, NULL};
932f8f22
GB
370
371 /* Check file */
45acf79e 372 if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
932f8f22 373 {
8853eed9
JJ
374 if (options == NULL || (!options->check_file_server_time &&
375 !options->use_etag)) {
376 /* Nothing to do as file already exists and we don't want to check server */
4e815e90 377 return DOWNLOAD_NOT_REQUIRED;
6a4a29aa 378 }
8853eed9 379
57ecf9cb
JJ
380 time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
381 /* Get the modified time of this file */
2a708810 382 GStatBuf buf;
fd437981 383 (void)g_stat ( fn, &buf );
57ecf9cb
JJ
384 time_t file_time = buf.st_mtime;
385 if ( (time(NULL) - file_time) < tile_age ) {
386 /* File cache is too recent, so return */
4e815e90 387 return DOWNLOAD_NOT_REQUIRED;
57ecf9cb
JJ
388 }
389
e69ac989 390 if (options != NULL && options->check_file_server_time) {
686baff0 391 cdo.time_condition = file_time;
6a4a29aa 392 }
e69ac989 393 if (options != NULL && options->use_etag) {
686baff0 394 get_etag(fn, &cdo);
55246377 395 }
f91cc826 396
932f8f22 397 } else {
a1618d62 398 gchar *dir = g_path_get_dirname ( fn );
5e4cce8f
RN
399 if ( g_mkdir_with_parents ( dir , 0777 ) != 0)
400 g_warning ("%s: Failed to mkdir %s", __FUNCTION__, dir );
a1618d62 401 g_free ( dir );
3335ae4e
EB
402 }
403
404 tmpfilename = g_strdup_printf("%s.tmp", fn);
4b992365
GB
405 if (!lock_file ( tmpfilename ) )
406 {
407 g_debug("%s: Couldn't take lock on temporary file \"%s\"\n", __FUNCTION__, tmpfilename);
408 g_free ( tmpfilename );
9137c580 409 if (options->use_etag)
686baff0 410 g_free ( cdo.etag );
4e815e90 411 return DOWNLOAD_FILE_WRITE_ERROR;
4b992365
GB
412 }
413 f = g_fopen ( tmpfilename, "w+b" ); /* truncate file and open it */
3335ae4e 414 if ( ! f ) {
4b992365 415 g_warning("Couldn't open temporary file \"%s\": %s", tmpfilename, g_strerror(errno));
3335ae4e 416 g_free ( tmpfilename );
9137c580 417 if (options->use_etag)
686baff0 418 g_free ( cdo.etag );
4e815e90 419 return DOWNLOAD_FILE_WRITE_ERROR;
932f8f22
GB
420 }
421
422 /* Call the backend function */
686baff0 423 ret = curl_download_get_url ( hostname, uri, f, options, ftp, &cdo, handle );
6a4a29aa 424
4e815e90
RN
425 DownloadResult_t result = DOWNLOAD_SUCCESS;
426
427 if (ret != CURL_DOWNLOAD_NO_ERROR && ret != CURL_DOWNLOAD_NO_NEWER_FILE) {
1ac37c09
GB
428 g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
429 failure = TRUE;
4e815e90 430 result = DOWNLOAD_HTTP_ERROR;
1ac37c09
GB
431 }
432
433 if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
434 g_debug("%s: file content checking failed", __FUNCTION__);
435 failure = TRUE;
4e815e90 436 result = DOWNLOAD_CONTENT_ERROR;
1ac37c09 437 }
932f8f22 438
1ec35593
MA
439 fclose ( f );
440 f = NULL;
441
1ac37c09 442 if (failure)
932f8f22 443 {
4258f4e2 444 g_warning(_("Download error: %s"), fn);
c5ecc990
RN
445 if ( g_remove ( tmpfilename ) != 0 )
446 g_warning( ("Failed to remove: %s"), tmpfilename);
4b992365 447 unlock_file ( tmpfilename );
3335ae4e 448 g_free ( tmpfilename );
e69ac989 449 if ( options != NULL && options->use_etag ) {
686baff0
RN
450 g_free ( cdo.etag );
451 g_free ( cdo.new_etag );
55246377 452 }
4e815e90 453 return result;
932f8f22
GB
454 }
455
4e815e90 456 if (ret == CURL_DOWNLOAD_NO_NEWER_FILE) {
85e9e947 457 (void)g_remove ( tmpfilename );
73e61a6e
RN
458 // update mtime of local copy
459 // Not security critical, thus potential Time of Check Time of Use race condition is not bad
460 // coverity[toctou]
461 if ( g_utime ( fn, NULL ) != 0 )
462 g_warning ( "%s couldn't set time on: %s", __FUNCTION__, fn );
4945e425 463 } else {
0e818e49
SW
464 if ( options != NULL && options->convert_file )
465 options->convert_file ( tmpfilename );
466
467 if ( options != NULL && options->use_etag ) {
686baff0 468 if ( cdo.new_etag ) {
0e818e49 469 /* server returned an etag value */
686baff0 470 set_etag(fn, tmpfilename, &cdo);
0e818e49
SW
471 }
472 }
473
4bdc96fc
RN
474 /* move completely-downloaded file to permanent location */
475 if ( g_rename ( tmpfilename, fn ) )
476 g_warning ("%s: file rename failed [%s] to [%s]", __FUNCTION__, tmpfilename, fn );
4945e425 477 }
4b992365 478 unlock_file ( tmpfilename );
6a4a29aa 479 g_free ( tmpfilename );
1ec35593 480
e69ac989 481 if ( options != NULL && options->use_etag ) {
686baff0
RN
482 g_free ( cdo.etag );
483 g_free ( cdo.new_etag );
55246377 484 }
4e815e90 485 return DOWNLOAD_SUCCESS;
932f8f22
GB
486}
487
4e815e90
RN
488/**
489 * uri: like "/uri.html?whatever"
490 * only reason for the "wrapper" is so we can do redirects.
491 */
686baff0 492DownloadResult_t a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadFileOptions *opt, void *handle )
85611cd9 493{
825413ba 494 return download ( hostname, uri, fn, opt, FALSE, handle );
0c1044e9
EB
495}
496
686baff0 497DownloadResult_t a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadFileOptions *opt, void *handle )
0c1044e9 498{
825413ba
SW
499 return download ( hostname, uri, fn, opt, TRUE, handle );
500}
501
502void * a_download_handle_init ()
503{
504 return curl_download_handle_init ();
505}
506
507void a_download_handle_cleanup ( void *handle )
508{
509 curl_download_handle_cleanup ( handle );
85611cd9 510}
e09b94fe
RN
511
512/**
513 * a_download_url_to_tmp_file:
514 * @uri: The URI (Uniform Resource Identifier)
515 * @options: Download options (maybe NULL)
516 *
517 * returns name of the temporary file created - NULL if unsuccessful
518 * this string needs to be freed once used
519 * the file needs to be removed once used
520 */
686baff0 521gchar *a_download_uri_to_tmp_file ( const gchar *uri, DownloadFileOptions *options )
e09b94fe
RN
522{
523 FILE *tmp_file;
524 int tmp_fd;
525 gchar *tmpname;
526
527 if ( (tmp_fd = g_file_open_tmp ("viking-download.XXXXXX", &tmpname, NULL)) == -1 ) {
528 g_critical (_("couldn't open temp file"));
529 return NULL;
530 }
531
532 tmp_file = fdopen(tmp_fd, "r+");
86b25a6c
RN
533 if ( !tmp_file )
534 return NULL;
e09b94fe
RN
535
536 if ( curl_download_uri ( uri, tmp_file, options, NULL, NULL ) ) {
537 // error
538 fclose ( tmp_file );
85e9e947 539 (void)g_remove ( tmpname );
e09b94fe
RN
540 g_free ( tmpname );
541 return NULL;
542 }
543 fclose ( tmp_file );
544
545 return tmpname;
546}