]> git.street.me.uk Git - andy/viking.git/blob - src/download.c
Add a preference to control the number of recent files made available.
[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
54 static gboolean check_file_first_line(FILE* f, gchar *patterns[])
55 {
56   gchar **s;
57   gchar *bp;
58   fpos_t pos;
59   gchar buf[33];
60   size_t nr;
61
62   memset(buf, 0, sizeof(buf));
63   fgetpos(f, &pos);
64   rewind(f);
65   nr = fread(buf, 1, sizeof(buf) - 1, f);
66   fsetpos(f, &pos);
67   for (bp = buf; (bp < (buf + sizeof(buf) - 1)) && (nr > (bp - buf)); bp++) {
68     if (!(isspace(*bp)))
69       break;
70   }
71   if ((bp >= (buf + sizeof(buf) -1)) || ((bp - buf) >= nr))
72     return FALSE;
73   for (s = patterns; *s; s++) {
74     if (strncasecmp(*s, bp, strlen(*s)) == 0)
75       return TRUE;
76   }
77   return FALSE;
78 }
79
80 gboolean a_check_html_file(FILE* f)
81 {
82   gchar * html_str[] = {
83     "<html",
84     "<!DOCTYPE html",
85     "<head",
86     "<title",
87     NULL
88   };
89
90   return check_file_first_line(f, html_str);
91 }
92
93 gboolean a_check_map_file(FILE* f)
94 {
95   /* FIXME no more true since a_check_kml_file */
96   return !a_check_html_file(f);
97 }
98
99 gboolean a_check_kml_file(FILE* f)
100 {
101   gchar * kml_str[] = {
102     "<?xml",
103     NULL
104   };
105
106   return check_file_first_line(f, kml_str);
107 }
108
109 static GList *file_list = NULL;
110 static GMutex *file_list_mutex = NULL;
111
112 /* spin button scales */
113 static VikLayerParamScale params_scales[] = {
114   {1, 365, 1, 0},               /* download_tile_age */
115 };
116
117 static VikLayerParamData convert_to_display ( VikLayerParamData value )
118 {
119   // From seconds into days
120   return VIK_LPD_UINT ( value.u / 86400 );
121 }
122
123 static VikLayerParamData convert_to_internal ( VikLayerParamData value )
124 {
125   // From days into seconds
126   return VIK_LPD_UINT ( 86400 * value.u );
127 }
128
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, &params_scales[0], NULL, NULL, NULL, convert_to_display, convert_to_internal },
131 };
132
133 void a_download_init (void)
134 {
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);
138
139         file_list_mutex = g_mutex_new();
140 }
141
142 static gboolean lock_file(const char *fn)
143 {
144         gboolean locked = FALSE;
145         g_mutex_lock(file_list_mutex);
146         if (g_list_find_custom(file_list, fn, (GCompareFunc)g_strcmp0) == NULL)
147         {
148                 // The filename is not yet locked
149                 file_list = g_list_append(file_list, (gpointer)fn),
150                 locked = TRUE;
151         }
152         g_mutex_unlock(file_list_mutex);
153         return locked;
154 }
155
156 static void unlock_file(const char *fn)
157 {
158         g_mutex_lock(file_list_mutex);
159         file_list = g_list_remove(file_list, (gconstpointer)fn);
160         g_mutex_unlock(file_list_mutex);
161 }
162
163
164 static void uncompress_zip ( gchar *name )
165 {
166         GError *error = NULL;
167         GMappedFile *mf;
168
169         if ((mf = g_mapped_file_new ( name, FALSE, &error )) == NULL) {
170                 g_critical(_("Couldn't map file %s: %s"), name, error->message);
171                 g_error_free(error);
172                 return;
173         }
174         gchar *file_contents = g_mapped_file_get_contents ( mf );
175
176         void *unzip_mem = NULL;
177         gulong ucsize;
178
179         if ((unzip_mem = unzip_file (file_contents, &ucsize)) == NULL) {
180                 g_mapped_file_unref ( mf );
181                 return;
182         }
183
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 );
188         }
189 }
190
191 /**
192  * a_try_decompress_file:
193  * @name:  The potentially compressed filename
194  *
195  * Perform magic to decide how which type of decompression to attempt
196  */
197 void a_try_decompress_file (gchar *name)
198 {
199 #ifdef HAVE_MAGIC_H
200         magic_t myt = magic_open ( MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME );
201         gboolean zip = FALSE;
202         gboolean bzip2 = FALSE;
203         if ( myt ) {
204 #ifdef WINDOWS
205                 // We have to 'package' the magic database ourselves :(
206                 //  --> %PROGRAM FILES%\Viking\magic.mgc
207                 magic_load ( myt, "magic.mgc" );
208 #else
209                 // Use system default
210                 magic_load ( myt, NULL );
211 #endif
212                 const char* magic = magic_file (myt, name);
213                 g_debug ("%s: magic output: %s", __FUNCTION__, magic );
214
215                 if ( g_strcmp0 (magic, "application/zip; charset=binary") == 0 )
216                         zip = TRUE;
217
218                 if ( g_strcmp0 (magic, "application/x-bzip2; charset=binary") == 0 )
219                         bzip2 = TRUE;
220
221                 magic_close ( myt );
222         }
223
224         if ( !(zip || bzip2) )
225                 return;
226
227         if ( zip ) {
228                 uncompress_zip ( name );
229         }
230         else if ( bzip2 ) {
231                 gchar* bz2_name = uncompress_bzip2 ( name );
232                 g_remove ( name );
233                 g_rename ( bz2_name, name );
234         }
235
236         return;
237 #endif
238 }
239
240 static int download( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *options, gboolean ftp, void *handle)
241 {
242   FILE *f;
243   int ret;
244   gchar *tmpfilename;
245   gboolean failure = FALSE;
246   DownloadFileOptions file_options = {0, NULL, NULL};
247
248   /* Check file */
249   if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
250   {
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 -3;
255     }
256
257     time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
258     /* Get the modified time of this file */
259     struct stat buf;
260     g_stat ( fn, &buf );
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 -3;
265     }
266
267     if (options->check_file_server_time) {
268       file_options.time_condition = file_time;
269     }
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;
276
277       /* check if etag is short enough */
278       if (etag_length > 100) {
279         g_free(file_options.etag);
280         file_options.etag = NULL;
281       }
282
283       /* TODO: should check that etag is a valid string */
284     }
285
286   } else {
287     gchar *dir = g_path_get_dirname ( fn );
288     g_mkdir_with_parents ( dir , 0777 );
289     g_free ( dir );
290   }
291
292   tmpfilename = g_strdup_printf("%s.tmp", fn);
293   if (!lock_file ( tmpfilename ) )
294   {
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 -4;
300   }
301   f = g_fopen ( tmpfilename, "w+b" );  /* truncate file and open it */
302   if ( ! f ) {
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 -4;
308   }
309
310   /* Call the backend function */
311   ret = curl_download_get_url ( hostname, uri, f, options, ftp, &file_options, handle );
312
313   if (ret != DOWNLOAD_NO_ERROR && ret != DOWNLOAD_NO_NEWER_FILE) {
314     g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
315     failure = TRUE;
316   }
317
318   if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
319     g_debug("%s: file content checking failed", __FUNCTION__);
320     failure = TRUE;
321   }
322
323   fclose ( f );
324   f = NULL;
325
326   if (failure)
327   {
328     g_warning(_("Download error: %s"), fn);
329     g_remove ( tmpfilename );
330     unlock_file ( tmpfilename );
331     g_free ( tmpfilename );
332     if (options->use_etag) {
333       g_free ( file_options.etag );
334       g_free ( file_options.new_etag );
335     }
336     return -1;
337   }
338
339   if ( options->convert_file )
340           options->convert_file ( tmpfilename );
341
342   if (options->use_etag) {
343     if (file_options.new_etag) {
344       /* server returned an etag value */
345       gchar *etag_filename = g_strdup_printf("%s.etag", fn);
346       g_file_set_contents (etag_filename, file_options.new_etag, -1, NULL);
347       g_free (etag_filename);
348       etag_filename = NULL;
349     }
350   }
351
352   if (ret == DOWNLOAD_NO_NEWER_FILE)  {
353     g_remove ( tmpfilename );
354 #if GLIB_CHECK_VERSION(2,18,0)
355     g_utime ( fn, NULL ); /* update mtime of local copy */
356 #else
357     utimes ( fn, NULL ); /* update mtime of local copy */
358 #endif
359   } else {
360     g_rename ( tmpfilename, fn ); /* move completely-downloaded file to permanent location */
361   }
362   unlock_file ( tmpfilename );
363   g_free ( tmpfilename );
364
365   if (options->use_etag) {
366     g_free ( file_options.etag );
367     g_free ( file_options.new_etag );
368   }
369   return 0;
370 }
371
372 /* success = 0, -1 = couldn't connect, -2 HTTP error, -3 file exists, -4 couldn't write to file... */
373 /* uri: like "/uri.html?whatever" */
374 /* only reason for the "wrapper" is so we can do redirects. */
375 int a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
376 {
377   return download ( hostname, uri, fn, opt, FALSE, handle );
378 }
379
380 int a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
381 {
382   return download ( hostname, uri, fn, opt, TRUE, handle );
383 }
384
385 void * a_download_handle_init ()
386 {
387   return curl_download_handle_init ();
388 }
389
390 void a_download_handle_cleanup ( void *handle )
391 {
392   curl_download_handle_cleanup ( handle );
393 }
394
395 /**
396  * a_download_url_to_tmp_file:
397  * @uri:         The URI (Uniform Resource Identifier)
398  * @options:     Download options (maybe NULL)
399  *
400  * returns name of the temporary file created - NULL if unsuccessful
401  *  this string needs to be freed once used
402  *  the file needs to be removed once used
403  */
404 gchar *a_download_uri_to_tmp_file ( const gchar *uri, DownloadMapOptions *options )
405 {
406   FILE *tmp_file;
407   int tmp_fd;
408   gchar *tmpname;
409
410   if ( (tmp_fd = g_file_open_tmp ("viking-download.XXXXXX", &tmpname, NULL)) == -1 ) {
411     g_critical (_("couldn't open temp file"));
412     return NULL;
413   }
414
415   tmp_file = fdopen(tmp_fd, "r+");
416
417   if ( curl_download_uri ( uri, tmp_file, options, NULL, NULL ) ) {
418     // error
419     fclose ( tmp_file );
420     g_remove ( tmpname );
421     g_free ( tmpname );
422     return NULL;
423   }
424   fclose ( tmp_file );
425
426   return tmpname;
427 }