source: lib/misc.c @ 0cf867b

Last change on this file since 0cf867b was a161d33, checked in by Sven Moritz Hallberg <sm@…>, at 2008-02-14T18:43:47Z

interpret &apos;

  • Property mode set to 100644
File size: 12.9 KB
Line 
1  /********************************************************************\
2  * BitlBee -- An IRC to other IM-networks gateway                     *
3  *                                                                    *
4  * Copyright 2002-2006 Wilmer van der Gaast and others                *
5  \********************************************************************/
6
7/*
8 * Various utility functions. Some are copied from Gaim to support the
9 * IM-modules, most are from BitlBee.
10 *
11 * Copyright (C) 1998-1999, Mark Spencer <markster@marko.net>
12 *                          (and possibly other members of the Gaim team)
13 * Copyright 2002-2006 Wilmer van der Gaast <wilmer@gaast.net>
14 */
15
16/*
17  This program is free software; you can redistribute it and/or modify
18  it under the terms of the GNU General Public License as published by
19  the Free Software Foundation; either version 2 of the License, or
20  (at your option) any later version.
21
22  This program is distributed in the hope that it will be useful,
23  but WITHOUT ANY WARRANTY; without even the implied warranty of
24  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  GNU General Public License for more details.
26
27  You should have received a copy of the GNU General Public License with
28  the Debian GNU/Linux distribution in /usr/share/common-licenses/GPL;
29  if not, write to the Free Software Foundation, Inc., 59 Temple Place,
30  Suite 330, Boston, MA  02111-1307  USA
31*/
32
33#define BITLBEE_CORE
34#include "nogaim.h"
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <ctype.h>
39#include <glib.h>
40#include <time.h>
41
42#ifdef HAVE_RESOLV_A
43#include <arpa/nameser.h>
44#include <resolv.h>
45#endif
46
47#include "ssl_client.h"
48
49void strip_linefeed(gchar *text)
50{
51        int i, j;
52        gchar *text2 = g_malloc(strlen(text) + 1);
53
54        for (i = 0, j = 0; text[i]; i++)
55                if (text[i] != '\r')
56                        text2[j++] = text[i];
57        text2[j] = '\0';
58
59        strcpy(text, text2);
60        g_free(text2);
61}
62
63char *normalize(const char *s)
64{
65        static char buf[BUF_LEN];
66        char *t, *u;
67        int x = 0;
68
69        g_return_val_if_fail((s != NULL), NULL);
70
71        u = t = g_strdup(s);
72
73        strcpy(t, s);
74        g_strdown(t);
75
76        while (*t && (x < BUF_LEN - 1)) {
77                if (*t != ' ') {
78                        buf[x] = *t;
79                        x++;
80                }
81                t++;
82        }
83        buf[x] = '\0';
84        g_free(u);
85        return buf;
86}
87
88time_t get_time(int year, int month, int day, int hour, int min, int sec)
89{
90        struct tm tm;
91
92        memset(&tm, 0, sizeof(struct tm));
93        tm.tm_year = year - 1900;
94        tm.tm_mon = month - 1;
95        tm.tm_mday = day;
96        tm.tm_hour = hour;
97        tm.tm_min = min;
98        tm.tm_sec = sec >= 0 ? sec : time(NULL) % 60;
99       
100        return mktime(&tm);
101}
102
103typedef struct htmlentity
104{
105        char code[7];
106        char is[3];
107} htmlentity_t;
108
109static const htmlentity_t ent[] =
110{
111        { "lt",     "<" },
112        { "gt",     ">" },
113        { "amp",    "&" },
114        { "apos",   "'" },
115        { "quot",   "\"" },
116        { "aacute", "á" },
117        { "eacute", "é" },
118        { "iacute", "é" },
119        { "oacute", "ó" },
120        { "uacute", "ú" },
121        { "agrave", "à" },
122        { "egrave", "è" },
123        { "igrave", "ì" },
124        { "ograve", "ò" },
125        { "ugrave", "ù" },
126        { "acirc",  "â" },
127        { "ecirc",  "ê" },
128        { "icirc",  "î" },
129        { "ocirc",  "ô" },
130        { "ucirc",  "û" },
131        { "auml",   "ä" },
132        { "euml",   "ë" },
133        { "iuml",   "ï" },
134        { "ouml",   "ö" },
135        { "uuml",   "ü" },
136        { "nbsp",   " " },
137        { "",        ""  }
138};
139
140void strip_html( char *in )
141{
142        char *start = in;
143        char *out = g_malloc( strlen( in ) + 1 );
144        char *s = out, *cs;
145        int i, matched;
146        int taglen;
147       
148        memset( out, 0, strlen( in ) + 1 );
149       
150        while( *in )
151        {
152                if( *in == '<' && ( isalpha( *(in+1) ) || *(in+1) == '/' ) )
153                {
154                        /* If in points at a < and in+1 points at a letter or a slash, this is probably
155                           a HTML-tag. Try to find a closing > and continue there. If the > can't be
156                           found, assume that it wasn't a HTML-tag after all. */
157                       
158                        cs = in;
159                       
160                        while( *in && *in != '>' )
161                                in ++;
162                       
163                        taglen = in-cs-1;   /* not <0 because the above loop runs at least once */
164                        if( *in )
165                        {
166                                if( g_strncasecmp( cs+1, "b", taglen) == 0 )
167                                        *(s++) = '\x02';
168                                else if( g_strncasecmp( cs+1, "/b", taglen) == 0 )
169                                        *(s++) = '\x02';
170                                else if( g_strncasecmp( cs+1, "i", taglen) == 0 )
171                                        *(s++) = '\x1f';
172                                else if( g_strncasecmp( cs+1, "/i", taglen) == 0 )
173                                        *(s++) = '\x1f';
174                                else if( g_strncasecmp( cs+1, "br", 2) == 0 )
175                                        *(s++) = '\n';
176                                in ++;
177                        }
178                        else
179                        {
180                                in = cs;
181                                *(s++) = *(in++);
182                        }
183                }
184                else if( *in == '&' )
185                {
186                        cs = ++in;
187                        while( *in && isalpha( *in ) )
188                                in ++;
189                       
190                        if( *in == ';' ) in ++;
191                        matched = 0;
192                       
193                        for( i = 0; *ent[i].code; i ++ )
194                                if( g_strncasecmp( ent[i].code, cs, strlen( ent[i].code ) ) == 0 )
195                                {
196                                        int j;
197                                       
198                                        for( j = 0; ent[i].is[j]; j ++ )
199                                                *(s++) = ent[i].is[j];
200                                       
201                                        matched = 1;
202                                        break;
203                                }
204
205                        /* None of the entities were matched, so return the string */
206                        if( !matched )
207                        {
208                                in = cs - 1;
209                                *(s++) = *(in++);
210                        }
211                }
212                else
213                {
214                        *(s++) = *(in++);
215                }
216        }
217       
218        strcpy( start, out );
219        g_free( out );
220}
221
222char *escape_html( const char *html )
223{
224        const char *c = html;
225        GString *ret;
226        char *str;
227       
228        if( html == NULL )
229                return( NULL );
230       
231        ret = g_string_new( "" );
232       
233        while( *c )
234        {
235                switch( *c )
236                {
237                        case '&':
238                                ret = g_string_append( ret, "&amp;" );
239                                break;
240                        case '<':
241                                ret = g_string_append( ret, "&lt;" );
242                                break;
243                        case '>':
244                                ret = g_string_append( ret, "&gt;" );
245                                break;
246                        case '"':
247                                ret = g_string_append( ret, "&quot;" );
248                                break;
249                        default:
250                                ret = g_string_append_c( ret, *c );
251                }
252                c ++;
253        }
254       
255        str = ret->str;
256        g_string_free( ret, FALSE );
257        return( str );
258}
259
260/* Decode%20a%20file%20name                                             */
261void http_decode( char *s )
262{
263        char *t;
264        int i, j, k;
265       
266        t = g_new( char, strlen( s ) + 1 );
267       
268        for( i = j = 0; s[i]; i ++, j ++ )
269        {
270                if( s[i] == '%' )
271                {
272                        if( sscanf( s + i + 1, "%2x", &k ) )
273                        {
274                                t[j] = k;
275                                i += 2;
276                        }
277                        else
278                        {
279                                *t = 0;
280                                break;
281                        }
282                }
283                else
284                {
285                        t[j] = s[i];
286                }
287        }
288        t[j] = 0;
289       
290        strcpy( s, t );
291        g_free( t );
292}
293
294/* Warning: This one explodes the string. Worst-cases can make the string 3x its original size! */
295/* This fuction is safe, but make sure you call it safely as well! */
296void http_encode( char *s )
297{
298        char *t;
299        int i, j;
300       
301        t = g_strdup( s );
302       
303        for( i = j = 0; t[i]; i ++, j ++ )
304        {
305                /* if( t[i] <= ' ' || ((unsigned char *)t)[i] >= 128 || t[i] == '%' ) */
306                if( !isalnum( t[i] ) )
307                {
308                        sprintf( s + j, "%%%02X", ((unsigned char*)t)[i] );
309                        j += 2;
310                }
311                else
312                {
313                        s[j] = t[i];
314                }
315        }
316        s[j] = 0;
317       
318        g_free( t );
319}
320
321/* Strip newlines from a string. Modifies the string passed to it. */ 
322char *strip_newlines( char *source )
323{
324        int i; 
325
326        for( i = 0; source[i] != '\0'; i ++ )
327                if( source[i] == '\n' || source[i] == '\r' )
328                        source[i] = ' ';
329       
330        return source;
331}
332
333/* Wrap an IPv4 address into IPv6 space. Not thread-safe... */
334char *ipv6_wrap( char *src )
335{
336        static char dst[64];
337        int i;
338       
339        for( i = 0; src[i]; i ++ )
340                if( ( src[i] < '0' || src[i] > '9' ) && src[i] != '.' )
341                        break;
342       
343        /* Hmm, it's not even an IP... */
344        if( src[i] )
345                return src;
346       
347        g_snprintf( dst, sizeof( dst ), "::ffff:%s", src );
348       
349        return dst;
350}
351
352/* Unwrap an IPv4 address into IPv6 space. Thread-safe, because it's very simple. :-) */
353char *ipv6_unwrap( char *src )
354{
355        int i;
356       
357        if( g_strncasecmp( src, "::ffff:", 7 ) != 0 )
358                return src;
359       
360        for( i = 7; src[i]; i ++ )
361                if( ( src[i] < '0' || src[i] > '9' ) && src[i] != '.' )
362                        break;
363       
364        /* Hmm, it's not even an IP... */
365        if( src[i] )
366                return src;
367       
368        return ( src + 7 );
369}
370
371/* Convert from one charset to another.
372   
373   from_cs, to_cs: Source and destination charsets
374   src, dst: Source and destination strings
375   size: Size if src. 0 == use strlen(). strlen() is not reliable for UNICODE/UTF16 strings though.
376   maxbuf: Maximum number of bytes to write to dst
377   
378   Returns the number of bytes written to maxbuf or -1 on an error.
379*/
380signed int do_iconv( char *from_cs, char *to_cs, char *src, char *dst, size_t size, size_t maxbuf )
381{
382        GIConv cd;
383        size_t res;
384        size_t inbytesleft, outbytesleft;
385        char *inbuf = src;
386        char *outbuf = dst;
387       
388        cd = g_iconv_open( to_cs, from_cs );
389        if( cd == (GIConv) -1 )
390                return( -1 );
391       
392        inbytesleft = size ? size : strlen( src );
393        outbytesleft = maxbuf - 1;
394        res = g_iconv( cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft );
395        *outbuf = '\0';
396        g_iconv_close( cd );
397       
398        if( res == (size_t) -1 )
399                return( -1 );
400        else
401                return( outbuf - dst );
402}
403
404/* A pretty reliable random number generator. Tries to use the /dev/random
405   devices first, and falls back to the random number generator from libc
406   when it fails. Opens randomizer devices with O_NONBLOCK to make sure a
407   lack of entropy won't halt BitlBee. */
408void random_bytes( unsigned char *buf, int count )
409{
410        static int use_dev = -1;
411       
412        /* Actually this probing code isn't really necessary, is it? */
413        if( use_dev == -1 )
414        {
415                if( access( "/dev/random", R_OK ) == 0 || access( "/dev/urandom", R_OK ) == 0 )
416                        use_dev = 1;
417                else
418                {
419                        use_dev = 0;
420                        srand( ( getpid() << 16 ) ^ time( NULL ) );
421                }
422        }
423       
424        if( use_dev )
425        {
426                int fd;
427               
428                /* At least on Linux, /dev/random can block if there's not
429                   enough entropy. We really don't want that, so if it can't
430                   give anything, use /dev/urandom instead. */
431                if( ( fd = open( "/dev/random", O_RDONLY | O_NONBLOCK ) ) >= 0 )
432                        if( read( fd, buf, count ) == count )
433                        {
434                                close( fd );
435                                return;
436                        }
437                close( fd );
438               
439                /* urandom isn't supposed to block at all, but just to be
440                   sure. If it blocks, we'll disable use_dev and use the libc
441                   randomizer instead. */
442                if( ( fd = open( "/dev/urandom", O_RDONLY | O_NONBLOCK ) ) >= 0 )
443                        if( read( fd, buf, count ) == count )
444                        {
445                                close( fd );
446                                return;
447                        }
448                close( fd );
449               
450                /* If /dev/random blocks once, we'll still try to use it
451                   again next time. If /dev/urandom also fails for some
452                   reason, stick with libc during this session. */
453               
454                use_dev = 0;
455                srand( ( getpid() << 16 ) ^ time( NULL ) );
456        }
457       
458        if( !use_dev )
459        {
460                int i;
461               
462                /* Possibly the LSB of rand() isn't very random on some
463                   platforms. Seems okay on at least Linux and OSX though. */
464                for( i = 0; i < count; i ++ )
465                        buf[i] = rand() & 0xff;
466        }
467}
468
469int is_bool( char *value )
470{
471        if( *value == 0 )
472                return 0;
473       
474        if( ( g_strcasecmp( value, "true" ) == 0 ) || ( g_strcasecmp( value, "yes" ) == 0 ) || ( g_strcasecmp( value, "on" ) == 0 ) )
475                return 1;
476        if( ( g_strcasecmp( value, "false" ) == 0 ) || ( g_strcasecmp( value, "no" ) == 0 ) || ( g_strcasecmp( value, "off" ) == 0 ) )
477                return 1;
478       
479        while( *value )
480                if( !isdigit( *value ) )
481                        return 0;
482                else
483                        value ++;
484       
485        return 1;
486}
487
488int bool2int( char *value )
489{
490        int i;
491       
492        if( ( g_strcasecmp( value, "true" ) == 0 ) || ( g_strcasecmp( value, "yes" ) == 0 ) || ( g_strcasecmp( value, "on" ) == 0 ) )
493                return 1;
494        if( ( g_strcasecmp( value, "false" ) == 0 ) || ( g_strcasecmp( value, "no" ) == 0 ) || ( g_strcasecmp( value, "off" ) == 0 ) )
495                return 0;
496       
497        if( sscanf( value, "%d", &i ) == 1 )
498                return i;
499       
500        return 0;
501}
502
503struct ns_srv_reply *srv_lookup( char *service, char *protocol, char *domain )
504{       
505        struct ns_srv_reply *reply = NULL;
506#ifdef HAVE_RESOLV_A
507        char name[1024];
508        unsigned char querybuf[1024];
509        const unsigned char *buf;
510        ns_msg nsh;
511        ns_rr rr;
512        int i, len, size;
513       
514        g_snprintf( name, sizeof( name ), "_%s._%s.%s", service, protocol, domain );
515       
516        if( ( size = res_query( name, ns_c_in, ns_t_srv, querybuf, sizeof( querybuf ) ) ) <= 0 )
517                return NULL;
518       
519        if( ns_initparse( querybuf, size, &nsh ) != 0 )
520                return NULL;
521       
522        if( ns_parserr( &nsh, ns_s_an, 0, &rr ) != 0 )
523                return NULL;
524       
525        size = ns_rr_rdlen( rr );
526        buf = ns_rr_rdata( rr );
527       
528        len = 0;
529        for( i = 6; i < size && buf[i]; i += buf[i] + 1 )
530                len += buf[i] + 1;
531       
532        if( i > size )
533                return NULL;
534       
535        reply = g_malloc( sizeof( struct ns_srv_reply ) + len );
536        memcpy( reply->name, buf + 7, len );
537       
538        for( i = buf[6]; i < len && buf[7+i]; i += buf[7+i] + 1 )
539                reply->name[i] = '.';
540       
541        if( i > len )
542        {
543                g_free( reply );
544                return NULL;
545        }
546       
547        reply->prio = ( buf[0] << 8 ) | buf[1];
548        reply->weight = ( buf[2] << 8 ) | buf[3];
549        reply->port = ( buf[4] << 8 ) | buf[5];
550#endif
551       
552        return reply;
553}
554
555/* Word wrapping. Yes, I know this isn't UTF-8 clean. I'm willing to take the risk. */
556char *word_wrap( char *msg, int line_len )
557{
558        GString *ret = g_string_sized_new( strlen( msg ) + 16 );
559       
560        while( strlen( msg ) > line_len )
561        {
562                int i;
563               
564                /* First try to find out if there's a newline already. Don't
565                   want to add more splits than necessary. */
566                for( i = line_len; i > 0 && msg[i] != '\n'; i -- );
567                if( msg[i] == '\n' )
568                {
569                        g_string_append_len( ret, msg, i + 1 );
570                        msg += i + 1;
571                        continue;
572                }
573               
574                for( i = line_len; i > 0; i -- )
575                {
576                        if( msg[i] == '-' )
577                        {
578                                g_string_append_len( ret, msg, i + 1 );
579                                g_string_append_c( ret, '\n' );
580                                msg += i + 1;
581                                break;
582                        }
583                        else if( msg[i] == ' ' )
584                        {
585                                g_string_append_len( ret, msg, i );
586                                g_string_append_c( ret, '\n' );
587                                msg += i + 1;
588                                break;
589                        }
590                }
591                if( i == 0 )
592                {
593                        g_string_append_len( ret, msg, line_len );
594                        g_string_append_c( ret, '\n' );
595                        msg += line_len;
596                }
597        }
598        g_string_append( ret, msg );
599       
600        return g_string_free( ret, FALSE );
601}
602
603gboolean ssl_sockerr_again( void *ssl )
604{
605        if( ssl )
606                return ssl_errno == SSL_AGAIN;
607        else
608                return sockerr_again();
609}
Note: See TracBrowser for help on using the repository browser.