source: lib/misc.c @ ca60550

Last change on this file since ca60550 was 613cc55, checked in by Wilmer van der Gaast <wilmer@…>, at 2008-01-24T22:22:46Z

Fixed two valgrind warnings (partially uninitialized "struct tm" vars.)

  • Property mode set to 100644
File size: 12.5 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        { "quot",   "\"" },
115        { "aacute", "á" },
116        { "eacute", "é" },
117        { "iacute", "é" },
118        { "oacute", "ó" },
119        { "uacute", "ú" },
120        { "agrave", "à" },
121        { "egrave", "è" },
122        { "igrave", "ì" },
123        { "ograve", "ò" },
124        { "ugrave", "ù" },
125        { "acirc",  "â" },
126        { "ecirc",  "ê" },
127        { "icirc",  "î" },
128        { "ocirc",  "ô" },
129        { "ucirc",  "û" },
130        { "auml",   "ä" },
131        { "euml",   "ë" },
132        { "iuml",   "ï" },
133        { "ouml",   "ö" },
134        { "uuml",   "ü" },
135        { "nbsp",   " " },
136        { "",        ""  }
137};
138
139void strip_html( char *in )
140{
141        char *start = in;
142        char *out = g_malloc( strlen( in ) + 1 );
143        char *s = out, *cs;
144        int i, matched;
145       
146        memset( out, 0, strlen( in ) + 1 );
147       
148        while( *in )
149        {
150                if( *in == '<' && ( isalpha( *(in+1) ) || *(in+1) == '/' ) )
151                {
152                        /* If in points at a < and in+1 points at a letter or a slash, this is probably
153                           a HTML-tag. Try to find a closing > and continue there. If the > can't be
154                           found, assume that it wasn't a HTML-tag after all. */
155                       
156                        cs = in;
157                       
158                        while( *in && *in != '>' )
159                                in ++;
160                       
161                        if( *in )
162                        {
163                                if( g_strncasecmp( cs+1, "br", 2) == 0 )
164                                        *(s++) = '\n';
165                                in ++;
166                        }
167                        else
168                        {
169                                in = cs;
170                                *(s++) = *(in++);
171                        }
172                }
173                else if( *in == '&' )
174                {
175                        cs = ++in;
176                        while( *in && isalpha( *in ) )
177                                in ++;
178                       
179                        if( *in == ';' ) in ++;
180                        matched = 0;
181                       
182                        for( i = 0; *ent[i].code; i ++ )
183                                if( g_strncasecmp( ent[i].code, cs, strlen( ent[i].code ) ) == 0 )
184                                {
185                                        int j;
186                                       
187                                        for( j = 0; ent[i].is[j]; j ++ )
188                                                *(s++) = ent[i].is[j];
189                                       
190                                        matched = 1;
191                                        break;
192                                }
193
194                        /* None of the entities were matched, so return the string */
195                        if( !matched )
196                        {
197                                in = cs - 1;
198                                *(s++) = *(in++);
199                        }
200                }
201                else
202                {
203                        *(s++) = *(in++);
204                }
205        }
206       
207        strcpy( start, out );
208        g_free( out );
209}
210
211char *escape_html( const char *html )
212{
213        const char *c = html;
214        GString *ret;
215        char *str;
216       
217        if( html == NULL )
218                return( NULL );
219       
220        ret = g_string_new( "" );
221       
222        while( *c )
223        {
224                switch( *c )
225                {
226                        case '&':
227                                ret = g_string_append( ret, "&amp;" );
228                                break;
229                        case '<':
230                                ret = g_string_append( ret, "&lt;" );
231                                break;
232                        case '>':
233                                ret = g_string_append( ret, "&gt;" );
234                                break;
235                        case '"':
236                                ret = g_string_append( ret, "&quot;" );
237                                break;
238                        default:
239                                ret = g_string_append_c( ret, *c );
240                }
241                c ++;
242        }
243       
244        str = ret->str;
245        g_string_free( ret, FALSE );
246        return( str );
247}
248
249/* Decode%20a%20file%20name                                             */
250void http_decode( char *s )
251{
252        char *t;
253        int i, j, k;
254       
255        t = g_new( char, strlen( s ) + 1 );
256       
257        for( i = j = 0; s[i]; i ++, j ++ )
258        {
259                if( s[i] == '%' )
260                {
261                        if( sscanf( s + i + 1, "%2x", &k ) )
262                        {
263                                t[j] = k;
264                                i += 2;
265                        }
266                        else
267                        {
268                                *t = 0;
269                                break;
270                        }
271                }
272                else
273                {
274                        t[j] = s[i];
275                }
276        }
277        t[j] = 0;
278       
279        strcpy( s, t );
280        g_free( t );
281}
282
283/* Warning: This one explodes the string. Worst-cases can make the string 3x its original size! */
284/* This fuction is safe, but make sure you call it safely as well! */
285void http_encode( char *s )
286{
287        char *t;
288        int i, j;
289       
290        t = g_strdup( s );
291       
292        for( i = j = 0; t[i]; i ++, j ++ )
293        {
294                /* if( t[i] <= ' ' || ((unsigned char *)t)[i] >= 128 || t[i] == '%' ) */
295                if( !isalnum( t[i] ) )
296                {
297                        sprintf( s + j, "%%%02X", ((unsigned char*)t)[i] );
298                        j += 2;
299                }
300                else
301                {
302                        s[j] = t[i];
303                }
304        }
305        s[j] = 0;
306       
307        g_free( t );
308}
309
310/* Strip newlines from a string. Modifies the string passed to it. */ 
311char *strip_newlines( char *source )
312{
313        int i; 
314
315        for( i = 0; source[i] != '\0'; i ++ )
316                if( source[i] == '\n' || source[i] == '\r' )
317                        source[i] = ' ';
318       
319        return source;
320}
321
322/* Wrap an IPv4 address into IPv6 space. Not thread-safe... */
323char *ipv6_wrap( char *src )
324{
325        static char dst[64];
326        int i;
327       
328        for( i = 0; src[i]; i ++ )
329                if( ( src[i] < '0' || src[i] > '9' ) && src[i] != '.' )
330                        break;
331       
332        /* Hmm, it's not even an IP... */
333        if( src[i] )
334                return src;
335       
336        g_snprintf( dst, sizeof( dst ), "::ffff:%s", src );
337       
338        return dst;
339}
340
341/* Unwrap an IPv4 address into IPv6 space. Thread-safe, because it's very simple. :-) */
342char *ipv6_unwrap( char *src )
343{
344        int i;
345       
346        if( g_strncasecmp( src, "::ffff:", 7 ) != 0 )
347                return src;
348       
349        for( i = 7; src[i]; i ++ )
350                if( ( src[i] < '0' || src[i] > '9' ) && src[i] != '.' )
351                        break;
352       
353        /* Hmm, it's not even an IP... */
354        if( src[i] )
355                return src;
356       
357        return ( src + 7 );
358}
359
360/* Convert from one charset to another.
361   
362   from_cs, to_cs: Source and destination charsets
363   src, dst: Source and destination strings
364   size: Size if src. 0 == use strlen(). strlen() is not reliable for UNICODE/UTF16 strings though.
365   maxbuf: Maximum number of bytes to write to dst
366   
367   Returns the number of bytes written to maxbuf or -1 on an error.
368*/
369signed int do_iconv( char *from_cs, char *to_cs, char *src, char *dst, size_t size, size_t maxbuf )
370{
371        GIConv cd;
372        size_t res;
373        size_t inbytesleft, outbytesleft;
374        char *inbuf = src;
375        char *outbuf = dst;
376       
377        cd = g_iconv_open( to_cs, from_cs );
378        if( cd == (GIConv) -1 )
379                return( -1 );
380       
381        inbytesleft = size ? size : strlen( src );
382        outbytesleft = maxbuf - 1;
383        res = g_iconv( cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft );
384        *outbuf = '\0';
385        g_iconv_close( cd );
386       
387        if( res == (size_t) -1 )
388                return( -1 );
389        else
390                return( outbuf - dst );
391}
392
393/* A pretty reliable random number generator. Tries to use the /dev/random
394   devices first, and falls back to the random number generator from libc
395   when it fails. Opens randomizer devices with O_NONBLOCK to make sure a
396   lack of entropy won't halt BitlBee. */
397void random_bytes( unsigned char *buf, int count )
398{
399        static int use_dev = -1;
400       
401        /* Actually this probing code isn't really necessary, is it? */
402        if( use_dev == -1 )
403        {
404                if( access( "/dev/random", R_OK ) == 0 || access( "/dev/urandom", R_OK ) == 0 )
405                        use_dev = 1;
406                else
407                {
408                        use_dev = 0;
409                        srand( ( getpid() << 16 ) ^ time( NULL ) );
410                }
411        }
412       
413        if( use_dev )
414        {
415                int fd;
416               
417                /* At least on Linux, /dev/random can block if there's not
418                   enough entropy. We really don't want that, so if it can't
419                   give anything, use /dev/urandom instead. */
420                if( ( fd = open( "/dev/random", O_RDONLY | O_NONBLOCK ) ) >= 0 )
421                        if( read( fd, buf, count ) == count )
422                        {
423                                close( fd );
424                                return;
425                        }
426                close( fd );
427               
428                /* urandom isn't supposed to block at all, but just to be
429                   sure. If it blocks, we'll disable use_dev and use the libc
430                   randomizer instead. */
431                if( ( fd = open( "/dev/urandom", O_RDONLY | O_NONBLOCK ) ) >= 0 )
432                        if( read( fd, buf, count ) == count )
433                        {
434                                close( fd );
435                                return;
436                        }
437                close( fd );
438               
439                /* If /dev/random blocks once, we'll still try to use it
440                   again next time. If /dev/urandom also fails for some
441                   reason, stick with libc during this session. */
442               
443                use_dev = 0;
444                srand( ( getpid() << 16 ) ^ time( NULL ) );
445        }
446       
447        if( !use_dev )
448        {
449                int i;
450               
451                /* Possibly the LSB of rand() isn't very random on some
452                   platforms. Seems okay on at least Linux and OSX though. */
453                for( i = 0; i < count; i ++ )
454                        buf[i] = rand() & 0xff;
455        }
456}
457
458int is_bool( char *value )
459{
460        if( *value == 0 )
461                return 0;
462       
463        if( ( g_strcasecmp( value, "true" ) == 0 ) || ( g_strcasecmp( value, "yes" ) == 0 ) || ( g_strcasecmp( value, "on" ) == 0 ) )
464                return 1;
465        if( ( g_strcasecmp( value, "false" ) == 0 ) || ( g_strcasecmp( value, "no" ) == 0 ) || ( g_strcasecmp( value, "off" ) == 0 ) )
466                return 1;
467       
468        while( *value )
469                if( !isdigit( *value ) )
470                        return 0;
471                else
472                        value ++;
473       
474        return 1;
475}
476
477int bool2int( char *value )
478{
479        int i;
480       
481        if( ( g_strcasecmp( value, "true" ) == 0 ) || ( g_strcasecmp( value, "yes" ) == 0 ) || ( g_strcasecmp( value, "on" ) == 0 ) )
482                return 1;
483        if( ( g_strcasecmp( value, "false" ) == 0 ) || ( g_strcasecmp( value, "no" ) == 0 ) || ( g_strcasecmp( value, "off" ) == 0 ) )
484                return 0;
485       
486        if( sscanf( value, "%d", &i ) == 1 )
487                return i;
488       
489        return 0;
490}
491
492struct ns_srv_reply *srv_lookup( char *service, char *protocol, char *domain )
493{       
494        struct ns_srv_reply *reply = NULL;
495#ifdef HAVE_RESOLV_A
496        char name[1024];
497        unsigned char querybuf[1024];
498        const unsigned char *buf;
499        ns_msg nsh;
500        ns_rr rr;
501        int i, len, size;
502       
503        g_snprintf( name, sizeof( name ), "_%s._%s.%s", service, protocol, domain );
504       
505        if( ( size = res_query( name, ns_c_in, ns_t_srv, querybuf, sizeof( querybuf ) ) ) <= 0 )
506                return NULL;
507       
508        if( ns_initparse( querybuf, size, &nsh ) != 0 )
509                return NULL;
510       
511        if( ns_parserr( &nsh, ns_s_an, 0, &rr ) != 0 )
512                return NULL;
513       
514        size = ns_rr_rdlen( rr );
515        buf = ns_rr_rdata( rr );
516       
517        len = 0;
518        for( i = 6; i < size && buf[i]; i += buf[i] + 1 )
519                len += buf[i] + 1;
520       
521        if( i > size )
522                return NULL;
523       
524        reply = g_malloc( sizeof( struct ns_srv_reply ) + len );
525        memcpy( reply->name, buf + 7, len );
526       
527        for( i = buf[6]; i < len && buf[7+i]; i += buf[7+i] + 1 )
528                reply->name[i] = '.';
529       
530        if( i > len )
531        {
532                g_free( reply );
533                return NULL;
534        }
535       
536        reply->prio = ( buf[0] << 8 ) | buf[1];
537        reply->weight = ( buf[2] << 8 ) | buf[3];
538        reply->port = ( buf[4] << 8 ) | buf[5];
539#endif
540       
541        return reply;
542}
543
544/* Word wrapping. Yes, I know this isn't UTF-8 clean. I'm willing to take the risk. */
545char *word_wrap( char *msg, int line_len )
546{
547        GString *ret = g_string_sized_new( strlen( msg ) + 16 );
548       
549        while( strlen( msg ) > line_len )
550        {
551                int i;
552               
553                /* First try to find out if there's a newline already. Don't
554                   want to add more splits than necessary. */
555                for( i = line_len; i > 0 && msg[i] != '\n'; i -- );
556                if( msg[i] == '\n' )
557                {
558                        g_string_append_len( ret, msg, i + 1 );
559                        msg += i + 1;
560                        continue;
561                }
562               
563                for( i = line_len; i > 0; i -- )
564                {
565                        if( msg[i] == '-' )
566                        {
567                                g_string_append_len( ret, msg, i + 1 );
568                                g_string_append_c( ret, '\n' );
569                                msg += i + 1;
570                                break;
571                        }
572                        else if( msg[i] == ' ' )
573                        {
574                                g_string_append_len( ret, msg, i );
575                                g_string_append_c( ret, '\n' );
576                                msg += i + 1;
577                                break;
578                        }
579                }
580                if( i == 0 )
581                {
582                        g_string_append_len( ret, msg, line_len );
583                        g_string_append_c( ret, '\n' );
584                        msg += line_len;
585                }
586        }
587        g_string_append( ret, msg );
588       
589        return g_string_free( ret, FALSE );
590}
591
592gboolean ssl_sockerr_again( void *ssl )
593{
594        if( ssl )
595                return ssl_errno == SSL_AGAIN;
596        else
597                return sockerr_again();
598}
Note: See TracBrowser for help on using the repository browser.