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