]> git.street.me.uk Git - andy/viking.git/blob - src/download.c
Merge branch 'DownloadDecompression'
[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                 magic_load ( myt, NULL );
205                 const char* magic = magic_file (myt, name);
206                 g_debug ("%s: magic output: %s", __FUNCTION__, magic );
207
208                 if ( g_strcmp0 (magic, "application/zip; charset=binary") == 0 )
209                         zip = TRUE;
210
211                 if ( g_strcmp0 (magic, "application/x-bzip2; charset=binary") == 0 )
212                         bzip2 = TRUE;
213
214                 magic_close ( myt );
215         }
216
217         if ( !(zip || bzip2) )
218                 return;
219
220         if ( zip ) {
221                 uncompress_zip ( name );
222         }
223         else if ( bzip2 ) {
224                 gchar* bz2_name = uncompress_bzip2 ( name );
225                 g_remove ( name );
226                 g_rename ( bz2_name, name );
227         }
228
229         return;
230 #endif
231 }
232
233 static int download( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *options, gboolean ftp, void *handle)
234 {
235   FILE *f;
236   int ret;
237   gchar *tmpfilename;
238   gboolean failure = FALSE;
239   DownloadFileOptions file_options = {0, NULL, NULL};
240
241   /* Check file */
242   if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
243   {
244     if (options == NULL || (!options->check_file_server_time &&
245                             !options->use_etag)) {
246       /* Nothing to do as file already exists and we don't want to check server */
247       return -3;
248     }
249
250     time_t tile_age = a_preferences_get(VIKING_PREFERENCES_NAMESPACE "download_tile_age")->u;
251     /* Get the modified time of this file */
252     struct stat buf;
253     g_stat ( fn, &buf );
254     time_t file_time = buf.st_mtime;
255     if ( (time(NULL) - file_time) < tile_age ) {
256       /* File cache is too recent, so return */
257       return -3;
258     }
259
260     if (options->check_file_server_time) {
261       file_options.time_condition = file_time;
262     }
263     if (options->use_etag) {
264       gchar *etag_filename = g_strdup_printf("%s.etag", fn);
265       gsize etag_length = 0;
266       g_file_get_contents (etag_filename, &(file_options.etag), &etag_length, NULL);
267       g_free (etag_filename);
268       etag_filename = NULL;
269
270       /* check if etag is short enough */
271       if (etag_length > 100) {
272         g_free(file_options.etag);
273         file_options.etag = NULL;
274       }
275
276       /* TODO: should check that etag is a valid string */
277     }
278
279   } else {
280     gchar *dir = g_path_get_dirname ( fn );
281     g_mkdir_with_parents ( dir , 0777 );
282     g_free ( dir );
283   }
284
285   tmpfilename = g_strdup_printf("%s.tmp", fn);
286   if (!lock_file ( tmpfilename ) )
287   {
288     g_debug("%s: Couldn't take lock on temporary file \"%s\"\n", __FUNCTION__, tmpfilename);
289     g_free ( tmpfilename );
290     if (options->use_etag)
291       g_free ( file_options.etag );
292     return -4;
293   }
294   f = g_fopen ( tmpfilename, "w+b" );  /* truncate file and open it */
295   if ( ! f ) {
296     g_warning("Couldn't open temporary file \"%s\": %s", tmpfilename, g_strerror(errno));
297     g_free ( tmpfilename );
298     if (options->use_etag)
299       g_free ( file_options.etag );
300     return -4;
301   }
302
303   /* Call the backend function */
304   ret = curl_download_get_url ( hostname, uri, f, options, ftp, &file_options, handle );
305
306   if (ret != DOWNLOAD_NO_ERROR && ret != DOWNLOAD_NO_NEWER_FILE) {
307     g_debug("%s: download failed: curl_download_get_url=%d", __FUNCTION__, ret);
308     failure = TRUE;
309   }
310
311   if (!failure && options != NULL && options->check_file != NULL && ! options->check_file(f)) {
312     g_debug("%s: file content checking failed", __FUNCTION__);
313     failure = TRUE;
314   }
315
316   fclose ( f );
317   f = NULL;
318
319   if (failure)
320   {
321     g_warning(_("Download error: %s"), fn);
322     g_remove ( tmpfilename );
323     unlock_file ( tmpfilename );
324     g_free ( tmpfilename );
325     if (options->use_etag) {
326       g_free ( file_options.etag );
327       g_free ( file_options.new_etag );
328     }
329     return -1;
330   }
331
332   if ( options->convert_file )
333           options->convert_file ( tmpfilename );
334
335   if (options->use_etag) {
336     if (file_options.new_etag) {
337       /* server returned an etag value */
338       gchar *etag_filename = g_strdup_printf("%s.etag", fn);
339       g_file_set_contents (etag_filename, file_options.new_etag, -1, NULL);
340       g_free (etag_filename);
341       etag_filename = NULL;
342     }
343   }
344
345   if (ret == DOWNLOAD_NO_NEWER_FILE)  {
346     g_remove ( tmpfilename );
347 #if GLIB_CHECK_VERSION(2,18,0)
348     g_utime ( fn, NULL ); /* update mtime of local copy */
349 #else
350     utimes ( fn, NULL ); /* update mtime of local copy */
351 #endif
352   } else {
353     g_rename ( tmpfilename, fn ); /* move completely-downloaded file to permanent location */
354   }
355   unlock_file ( tmpfilename );
356   g_free ( tmpfilename );
357
358   if (options->use_etag) {
359     g_free ( file_options.etag );
360     g_free ( file_options.new_etag );
361   }
362   return 0;
363 }
364
365 /* success = 0, -1 = couldn't connect, -2 HTTP error, -3 file exists, -4 couldn't write to file... */
366 /* uri: like "/uri.html?whatever" */
367 /* only reason for the "wrapper" is so we can do redirects. */
368 int a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
369 {
370   return download ( hostname, uri, fn, opt, FALSE, handle );
371 }
372
373 int a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadMapOptions *opt, void *handle )
374 {
375   return download ( hostname, uri, fn, opt, TRUE, handle );
376 }
377
378 void * a_download_handle_init ()
379 {
380   return curl_download_handle_init ();
381 }
382
383 void a_download_handle_cleanup ( void *handle )
384 {
385   curl_download_handle_cleanup ( handle );
386 }
387
388 /**
389  * a_download_url_to_tmp_file:
390  * @uri:         The URI (Uniform Resource Identifier)
391  * @options:     Download options (maybe NULL)
392  *
393  * returns name of the temporary file created - NULL if unsuccessful
394  *  this string needs to be freed once used
395  *  the file needs to be removed once used
396  */
397 gchar *a_download_uri_to_tmp_file ( const gchar *uri, DownloadMapOptions *options )
398 {
399   FILE *tmp_file;
400   int tmp_fd;
401   gchar *tmpname;
402
403   if ( (tmp_fd = g_file_open_tmp ("viking-download.XXXXXX", &tmpname, NULL)) == -1 ) {
404     g_critical (_("couldn't open temp file"));
405     return NULL;
406   }
407
408   tmp_file = fdopen(tmp_fd, "r+");
409
410   if ( curl_download_uri ( uri, tmp_file, options, NULL, NULL ) ) {
411     // error
412     fclose ( tmp_file );
413     g_remove ( tmpname );
414     g_free ( tmpname );
415     return NULL;
416   }
417   fclose ( tmp_file );
418
419   return tmpname;
420 }