removing signedness warnings coming from libxml2
[OpenSRF.git] / src / jserver / osrf_chat.c
1 /*
2 Copyright (C) 2005  Georgia Public Library Service 
3 Bill Erickson <billserickson@gmail.com>
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14 */
15
16 #include "osrf_chat.h"
17 #include <string.h>
18 #include <stdio.h>
19 #include <time.h>
20
21 static int osrfChatXMLErrorOcurred = 0;
22
23 /* This is used by code in osrfChatPushData, but that code is
24    currently commented out.  Uncomment the next line if needed. */
25 //static int osrfChatClientSentDisconnect = 0;
26
27 /* shorter version of strcmp */
28 static int eq(const char* a, const char* b) { return (a && b && !strcmp(a,b)); }
29 //#define eq(a,b) ((a && b && !strcmp(a,b)) ? 1 : 0)
30
31 /* gnarly debug function */
32 static void chatdbg( osrfChatServer* server ) {
33
34         if(!server) return;
35         return; /* heavy logging, should only be used in heavy debug mode */
36
37         growing_buffer* buf = buffer_init(256);
38
39         buffer_add(buf, "---------------------------------------------------------------------\n");
40
41         buffer_fadd(buf, 
42                 "ChopChop Debug:\n"
43                 "Connections:           %lu\n"
44                 "Named nodes in hash:   %lu\n"
45                 "Domain:                %s\n"
46                 "Port:                  %d\n"
47                 "S2S Port:              %d\n"
48                 "-------------------------------------------------------\n",
49                 osrfListGetCount(server->nodeList), osrfHashGetCount(server->nodeHash),
50                 server->domain, server->port, server->s2sport );
51
52         osrfListIterator* itr = osrfNewListIterator(server->nodeList);
53         osrfChatNode* node;
54
55         while( (node = osrfListIteratorNext(itr)) ) {
56
57                 buffer_fadd( buf, 
58                         "sockid:    %d\n"
59                         "Remote:    %s\n"
60                         "State:     %d\n"
61                         "XMLState:  %d\n"
62                         "In Parse:  %d\n"
63                         "to:        %s\n"
64                         "Resource:  %s\n"
65                         "Username:  %s\n"
66                         "Domain:    %s\n"
67                         "Authkey:   %s\n"
68                         "type:          %d\n"
69                         "-------------------------------------------------------\n",
70                         node->sockid, node->remote, node->state, node->xmlstate, node->inparse,
71                         node->to, node->resource, node->username, node->domain, node->authkey, node->type );
72         }
73
74         osrfLogDebug( OSRF_LOG_MARK, "DEBUG:\n%s", buf->buf );
75         buffer_free(buf);
76         osrfListIteratorFree(itr);
77 }
78
79 osrfChatServer* osrfNewChatServer( char* domain, char* secret, int s2sport ) {
80         if(!(domain && secret)) return NULL;
81
82         osrfChatServer* server = safe_malloc(sizeof(osrfChatServer));
83
84         server->nodeHash        = osrfNewHash();
85         server->nodeList        = osrfNewList();
86         server->deadNodes = osrfNewList();
87         server->nodeList->freeItem = &osrfChatNodeFree;
88         server->domain          = strdup(domain);
89         server->secret      = strdup(secret);
90         server->s2sport = s2sport;
91         server->port        = 0;
92
93         // Build socket manager
94         server->mgr = safe_malloc(sizeof(socket_manager));
95         server->mgr->data_received = &osrfChatHandleData;
96         server->mgr->blob = server;
97         server->mgr->on_socket_closed = &osrfChatSocketClosed;
98
99         return server;
100 }
101
102 void osrfChatCleanupClients( osrfChatServer* server ) {
103         if(!server) return;
104         osrfListFree(server->deadNodes);
105         server->deadNodes = osrfNewList();
106 }
107
108
109
110 osrfChatNode* osrfNewChatNode( int sockid, char* domain ) {
111         if(sockid < 1 || !domain) return NULL;
112         osrfChatNode* node      = safe_malloc(sizeof(osrfChatNode));
113         node->state                             = OSRF_CHAT_STATE_NONE;
114         node->msgs                              = NULL; /* only s2s nodes cache messages */
115         node->parserCtx         = xmlCreatePushParserCtxt(osrfChatSaxHandler, node, "", 0, NULL);
116         node->msgDoc                    = xmlNewDoc(BAD_CAST "1.0");
117         node->domain = strdup(domain);
118         xmlKeepBlanksDefault(0);
119         node->authkey                   = NULL;
120         node->username                  = NULL;
121         node->resource                  = NULL;
122         node->to                                        = NULL;
123         node->type = 0;
124         return node;
125 }
126
127
128 osrfChatNode* osrfNewChatS2SNode( char* domain, char* remote ) {
129         if(!(domain && remote)) return NULL;
130         osrfChatNode* n = osrfNewChatNode( 1, domain );
131         n->state                = OSRF_CHAT_STATE_S2S_CHALLENGE;
132         n->sockid       = -1;
133         n->remote       = strdup(remote);
134         n->msgs         = osrfNewList();
135         n->msgs->freeItem = &osrfChatS2SMessageFree;
136         n->type = 1;
137         return n;
138 }
139
140 void osrfChatS2SMessageFree(void* n) { free(n); }
141
142 void osrfChatNodeFree( void* node ) {
143         if(!node) return;
144         osrfChatNode* n = (osrfChatNode*) node;
145
146         /* we can't free messages that are mid-parse because the
147                 we can't free the parser context */
148         if(n->inparse) {
149                 n->inparse = 0;
150                 osrfListPush(n->parent->deadNodes, n);
151                 return;
152         }
153
154         free(n->remote);
155         free(n->to);
156         free(n->username);
157         free(n->resource);
158         free(n->domain);
159         free(n->authkey);
160
161         osrfListFree(n->msgs);
162
163         if(n->parserCtx) {
164                 xmlFreeDoc(n->parserCtx->myDoc);
165                 xmlFreeParserCtxt(n->parserCtx);
166         }
167
168         xmlFreeDoc(n->msgDoc);
169         free(n);
170 }
171
172
173
174 int osrfChatServerConnect( osrfChatServer* cs,  int port, int s2sport, char* listenAddr ) {
175         if(!(cs && port && listenAddr)) return -1;
176         cs->port = port;
177         cs->s2sport = s2sport;
178         if( socket_open_tcp_server(cs->mgr, port, listenAddr ) < 0 )
179                 return -1;
180         if( socket_open_tcp_server(cs->mgr, s2sport, listenAddr ) < 0 )
181                 return -1;
182         return 0;
183 }
184
185
186 int osrfChatServerWait( osrfChatServer* server ) {
187         if(!server) return -1;
188         while(1) {
189                 if(socket_wait_all(server->mgr, -1) < 0)
190                         osrfLogWarning( OSRF_LOG_MARK,  "jserver_wait(): socket_wait_all() returned error");
191         }
192         return -1;
193 }
194
195
196 void osrfChatServerFree(osrfChatServer* server ) {
197         if(!server) return;
198         osrfHashFree(server->nodeHash);
199         osrfListFree(server->nodeList);
200         osrfListFree(server->deadNodes);
201         free(server->mgr);
202         free(server->domain);
203         free(server->secret);
204
205         free(server);
206 }
207
208
209 void osrfChatHandleData( void* cs, 
210         socket_manager* mgr, int sockid, char* data, int parent_id ) {
211
212         if(!(cs && mgr && sockid && data)) return;
213
214         osrfChatServer* server = (osrfChatServer*) cs;
215
216         osrfChatNode* node = osrfListGetIndex( server->nodeList, sockid );
217
218         if(node)
219                 osrfLogDebug( OSRF_LOG_MARK, "Found node for sockid %d with state %d", sockid, node->state);
220
221         if(!node) {
222                 osrfLogDebug( OSRF_LOG_MARK, "Adding new connection for sockid %d", sockid );
223                 node = osrfChatAddNode( server, sockid );
224         }
225
226         if(node) {
227                 if( (osrfChatPushData( server, node, data ) == -1) ) {
228                         osrfLogError( OSRF_LOG_MARK, 
229                                         "Node at socket %d with remote address %s and destination %s, "
230                                         "received bad XML [%s], disconnecting...", sockid, node->remote, node->to, data );
231                         osrfChatSendRaw(  node, OSRF_CHAT_PARSE_ERROR );
232                         osrfChatRemoveNode( server, node );
233                 }
234         }
235
236         osrfChatCleanupClients(server); /* clean up old dead clients */
237 }
238
239
240 void osrfChatSocketClosed( void* blob, int sockid ) {
241         if(!blob) return;
242         osrfChatServer* server = (osrfChatServer*) blob;
243         osrfChatNode* node = osrfListGetIndex(server->nodeList, sockid);
244         osrfChatRemoveNode( server, node );
245 }
246
247 osrfChatNode* osrfChatAddNode( osrfChatServer* server, int sockid ) {
248         if(!(server && sockid)) return NULL;
249         osrfChatNode* node = osrfNewChatNode(sockid, server->domain);
250         node->parent = server;
251         node->sockid = sockid;
252         osrfListSet( server->nodeList, node, sockid );
253         return node;
254 }
255
256 void osrfChatRemoveNode( osrfChatServer* server, osrfChatNode* node ) {
257         if(!(server && node)) return;
258         socket_disconnect(server->mgr, node->sockid);
259         if(node->remote) 
260                 osrfHashRemove( server->nodeHash, node->remote );
261         osrfListRemove( server->nodeList, node->sockid ); /* this will free it */
262 }
263
264 int osrfChatSendRaw( osrfChatNode* node, char* msgXML ) {
265         if(!(node && msgXML)) return -1;
266         /* wait at most 3 second for this client to take our data */
267         return socket_send_timeout( node->sockid, msgXML, 3000000 ); 
268 }
269
270 void osrfChatNodeFinish( osrfChatServer* server, osrfChatNode* node ) {
271         if(!(server && node)) return;
272         osrfChatSendRaw( node, "</stream:stream>");
273         osrfChatRemoveNode( server, node );
274 }
275
276
277 int osrfChatSend( osrfChatServer* cs, osrfChatNode* node, char* toAddr, char* fromAddr, char* msgXML ) {
278         if(!(cs && node && toAddr && msgXML)) return -1;
279
280         int l = strlen(toAddr);
281         char dombuf[l];
282         bzero(dombuf, l);
283         jid_get_domain( toAddr, dombuf, l );    
284
285         if( eq( dombuf, cs->domain ) ) { /* this is to a user we host */
286
287                 osrfLogInfo( OSRF_LOG_MARK, "Sending message on local connection\nfrom: %s\nto: %s", fromAddr, toAddr );
288                 osrfChatNode* tonode = osrfHashGet(cs->nodeHash, toAddr);
289                 if(tonode) {
290
291                         /* if we can't send to the recipient (recipient is gone or too busy, 
292                          * we drop the recipient and inform the sender that the recipient
293                          * is no more */
294                         if( osrfChatSendRaw( tonode, msgXML ) < 0 ) {
295
296                                 osrfChatRemoveNode( cs, tonode );
297                                 char* xml = va_list_to_string( OSRF_CHAT_NO_RECIPIENT, toAddr, fromAddr );
298
299                                 osrfLogError( OSRF_LOG_MARK, "Node failed to function. "
300                                                 "Responding to caller with error: %s", toAddr);
301
302
303                                 if( osrfChatSendRaw( node, xml ) < 0 ) {
304                                         osrfLogError(OSRF_LOG_MARK, "Sending node is now gone..removing");
305                                         osrfChatRemoveNode( cs, node );
306                                 }
307                                 free(xml);
308                         }
309
310                 } else {
311
312                         /* send an error message saying we don't have this connection */
313                         osrfLogInfo( OSRF_LOG_MARK, "We have no connection for %s", toAddr);
314                         char* xml = va_list_to_string( OSRF_CHAT_NO_RECIPIENT, toAddr, fromAddr );
315                         if( osrfChatSendRaw( node, xml ) < 0 ) 
316                                 osrfChatRemoveNode( cs, node );
317                         free(xml);
318                 }
319
320         } else {
321
322                 osrfChatNode* tonode = osrfHashGet(cs->nodeHash, dombuf);
323                 if(tonode) {
324                         if( tonode->state == OSRF_CHAT_STATE_CONNECTED ) {
325                                 osrfLogDebug( OSRF_LOG_MARK, "Routing message to server %s", dombuf);
326
327                                 if( osrfChatSendRaw( tonode, msgXML ) < 0 ) {
328                                         osrfLogError( OSRF_LOG_MARK, "Node failed to function: %s", toAddr);
329                                         char* xml = va_list_to_string( OSRF_CHAT_NO_RECIPIENT, toAddr, fromAddr );
330                                         if( osrfChatSendRaw( node, xml ) < 0 ) 
331                                                 osrfChatRemoveNode( cs, node );
332                                         free(xml);
333                                         osrfChatRemoveNode( cs, tonode );
334                                 }
335
336                         } else {
337                                 osrfLogInfo( OSRF_LOG_MARK, "Received s2s message and we're still trying to connect...caching");
338                                 osrfListPush( tonode->msgs, strdup(msgXML) );
339                         }
340
341                 } else {
342
343                         if( osrfChatInitS2S( cs, dombuf, toAddr, msgXML ) != 0 ) {
344                                 osrfLogWarning( OSRF_LOG_MARK, "We are unable to connect to remote server %s for recipient %s", dombuf, toAddr);
345                                 char* xml = va_list_to_string( OSRF_CHAT_NO_RECIPIENT, toAddr, fromAddr );
346                                 osrfChatSendRaw( node, xml );
347                                 free(xml);
348                         }
349                 }
350         }
351
352         return 0;
353 }
354
355
356 /*
357 void osrfChatCacheS2SMessage( char* toAddr, char* msgXML, osrfChatNode* snode ) {
358         if(!(toAddr && msgXML)) return;
359         osrfChatS2SMessage* msg = safe_malloc(sizeof(osrfChatS2SMessage));
360         msg->toAddr = strdup(toAddr);
361         msg->msgXML = strdup(msgXML);
362         osrfLogInfo( OSRF_LOG_MARK, "Pushing client message onto s2s queue waiting for connect... ");
363         osrfListPush( snode->msgs, msgXML );
364 }
365 */
366
367
368 int osrfChatInitS2S( osrfChatServer* cs, char* remote, char* toAddr, char* msgXML ) {
369         if(!(cs && remote && toAddr && msgXML)) return -1;
370
371         osrfLogInfo( OSRF_LOG_MARK, "Initing server2server connection to domain %s", remote );
372         osrfChatNode* snode = osrfNewChatS2SNode( cs->domain, remote );
373         snode->parent = cs;
374
375         /* try to connect to the remote site */
376         snode->sockid = socket_open_tcp_client(cs->mgr, cs->s2sport, remote);
377         if(snode->sockid < 1) {
378                 osrfLogWarning( OSRF_LOG_MARK, "Unable to connect to remote server at %s", remote );
379                 return -1;
380         }
381
382         /* store the message we were supposed to deliver until we're fully connected */
383         //osrfChatCacheS2SMessage( toAddr, msgXML, snode );
384         osrfListPush( snode->msgs, strdup(msgXML) );
385         osrfHashSet(cs->nodeHash, snode, remote );
386         osrfListSet(cs->nodeList, snode, snode->sockid );
387
388         /* send the initial s2s request */
389         osrfChatSendRaw( snode, OSRF_CHAT_S2S_INIT );
390
391         osrfLogDebug( OSRF_LOG_MARK, "Added new s2s node...");
392         chatdbg(cs);
393
394         return 0;
395 }
396
397
398 /* commence SAX handling code */
399
400 int osrfChatPushData( osrfChatServer* server, osrfChatNode* node, char* data ) {
401         if(!(node && data)) return -1;
402
403         chatdbg(server);
404
405         osrfLogDebug( OSRF_LOG_MARK, "pushing data into xml parser for node %d with state %d:\n%s", 
406                                                  node->sockid, node->state, data);
407         node->inparse = 1;
408         xmlParseChunk(node->parserCtx, data, strlen(data), 0);
409         node->inparse = 0;
410
411         if(osrfChatXMLErrorOcurred) {
412                 osrfChatXMLErrorOcurred = 0;
413                 return -1;
414         }
415
416         /* we can't do cleanup of the XML handlers while in the middle of a 
417                 data push, so set flags in the data push and doe the cleanup here */
418         /*
419         if(osrfChatClientSentDisconnect) {
420                 osrfChatClientSentDisconnect  = 0;
421                 osrfChatNodeFinish( server, node );
422         }
423         */
424
425         return 0;
426 }
427
428
429 void osrfChatStartStream( void* blob ) {
430         osrfLogDebug( OSRF_LOG_MARK, "Starting new client stream...");
431 }
432
433
434 void osrfChatStartElement( void* blob, const xmlChar *name, const xmlChar **atts ) {
435         if(!(blob && name)) return;
436         osrfChatNode* node = (osrfChatNode*) blob;
437
438         int status = -1;
439         char* nm = (char*) name;
440
441         osrfLogDebug( OSRF_LOG_MARK, "Starting element %s with namespace %s and node state %d", 
442                                                  nm, xmlSaxAttr(atts, "xmlns"), node->state );
443
444         switch( node->state ) {
445
446                 case OSRF_CHAT_STATE_NONE:
447                         status = osrfChatHandleNewConnection( node, nm, atts );
448                         osrfLogDebug( OSRF_LOG_MARK, "After NewConnection we have state %d", node->state);
449                         break;
450
451                 case OSRF_CHAT_STATE_CONNECTING:
452                         status = osrfChatHandleConnecting( node, nm, atts );
453                         break;
454
455                 case OSRF_CHAT_STATE_CONNECTED:
456                         status = osrfChatHandleConnected( node, nm, atts );
457                         break;
458
459                 case OSRF_CHAT_STATE_S2S_CHALLENGE:      
460                         status = osrfChatHandleS2SChallenge( node, nm, atts );
461                         break;
462
463                 case OSRF_CHAT_STATE_S2S_RESPONSE: /* server waiting for client response to challenge */
464                         if(eq(nm, "db:result")) {
465                                 char* remote = xmlSaxAttr(atts, "from");
466                                 if(remote) node->remote = strdup(remote); /* copy off the client's id */
467                                 status = 0;
468                                 node->xmlstate |= OSRF_CHAT_STATE_INS2SRESULT;
469                         } else status = -1; 
470                         break;
471
472                 case OSRF_CHAT_STATE_S2S_VERIFY:        /* client : waiting for server verify message */
473                         if(eq(nm, "db:verify")) {
474                                 char* id = xmlSaxAttr( atts, "id" );
475                                 if(id) {
476                                         char* xml = va_list_to_string( OSRF_CHAT_S2S_VERIFY_RESPONSE, 
477                                                         node->remote, node->domain, id );
478                                         osrfChatSendRaw( node, xml );
479                                         free(xml);
480                                         node->state = OSRF_CHAT_STATE_S2S_VERIFY_FINAL;
481                                         status = 0;
482                                 }
483                         }
484                         break;
485
486                 case OSRF_CHAT_STATE_S2S_VERIFY_RESPONSE:       /* server waiting for client verify response */
487                 case OSRF_CHAT_STATE_S2S_VERIFY_FINAL: /* client waitig for final verify */
488                         status = osrfChatHandleS2SConnected( node, nm, atts );
489                         break;
490
491         }
492
493         if(status != 0) 
494                 osrfChatParseError( node, "We don't know how to handle the XML data received" );
495 }
496
497 #define CHAT_CHECK_VARS(x,y,z) if(!(x && y)) return -1; if(z) osrfLogDebug( OSRF_LOG_MARK, z);
498
499
500
501 int osrfChatHandleS2SConnected( osrfChatNode* node, const char* name, const xmlChar**atts ) {
502         CHAT_CHECK_VARS(node, name, "osrfChatHandleS2SConnected" );
503
504         int status = -1;
505
506         if(eq(name,"db:verify")) { /* server receives verify from client */
507                 char* xml = va_list_to_string(OSRF_CHAT_S2S_VERIFY_FINAL, node->domain, node->remote ); 
508                 osrfChatSendRaw(node, xml );
509                 free(xml);
510                 status = 0;
511         }
512
513         if(eq(name, "db:result")) {
514                 /* send all the messages that we have queued for this server */
515                 node->state = OSRF_CHAT_STATE_CONNECTED;
516                 osrfListIterator* itr = osrfNewListIterator(node->msgs);
517
518                 char* xml;
519                 while( (xml = (char*) osrfListIteratorNext(itr)) ) {
520                         xmlDocPtr doc = xmlParseMemory(xml, strlen(xml));
521                         if(doc) {
522                                 char* from = (char*) xmlGetProp(xmlDocGetRootElement(doc), BAD_CAST "from");
523                                 char* to = (char*) xmlGetProp(xmlDocGetRootElement(doc), BAD_CAST "to");
524                                 osrfChatSend( node->parent, node, to, from, xml );
525                                 osrfLogDebug( OSRF_LOG_MARK, "Sending cached message from %s to %s", from, to);
526                                 xmlFree(to); xmlFree(from);
527                                 xmlFreeDoc(doc);
528                         }
529                 }
530
531                 osrfListIteratorFree(itr);
532                 osrfListFree(node->msgs);
533                 node->msgs = NULL;
534                 status = 0;
535         }
536
537         if(status == 0) {
538                 osrfLogInfo( OSRF_LOG_MARK, "Successfully made S2S connection to %s", node->remote );
539                 node->state = OSRF_CHAT_STATE_CONNECTED;
540                 node->xmlstate = 0;
541         }
542
543         return status;
544 }
545
546
547 /** check the namespace of the stream message to see if it's a server or client connection */
548 int osrfChatHandleNewConnection( osrfChatNode* node, const char* name, const xmlChar** atts ) {
549         CHAT_CHECK_VARS(node, name, "osrfChatHandleNewConnection()");
550
551         if(!eq(name, "stream:stream")) return -1;
552
553         node->authkey = osrfChatMkAuthKey();
554         char* ns = xmlSaxAttr(atts, "xmlns");
555         if(!ns) return -1;
556
557         if(eq(ns, "jabber:client")) { /* client connection */
558
559                 char* domain = xmlSaxAttr( atts, "to" );
560                 if(!domain) return -1; 
561         
562                 if(!eq(domain, node->domain)) {
563                         osrfLogWarning( OSRF_LOG_MARK, 
564                                 "Client attempting to connect to invalid domain %s. Our domain is %s", domain, node->domain);
565                         return -1;
566                 }
567         
568                 char* buf = va_list_to_string( OSRF_CHAT_START_STREAM, domain, node->authkey );
569                 node->state = OSRF_CHAT_STATE_CONNECTING;
570
571                 osrfLogDebug( OSRF_LOG_MARK, "Server node %d setting state to OSRF_CHAT_STATE_CONNECTING[%d]",
572                                                          node->sockid, node->state );
573         
574                 osrfLogDebug( OSRF_LOG_MARK, "Server responding to connect message with\n%s\n", buf );
575                 osrfChatSendRaw( node, buf );
576                 free(buf);
577                 return 0;
578         }
579
580         /* server to server init */
581         if(eq(ns, "jabber:server")) { /* client connection */
582                 osrfLogInfo( OSRF_LOG_MARK, "We received a new server 2 server connection, generating auth key...");
583                 char* xml = va_list_to_string( OSRF_CHAT_S2S_CHALLENGE, node->authkey );
584                 osrfChatSendRaw( node, xml );
585                 free(xml);
586                 node->state = OSRF_CHAT_STATE_S2S_RESPONSE; /* the next message should be the response */
587                 node->type = 1;
588                 return 0;
589         }
590
591         return -1;
592 }
593
594
595
596 char* osrfChatMkAuthKey() {
597         char keybuf[112];
598         bzero(keybuf, 112);
599         snprintf(keybuf, 111, "%d%ld%s", (int) time(NULL), (long) getpid(), getenv("HOSTNAME"));
600         return strdup(shahash(keybuf));
601 }
602
603 int osrfChatHandleConnecting( osrfChatNode* node, const char* name, const xmlChar** atts ) {
604         CHAT_CHECK_VARS(node, name, "osrfChatHandleConnecting()");
605         osrfLogDebug( OSRF_LOG_MARK, "Handling connect node %s", name );
606
607         if(eq(name, "iq")) node->xmlstate |= OSRF_CHAT_STATE_INIQ;
608         else if(eq(name,"username")) node->xmlstate |= OSRF_CHAT_STATE_INUSERNAME;
609         else if(eq(name,"resource")) node->xmlstate |= OSRF_CHAT_STATE_INRESOURCE;
610         return 0;
611 }
612
613 int osrfChatHandleConnected( osrfChatNode* node, const char* name, const xmlChar** atts ) {
614         CHAT_CHECK_VARS(node, name, "osrfChatHandleConnected()");
615
616         if(eq(name,"message")) {
617
618                 /* drop the old message and start with a new one */
619                 xmlNodePtr root = xmlNewNode(NULL, BAD_CAST name);
620                 xmlAddAttrs(root, atts);
621                 xmlNodePtr oldRoot = xmlDocSetRootElement(node->msgDoc, root);
622                 free(node->to);
623
624                 char* to = xmlSaxAttr(atts, "to");
625                 if(!to) to = "";
626
627                 node->to = strdup(to);
628                 if(oldRoot) xmlFreeNode(oldRoot);
629                 node->xmlstate = OSRF_CHAT_STATE_INMESSAGE;
630
631         } else {
632
633                 /* all non "message" nodes are simply added to the message */
634                 xmlNodePtr nodep = xmlNewNode(NULL, BAD_CAST name);
635                 xmlAddAttrs(nodep, atts);
636                 xmlAddChild(xmlDocGetRootElement(node->msgDoc), nodep);
637         }
638
639         return 0;
640 }
641
642 /* takes s2s secret, hashdomain, and the s2s auth token */
643 static char* osrfChatGenerateS2SKey( char* secret, char* hashdomain, char* authtoken ) {
644         if(!(secret && hashdomain && authtoken)) return NULL;
645         osrfLogInfo( OSRF_LOG_MARK, "Generating s2s key with auth token: %s", authtoken );
646         char* a = shahash(secret);
647         osrfLogDebug( OSRF_LOG_MARK, "S2S secret hash: %s", a);
648         char* b = va_list_to_string("%s%s", a, hashdomain);
649         char* c = shahash(b);
650         osrfLogDebug( OSRF_LOG_MARK, "S2S intermediate hash: %s", c);
651         char* d = va_list_to_string("%s%s", c, authtoken);
652         char* e = strdup(shahash(d));
653         free(b); free(d); 
654         return e;
655 }
656
657 int osrfChatHandleS2SChallenge( osrfChatNode* node, const char* name, const xmlChar** atts ) {
658         CHAT_CHECK_VARS(node, name, "osrfChatHandleS2SChallenge()");
659
660 /* here we respond to the stream challenge */
661         if(eq(name, "stream:stream")) {
662                 char* id = xmlSaxAttr(atts, "id");
663                 if(id) {
664                         /* we use our domain in the s2s challenge hash */
665                         char* d = osrfChatGenerateS2SKey(node->parent->secret, node->domain, id );
666                         char* e = va_list_to_string(OSRF_CHAT_S2S_RESPONSE, node->remote, node->domain, d );
667                         osrfLogInfo( OSRF_LOG_MARK, "Answering s2s challenge with key:  %s", e );
668                         osrfChatSendRaw( node, e );
669                         free(d); free(e);
670                         node->state = OSRF_CHAT_STATE_S2S_VERIFY;
671                         return 0;
672                 }
673         }
674
675         return -1;
676 }
677
678 /*
679 int osrfChatHandleS2SResponse( osrfChatNode* node, const char* name, const xmlChar** atts ) {
680         CHAT_CHECK_VARS(node, name, "osrfChatHandleS2SResponse()");
681
682         if(eq(name, "db:result")) {
683                 node->xmlstate |= OSRF_CHAT_STATE_INS2SRESULT;
684                 return 0;
685         }
686
687         return -1;
688 }
689 */
690
691
692
693 void osrfChatEndElement( void* blob, const xmlChar* name ) {
694         if(!(blob && name)) return;
695         osrfChatNode* node = (osrfChatNode*) blob;
696
697         char* nm = (char*) name;
698
699         if(eq(nm,"stream:stream")) {
700                 osrfChatNodeFinish( node->parent, node );
701                 return;
702         }
703
704         if( node->state == OSRF_CHAT_STATE_CONNECTED ) {
705                 if(eq(nm, "message")) {
706
707                         xmlNodePtr msg = xmlDocGetRootElement(node->msgDoc);
708                         if(msg && node->type == 0)
709                                 xmlSetProp(msg, BAD_CAST "from", BAD_CAST node->remote );
710                         char* string = xmlDocToString(node->msgDoc, 0 );
711
712                         char* from = (char*) xmlGetProp(msg, BAD_CAST "from");
713                         osrfLogDebug( OSRF_LOG_MARK,  "Routing message to %s\n%s\n", node->to, from, string );
714                         osrfChatSend( node->parent, node, node->to, from, string ); 
715                         xmlFree(from);
716                         free(string);
717                 }
718         }
719
720         if( node->state == OSRF_CHAT_STATE_CONNECTING ) {
721                 if( node->xmlstate & OSRF_CHAT_STATE_INIQ ) {
722
723                         if(eq(nm, "iq")) {
724                                 node->xmlstate &= ~OSRF_CHAT_STATE_INIQ;
725                                 node->remote = va_list_to_string( 
726                                                 "%s@%s/%s", node->username, node->domain, node->resource );
727
728                                 osrfLogInfo( OSRF_LOG_MARK, "%s successfully logged in", node->remote );
729
730                                 osrfLogDebug( OSRF_LOG_MARK, "Setting remote address to %s", node->remote );
731                                 osrfChatSendRaw( node, OSRF_CHAT_LOGIN_OK );
732                                 if(osrfHashGet( node->parent->nodeHash, node->remote ) ) {
733                                         osrfLogWarning( OSRF_LOG_MARK, "New node replaces existing node for remote id %s", node->remote);
734                                         osrfHashRemove(node->parent->nodeHash, node->remote);
735                                 }
736                                 osrfHashSet( node->parent->nodeHash, node, node->remote );
737                                 node->state = OSRF_CHAT_STATE_CONNECTED;
738                         }
739                 }
740         }
741 }
742
743
744 void osrfChatHandleCharacter( void* blob, const xmlChar *ch, int len) {
745         if(!(blob && ch && len)) return;
746         osrfChatNode* node = (osrfChatNode*) blob;
747
748         /*
749         osrfLogDebug( OSRF_LOG_MARK, "Char Handler: state %d, xmlstate %d, chardata %s", 
750                         node->state, node->xmlstate, (char*) ch );
751                         */
752
753         if( node->state == OSRF_CHAT_STATE_CONNECTING ) {
754                 if( node->xmlstate & OSRF_CHAT_STATE_INIQ ) {
755
756                         if( node->xmlstate & OSRF_CHAT_STATE_INUSERNAME ) {
757                                 free(node->username);
758                                 node->username = strndup((char*) ch, len);
759                                 node->xmlstate &= ~OSRF_CHAT_STATE_INUSERNAME;
760                         }
761
762                         if( node->xmlstate & OSRF_CHAT_STATE_INRESOURCE ) {
763                                 free(node->resource);
764                                 node->resource = strndup((char*) ch, len);
765                                 node->xmlstate &= ~OSRF_CHAT_STATE_INRESOURCE;
766                         }
767                 }
768
769                 return;
770         } 
771         
772         if( node->state == OSRF_CHAT_STATE_CONNECTED ) {
773                 xmlNodePtr last = xmlGetLastChild(xmlDocGetRootElement(node->msgDoc));
774                 xmlNodePtr txt = xmlNewTextLen(ch, len);
775                 xmlAddChild(last, txt);
776                 return;
777         }
778
779         if( node->state == OSRF_CHAT_STATE_S2S_RESPONSE &&
780                         (node->xmlstate & OSRF_CHAT_STATE_INS2SRESULT) ) {
781
782                 char* key = strndup((char*) ch, len);
783                 osrfLogDebug( OSRF_LOG_MARK, "Got s2s key from %s : %s", node->remote, key );
784                 char* e = osrfChatGenerateS2SKey(node->parent->secret, node->remote, node->authkey );
785                 osrfLogInfo( OSRF_LOG_MARK, "\nReceived s2s key from server: %s\nKey should be: %s", key, e );
786
787                 if(eq(key, e)) {
788                         char* msg = va_list_to_string(OSRF_CHAT_S2S_VERIFY_REQUEST,  
789                                         node->authkey, node->domain, node->remote, e );
790                         osrfChatSendRaw(node, msg );
791                         free(msg);
792                         node->state = OSRF_CHAT_STATE_S2S_VERIFY_RESPONSE;
793                         node->xmlstate = 0;
794
795                 } else {
796                         osrfLogWarning( OSRF_LOG_MARK, "Server2Server keys do not match!");
797                 }
798
799                 /* do the hash dance again */
800         }
801
802         /* XXX free 'e' and 'key' ?? */
803
804 }
805
806
807 void osrfChatParseError( void* blob, const char* msg, ... ) {
808
809         osrfChatXMLErrorOcurred = 1;
810 }
811
812
813
814