]> git.0d.be Git - empathy.git/blob - libempathy/empathy-utils.c
Fix 2 leaks thanks to valgrind.
[empathy.git] / libempathy / empathy-utils.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2003-2007 Imendio AB
4  * Copyright (C) 2007 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (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 GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Authors: Richard Hult <richard@imendio.com>
22  *          Martyn Russell <martyn@imendio.com>
23  *          Xavier Claessens <xclaesse@gmail.com>
24  */
25
26 #include "config.h"
27
28 #include <string.h>
29 #include <time.h>
30 #include <sys/types.h>
31 #include <regex.h>
32
33 #include <glib/gi18n.h>
34
35 #include <libxml/uri.h>
36 #include <libtelepathy/tp-helpers.h>
37
38 #include "empathy-debug.h"
39 #include "empathy-utils.h"
40 #include "empathy-contact-manager.h"
41
42 #define DEBUG_DOMAIN "Utils"
43
44 static void regex_init (void);
45
46 gchar *
47 empathy_substring (const gchar *str,
48                   gint         start,
49                   gint         end)
50 {
51         return g_strndup (str + start, end - start);
52 }
53
54 /*
55  * Regular Expression code to match urls.
56  */
57 #define USERCHARS "-A-Za-z0-9"
58 #define PASSCHARS "-A-Za-z0-9,?;.:/!%$^*&~\"#'"
59 #define HOSTCHARS "-A-Za-z0-9"
60 #define PATHCHARS "-A-Za-z0-9_$.+!*(),;:@&=?/~#%"
61 #define SCHEME    "(news:|telnet:|nntp:|file:/|https?:|ftps?:|webcal:)"
62 #define USER      "[" USERCHARS "]+(:["PASSCHARS "]+)?"
63 #define URLPATH   "/[" PATHCHARS "]*[^]'.}>) \t\r\n,\\\"]"
64
65 static regex_t dingus[EMPATHY_REGEX_ALL];
66
67 static void
68 regex_init (void)
69 {
70         static gboolean  inited = FALSE;
71         const gchar     *expression;
72         gint             i;
73
74         if (inited) {
75                 return;
76         }
77
78         for (i = 0; i < EMPATHY_REGEX_ALL; i++) {
79                 switch (i) {
80                 case EMPATHY_REGEX_AS_IS:
81                         expression =
82                                 SCHEME "//(" USER "@)?[" HOSTCHARS ".]+"
83                                 "(:[0-9]+)?(" URLPATH ")?";
84                         break;
85                 case EMPATHY_REGEX_BROWSER:
86                         expression =
87                                 "(www|ftp)[" HOSTCHARS "]*\\.[" HOSTCHARS ".]+"
88                                 "(:[0-9]+)?(" URLPATH ")?";
89                         break;
90                 case EMPATHY_REGEX_EMAIL:
91                         expression =
92                                 "(mailto:)?[a-z0-9][a-z0-9.-]*@[a-z0-9]"
93                                 "[a-z0-9-]*(\\.[a-z0-9][a-z0-9-]*)+";
94                         break;
95                 case EMPATHY_REGEX_OTHER:
96                         expression =
97                                 "news:[-A-Z\\^_a-z{|}~!\"#$%&'()*+,./0-9;:=?`]+"
98                                 "@[" HOSTCHARS ".]+(:[0-9]+)?";
99                         break;
100                 default:
101                         /* Silence the compiler. */
102                         expression = NULL;
103                         continue;
104                 }
105
106                 memset (&dingus[i], 0, sizeof (regex_t));
107                 regcomp (&dingus[i], expression, REG_EXTENDED | REG_ICASE);
108         }
109
110         inited = TRUE;
111 }
112
113 gint
114 empathy_regex_match (EmpathyRegExType  type,
115                     const gchar     *msg,
116                     GArray          *start,
117                     GArray          *end)
118 {
119         regmatch_t matches[1];
120         gint       ret = 0;
121         gint       num_matches = 0;
122         gint       offset = 0;
123         gint       i;
124
125         g_return_val_if_fail (type >= 0 || type <= EMPATHY_REGEX_ALL, 0);
126
127         regex_init ();
128
129         while (!ret && type != EMPATHY_REGEX_ALL) {
130                 ret = regexec (&dingus[type], msg + offset, 1, matches, 0);
131                 if (ret == 0) {
132                         gint s;
133
134                         num_matches++;
135
136                         s = matches[0].rm_so + offset;
137                         offset = matches[0].rm_eo + offset;
138
139                         g_array_append_val (start, s);
140                         g_array_append_val (end, offset);
141                 }
142         }
143
144         if (type != EMPATHY_REGEX_ALL) {
145                 empathy_debug (DEBUG_DOMAIN,
146                               "Found %d matches for regex type:%d",
147                               num_matches, type);
148                 return num_matches;
149         }
150
151         /* If EMPATHY_REGEX_ALL then we run ALL regex's on the string. */
152         for (i = 0; i < EMPATHY_REGEX_ALL; i++, ret = 0) {
153                 while (!ret) {
154                         ret = regexec (&dingus[i], msg + offset, 1, matches, 0);
155                         if (ret == 0) {
156                                 gint s;
157
158                                 num_matches++;
159
160                                 s = matches[0].rm_so + offset;
161                                 offset = matches[0].rm_eo + offset;
162
163                                 g_array_append_val (start, s);
164                                 g_array_append_val (end, offset);
165                         }
166                 }
167         }
168
169         empathy_debug (DEBUG_DOMAIN,
170                       "Found %d matches for ALL regex types",
171                       num_matches);
172
173         return num_matches;
174 }
175
176 gint
177 empathy_strcasecmp (const gchar *s1,
178                    const gchar *s2)
179 {
180         return empathy_strncasecmp (s1, s2, -1);
181 }
182
183 gint
184 empathy_strncasecmp (const gchar *s1,
185                     const gchar *s2,
186                     gsize        n)
187 {
188         gchar *u1, *u2;
189         gint   ret_val;
190
191         u1 = g_utf8_casefold (s1, n);
192         u2 = g_utf8_casefold (s2, n);
193
194         ret_val = g_utf8_collate (u1, u2);
195         g_free (u1);
196         g_free (u2);
197
198         return ret_val;
199 }
200
201 /* Stolen from telepathy-glib */
202 gboolean
203 empathy_strdiff (const gchar *left, const gchar *right)
204 {
205   if ((NULL == left) != (NULL == right))
206     return TRUE;
207
208   else if (left == right)
209     return FALSE;
210
211   else
212     return (0 != strcmp (left, right));
213 }
214
215 /* Stolen from telepathy-glib */
216 static inline gboolean
217 _esc_ident_bad (gchar c, gboolean is_first)
218 {
219   return ((c < 'a' || c > 'z') &&
220           (c < 'A' || c > 'Z') &&
221           (c < '0' || c > '9' || is_first));
222 }
223
224 /* Stolen from telepathy-glib */
225 gchar *
226 empathy_escape_as_identifier (const gchar *name)
227 {
228   gboolean bad = FALSE;
229   size_t len = 0;
230   GString *op;
231   const gchar *ptr, *first_ok;
232
233   g_return_val_if_fail (name != NULL, NULL);
234
235   for (ptr = name; *ptr; ptr++)
236     {
237       if (_esc_ident_bad (*ptr, ptr == name))
238         {
239           bad = TRUE;
240           len += 3;
241         }
242       else
243         len++;
244     }
245
246   /* fast path if it's clean */
247   if (!bad)
248     return g_strdup (name);
249
250   /* If strictly less than ptr, first_ok is the first uncopied safe character.
251    */
252   first_ok = name;
253   op = g_string_sized_new (len);
254   for (ptr = name; *ptr; ptr++)
255     {
256       if (_esc_ident_bad (*ptr, ptr == name))
257         {
258           /* copy preceding safe characters if any */
259           if (first_ok < ptr)
260             {
261               g_string_append_len (op, first_ok, ptr - first_ok);
262             }
263           /* escape the unsafe character */
264           g_string_append_printf (op, "_%02x", (unsigned char)(*ptr));
265           /* restart after it */
266           first_ok = ptr + 1;
267         }
268     }
269   /* copy trailing safe characters if any */
270   if (first_ok < ptr)
271     {
272       g_string_append_len (op, first_ok, ptr - first_ok);
273     }
274   return g_string_free (op, FALSE);
275 }
276
277 gboolean
278 empathy_xml_validate (xmlDoc      *doc,
279                      const gchar *dtd_filename)
280 {
281         gchar        *path, *escaped;
282         xmlValidCtxt  cvp;
283         xmlDtd       *dtd;
284         gboolean      ret;
285
286         path = g_build_filename (DATADIR, "empathy", dtd_filename, NULL);
287
288         /* The list of valid chars is taken from libxml. */
289         escaped = xmlURIEscapeStr (path, ":@&=+$,/?;");
290
291         g_free (path);
292
293         memset (&cvp, 0, sizeof (cvp));
294         dtd = xmlParseDTD (NULL, escaped);
295         ret = xmlValidateDtd (&cvp, doc, dtd);
296
297         xmlFree (escaped);
298         xmlFreeDtd (dtd);
299
300         return ret;
301 }
302
303 xmlNodePtr
304 empathy_xml_node_get_child (xmlNodePtr   node, 
305                            const gchar *child_name)
306 {
307         xmlNodePtr l;
308
309         g_return_val_if_fail (node != NULL, NULL);
310         g_return_val_if_fail (child_name != NULL, NULL);
311
312         for (l = node->children; l; l = l->next) {
313                 if (l->name && strcmp (l->name, child_name) == 0) {
314                         return l;
315                 }
316         }
317
318         return NULL;
319 }
320
321 xmlChar *
322 empathy_xml_node_get_child_content (xmlNodePtr   node, 
323                                    const gchar *child_name)
324 {
325         xmlNodePtr l;
326
327         g_return_val_if_fail (node != NULL, NULL);
328         g_return_val_if_fail (child_name != NULL, NULL);
329
330         l = empathy_xml_node_get_child (node, child_name);
331         if (l) {
332                 return xmlNodeGetContent (l);
333         }
334                 
335         return NULL;
336 }
337
338 xmlNodePtr
339 empathy_xml_node_find_child_prop_value (xmlNodePtr   node, 
340                                        const gchar *prop_name,
341                                        const gchar *prop_value)
342 {
343         xmlNodePtr l;
344         xmlNodePtr found = NULL;
345
346         g_return_val_if_fail (node != NULL, NULL);
347         g_return_val_if_fail (prop_name != NULL, NULL);
348         g_return_val_if_fail (prop_value != NULL, NULL);
349
350         for (l = node->children; l && !found; l = l->next) {
351                 xmlChar *prop;
352
353                 if (!xmlHasProp (l, prop_name)) {
354                         continue;
355                 }
356
357                 prop = xmlGetProp (l, prop_name);
358                 if (prop && strcmp (prop, prop_value) == 0) {
359                         found = l;
360                 }
361                 
362                 xmlFree (prop);
363         }
364                 
365         return found;
366 }
367
368 guint
369 empathy_account_hash (gconstpointer key)
370 {
371         return g_str_hash (mc_account_get_unique_name (MC_ACCOUNT (key)));
372 }
373
374 gboolean
375 empathy_account_equal (gconstpointer a,
376                       gconstpointer b)
377 {
378         const gchar *name_a;
379         const gchar *name_b;
380
381         name_a = mc_account_get_unique_name (MC_ACCOUNT (a));
382         name_b = mc_account_get_unique_name (MC_ACCOUNT (b));
383
384         return g_str_equal (name_a, name_b);
385 }
386
387 MissionControl *
388 empathy_mission_control_new (void)
389 {
390         static MissionControl *mc = NULL;
391
392         if (!mc) {
393                 mc = mission_control_new (tp_get_bus ());
394                 g_object_add_weak_pointer (G_OBJECT (mc), (gpointer) &mc);
395         } else {
396                 g_object_ref (mc);
397         }
398
399         return mc;
400 }
401
402 gchar *
403 empathy_inspect_channel (McAccount *account,
404                          TpChan    *tp_chan)
405 {
406         g_return_val_if_fail (MC_IS_ACCOUNT (account), NULL);
407         g_return_val_if_fail (TELEPATHY_IS_CHAN (tp_chan), NULL);
408
409         return empathy_inspect_handle (account,
410                                        tp_chan->handle,
411                                        tp_chan->handle_type);
412 }
413
414 gchar *
415 empathy_inspect_handle (McAccount *account,
416                         guint      handle,
417                         guint      handle_type)
418 {
419         MissionControl  *mc;
420         TpConn          *tp_conn;
421         GArray          *handles;
422         gchar          **names;
423         gchar           *name;
424         GError          *error;
425
426         g_return_val_if_fail (MC_IS_ACCOUNT (account), NULL);
427         g_return_val_if_fail (handle != 0, NULL);
428         g_return_val_if_fail (handle_type != 0, NULL);
429
430         mc = empathy_mission_control_new ();
431         tp_conn = mission_control_get_connection (mc, account, NULL);
432         g_object_unref (mc);
433
434         if (!tp_conn) {
435                 return NULL;
436         }
437
438         /* Get the handle's name */
439         handles = g_array_new (FALSE, FALSE, sizeof (guint));
440         g_array_append_val (handles, handle);
441         if (!tp_conn_inspect_handles (DBUS_G_PROXY (tp_conn),
442                                       handle_type,
443                                       handles,
444                                       &names,
445                                       &error)) {
446                 empathy_debug (DEBUG_DOMAIN, 
447                               "Couldn't get id: %s",
448                               error ? error->message : "No error given");
449
450                 g_clear_error (&error);
451                 g_array_free (handles, TRUE);
452                 g_object_unref (tp_conn);
453                 
454                 return NULL;
455         }
456
457         g_array_free (handles, TRUE);
458         name = *names;
459         g_free (names);
460         g_object_unref (tp_conn);
461
462         return name;
463 }
464