]> git.street.me.uk Git - andy/viking.git/blob - src/download.c
DOC: Fix typo
[andy/viking.git] / src / download.c
1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
2 /*
3  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
4  *
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>
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
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #include <stdio.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <string.h>
33 #ifdef HAVE_SYS_TYPES_H
34 #include <sys/types.h>
35 #endif
36 #ifdef HAVE_UTIME_H
37 #include <utime.h>
38 #endif
39 #include <glib.h>
40 #include <glib/gstdio.h>
41 #include <glib/gi18n.h>
42
43 #ifdef HAVE_MAGIC_H
44 #include <magic.h>
45 #endif
46 #include "compression.h"
47
48 #include "download.h"
49
50 #include "curl_download.h"
51 #include "preferences.h"
52 #include "globals.h"
53 #include "vik_compat.h"
54
55 static gboolean check_file_first_line(FILE* f, gchar *patterns[])
56 {
57   gchar **s;
58   gchar *bp;
59   fpos_t pos;
60   gchar buf[33];
61   size_t nr;
62
63   memset(buf, 0, sizeof(buf));
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))
73     return FALSE;
74   for (s = patterns; *s; s++) {
75     if (strncasecmp(*s, bp, strlen(*s)) == 0)
76       return TRUE;
77   }
78   return FALSE;
79 }
80
81 gboolean 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
94 gboolean a_check_map_file(FILE* f)
95 {
96   /* FIXME no more true since a_check_kml_file */
97   return !a_check_html_file(f);
98 }
99
100 gboolean a_check_kml_file(FILE* f)
101 {
102   gchar * kml_str[] = {
103     "<?xml",
104     NULL
105   };
106
107   return check_file_first_line(f, kml_str);
108 }
109
110 static GList *file_list = NULL;
111 static GMutex *file_list_mutex = NULL;
112
113 /* spin button scales */
114 static VikLayerParamScale params_scales[] = {
115   {1, 365, 1, 0},               /* download_tile_age */
116 };
117
118 static VikLayerParamData convert_to_display ( VikLayerParamData value )
119 {
120   // From seconds into days
121   return VIK_LPD_UINT ( value.u / 86400 );
122 }
123
124 static VikLayerParamData convert_to_internal ( VikLayerParamData value )
125 {
126   // From days into seconds
127   return VIK_LPD_UINT ( 86400 * value.u );
128 }
129
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, &params_scales[0], NULL, NULL, NULL, convert_to_display, convert_to_internal },
132 };
133
134 void a_download_init (void)
135 {
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();
140 }
141
142 void a_download_uninit (void)
143 {
144         vik_mutex_free(file_list_mutex);
145 }
146
147 static gboolean lock_file(const char *fn)
148 {
149         gboolean locked = FALSE;
150         g_mutex_lock(file_list_mutex);
151         if (g_list_find_custom(file_list, fn, (GCompareFunc)g_strcmp0) == NULL)
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
161 static 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
168 /**
169  * Unzip a file - replacing the file with the unzipped contents of the self
170  */
171 static 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
191         // This overwrites any previous file contents
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  */
204 void a_try_decompress_file (gchar *name)
205 {
206 #ifdef HAVE_MAGIC_H
207 #ifdef MAGIC_VERSION
208         // Or magic_version() if available - probably need libmagic 5.18 or so
209         //  (can't determine exactly which version the versioning became available)
210         g_debug ("%s: magic version: %d", __FUNCTION__, MAGIC_VERSION );
211 #endif
212         magic_t myt = magic_open ( MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME );
213         gboolean zip = FALSE;
214         gboolean bzip2 = FALSE;
215         if ( myt ) {
216 #ifdef WINDOWS
217                 // We have to 'package' the magic database ourselves :(
218                 //  --> %PROGRAM FILES%\Viking\magic.mgc
219                 int ml = magic_load ( myt, ".\\magic.mgc" );
220 #else
221                 // Use system default
222                 int ml = magic_load ( myt, NULL );
223 #endif
224                 if ( ml == 0 ) {
225                         const char* magic = magic_file (myt, name);
226                         g_debug ("%s: magic output: %s", __FUNCTION__, magic );
227
228                         if ( g_strcmp0 (magic, "application/zip; charset=binary") == 0 )
229                                 zip = TRUE;
230
231                         if ( g_strcmp0 (magic, "application/x-bzip2; charset=binary") == 0 )
232                                 bzip2 = TRUE;
233                 }
234                 else {
235                         g_critical ("%s: magic load database failure", __FUNCTION__ );
236                 }
237
238                 magic_close ( myt );
239         }
240
241         if ( !(zip || bzip2) )
242                 return;
243
244         if ( zip ) {
245                 uncompress_zip ( name );
246         }
247         else if ( bzip2 ) {
248                 gchar* bz2_name = uncompress_bzip2 ( name );
249                 if ( bz2_name ) {
250                         if ( g_remove ( name ) )
251                                 g_critical ("%s: remove file failed [%s]", __FUNCTION__, name );
252                         if ( g_rename (bz2_name, name) )
253                                 g_critical ("%s: file rename failed [%s] to [%s]", __FUNCTION__, bz2_name, name );
254                 }
255         }
256
257         return;
258 #endif
259 }
260
261 static DownloadResult_t download( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *options, gboolean ftp, void *handle)
262 {
263   FILE *f;
264   int ret;
265   gchar *tmpfilename;
266   gboolean failure = FALSE;
267   DownloadFileOptions file_options = {0, NULL, NULL};
268
269   /* Check file */
270   if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
271   {
272     if (options == NULL || (!options->check_file_server_time &&
273                             !options->use_etag)) {
274       /* Nothing to do as file already exists and we don't want to check server */
275       return DOWNLOAD_NOT_REQUIRED;
276     }
277
278     time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
279     /* Get the modified time of this file */
280     struct stat buf;
281     g_stat ( fn, &buf );
282     time_t file_time = buf.st_mtime;
283     if ( (time(NULL) - file_time) < tile_age ) {
284       /* File cache is too recent, so return */
285       return DOWNLOAD_NOT_REQUIRED;
286     }
287
288     if (options->check_file_server_time) {
289       file_options.time_condition = file_time;
290     }
291     if (options->use_etag) {
292       gchar *etag_filename = g_strdup_printf("%s.etag", fn);
293       gsize etag_length = 0;
294       g_file_get_contents (etag_filename, &(file_options.etag), &etag_length, NULL);
295       g_free (etag_filename);
296       etag_filename = NULL;
297
298       /* check if etag is short enough */
299       if (etag_length > 100) {
300         g_free(file_options.etag);
301         file_options.etag = NULL;
302       }
303
304       /* TODO: should check that etag is a valid string */
305     }
306
307   } else {
308     gchar *dir = g_path_get_dirname ( fn );
309     g_mkdir_with_parents ( dir , 0777 );
310     g_free ( dir );
311   }
312
313   tmpfilename = g_strdup_printf("%s.tmp", fn);
314   if (!lock_file ( tmpfilename ) )
315   {
316     g_debug("%s: Couldn't take lock on temporary file \"%s\"\n", __FUNCTION__, tmpfilename);
317     g_free ( tmpfilename );
318     if (options->use_etag)
319       g_free ( file_options.etag );
320     return DOWNLOAD_FILE_WRITE_ERROR;
321   }
322   f = g_fopen ( tmpfilename, "w+b" );  /* truncate file and open it */
323   if ( ! f ) {
324     g_warning("Couldn't open temporary file \"%s\": %s", tmpfilename, g_strerror(errno));
325     g_free ( tmpfilename );
326     if (options->use_etag)
327       g_free ( file_options.etag );
328     return DOWNLOAD_FILE_WRITE_ERROR;
329   }
330
331   /* Call the backend function */
332   ret = curl_download_get_url ( hostname, uri, f, options, ftp, &file_options, handle );
333
334   DownloadResult_t result = DOWNLOAD_SUCCESS;
335
336   if (ret != CURL_DOWNLOAD_NO_ERROR && ret != CURL_DOWNLOAD_NO_NEWER_FILE) {
337     g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
338     failure = TRUE;
339     result = DOWNLOAD_HTTP_ERROR;
340   }
341
342   if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
343     g_debug("%s: file content checking failed", __FUNCTION__);
344     failure = TRUE;
345     result = DOWNLOAD_CONTENT_ERROR;
346   }
347
348   fclose ( f );
349   f = NULL;
350
351   if (failure)
352   {
353     g_warning(_("Download error: %s"), fn);
354     g_remove ( tmpfilename );
355     unlock_file ( tmpfilename );
356     g_free ( tmpfilename );
357     if (options->use_etag) {
358       g_free ( file_options.etag );
359       g_free ( file_options.new_etag );
360     }
361     return result;
362   }
363
364   if ( options->convert_file )
365           options->convert_file ( tmpfilename );
366
367   if (options->use_etag) {
368     if (file_options.new_etag) {
369       /* server returned an etag value */
370       gchar *etag_filename = g_strdup_printf("%s.etag", fn);
371       g_file_set_contents (etag_filename, file_options.new_etag, -1, NULL);
372       g_free (etag_filename);
373       etag_filename = NULL;
374     }
375   }
376
377   if (ret == CURL_DOWNLOAD_NO_NEWER_FILE)  {
378     g_remove ( tmpfilename );
379 #if GLIB_CHECK_VERSION(2,18,0)
380     g_utime ( fn, NULL ); /* update mtime of local copy */
381 #else
382     utimes ( fn, NULL ); /* update mtime of local copy */
383 #endif
384   } else {
385      /* move completely-downloaded file to permanent location */
386      if ( g_rename ( tmpfilename, fn ) )
387         g_warning ("%s: file rename failed [%s] to [%s]", __FUNCTION__, tmpfilename, fn );
388   }
389   unlock_file ( tmpfilename );
390   g_free ( tmpfilename );
391
392   if (options->use_etag) {
393     g_free ( file_options.etag );
394     g_free ( file_options.new_etag );
395   }
396   return DOWNLOAD_SUCCESS;
397 }
398
399 /**
400  * uri: like "/uri.html?whatever"
401  * only reason for the "wrapper" is so we can do redirects.
402  */
403 DownloadResult_t a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
404 {
405   return download ( hostname, uri, fn, opt, FALSE, handle );
406 }
407
408 DownloadResult_t a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
409 {
410   return download ( hostname, uri, fn, opt, TRUE, handle );
411 }
412
413 void * a_download_handle_init ()
414 {
415   return curl_download_handle_init ();
416 }
417
418 void a_download_handle_cleanup ( void *handle )
419 {
420   curl_download_handle_cleanup ( handle );
421 }
422
423 /**
424  * a_download_url_to_tmp_file:
425  * @uri:         The URI (Uniform Resource Identifier)
426  * @options:     Download options (maybe NULL)
427  *
428  * returns name of the temporary file created - NULL if unsuccessful
429  *  this string needs to be freed once used
430  *  the file needs to be removed once used
431  */
432 gchar *a_download_uri_to_tmp_file ( const gchar *uri, DownloadMapOptions *options )
433 {
434   FILE *tmp_file;
435   int tmp_fd;
436   gchar *tmpname;
437
438   if ( (tmp_fd = g_file_open_tmp ("viking-download.XXXXXX", &tmpname, NULL)) == -1 ) {
439     g_critical (_("couldn't open temp file"));
440     return NULL;
441   }
442
443   tmp_file = fdopen(tmp_fd, "r+");
444   if ( !tmp_file )
445     return NULL;
446
447   if ( curl_download_uri ( uri, tmp_file, options, NULL, NULL ) ) {
448     // error
449     fclose ( tmp_file );
450     g_remove ( tmpname );
451     g_free ( tmpname );
452     return NULL;
453   }
454   fclose ( tmp_file );
455
456   return tmpname;
457 }