Fix memory leak in libravatar
[claws.git] / src / plugins / libravatar / libravatar.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2014 Hiroyuki Yamamoto and the Claws Mail Team
4  * Copyright (C) 2014 Ricardo Mones
5  *
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 3 of the License, or
9  * (at your option) any later version.
10  *
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.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include <glib.h>
26 #include <glib/gi18n.h>
27
28 #include <curl/curl.h>
29
30 #include "version.h"
31 #include "libravatar.h"
32 #include "libravatar_prefs.h"
33 #include "libravatar_missing.h"
34 #include "libravatar_federation.h"
35 #include "prefs_common.h"
36 #include "procheader.h"
37 #include "procmsg.h"
38 #include "utils.h"
39 #include "md5.h"
40
41 /* indexes of keys are default_mode - 10 if applicable */
42 static const char *def_mode[] = {
43         "404",  /* not used, only useful in web pages */
44         "mm",
45         "identicon",
46         "monsterid",
47         "wavatar",
48         "retro"
49 };
50
51 static guint update_hook_id;
52 static guint render_hook_id;
53 static gchar *cache_dir = NULL; /* dir-separator terminated */
54
55 static gboolean libravatar_header_update_hook(gpointer source, gpointer data)
56 {
57         AvatarCaptureData *acd = (AvatarCaptureData *)source;
58
59         debug_print("libravatar avatar_header_update invoked\n");
60
61         if (!strcmp(acd->header, "From:")) {
62                 gchar *a, *lower;
63
64                 a = g_strdup(acd->content);
65                 extract_address(a);
66
67                 /* string to lower */
68                 for (lower = a; *lower; lower++)
69                         *lower = g_ascii_tolower(*lower);
70
71                 debug_print("libravatar added '%s'\n", a);
72                 procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_LIBRAVATAR, a);
73                 g_free(a);
74         }
75
76         return FALSE; /* keep getting */
77 }
78
79 static gchar *federated_base_url_from_address(const gchar *address)
80 {
81 #if (defined USE_GNUTLS && GLIB_CHECK_VERSION(2,22,0))
82         gchar *base_url = NULL;
83
84         if (!libravatarprefs.allow_federated) {
85                 debug_print("federated domains disabled by configuration\n");
86                 goto default_url;
87         }
88
89         base_url = federated_url_for_address(address);
90         if (base_url != NULL) {
91                 return base_url;
92         }
93
94 default_url:
95 #endif
96         return g_strdup(libravatarprefs.base_url);
97 }
98
99 static GtkWidget *image_widget_from_filename(const gchar *filename)
100 {
101         GtkWidget *image = NULL;
102         GdkPixbuf *picture = NULL;
103         GError *error = NULL;
104         gint w, h;
105
106         gdk_pixbuf_get_file_info(filename, &w, &h);
107
108         if (w != AVATAR_SIZE || h != AVATAR_SIZE)
109                 /* server can provide a different size from the requested in URL */
110                 picture = gdk_pixbuf_new_from_file_at_scale(
111                                 filename, AVATAR_SIZE, AVATAR_SIZE, TRUE, &error);
112         else    /* exact size */
113                 picture = gdk_pixbuf_new_from_file(filename, &error);
114
115         if (error != NULL) {
116                 g_warning("Failed to load image '%s': %s\n", filename, error->message);
117                 g_error_free(error);
118         } else {
119                 if (picture) {
120                         image = gtk_image_new_from_pixbuf(picture);
121                         g_object_unref(picture);
122                 } else
123                         g_warning("Failed to load image '%s': no error returned!\n", filename);
124         }
125
126         return image;
127 }
128
129 static gchar *cache_name_for_md5(const gchar *md5)
130 {
131         if (libravatarprefs.default_mode >= DEF_MODE_MM
132                         && libravatarprefs.default_mode <= DEF_MODE_RETRO) {
133                 /* cache dir for generated avatars */
134                 return g_strconcat(cache_dir, def_mode[libravatarprefs.default_mode - 10],
135                                    G_DIR_SEPARATOR_S, md5, NULL);
136         }
137         /* default cache dir */
138         return g_strconcat(cache_dir, md5, NULL);
139 }
140
141 static size_t write_image_data_cb(void *ptr, size_t size, size_t nmemb, void *stream)
142 {
143         size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
144         debug_print("received %zu bytes from avatar server\n", written);
145
146         return written;
147 }
148
149 static GtkWidget *image_widget_from_url(const gchar *url, const gchar *md5)
150 {
151         GtkWidget *image = NULL;
152         gchar *filename;
153         FILE *file;
154         CURL *curl;
155
156         curl = curl_easy_init();
157         if (curl == NULL) {
158                 g_warning("could not initialize curl to get image from url\n");
159                 return NULL;
160         }
161         curl_easy_setopt(curl, CURLOPT_URL, url);
162         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_image_data_cb);
163         curl_easy_setopt(curl, CURLOPT_TIMEOUT, prefs_common_get_prefs()->io_timeout_secs);
164         curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
165
166         filename = cache_name_for_md5(md5);
167         file = fopen(filename, "wb");
168         if (file != NULL) {
169                 long filesize;
170
171                 if (libravatarprefs.allow_redirects) {
172                         long maxredirs = (libravatarprefs.default_mode == DEF_MODE_URL)? 3L
173                                 : ((libravatarprefs.default_mode == DEF_MODE_MM)? 2L: 1L);
174
175                         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
176                         curl_easy_setopt(curl, CURLOPT_MAXREDIRS, maxredirs);
177                 }
178                 curl_easy_setopt(curl, CURLOPT_FILE, file);
179                 debug_print("retrieving URL to file: %s -> %s\n", url, filename);
180                 curl_easy_perform(curl);
181                 filesize = ftell(file);
182                 fclose(file);
183
184                 if (filesize < MIN_PNG_SIZE)
185                         debug_print("not enough data for an avatar image: %ld bytes\n", filesize);
186                 else
187                         image = image_widget_from_filename(filename);
188
189                 if (!libravatarprefs.cache_icons || filesize == 0) {
190                         if (g_unlink(filename) < 0)
191                                 g_warning("failed to delete cache file %s\n", filename);
192                 }
193
194                 if (filesize == 0)
195                         missing_add_md5(libravatarmisses, md5);
196         } else {
197                 g_warning("could not open '%s' for writting\n", filename);
198         }
199         curl_easy_cleanup(curl);
200         g_free(filename);
201
202         return image;
203 }
204
205 static gboolean is_recent_enough(const gchar *filename)
206 {
207         struct stat s;
208         time_t t;
209
210         if (libravatarprefs.cache_icons) {
211                 t = time(NULL);
212                 if (t != (time_t)-1 && !g_stat(filename, &s)) {
213                         if (t - s.st_ctime <= libravatarprefs.cache_interval * 3600)
214                                 return TRUE;
215                 }
216         }
217
218         return FALSE; /* re-download */
219 }
220
221 static GtkWidget *image_widget_from_cached_md5(const gchar *md5)
222 {
223         GtkWidget *image = NULL;
224         gchar *filename;
225
226         filename = cache_name_for_md5(md5);
227         if (is_file_exist(filename) && is_recent_enough(filename)) {
228                 debug_print("found cached image for %s\n", md5);
229                 image = image_widget_from_filename(filename);
230         }
231         g_free(filename);
232
233         return image;
234 }
235
236 static gchar *libravatar_url_for_md5(const gchar *base, const gchar *md5)
237 {
238         if (libravatarprefs.default_mode >= DEF_MODE_404) {
239                 return g_strdup_printf("%s/%s?s=%u&d=%s",
240                                 base, md5, AVATAR_SIZE,
241                                 def_mode[libravatarprefs.default_mode - 10]);
242         } else if (libravatarprefs.default_mode == DEF_MODE_URL) {
243                 return g_strdup_printf("%s/%s?s=%u&d=%s",
244                                 base, md5, AVATAR_SIZE,
245                                 libravatarprefs.default_mode_url);
246         } else if (libravatarprefs.default_mode == DEF_MODE_NONE) {
247                 return g_strdup_printf("%s/%s?s=%u",
248                                 base, md5, AVATAR_SIZE);
249         }
250
251         g_warning("invalid libravatar default mode: %d\n", libravatarprefs.default_mode);
252         return NULL;
253 }
254
255 static gboolean libravatar_image_render_hook(gpointer source, gpointer data)
256 {
257         AvatarRender *ar = (AvatarRender *)source;
258         GtkWidget *image = NULL;
259         gchar *a = NULL, *url = NULL;
260         gchar md5sum[33];
261
262         debug_print("libravatar avatar_image_render invoked\n");
263
264         a = procmsg_msginfo_get_avatar(ar->full_msginfo, AVATAR_LIBRAVATAR);
265         if (a != NULL) {
266                 gchar *base;
267
268                 md5_hex_digest(md5sum, a);
269                 /* try missing cache */
270                 if (is_missing_md5(libravatarmisses, md5sum)) {
271                         return FALSE;
272                 }
273                 /* try disk cache */
274                 image = image_widget_from_cached_md5(md5sum);
275                 if (image != NULL) {
276                         if (ar->image) /* previous plugin set one */
277                                 gtk_widget_destroy(ar->image);
278                         ar->image = image;
279                         ar->type  = AVATAR_LIBRAVATAR;
280                         return FALSE;
281                 }
282                 /* not cached copy: try network */
283                 if (prefs_common.work_offline) {
284                         debug_print("working off-line: libravatar network retrieval skipped\n");
285                         return FALSE;
286                 }
287                 base = federated_base_url_from_address(a);
288                 url = libravatar_url_for_md5(base, md5sum);
289                 if (url != NULL) {
290                         image = image_widget_from_url(url, md5sum);
291                         g_free(url);
292                         if (image != NULL) {
293                                 if (ar->image) /* previous plugin set one */
294                                         gtk_widget_destroy(ar->image);
295                                 ar->image = image;
296                                 ar->type  = AVATAR_LIBRAVATAR;
297                         }
298                 }
299                 g_free(base);
300
301                 return TRUE;
302         }
303
304         return FALSE; /* keep rendering */
305 }
306
307 static gint cache_dir_init()
308 {
309         gchar *subdir;
310         int i;
311
312         cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
313                                 LIBRAVATAR_CACHE_DIR, G_DIR_SEPARATOR_S,
314                                 NULL);
315         if (!is_dir_exist(cache_dir)) {
316                 if (make_dir(cache_dir) < 0) {
317                         g_free(cache_dir);
318                         return -1;
319                 }
320         }
321         for (i = DEF_MODE_MM; i <= DEF_MODE_RETRO; ++i) {
322                 subdir = g_strconcat(cache_dir, def_mode[i - 10], NULL);
323                 if (!is_dir_exist(subdir)) {
324                         if (make_dir(subdir) < 0) {
325                                 g_warning("cannot create directory %s\n", subdir);
326                                 g_free(subdir);
327                                 return -1;
328                         }
329                 }
330                 g_free(subdir);
331         }
332
333         return 0;
334 }
335
336 static gint missing_cache_init()
337 {
338         gchar *cache_file = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
339                                         LIBRAVATAR_CACHE_DIR, G_DIR_SEPARATOR_S,
340                                         LIBRAVATAR_MISSING_FILE, NULL);
341
342         libravatarmisses = missing_load_from_file(cache_file);
343         g_free(cache_file);
344
345         if (libravatarmisses == NULL)
346                 return -1;
347
348         return 0;
349 }
350
351 static void missing_cache_done()
352 {
353         gchar *cache_file;
354
355         if (libravatarmisses != NULL) {
356                 cache_file = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
357                                         LIBRAVATAR_CACHE_DIR, G_DIR_SEPARATOR_S,
358                                         LIBRAVATAR_MISSING_FILE, NULL);
359                 missing_save_to_file(libravatarmisses, cache_file);
360                 g_free(cache_file);
361                 g_hash_table_destroy(libravatarmisses);
362         }
363 }
364
365 /**
366  * Initialize plugin.
367  *
368  * @param error  For storing the returned error message.
369  *
370  * @return 0 if initialization succeeds, -1 on failure.
371  */
372 gint plugin_init(gchar **error)
373 {
374         if (!check_plugin_version(MAKE_NUMERIC_VERSION(3,9,3,29),
375                                   VERSION_NUMERIC, _("Libravatar"), error))
376                 return -1;
377         /* get info from headers */
378         update_hook_id = hooks_register_hook(AVATAR_HEADER_UPDATE_HOOKLIST,
379                                              libravatar_header_update_hook,
380                                              NULL);
381         if (update_hook_id == -1) {
382                 *error = g_strdup(_("Failed to register avatar header update hook"));
383                 return -1;
384         }
385         /* get image for displaying */
386         render_hook_id = hooks_register_hook(AVATAR_IMAGE_RENDER_HOOKLIST,
387                                              libravatar_image_render_hook,
388                                              NULL);
389         if (render_hook_id == -1) {
390                 *error = g_strdup(_("Failed to register avatar image render hook"));
391                 return -1;
392         }
393         /* cache dir */
394         if (cache_dir_init() == -1) {
395                 *error = g_strdup(_("Failed to create avatar image cache directory"));
396                 return -1;
397         }
398         /* preferences page */
399         libravatar_prefs_init();
400         /* curl library */
401         curl_global_init(CURL_GLOBAL_DEFAULT);
402         /* missing cache */
403         if (missing_cache_init() == -1) {
404                 *error = g_strdup(_("Failed to load missing items cache"));
405                 return -1;
406         }
407         debug_print("Libravatar plugin loaded\n");
408
409         return 0;
410 }
411
412 /**
413  * Destructor for the plugin.
414  * Unregister the callback function and frees matcher.
415  *
416  * @return Always TRUE.
417  */
418 gboolean plugin_done(void)
419 {
420         if (render_hook_id != -1) {
421                 hooks_unregister_hook(AVATAR_IMAGE_RENDER_HOOKLIST,
422                                       render_hook_id);
423                 render_hook_id = -1;
424         }
425         if (update_hook_id != -1) {
426                 hooks_unregister_hook(AVATAR_HEADER_UPDATE_HOOKLIST,
427                                       update_hook_id);
428                 update_hook_id = -1;
429         }
430         libravatar_prefs_done();
431         missing_cache_done();
432         if (cache_dir != NULL)
433                 g_free(cache_dir);
434         debug_print("Libravatar plugin unloaded\n");
435
436         return TRUE;
437 }
438
439 /**
440  * Get the name of the plugin.
441  *
442  * @return The plugin's name, maybe translated.
443  */
444 const gchar *plugin_name(void)
445 {
446         return _("Libravatar");
447 }
448
449 /**
450  * Get the description of the plugin.
451  *
452  * @return The plugin's description, maybe translated.
453  */
454 const gchar *plugin_desc(void)
455 {
456         return _("Display libravatar profiles' images for mail messages. More\n"
457                  "info about libravatar at http://www.libravatar.org/. If you have\n"
458                  "a gravatar.com profile but not a libravatar one, those will also\n"
459                  "be retrieved (when redirections are allowed in plugin config).\n"
460                  "Plugin config page is available from main window at:\n"
461                  "/Configuration/Preferences/Plugins/Libravatar.\n\n"
462                  "This plugin uses libcurl to retrieve images, so if you're behind a\n"
463                  "proxy please refer to curl(1) manpage for details on 'http_proxy'\n"
464                  "configuration. More details about this and others on README file.\n\n"
465                  "Feedback to <ricardo@mones.org> is welcome.\n");
466 }
467
468 /**
469  * Get the kind of plugin.
470  *
471  * @return The "GTK2" constant.
472  */
473 const gchar *plugin_type(void)
474 {
475         return "GTK2";
476 }
477
478 /**
479  * Get the license acronym the plugin is released under.
480  *
481  * @return The "GPL3+" constant.
482  */
483 const gchar *plugin_licence(void)
484 {
485         return "GPL3+";
486 }
487
488 /**
489  * Get the version of the plugin.
490  *
491  * @return The current version string.
492  */
493 const gchar *plugin_version(void)
494 {
495         return VERSION;
496 }
497
498 /**
499  * Get the features implemented by the plugin.
500  *
501  * @return A constant PluginFeature structure with the features.
502  */
503 struct PluginFeature *plugin_provides(void)
504 {
505         static struct PluginFeature features[] =
506                 { {PLUGIN_OTHER, N_("Libravatar")},
507                   {PLUGIN_NOTHING, NULL}};
508
509         return features;
510 }
511