]> Pileus Git - grits/blob - src/data/gis-http.c
Fix some possible memory issues in GisHttp
[grits] / src / data / gis-http.c
1 /*
2  * Copyright (C) 2009-2010 Andy Spencer <andy753421@gmail.com>
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /**
19  * SECTION:gis-http
20  * @short_description: Hyper Text Transfer Protocol
21  *
22  * #GisHttp is a small wrapper around libsoup to provide data access using the
23  * Hyper Text Transfer Protocol. Each #GisHttp should be associated with a
24  * particular server or dataset, all the files downloaded for this dataset will
25  * be cached together in $HOME.cache/libgis/
26  */
27
28 #include <config.h>
29 #include <glib.h>
30 #include <glib/gstdio.h>
31 #include <libsoup/soup.h>
32
33 #include "gis-http.h"
34
35 gchar *_get_cache_path(GisHttp *http, const gchar *local)
36 {
37         return g_build_filename(g_get_user_cache_dir(), PACKAGE,
38                         http->prefix, local, NULL);
39 }
40
41 /**
42  * gis_http_new:
43  * @prefix: The prefix in the cache to store the downloaded files.
44  *          For example: * "/nexrad/level2/".
45  *
46  * Create a new #GisHttp for the given prefix
47  *
48  * Returns: the new #GisHttp
49  */
50 GisHttp *gis_http_new(const gchar *prefix)
51 {
52         g_debug("GisHttp: new - %s", prefix);
53         GisHttp *http = g_new0(GisHttp, 1);
54         http->soup = soup_session_sync_new();
55         http->prefix = g_strdup(prefix);
56         g_object_set(http->soup, "user-agent", PACKAGE_STRING, NULL);
57         return http;
58 }
59
60 /**
61  * gis_http_free:
62  * @http: the #GisHttp to free
63  *
64  * Frees resources used by @http and cancels any pending requests.
65  */
66 void gis_http_free(GisHttp *http)
67 {
68         g_debug("GisHttp: free - %s", http->prefix);
69         soup_session_abort(http->soup);
70         g_object_unref(http->soup);
71         g_free(http->prefix);
72         g_free(http);
73 }
74
75 /* For passing data to the chunck callback */
76 struct _CacheInfo {
77         FILE  *fp;
78         gchar *path;
79         GisChunkCallback callback;
80         gpointer user_data;
81 };
82 struct _CacheInfoMain {
83         gchar *path;
84         GisChunkCallback callback;
85         gpointer user_data;
86         goffset cur, total;
87 };
88
89 /* call the user callback from the main thread,
90  * since it's usually UI updates */
91 static gboolean _chunk_main_cb(gpointer _infomain)
92 {
93         struct _CacheInfoMain *infomain = _infomain;
94         infomain->callback(infomain->path,
95                         infomain->cur, infomain->total,
96                         infomain->user_data);
97         g_free(infomain);
98         return FALSE;
99 }
100
101 /**
102  * Append data to the file and call the users callback if they supplied one.
103  */
104 static void _chunk_cb(SoupMessage *message, SoupBuffer *chunk, gpointer _info)
105 {
106         struct _CacheInfo *info = _info;
107
108         if (!SOUP_STATUS_IS_SUCCESSFUL(message->status_code)) {
109                 g_warning("GisHttp: _chunk_cb - soup failed with %d",
110                                 message->status_code);
111                 return;
112         }
113
114         if (!fwrite(chunk->data, chunk->length, 1, info->fp))
115                 g_error("GisHttp: _chunk_cb - Unable to write data");
116
117         if (info->callback) {
118                 struct _CacheInfoMain *infomain = g_new0(struct _CacheInfoMain, 1);
119                 infomain->path      = info->path;
120                 infomain->callback  = info->callback;
121                 infomain->user_data = info->user_data;
122                 infomain->cur       = ftell(info->fp);
123                 goffset st=0, end=0;
124                 soup_message_headers_get_content_range(message->response_headers,
125                                 &st, &end, &infomain->total);
126                 g_idle_add(_chunk_main_cb, infomain);
127         }
128
129 }
130
131 /**
132  * gis_http_fetch:
133  * @http:      the #GisHttp connection to use
134  * @uri:       the URI to fetch
135  * @local:     the local name to give to the file
136  * @mode:      the update type to use when fetching data
137  * @callback:  callback to call when a chunk of data is received
138  * @user_data: user data to pass to the callback
139  *
140  * Fetch a file from the cache. Whether the file is actually loaded from the
141  * remote server depends on the value of @mode.
142  *
143  * Returns: The local path to the complete file
144  */
145 /* TODO: use .part extentions and continue even when using GIS_ONCE */
146 gchar *gis_http_fetch(GisHttp *http, const gchar *uri, const char *local,
147                 GisCacheType mode, GisChunkCallback callback, gpointer user_data)
148 {
149         g_debug("GisHttp: fetch - %s mode=%d", local, mode);
150         gchar *path = _get_cache_path(http, local);
151
152         /* Unlink the file if we're refreshing it */
153         if (mode == GIS_REFRESH)
154                 g_remove(path);
155
156         /* Do the cache if necessasairy */
157         if (!(mode == GIS_ONCE && g_file_test(path, G_FILE_TEST_EXISTS)) &&
158                         mode != GIS_LOCAL) {
159                 g_debug("GisHttp: fetch - Caching file %s", local);
160
161                 /* Open the file for writting */
162                 gchar *part = path;
163                 if (!g_file_test(path, G_FILE_TEST_EXISTS))
164                         part = g_strdup_printf("%s.part", path);
165                 FILE *fp = fopen_p(part, "ab");
166                 fseek(fp, 0, SEEK_END); // "a" is broken on Windows, twice
167
168                 /* Make temp data */
169                 struct _CacheInfo info = {
170                         .fp        = fp,
171                         .path      = path,
172                         .callback  = callback,
173                         .user_data = user_data,
174                 };
175
176                 /* Download the file */
177                 SoupMessage *message = soup_message_new("GET", uri);
178                 if (message == NULL)
179                         g_error("message is null, cannot parse uri");
180                 g_signal_connect(message, "got-chunk", G_CALLBACK(_chunk_cb), &info);
181                 soup_message_headers_set_range(message->request_headers, ftell(fp), -1);
182                 soup_session_send_message(http->soup, message);
183
184                 /* Close file */
185                 fclose(fp);
186                 if (path != part && SOUP_STATUS_IS_SUCCESSFUL(message->status_code)) {
187                         g_rename(part, path);
188                         g_free(part);
189                 }
190
191                 /* Finished */
192                 if (message->status_code == 416) {
193                         /* Range unsatisfiable, file already complete */
194                 } else if (!SOUP_STATUS_IS_SUCCESSFUL(message->status_code)) {
195                         g_warning("GisHttp: done_cb - error copying file, status=%d\n"
196                                         "\tsrc=%s\n"
197                                         "\tdst=%s",
198                                         message->status_code, uri, path);
199                         return NULL;
200                 }
201         }
202
203
204         /* TODO: free everything.. */
205         return path;
206 }
207
208 /**
209  * gis_http_available:
210  * @http:    the #GisHttp connection to use
211  * @filter:  filter used to extract files from the index, or NULL
212  *           For example: "href=\"([^"]*)\""
213  * @cache:   path to the local cache, or NULL to not search the cache
214  * @extract: regex used to extract filenames from the page, should match the
215  *           filename as $1, or NULL to use /http="([^"])"/
216  * @index:   path to the index page, or NULL to not search online
217  *
218  * Look through the cache and an HTTP index page for a list of available files.
219  * The name of each file that matches the filter is added to the returned list.
220  *
221  * The list as well as the strings contained in it should be freed afterwards.
222  *
223  * Returns the list of matching filenames
224  */
225 GList *gis_http_available(GisHttp *http,
226                 gchar *filter, gchar *cache,
227                 gchar *extract, gchar *index)
228 {
229         g_debug("GisHttp: available - %s~=%s %s~=%s",
230                         filter, cache, extract, index);
231         GRegex *filter_re = g_regex_new(filter, 0, 0, NULL);
232         GList  *files = NULL;
233
234         /* Add cached files */
235         if (cache) {
236                 const gchar *file;
237                 gchar *path = _get_cache_path(http, cache);
238                 GDir  *dir  = g_dir_open(path, 0, NULL);
239                 while ((file = g_dir_read_name(dir)))
240                         if (g_regex_match(filter_re, file, 0, NULL))
241                                 files = g_list_prepend(files, g_strdup(file));
242                 g_free(path);
243                 g_dir_close(dir);
244         }
245
246         /* Add online files if online */
247         if (index) {
248                 gchar tmp[32];
249                 g_snprintf(tmp, sizeof(tmp), ".index.%x", g_random_int());
250                 gchar *path = gis_http_fetch(http, index, tmp,
251                                 GIS_REFRESH, NULL, NULL);
252                 if (!path)
253                         return files;
254                 gchar *html;
255                 g_file_get_contents(path, &html, NULL, NULL);
256                 if (!html)
257                         return files;
258
259                 /* Match hrefs by default, this regex is not very accurate */
260                 GRegex *extract_re = g_regex_new(
261                                 extract ?: "href=\"([^\"]*)\"", 0, 0, NULL);
262                 GMatchInfo *info;
263                 g_regex_match(extract_re, html, 0, &info);
264                 while (g_match_info_matches(info)) {
265                         gchar *file = g_match_info_fetch(info, 1);
266                         if (file) {
267                                 if (g_regex_match(filter_re, file, 0, NULL))
268                                         files = g_list_prepend(files, file);
269                                 else
270                                         g_free(file);
271                         }
272                         g_match_info_next(info, NULL);
273                 }
274
275                 g_regex_unref(extract_re);
276                 g_match_info_free(info);
277                 g_unlink(path);
278                 g_free(path);
279                 g_free(html);
280         }
281
282         g_regex_unref(filter_re);
283
284         return files;
285 }