2 * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
4 * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30 #include <glib/gstdio.h>
31 #include <glib/gi18n.h>
35 #include "curl_download.h"
37 static int check_map_file(FILE* f)
41 int res = 0; /* good */
54 memset(buf, 0, sizeof(buf));
57 nr = fread(buf, 1, sizeof(buf) - 1, f);
59 for (bp = buf; (bp < (buf + sizeof(buf) - 1)) && (nr > (bp - buf)); bp++) {
63 if ((bp >= (buf + sizeof(buf) -1)) || ((bp - buf) >= nr))
65 for (s = html_str; *s; s++) {
66 if (strncasecmp(*s, bp, strlen(*s)) == 0)
72 static int download( const char *hostname, const char *uri, const char *fn, DownloadOptions *options, gboolean ftp)
79 if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == TRUE )
81 /* File exists: return */
84 gchar *dir = g_path_get_dirname ( fn );
85 g_mkdir_with_parents ( dir , 0777 );
88 /* create placeholder file */
89 if ( ! (f = g_fopen ( fn, "w+b" )) ) /* immediately open file so other threads won't -- prevents race condition */
95 tmpfilename = g_strdup_printf("%s.tmp", fn);
96 f = g_fopen ( tmpfilename, "w+b" );
98 g_free ( tmpfilename );
99 g_remove ( fn ); /* couldn't create temporary. delete 0-byte file. */
103 /* Call the backend function */
104 ret = curl_download_get_url ( hostname, uri, f, options, ftp );
106 if (ret == -1 || ret == 1 || ret == -2 || check_map_file(f))
108 g_warning(_("Download error: %s"), fn);
111 g_remove ( tmpfilename );
112 g_free ( tmpfilename );
113 g_remove ( fn ); /* couldn't create temporary. delete 0-byte file. */
119 rename ( tmpfilename, fn ); /* move completely-downloaded file to permanent location */
120 g_free ( tmpfilename );
124 /* success = 0, -1 = couldn't connect, -2 HTTP error, -3 file exists, -4 couldn't write to file... */
125 /* uri: like "/uri.html?whatever" */
126 /* only reason for the "wrapper" is so we can do redirects. */
127 int a_http_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadOptions *opt )
129 return download ( hostname, uri, fn, opt, FALSE );
132 int a_ftp_download_get_url ( const char *hostname, const char *uri, const char *fn, DownloadOptions *opt )
134 return download ( hostname, uri, fn, opt, TRUE );