]> git.street.me.uk Git - andy/viking.git/blob - src/download.c
[QA] Generally print warnings to the console for low level file operations
[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   if ( !fgetpos(f, &pos) )
65     return FALSE;
66   rewind(f);
67   nr = fread(buf, 1, sizeof(buf) - 1, f);
68   if ( !fgetpos(f, &pos) )
69     return FALSE;
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))
75     return FALSE;
76   for (s = patterns; *s; s++) {
77     if (strncasecmp(*s, bp, strlen(*s)) == 0)
78       return TRUE;
79   }
80   return FALSE;
81 }
82
83 gboolean 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
96 gboolean a_check_map_file(FILE* f)
97 {
98   /* FIXME no more true since a_check_kml_file */
99   return !a_check_html_file(f);
100 }
101
102 gboolean a_check_kml_file(FILE* f)
103 {
104   gchar * kml_str[] = {
105     "<?xml",
106     NULL
107   };
108
109   return check_file_first_line(f, kml_str);
110 }
111
112 static GList *file_list = NULL;
113 static GMutex *file_list_mutex = NULL;
114
115 /* spin button scales */
116 static VikLayerParamScale params_scales[] = {
117   {1, 365, 1, 0},               /* download_tile_age */
118 };
119
120 static VikLayerParamData convert_to_display ( VikLayerParamData value )
121 {
122   // From seconds into days
123   return VIK_LPD_UINT ( value.u / 86400 );
124 }
125
126 static VikLayerParamData convert_to_internal ( VikLayerParamData value )
127 {
128   // From days into seconds
129   return VIK_LPD_UINT ( 86400 * value.u );
130 }
131
132 static VikLayerParam prefs[] = {
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 },
134 };
135
136 void a_download_init (void)
137 {
138         VikLayerParamData tmp;
139         tmp.u = VIK_CONFIG_DEFAULT_TILE_AGE / 86400; // Now in days
140         a_preferences_register(prefs, tmp, VIKING_PREFERENCES_GROUP_KEY);
141         file_list_mutex = vik_mutex_new();
142 }
143
144 void a_download_uninit (void)
145 {
146         vik_mutex_free(file_list_mutex);
147 }
148
149 static gboolean lock_file(const char *fn)
150 {
151         gboolean locked = FALSE;
152         g_mutex_lock(file_list_mutex);
153         if (g_list_find_custom(file_list, fn, (GCompareFunc)g_strcmp0) == NULL)
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
163 static 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
170 /**
171  * Unzip a file - replacing the file with the unzipped contents of the self
172  */
173 static 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
193         // This overwrites any previous file contents
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  */
206 void a_try_decompress_file (gchar *name)
207 {
208 #ifdef HAVE_MAGIC_H
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
214         magic_t myt = magic_open ( MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME );
215         gboolean zip = FALSE;
216         gboolean bzip2 = FALSE;
217         if ( myt ) {
218 #ifdef WINDOWS
219                 // We have to 'package' the magic database ourselves :(
220                 //  --> %PROGRAM FILES%\Viking\magic.mgc
221                 int ml = magic_load ( myt, ".\\magic.mgc" );
222 #else
223                 // Use system default
224                 int ml = magic_load ( myt, NULL );
225 #endif
226                 if ( ml == 0 ) {
227                         const char* magic = magic_file (myt, name);
228                         g_debug ("%s: magic output: %s", __FUNCTION__, magic );
229
230                         if ( g_strcmp0 (magic, "application/zip; charset=binary") == 0 )
231                                 zip = TRUE;
232
233                         if ( g_strcmp0 (magic, "application/x-bzip2; charset=binary") == 0 )
234                                 bzip2 = TRUE;
235                 }
236                 else {
237                         g_critical ("%s: magic load database failure", __FUNCTION__ );
238                 }
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 );
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                 }
257         }
258
259         return;
260 #endif
261 }
262
263 static DownloadResult_t download( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *options, gboolean ftp, void *handle)
264 {
265   FILE *f;
266   int ret;
267   gchar *tmpfilename;
268   gboolean failure = FALSE;
269   DownloadFileOptions file_options = {0, NULL, NULL};
270
271   /* Check file */
272   if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
273   {
274     if (options == NULL || (!options->check_file_server_time &&
275                             !options->use_etag)) {
276       /* Nothing to do as file already exists and we don't want to check server */
277       return DOWNLOAD_NOT_REQUIRED;
278     }
279
280     time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
281     /* Get the modified time of this file */
282     struct stat buf;
283     (void)g_stat ( fn, &buf );
284     time_t file_time = buf.st_mtime;
285     if ( (time(NULL) - file_time) < tile_age ) {
286       /* File cache is too recent, so return */
287       return DOWNLOAD_NOT_REQUIRED;
288     }
289
290     if (options->check_file_server_time) {
291       file_options.time_condition = file_time;
292     }
293     if (options->use_etag) {
294       gchar *etag_filename = g_strdup_printf("%s.etag", fn);
295       gsize etag_length = 0;
296       g_file_get_contents (etag_filename, &(file_options.etag), &etag_length, NULL);
297       g_free (etag_filename);
298       etag_filename = NULL;
299
300       /* check if etag is short enough */
301       if (etag_length > 100) {
302         g_free(file_options.etag);
303         file_options.etag = NULL;
304       }
305
306       /* TODO: should check that etag is a valid string */
307     }
308
309   } else {
310     gchar *dir = g_path_get_dirname ( fn );
311     g_mkdir_with_parents ( dir , 0777 );
312     g_free ( dir );
313   }
314
315   tmpfilename = g_strdup_printf("%s.tmp", fn);
316   if (!lock_file ( tmpfilename ) )
317   {
318     g_debug("%s: Couldn't take lock on temporary file \"%s\"\n", __FUNCTION__, tmpfilename);
319     g_free ( tmpfilename );
320     if (options->use_etag)
321       g_free ( file_options.etag );
322     return DOWNLOAD_FILE_WRITE_ERROR;
323   }
324   f = g_fopen ( tmpfilename, "w+b" );  /* truncate file and open it */
325   if ( ! f ) {
326     g_warning("Couldn't open temporary file \"%s\": %s", tmpfilename, g_strerror(errno));
327     g_free ( tmpfilename );
328     if (options->use_etag)
329       g_free ( file_options.etag );
330     return DOWNLOAD_FILE_WRITE_ERROR;
331   }
332
333   /* Call the backend function */
334   ret = curl_download_get_url ( hostname, uri, f, options, ftp, &file_options, handle );
335
336   DownloadResult_t result = DOWNLOAD_SUCCESS;
337
338   if (ret != CURL_DOWNLOAD_NO_ERROR && ret != CURL_DOWNLOAD_NO_NEWER_FILE) {
339     g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
340     failure = TRUE;
341     result = DOWNLOAD_HTTP_ERROR;
342   }
343
344   if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
345     g_debug("%s: file content checking failed", __FUNCTION__);
346     failure = TRUE;
347     result = DOWNLOAD_CONTENT_ERROR;
348   }
349
350   fclose ( f );
351   f = NULL;
352
353   if (failure)
354   {
355     g_warning(_("Download error: %s"), fn);
356     g_remove ( tmpfilename );
357     unlock_file ( tmpfilename );
358     g_free ( tmpfilename );
359     if (options->use_etag) {
360       g_free ( file_options.etag );
361       g_free ( file_options.new_etag );
362     }
363     return result;
364   }
365
366   if ( options->convert_file )
367           options->convert_file ( tmpfilename );
368
369   if (options->use_etag) {
370     if (file_options.new_etag) {
371       /* server returned an etag value */
372       gchar *etag_filename = g_strdup_printf("%s.etag", fn);
373       g_file_set_contents (etag_filename, file_options.new_etag, -1, NULL);
374       g_free (etag_filename);
375       etag_filename = NULL;
376     }
377   }
378
379   if (ret == CURL_DOWNLOAD_NO_NEWER_FILE)  {
380     (void)g_remove ( tmpfilename );
381 #if GLIB_CHECK_VERSION(2,18,0)
382     g_utime ( fn, NULL ); /* update mtime of local copy */
383 #else
384     utimes ( fn, NULL ); /* update mtime of local copy */
385 #endif
386   } else {
387      /* move completely-downloaded file to permanent location */
388      if ( g_rename ( tmpfilename, fn ) )
389         g_warning ("%s: file rename failed [%s] to [%s]", __FUNCTION__, tmpfilename, fn );
390   }
391   unlock_file ( tmpfilename );
392   g_free ( tmpfilename );
393
394   if (options->use_etag) {
395     g_free ( file_options.etag );
396     g_free ( file_options.new_etag );
397   }
398   return DOWNLOAD_SUCCESS;
399 }
400
401 /**
402  * uri: like "/uri.html?whatever"
403  * only reason for the "wrapper" is so we can do redirects.
404  */
405 DownloadResult_t a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
406 {
407   return download ( hostname, uri, fn, opt, FALSE, handle );
408 }
409
410 DownloadResult_t a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
411 {
412   return download ( hostname, uri, fn, opt, TRUE, handle );
413 }
414
415 void * a_download_handle_init ()
416 {
417   return curl_download_handle_init ();
418 }
419
420 void a_download_handle_cleanup ( void *handle )
421 {
422   curl_download_handle_cleanup ( handle );
423 }
424
425 /**
426  * a_download_url_to_tmp_file:
427  * @uri:         The URI (Uniform Resource Identifier)
428  * @options:     Download options (maybe NULL)
429  *
430  * returns name of the temporary file created - NULL if unsuccessful
431  *  this string needs to be freed once used
432  *  the file needs to be removed once used
433  */
434 gchar *a_download_uri_to_tmp_file ( const gchar *uri, DownloadMapOptions *options )
435 {
436   FILE *tmp_file;
437   int tmp_fd;
438   gchar *tmpname;
439
440   if ( (tmp_fd = g_file_open_tmp ("viking-download.XXXXXX", &tmpname, NULL)) == -1 ) {
441     g_critical (_("couldn't open temp file"));
442     return NULL;
443   }
444
445   tmp_file = fdopen(tmp_fd, "r+");
446   if ( !tmp_file )
447     return NULL;
448
449   if ( curl_download_uri ( uri, tmp_file, options, NULL, NULL ) ) {
450     // error
451     fclose ( tmp_file );
452     (void)g_remove ( tmpname );
453     g_free ( tmpname );
454     return NULL;
455   }
456   fclose ( tmp_file );
457
458   return tmpname;
459 }