source: lib/xmltree.c @ 0e788f5

Last change on this file since 0e788f5 was 0e788f5, checked in by Wilmer van der Gaast <wilmer@…>, at 2013-02-21T19:15:59Z

I'm still bored on a long flight. Wrote a script to automatically update
my copyright mentions since some were getting pretty stale. Left files not
touched since before 2012 alone so that this change doesn't touch almost
EVERY source file.

  • Property mode set to 100644
File size: 17.6 KB
RevLine 
[8f243ad]1/***************************************************************************\
2*                                                                           *
3*  BitlBee - An IRC to IM gateway                                           *
4*  Simple XML (stream) parse tree handling code (Jabber/XMPP, mainly)       *
5*                                                                           *
[0e788f5]6*  Copyright 2006-2012 Wilmer van der Gaast <wilmer@gaast.net>              *
[8f243ad]7*                                                                           *
8*  This library is free software; you can redistribute it and/or            *
9*  modify it under the terms of the GNU Lesser General Public               *
10*  License as published by the Free Software Foundation, version            *
11*  2.1.                                                                     *
12*                                                                           *
13*  This library is distributed in the hope that it will be useful,          *
14*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
15*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
16*  Lesser General Public License for more details.                          *
17*                                                                           *
18*  You should have received a copy of the GNU Lesser General Public License *
19*  along with this library; if not, write to the Free Software Foundation,  *
20*  Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA           *
21*                                                                           *
22****************************************************************************/
23
24#include <glib.h>
25#include <string.h>
26#include <unistd.h>
27#include <ctype.h>
28#include <stdio.h>
29
30#include "xmltree.h"
31
[7a2a486]32#define g_strcasecmp g_ascii_strcasecmp
33#define g_strncasecmp g_ascii_strncasecmp
34
[8f243ad]35static void xt_start_element( GMarkupParseContext *ctx, const gchar *element_name, const gchar **attr_names, const gchar **attr_values, gpointer data, GError **error )
36{
37        struct xt_parser *xt = data;
38        struct xt_node *node = g_new0( struct xt_node, 1 ), *nt;
39        int i;
40       
41        node->parent = xt->cur;
42        node->name = g_strdup( element_name );
43       
44        /* First count the number of attributes */
45        for( i = 0; attr_names[i]; i ++ );
46       
47        /* Then allocate a NULL-terminated array. */
48        node->attr = g_new0( struct xt_attr, i + 1 );
49       
50        /* And fill it, saving one variable by starting at the end. */
51        for( i --; i >= 0; i -- )
52        {
53                node->attr[i].key = g_strdup( attr_names[i] );
54                node->attr[i].value = g_strdup( attr_values[i] );
55        }
56       
57        /* Add it to the linked list of children nodes, if we have a current
58           node yet. */
59        if( xt->cur )
60        {
61                if( xt->cur->children )
62                {
63                        for( nt = xt->cur->children; nt->next; nt = nt->next );
64                        nt->next = node;
65                }
66                else
67                {
68                        xt->cur->children = node;
69                }
70        }
71        else if( xt->root )
72        {
73                /* ERROR situation: A second root-element??? */
74        }
75       
76        /* Now this node will be the new current node. */
77        xt->cur = node;
78        /* And maybe this is the root? */
79        if( xt->root == NULL )
80                xt->root = node;
81}
82
83static void xt_text( GMarkupParseContext *ctx, const gchar *text, gsize text_len, gpointer data, GError **error )
84{
85        struct xt_parser *xt = data;
86        struct xt_node *node = xt->cur;
87       
88        if( node == NULL )
89                return;
90       
91        /* FIXME: Does g_renew also OFFICIALLY accept NULL arguments? */
92        node->text = g_renew( char, node->text, node->text_len + text_len + 1 );
93        memcpy( node->text + node->text_len, text, text_len );
94        node->text_len += text_len;
95        /* Zero termination is always nice to have. */
96        node->text[node->text_len] = 0;
97}
98
99static void xt_end_element( GMarkupParseContext *ctx, const gchar *element_name, gpointer data, GError **error )
100{
101        struct xt_parser *xt = data;
102       
103        xt->cur->flags |= XT_COMPLETE;
104        xt->cur = xt->cur->parent;
105}
106
107GMarkupParser xt_parser_funcs =
108{
109        xt_start_element,
110        xt_end_element,
111        xt_text,
112        NULL,
113        NULL
114};
115
[4bbcba3]116struct xt_parser *xt_new( const struct xt_handler_entry *handlers, gpointer data )
[8f243ad]117{
118        struct xt_parser *xt = g_new0( struct xt_parser, 1 );
119       
120        xt->data = data;
[4bbcba3]121        xt->handlers = handlers;
[8f243ad]122        xt_reset( xt );
123       
124        return xt;
125}
126
127/* Reset the parser, flush everything we have so far. For example, we need
128   this for XMPP when doing TLS/SASL to restart the stream. */
129void xt_reset( struct xt_parser *xt )
130{
131        if( xt->parser )
132                g_markup_parse_context_free( xt->parser );
133       
134        xt->parser = g_markup_parse_context_new( &xt_parser_funcs, 0, xt, NULL );
135       
136        if( xt->root )
137        {
138                xt_free_node( xt->root );
139                xt->root = NULL;
140                xt->cur = NULL;
141        }
142}
143
144/* Feed the parser, don't execute any handler. Returns -1 on errors, 0 on
145   end-of-stream and 1 otherwise. */
[d93c0eb9]146int xt_feed( struct xt_parser *xt, const char *text, int text_len )
[8f243ad]147{
148        if( !g_markup_parse_context_parse( xt->parser, text, text_len, &xt->gerr ) )
149        {
150                return -1;
151        }
152       
153        return !( xt->root && xt->root->flags & XT_COMPLETE );
154}
155
156/* Find completed nodes and see if a handler has to be called. Passing
157   a node isn't necessary if you want to start at the root, just pass
[101d84f]158   NULL. This second argument is needed for recursive calls. */
159int xt_handle( struct xt_parser *xt, struct xt_node *node, int depth )
[8f243ad]160{
161        struct xt_node *c;
162        xt_status st;
163        int i;
164       
[101d84f]165        if( xt->root == NULL )
[b0ee720]166                return 1;
[101d84f]167       
[8f243ad]168        if( node == NULL )
[101d84f]169                return xt_handle( xt, xt->root, depth );
[8f243ad]170       
[101d84f]171        if( depth != 0 )
172                for( c = node->children; c; c = c->next )
173                        if( !xt_handle( xt, c, depth > 0 ? depth - 1 : depth ) )
174                                return 0;
[8f243ad]175       
176        if( node->flags & XT_COMPLETE && !( node->flags & XT_SEEN ) )
177        {
[4452e69]178                if( xt->handlers ) for( i = 0; xt->handlers[i].func; i ++ )
[8f243ad]179                {
180                        /* This one is fun! \o/ */
181                       
[4452e69]182                            /* If handler.name == NULL it means it should always match. */
[8f243ad]183                        if( ( xt->handlers[i].name == NULL || 
[4452e69]184                              /* If it's not, compare. There should always be a name. */
[8f243ad]185                              g_strcasecmp( xt->handlers[i].name, node->name ) == 0 ) &&
[4452e69]186                            /* If handler.parent == NULL, it's a match. */
[8f243ad]187                            ( xt->handlers[i].parent == NULL ||
[4452e69]188                              /* If there's a parent node, see if the name matches. */
[8f243ad]189                              ( node->parent ? g_strcasecmp( xt->handlers[i].parent, node->parent->name ) == 0 : 
[4452e69]190                              /* If there's no parent, the handler should mention <root> as a parent. */
191                                               strcmp( xt->handlers[i].parent, "<root>" ) == 0 ) ) )
[8f243ad]192                        {
193                                st = xt->handlers[i].func( node, xt->data );
194                               
195                                if( st == XT_ABORT )
196                                        return 0;
197                                else if( st != XT_NEXT )
198                                        break;
199                        }
200                }
201               
202                node->flags |= XT_SEEN;
203        }
204       
205        return 1;
206}
207
208/* Garbage collection: Cleans up all nodes that are handled. Useful for
209   streams because there's no reason to keep a complete packet history
210   in memory. */
[101d84f]211void xt_cleanup( struct xt_parser *xt, struct xt_node *node, int depth )
[8f243ad]212{
213        struct xt_node *c, *prev;
214       
[21167d2]215        if( !xt || !xt->root )
216                return;
217       
[8f243ad]218        if( node == NULL )
[daae10f]219        {
220                xt_cleanup( xt, xt->root, depth );
221                return;
222        }
[8f243ad]223       
224        if( node->flags & XT_SEEN && node == xt->root )
225        {
226                xt_free_node( xt->root );
227                xt->root = xt->cur = NULL;
228                /* xt->cur should be NULL already, BTW... */
229               
230                return;
231        }
232       
233        /* c contains the current node, prev the previous node (or NULL).
234           I admit, this one's pretty horrible. */
235        for( c = node->children, prev = NULL; c; prev = c, c = c ? c->next : node->children )
236        {
237                if( c->flags & XT_SEEN )
238                {
239                        /* Remove the node from the linked list. */
240                        if( prev )
241                                prev->next = c->next;
242                        else
243                                node->children = c->next;
244                       
245                        xt_free_node( c );
246                       
247                        /* Since the for loop wants to get c->next, make sure
248                           c points at something that exists (and that c->next
249                           will actually be the next item we should check). c
250                           can be NULL now, if we just removed the first item.
251                           That explains the ? thing in for(). */
252                        c = prev;
253                }
254                else
255                {
256                        /* This node can't be cleaned up yet, but maybe a
257                           subnode can. */
[101d84f]258                        if( depth != 0 )
259                                xt_cleanup( xt, c, depth > 0 ? depth - 1 : depth );
[8f243ad]260                }
261        }
262}
263
[d0752e8]264struct xt_node *xt_from_string( const char *in, int len )
[d93c0eb9]265{
266        struct xt_parser *parser;
[6f55bec]267        struct xt_node *ret = NULL;
[d93c0eb9]268       
[d0752e8]269        if( len == 0 )
270                len = strlen( in );
271       
[d93c0eb9]272        parser = xt_new( NULL, NULL );
[d0752e8]273        xt_feed( parser, in, len );
[6f55bec]274        if( parser->cur == NULL )
275        {
276                ret = parser->root;
277                parser->root = NULL;
278        }
[d93c0eb9]279        xt_free( parser );
280       
281        return ret;
282}
283
[8f243ad]284static void xt_to_string_real( struct xt_node *node, GString *str )
285{
286        char *buf;
287        struct xt_node *c;
288        int i;
289       
290        g_string_append_printf( str, "<%s", node->name );
291       
292        for( i = 0; node->attr[i].key; i ++ )
293        {
294                buf = g_markup_printf_escaped( " %s=\"%s\"", node->attr[i].key, node->attr[i].value );
295                g_string_append( str, buf );
296                g_free( buf );
297        }
298       
299        if( node->text == NULL && node->children == NULL )
300        {
301                g_string_append( str, "/>" );
302                return;
303        }
304       
305        g_string_append( str, ">" );
306        if( node->text_len > 0 )
307        {
308                buf = g_markup_escape_text( node->text, node->text_len );
309                g_string_append( str, buf );
310                g_free( buf );
311        }
312       
313        for( c = node->children; c; c = c->next )
314                xt_to_string_real( c, str );
315       
316        g_string_append_printf( str, "</%s>", node->name );
317}
318
319char *xt_to_string( struct xt_node *node )
320{
321        GString *ret;
322        char *real;
323       
324        ret = g_string_new( "" );
325        xt_to_string_real( node, ret );
326       
327        real = ret->str;
328        g_string_free( ret, FALSE );
329       
330        return real;
331}
332
333void xt_print( struct xt_node *node )
334{
335        int i;
336        struct xt_node *c;
337       
338        /* Indentation */
339        for( c = node; c->parent; c = c->parent )
[ca974d7]340                fprintf( stderr, "    " );
[8f243ad]341       
342        /* Start the tag */
[ca974d7]343        fprintf( stderr, "<%s", node->name );
[8f243ad]344       
345        /* Print the attributes */
346        for( i = 0; node->attr[i].key; i ++ )
[327af51]347        {
348                char *v = g_markup_escape_text( node->attr[i].value, -1 );
[ca974d7]349                fprintf( stderr, " %s=\"%s\"", node->attr[i].key, v );
[327af51]350                g_free( v );
351        }
[8f243ad]352       
353        /* /> in case there's really *nothing* inside this tag, otherwise
354           just >. */
355        /* If this tag doesn't have any content at all... */
356        if( node->text == NULL && node->children == NULL )
357        {
[ca974d7]358                fprintf( stderr, "/>\n" );
[8f243ad]359                return;
360                /* Then we're finished! */
361        }
362       
363        /* Otherwise... */
[ca974d7]364        fprintf( stderr, ">" );
[8f243ad]365       
366        /* Only print the text if it contains more than whitespace (TEST). */
367        if( node->text_len > 0 )
368        {
369                for( i = 0; node->text[i] && isspace( node->text[i] ); i ++ );
370                if( node->text[i] )
[327af51]371                {
372                        char *v = g_markup_escape_text( node->text, -1 );
[ca974d7]373                        fprintf( stderr, "%s", v );
[327af51]374                        g_free( v );
375                }
[8f243ad]376        }
377       
378        if( node->children )
[ca974d7]379                fprintf( stderr, "\n" );
[8f243ad]380       
381        for( c = node->children; c; c = c->next )
382                xt_print( c );
383       
384        if( node->children )
385                for( c = node; c->parent; c = c->parent )
[ca974d7]386                        fprintf( stderr, "    " );
[8f243ad]387       
388        /* Non-empty tag is now finished. */
[ca974d7]389        fprintf( stderr, "</%s>\n", node->name );
[8f243ad]390}
391
[022df46]392struct xt_node *xt_dup( struct xt_node *node )
393{
394        struct xt_node *dup = g_new0( struct xt_node, 1 );
395        struct xt_node *c, *dc = NULL;
396        int i;
397       
398        /* Let's NOT copy the parent element here BTW! Only do it for children. */
399       
400        dup->name = g_strdup( node->name );
401        dup->flags = node->flags;
402        if( node->text )
403        {
404                dup->text = g_memdup( node->text, node->text_len + 1 );
405                dup->text_len = node->text_len;
406        }
407       
408        /* Count the number of attributes and allocate the new array. */
409        for( i = 0; node->attr[i].key; i ++ );
410        dup->attr = g_new0( struct xt_attr, i + 1 );
411       
412        /* Copy them all! */
413        for( i --; i >= 0; i -- )
414        {
415                dup->attr[i].key = g_strdup( node->attr[i].key );
416                dup->attr[i].value = g_strdup( node->attr[i].value );
417        }
418       
419        /* This nice mysterious loop takes care of the children. */
420        for( c = node->children; c; c = c->next )
421        {
422                if( dc == NULL )
423                        dc = dup->children = xt_dup( c );
424                else
425                        dc = ( dc->next = xt_dup( c ) );
426               
427                dc->parent = dup;
428        }
429       
430        return dup;
431}
432
[8f243ad]433/* Frees a node. This doesn't clean up references to itself from parents! */
434void xt_free_node( struct xt_node *node )
435{
436        int i;
437       
[21167d2]438        if( !node )
439                return;
440       
[8f243ad]441        g_free( node->name );
442        g_free( node->text );
443       
444        for( i = 0; node->attr[i].key; i ++ )
445        {
446                g_free( node->attr[i].key );
447                g_free( node->attr[i].value );
448        }
449        g_free( node->attr );
450       
451        while( node->children )
452        {
453                struct xt_node *next = node->children->next;
454               
455                xt_free_node( node->children );
456                node->children = next;
457        }
458       
459        g_free( node );
460}
461
462void xt_free( struct xt_parser *xt )
463{
[21167d2]464        if( !xt )
465                return;
466       
[8f243ad]467        if( xt->root )
468                xt_free_node( xt->root );
469       
470        g_markup_parse_context_free( xt->parser );
471       
472        g_free( xt );
473}
474
475/* To find a node's child with a specific name, pass the node's children
476   list, not the node itself! The reason you have to do this by hand: So
477   that you can also use this function as a find-next. */
[40ef702]478struct xt_node *xt_find_node( struct xt_node *node, const char *name )
[8f243ad]479{
480        while( node )
481        {
[3742fb6]482                char *colon;
483               
484                if( g_strcasecmp( node->name, name ) == 0 ||
485                    ( ( colon = strchr( node->name, ':' ) ) &&
486                      g_strcasecmp( colon + 1, name ) == 0 ) )
[8f243ad]487                        break;
488               
489                node = node->next;
490        }
491       
492        return node;
493}
494
[d912fe4]495/* More advanced than the one above, understands something like
496   ../foo/bar to find a subnode bar of a node foo which is a child
497   of node's parent. Pass the node directly, not its list of children. */
498struct xt_node *xt_find_path( struct xt_node *node, const char *name )
499{
500        while( name && *name && node )
501        {
502                char *colon, *slash;
503                int n;
504               
505                if( ( slash = strchr( name, '/' ) ) )
506                        n = slash - name;
507                else
508                        n = strlen( name );
509               
510                if( strncmp( name, "..", n ) == 0 )
511                {
512                        node = node->parent;
513                }
514                else
515                {
516                        node = node->children;
517                       
518                        while( node )
519                        {
520                                if( g_strncasecmp( node->name, name, n ) == 0 ||
521                                    ( ( colon = strchr( node->name, ':' ) ) &&
522                                      g_strncasecmp( colon + 1, name, n ) == 0 ) )
523                                        break;
524                               
525                                node = node->next;
526                        }
527                }
528               
529                name = slash ? slash + 1 : NULL;
530        }
531       
532        return node;
533}
534
[40ef702]535char *xt_find_attr( struct xt_node *node, const char *key )
[8f243ad]536{
537        int i;
[3742fb6]538        char *colon;
[8f243ad]539       
[21167d2]540        if( !node )
541                return NULL;
542       
[8f243ad]543        for( i = 0; node->attr[i].key; i ++ )
544                if( g_strcasecmp( node->attr[i].key, key ) == 0 )
545                        break;
546       
[3742fb6]547        /* This is an awful hack that only takes care of namespace prefixes
548           inside a tag. Since IMHO excessive namespace usage in XMPP is
549           massive overkill anyway (this code exists for almost four years
550           now and never really missed it): Meh. */
551        if( !node->attr[i].key && strcmp( key, "xmlns" ) == 0 &&
552            ( colon = strchr( node->name, ':' ) ) )
553        {
554                *colon = '\0';
555                for( i = 0; node->attr[i].key; i ++ )
556                        if( strncmp( node->attr[i].key, "xmlns:", 6 ) == 0 &&
557                            strcmp( node->attr[i].key + 6, node->name ) == 0 )
558                                break;
559                *colon = ':';
560        }
561       
[8f243ad]562        return node->attr[i].value;
563}
564
[e6b41b1]565/* Strip a few non-printable characters that aren't allowed in XML streams
566   (and upset some XMPP servers for example). */
567void xt_strip_text( char *in )
568{
569        char *out = in;
570        static const char nonprint[32] = {
571                0, 0, 0, 0, 0, 0, 0, 0, /* 0..7 */
572                0, 1, 1, 0, 0, 1, 0, 0, /* 9 (tab), 10 (\n), 13 (\r) */
573        };
574       
575        if( !in )
576                return;
577
578        while( *in )
579        {
580                if( (unsigned int) *in >= ' ' || nonprint[(unsigned int) *in] )
581                        *out ++ = *in;
582                in ++;
583        }
584        *out = *in;
585}
586
[94acdd0]587struct xt_node *xt_new_node( char *name, const char *text, struct xt_node *children )
[8f243ad]588{
589        struct xt_node *node, *c;
590       
591        node = g_new0( struct xt_node, 1 );
592        node->name = g_strdup( name );
593        node->children = children;
594        node->attr = g_new0( struct xt_attr, 1 );
595       
596        if( text )
597        {
[e6b41b1]598                node->text = g_strdup( text );
599                xt_strip_text( node->text );
600                node->text_len = strlen( node->text );
[8f243ad]601        }
602       
603        for( c = children; c; c = c->next )
604        {
605                if( c->parent != NULL )
606                {
607                        /* ERROR CONDITION: They seem to have a parent already??? */
608                }
609               
610                c->parent = node;
611        }
612       
613        return node;
614}
615
616void xt_add_child( struct xt_node *parent, struct xt_node *child )
617{
618        struct xt_node *node;
619       
620        /* This function can actually be used to add more than one child, so
621           do handle this properly. */
622        for( node = child; node; node = node->next )
623        {
624                if( node->parent != NULL )
625                {
626                        /* ERROR CONDITION: They seem to have a parent already??? */
627                }
628               
629                node->parent = parent;
630        }
631       
632        if( parent->children == NULL )
633        {
634                parent->children = child;
635        }
636        else
637        {
638                for( node = parent->children; node->next; node = node->next );
639                node->next = child;
640        }
641}
642
[b46769d]643/* Same, but at the beginning. */
644void xt_insert_child( struct xt_node *parent, struct xt_node *child )
645{
[afb9ea9]646        struct xt_node *node, *last = NULL;
647       
648        if( child == NULL )
649                return; /* BUG */
[b46769d]650       
651        for( node = child; node; node = node->next )
652        {
653                if( node->parent != NULL )
654                {
655                        /* ERROR CONDITION: They seem to have a parent already??? */
656                }
657               
658                node->parent = parent;
659                last = node;
660        }
661       
662        last->next = parent->children;
663        parent->children = child;
664}
665
[40ef702]666void xt_add_attr( struct xt_node *node, const char *key, const char *value )
[8f243ad]667{
668        int i;
669       
[090f1cb]670        /* Now actually it'd be nice if we can also change existing attributes
671           (which actually means this function doesn't have the right name).
672           So let's find out if we have this attribute already... */
673        for( i = 0; node->attr[i].key; i ++ )
674                if( strcmp( node->attr[i].key, key ) == 0 )
675                        break;
676       
677        if( node->attr[i].key == NULL )
678        {
679                /* If not, allocate space for a new attribute. */
680                node->attr = g_renew( struct xt_attr, node->attr, i + 2 );
681                node->attr[i].key = g_strdup( key );
682                node->attr[i+1].key = NULL;
683        }
684        else
685        {
686                /* Otherwise, free the old value before setting the new one. */
687                g_free( node->attr[i].value );
688        }
689       
[8f243ad]690        node->attr[i].value = g_strdup( value );
691}
[259edd4]692
[40ef702]693int xt_remove_attr( struct xt_node *node, const char *key )
[259edd4]694{
695        int i, last;
696       
697        for( i = 0; node->attr[i].key; i ++ )
698                if( strcmp( node->attr[i].key, key ) == 0 )
699                        break;
700       
701        /* If we didn't find the attribute... */
702        if( node->attr[i].key == NULL )
703                return 0;
704       
705        g_free( node->attr[i].key );
706        g_free( node->attr[i].value );
707       
708        /* If it's the last, this is easy: */
709        if( node->attr[i+1].key == NULL )
710        {
711                node->attr[i].key = node->attr[i].value = NULL;
712        }
713        else /* It's also pretty easy, actually. */
714        {
715                /* Find the last item. */
716                for( last = i + 1; node->attr[last+1].key; last ++ );
717               
718                node->attr[i] = node->attr[last];
719                node->attr[last].key = NULL;
720                node->attr[last].value = NULL;
721        }
722       
723        /* Let's not bother with reallocating memory here. It takes time and
724           most packets don't stay in memory for long anyway. */
725       
726        return 1;
727}
Note: See TracBrowser for help on using the repository browser.