9311670af30382108a5aa759bae226b76e97418e
[Evergreen.git] / OpenSRF / src / router / router.c
1 #include "router.h"
2 #include <sys/types.h>
3 #include <signal.h>
4
5 #define ROUTER_MAX_MSGS_PER_PACKET 12
6 char* router_resource;
7 transport_router_registrar* routt;
8 void _build_trusted_sites( transport_router_registrar* router );
9
10
11 void sig_hup_handler( int a ) { 
12         router_registrar_free( routt ); 
13         config_reader_free();   
14         log_free();
15         free( router_resource );
16         exit(0); 
17 }
18
19
20 int main( int argc, char* argv[] ) {
21
22         if( argc < 2 ) {
23                 fatal_handler( "Usage: %s <path_to_config_file>", argv[0] );
24                 exit(0);
25         }
26
27         config_reader_init( "opensrf.router", argv[1] );        
28         if( conf_reader == NULL ) fatal_handler( "main(): Config is NULL" ); 
29
30         /* laod the config options */
31         char* server                    = config_value("opensrf.router", "//router/transport/server");
32         char* port                              = config_value("opensrf.router", "//router/transport/port");
33         char* username                  = config_value("opensrf.router", "//router/transport/username");
34         char* password                  = config_value("opensrf.router", "//router/transport/password");
35         router_resource         = config_value("opensrf.router", "//router/transport/resource");
36         char* con_timeout               = config_value("opensrf.router", "//router/transport/connect_timeout" );
37         char* max_retries               = config_value("opensrf.router", "//router/transport/max_reconnect_attempts" );
38         char* component         = config_value("opensrf.router", "//router/component" );
39
40
41         /* set up the logger */
42         char* level = config_value("opensrf.router","//log/level");
43         char* log_file = config_value("opensrf.router","//log/file");
44         int llevel = atoi(level);
45         fprintf(stderr, "Level %d; file %s\n", llevel, log_file );
46
47         if(!log_init( llevel, log_file )) 
48                 fprintf(stderr, "Unable to init logging, going to stderr...\n" );
49
50
51         free(level);
52         free(log_file);
53
54         fprintf(stderr, "Router connecting as \nserver: %s \nport: %s \nuser:%s \nresource:%s\n", 
55                         server, port, username, router_resource );
56
57         int iport                       = atoi( port );
58         int con_itimeout        = atoi( con_timeout );
59         int max_retries_        = atoi(max_retries);
60         int icomponent = 0;
61         if(component) 
62                 icomponent = atoi(component);
63
64         if( iport < 1 ) { 
65                 fatal_handler( "Port is negative or 0" );
66                 return 99;
67         }
68
69
70         /* build the router_registrar */
71         transport_router_registrar* router_registrar = 
72                 router_registrar_init( server, iport, username, password, router_resource, 0, con_itimeout, icomponent ); 
73
74         routt = router_registrar;
75
76         free(server);
77         free(port);
78         free(username);
79         free(password);
80         free(con_timeout);
81         free(max_retries);
82
83         daemonize();
84
85         signal(SIGHUP,sig_hup_handler);
86         signal(SIGINT,sig_hup_handler);
87         signal(SIGTERM,sig_hup_handler);
88
89
90         int counter = 0;
91         /* wait for incoming... */
92         while( ++counter <= max_retries_ ) {
93
94                 /* connect to jabber */
95                 if( router_registrar_connect( router_registrar ) )  {
96                         info_handler( "Connected..." );
97                         fprintf(stderr, "- Connected -\n");
98                         counter = 0;
99                         listen_loop( router_registrar );
100                 } else  
101                         fatal_handler( "Could not connect to Jabber Server" );
102
103                 /* this should never happen */
104                 warning_handler( "Jabber server probably went away, attempting reconnect" );
105
106                 sleep(5);
107         }
108
109
110         router_registrar_free( router_registrar );
111         config_reader_free();   
112         return 1;
113
114 }
115
116 transport_router_registrar* router_registrar_init( char* server, 
117                 int port, char* username, char* password, 
118                 char* resource, int client_timeout, int con_timeout, int component ) {
119
120         if( server == NULL ) { return NULL; }
121         
122         /* allocate a new router_registrar object */
123         size_t size = sizeof( transport_router_registrar );
124         transport_router_registrar* router_registrar = (transport_router_registrar*) safe_malloc( size );
125
126         router_registrar->client_timeout        = client_timeout;
127         router_registrar->jabber = jabber_connect_init( server, port, username, password, resource, con_timeout, component );
128         _build_trusted_sites( router_registrar );
129         info_handler( "Trusted stuff %s, %s, %s", router_registrar->trusted_servers[0], 
130                 router_registrar->trusted_clients[0], router_registrar->trusted_clients[1] );
131         return router_registrar;
132
133 }
134
135 void _build_trusted_sites( transport_router_registrar* router ) {
136
137         router->trusted_servers = (char**) safe_malloc(sizeof(char**));
138         router->trusted_clients = (char**) safe_malloc(sizeof(char**));
139
140         *(router->trusted_servers) = (char*) safe_malloc(ROUTER_MAX_TRUSTED);
141         *(router->trusted_clients) = (char*) safe_malloc(ROUTER_MAX_TRUSTED);
142
143         int i = 0;
144         while( ++i ) {
145                 char* server = config_value("opensrf.router","//router/trusted_domains/server%d", i );
146                 if(server == NULL)
147                         break;
148                 
149                 router->trusted_servers[i-1] = server;
150         }
151
152         i = 0;
153         while( ++i ) {
154                 char* client = config_value( "opensrf.router","//router/trusted_domains/client%d", i );
155                 if(client == NULL)
156                         break;
157                 router->trusted_clients[i-1] = client;
158         }
159
160         if( router->trusted_servers[0] == NULL ||
161                         router->trusted_clients[0] == NULL )
162
163                 fatal_handler( "You must specify at least one trusted server and client in the config file");
164 }
165
166
167 jabber_connect* jabber_connect_init( char* server, 
168                 int port, char* username, char* password, char* resource, int connect_timeout, int component ) {
169
170         size_t len = sizeof(jabber_connect);
171         jabber_connect* jabber = (jabber_connect*) safe_malloc( len );
172
173         jabber->port                            = port;
174         jabber->connect_timeout = connect_timeout;
175
176         jabber->server                          = strdup(server);
177         jabber->username                        = strdup(username);
178         jabber->password                        = strdup(password);
179         jabber->resource                        = strdup(resource);
180
181         if( jabber->server == NULL || jabber->username == NULL ||
182                         jabber->password == NULL || jabber->resource == NULL ) {
183                 fatal_handler( "jabber_init(): Out of Memory" );
184                 return NULL;
185         }
186
187         /* build the transport client */
188         jabber->t_client = client_init( jabber->server, jabber->port, component );
189
190         return jabber;
191 }
192
193 /* connect the router_registrar to jabber */
194 int router_registrar_connect( transport_router_registrar* router ) {
195         return j_connect( router->jabber );
196 }
197
198 /* connect a jabber_connect object jabber */
199 int j_connect( jabber_connect* jabber ) {
200         if( jabber == NULL ) { return 0; }
201         return client_connect( jabber->t_client, 
202                         jabber->username, jabber->password, jabber->resource, 
203                         jabber->connect_timeout, AUTH_DIGEST );
204 }
205
206 int fill_fd_set( transport_router_registrar* router, fd_set* set ) {
207         
208         int max_fd;
209         FD_ZERO(set);
210
211         int router_fd = router->jabber->t_client->session->sock_obj->sock_fd;
212         max_fd = router_fd;
213         FD_SET( router_fd, set );
214
215         server_class_node* cur_node = router->server_class_list;
216         while( cur_node != NULL ) {
217                 int cur_class_fd = cur_node->jabber->t_client->session->sock_obj->sock_fd;
218                 if( cur_class_fd > max_fd ) 
219                         max_fd = cur_class_fd;
220                 FD_SET( cur_class_fd, set );
221                 cur_node = cur_node->next;
222         }
223
224         FD_CLR( 0, set );
225         return max_fd;
226 }
227
228
229 void listen_loop( transport_router_registrar* router ) {
230
231         if( router == NULL )
232                 return;
233
234         int select_ret;
235         int router_fd = router->jabber->t_client->session->sock_obj->sock_fd;
236         transport_message* cur_msg;
237
238         while(1) {
239
240                 fd_set listen_set;
241                 int max_fd = fill_fd_set( router, &listen_set );
242
243                 if( max_fd < 1 ) 
244                         fatal_handler( "fill_fd_set return bogus max_fd: %d", max_fd );
245
246                 int num_handled = 0;
247                 info_handler( "Going into select" );
248
249                 if( (select_ret=select(max_fd+ 1, &listen_set, NULL, NULL, NULL)) < 0 ) {
250
251                         warning_handler( "Select returned error %d", select_ret );
252                         warning_handler( "Select Error %d on fd %d", errno );
253                         perror( "Select Error" );
254                         warning_handler( "Errors: EBADF %d, EINTR %d, EINVAL %d, ENOMEM %d",
255                                         EBADF, EINTR, EINVAL, ENOMEM );
256                         continue;
257
258                 } else {
259
260                         info_handler( "Select returned %d", select_ret );
261                         
262                         if( FD_ISSET( router_fd, &listen_set ) ) {
263                                 cur_msg = client_recv( router->jabber->t_client, 1 );
264
265                                 /* We only process a message if we have some trusted servers and the current
266                                         message came from one of those servers */
267                                 if(cur_msg) {
268
269                                         if(router->trusted_servers && router->trusted_servers[0]) {
270
271                                                 int i = 0;
272                                                 int found = 0;
273         
274                                                 if( cur_msg->sender ) {
275
276                                                         int len = strlen(cur_msg->sender) + 1; /* there's no way it could be that big, but... */
277                                                         char server_buf[len];
278                                                         memset(server_buf,0,len);
279                                                         jid_get_domain( cur_msg->sender, server_buf );
280                                                         info_handler("Received top level message from %s", server_buf );
281                 
282                                                         while(1) {
283                                                                 if(router->trusted_servers[i] == NULL)
284                                                                         break;
285                                                                 if(!strcmp(router->trusted_servers[i], server_buf)) {
286                                                                         found = 1;
287                                                                         break;
288                                                                 }
289                                                                 i++;
290                                                         }
291                                                 }
292
293                                                 if(found)
294                                                         router_registrar_handle_msg( router, cur_msg );
295                                                 else
296                                                         warning_handler( "Received top level message from unpriveleged sender %s", cur_msg->sender );
297                                         }
298         
299                                         message_free( cur_msg );
300                                 }
301
302                                 if( ++num_handled == select_ret ) 
303                                         continue;
304                         }
305
306                         /* cycle through the children and find any whose fd's are ready for reading */
307                         server_class_node* cur_node = router->server_class_list;
308                         while( cur_node != NULL ) {
309                                 debug_handler( "Checking File Descriptor" );
310                                 int cur_fd = cur_node->jabber->t_client->session->sock_obj->sock_fd;
311
312                                 if( FD_ISSET(cur_fd, &listen_set) ) {
313                                         ++num_handled;
314                                         FD_CLR(cur_fd,&listen_set);
315
316                                         cur_msg = client_recv( cur_node->jabber->t_client, 1 );
317
318                                         if(cur_msg) {
319
320                                                 info_handler( "%s received from %s", cur_node->server_class, cur_msg->sender );
321                                                 int handle_ret = server_class_handle_msg( router, cur_node, cur_msg );
322         
323                                                 if( handle_ret == -1 ) {
324                                                         warning_handler( "server_class_handle_msg() returned -1" );
325                                                         cur_node = router->server_class_list; /*start over*/
326                                                         continue;
327         
328                                                 } else if( handle_ret == 0 ) {
329                                                         /* delete and continue */
330                                                         warning_handler( "server_class_handle_msg() returned 0" );
331                                                         //server_class_node* tmp_node = cur_node->next;
332                                                         remove_server_class( router, cur_node );        
333                                                         debug_handler( "Removed Server Class" );
334                                                         cur_node = router->server_class_list; /*start over*/
335                                                         //cur_node = tmp_node;
336                                                         continue;
337                                                 } 
338         
339                                                 info_handler( "%s handled message successfully", cur_node->server_class );
340                                                 /* dont free message here */
341                                                 if( num_handled == select_ret ) 
342                                                         break;
343                                         }
344
345                                 }
346
347                                 if( num_handled == select_ret ) 
348                                         break;
349
350                                 cur_node = cur_node->next;
351
352                         } /* cycling through the server_class list */
353
354                 } /* no select errors */
355         } 
356 }
357
358
359 /* determine where to route top level messages */
360 int router_registrar_handle_msg( transport_router_registrar* router_registrar, transport_message* msg ) {
361
362         info_handler( "Received class: %s : command %s ", msg->router_class, msg->router_command );
363
364         if( router_registrar == NULL || msg == NULL ) { return 0; }
365
366         if( msg->router_command == NULL || !strcmp(msg->router_command,"") ) {
367                 return router_registrar_handle_app_request( router_registrar, msg );
368         }
369
370         // user issued a ruoter query
371         /* a query command has router_command="query" and the actual query type
372                 is the content of the message */
373         if( !strcmp(msg->router_command,"query")) {
374                 info_handler( "Router received query command" );
375
376                 // user issues a servers query
377                 if( !strcmp(msg->body, "servers")) {
378
379                         info_handler( "Router received servers query command" );
380                         router_return_server_info( router_registrar, msg );
381                         return 1;
382                 }
383         }
384
385
386         info_handler("Looking for server_class_node %s...",msg->router_class);
387         server_class_node* active_class_node = find_server_class( router_registrar, msg->router_class );
388
389         if( active_class_node == NULL ) { 
390                 info_handler("Could not find server_class_node %s, creating one.",msg->router_class);
391
392                 /* there is no server_class for msg->router_class so we build it here */
393                 if( strcmp( msg->router_command, "register") == 0 ) {
394
395                         info_handler("Adding server_class_node for %s",msg->router_class);
396                         active_class_node = 
397                                 init_server_class( router_registrar, msg->sender, msg->router_class ); 
398
399                         if( active_class_node == NULL ) {
400                                 fatal_handler( "router_listen(): active_class_node == NULL for %s", msg->sender );
401                                 return 0;
402                         }
403
404                         if (router_registrar->server_class_list != NULL) {
405                                 active_class_node->next = router_registrar->server_class_list;
406                                 router_registrar->server_class_list->prev = active_class_node;
407                         }
408                         router_registrar->server_class_list = active_class_node;
409
410                         //spawn_server_class( (void*) active_class_node );
411
412                 } else {
413                         warning_handler( "router_register_handler_msg(): Bad Command [%s] for class [%s]",
414                                 msg->router_command, msg->router_class );
415                 }
416
417         } else if( strcmp( msg->router_command, "register") == 0 ) {
418                 /* there is a server_class for msg->router_class so we 
419                         need to either add a new server_node or update the existing one */
420
421                 
422                 server_node* s_node = find_server_node( active_class_node, msg->sender );
423
424                 if( s_node != NULL ) {
425                         s_node->available = 1;
426                         s_node->upd_time = time(NULL);
427                         info_handler( "Found matching registered server: %s. Updating.",
428                                         s_node->remote_id );
429                 } else {
430                         s_node = init_server_node( msg->sender );
431
432                         info_handler( "Adding server_node for: %s.", s_node->remote_id );
433
434                         if (s_node == NULL ) {
435                                 warning_handler( " Could not create new xerver_node for %s.",
436                                         msg->sender );
437                                 return 0;
438                         }
439
440                         s_node->next = active_class_node->current_server_node->next;
441                         s_node->prev = active_class_node->current_server_node;
442
443                         active_class_node->current_server_node->next->prev = s_node;
444                         active_class_node->current_server_node->next = s_node;
445                 }
446
447
448         } else if( strcmp( msg->router_command, "unregister") == 0 ) {
449
450                 if( ! unregister_server_node( active_class_node, msg->sender ) ) {
451                         remove_server_class( router_registrar, active_class_node );
452                         debug_handler( "Removed server class after final unregister");
453                 }
454
455         } else {
456                 warning_handler( "router_register_handler_msg(): Bad Command [%s] for class [%s]",
457                         msg->router_command, msg->router_class );
458         }
459
460         return 1;
461 }
462
463
464 /* removes a server class node from the top level router_registrar */
465 int unregister_server_node( server_class_node* active_class_node, char* remote_id ) {
466
467         server_node* d_node = find_server_node( active_class_node, remote_id );
468
469         if ( d_node != NULL ) {
470
471                 info_handler( "Removing server_node for: %s.", d_node->remote_id );
472
473                 if ( d_node->next == NULL ) {
474                         warning_handler( "NEXT is NULL in ring [%s] -- "
475                                 "THIS SHOULD NEVER HAPPEN",
476                                 d_node->remote_id );
477
478                 }
479                 
480                 if ( d_node->prev == NULL ) {
481                         warning_handler( "PREV is NULL in a ring [%s] -- "
482                                 "THIS SHOULD NEVER HAPPEN",
483                                 d_node->remote_id );
484
485                 }
486
487                 if ( d_node->next == d_node && d_node->prev == d_node) {
488                         info_handler( "Last node, setting ring to NULL: %s.",
489                                 d_node->remote_id );
490
491                         active_class_node->current_server_node = NULL;
492
493                         server_node_free( d_node );
494                         return 0;
495
496                 } else {
497                         info_handler( "Nodes remain, splicing: %s, %s",
498                                 d_node->prev->remote_id,
499                                 d_node->next->remote_id);
500
501                 info_handler( "d_node => %x, next => %x, prev => %x",
502                                         d_node, d_node->next, d_node->prev );
503
504
505                         d_node->prev->next = d_node->next;
506                         d_node->next->prev = d_node->prev;
507
508                         info_handler( "prev => %x, prev->next => %x, prev->prev => %x",
509                                 d_node->prev, d_node->prev->next, d_node->prev->prev );
510
511                         info_handler( "next => %x, next->next => %x, next->prev => %x",
512                                 d_node->next, d_node->next->next, d_node->next->prev );
513                                 
514                         if (active_class_node->current_server_node == d_node)
515                                 active_class_node->current_server_node = d_node->next;
516
517
518                         server_node_free( d_node );
519                 }
520         } 
521
522         return 1;
523 }
524
525 server_node * find_server_node ( server_class_node * class, const char * remote_id ) {
526
527         if ( class == NULL ) {
528                 warning_handler(" find_server_node(): bad arg!");
529                 return NULL;
530         }
531
532         server_node * start_node = class->current_server_node;
533         server_node * node = class->current_server_node;
534
535         do {
536                 if (node == NULL)
537                         return NULL;
538
539                 if ( strcmp(node->remote_id, remote_id) == 0 )
540                         return node;
541
542                 node = node->next;
543
544         } while ( node != start_node );
545
546         return NULL;
547 }
548
549 /* if we return -1, then we just deleted the server_class you were looking for
550         if we return 0, then some other error has occured
551         we return 1 otherwise */
552 int remove_server_class( transport_router_registrar* router, server_class_node* class ) {
553         if( class == NULL )
554                 return 0;
555
556         transport_message * msg = NULL;
557         while ( (msg = client_recv(class->jabber->t_client, 0)) != NULL ) {
558                 debug_handler( "Looping on messages to dead class" );
559                 if( server_class_handle_msg(router, class, msg) < 0 ) {
560                   debug_handler( "This class was freed by a recursive call, exiting 'remove_server_class'");
561                   //message_free(msg); - this will be freed by server_class_handle_msg
562                   debug_handler( "Message Freed");
563                   return -1;
564                 }
565                 message_free(msg);
566         }
567         
568
569         free( class->server_class );
570         class->server_class = NULL;
571
572         find_server_class( router, router_resource ); /* find deletes for us */
573         debug_handler( "Successfuly called 'find_server_class' on class to delete" );
574
575         if( router->server_class_list == NULL ) 
576                 return 0;
577         return 1;
578 }
579
580 server_class_node * find_server_class ( transport_router_registrar * router, const char * class_id ) {
581
582         if ( router == NULL ) {
583                 warning_handler(" find_server_class(): bad arg!");
584                 return NULL;
585         }
586
587         info_handler( "Finding server class for %s", class_id );
588         server_class_node * class = router->server_class_list;
589         server_class_node * dead_class = NULL;
590
591         while ( class != NULL ) {
592
593                 if ( class->server_class == NULL ) {
594                         info_handler( "Found an empty server class" );
595
596                         if ( class->prev != NULL ) {
597                                 class->prev->next = class->next;
598                                 if( class->next != NULL ) {
599                                         class->next->prev = class->prev;
600                                 }
601
602                         } else {
603                                 info_handler( "Empty class is the first on the list" );
604                                 if( class->next != NULL ) 
605                                         router->server_class_list = class->next;
606
607                                 else { /* we're the last class node in the class node list */
608                                         info_handler( "Empty class is the last on the list" );
609                                         server_class_node_free( router->server_class_list );
610                                         router->server_class_list = NULL;
611                                         break;
612                                 }
613                                         
614                         }
615
616                         dead_class = class;
617                         class = class->next;
618
619                         info_handler( "Tossing our dead class" );
620                         server_class_node_free( dead_class );
621
622                         if ( class == NULL )
623                                 return NULL;
624                 }
625
626                 if ( strcmp(class->server_class, class_id) == 0 )
627                         return class;
628                 info_handler( "%s != %s", class->server_class, class_id );
629
630                 class = class->next;
631         }
632
633         debug_handler( "Returning NULL from find_server_class()" );
634         return NULL;
635 }
636
637 /* builds a new server class and connects to the jabber server with the new resource */
638 server_class_node* init_server_class( 
639                 transport_router_registrar* router, char* remote_id, char* server_class ) {
640
641         size_t len = sizeof( server_class_node );
642         server_class_node* node = (server_class_node*) safe_malloc( len );
643
644         node->jabber = jabber_connect_init( router->jabber->server,
645                         router->jabber->port, router->jabber->username, 
646                         router->jabber->password, server_class, router->jabber->connect_timeout, router->component );
647
648
649
650         node->server_class = strdup( server_class );
651         if( server_class == NULL ) {
652                 fatal_handler( "imit_server_class(): out of memory for %s", server_class );
653                 return NULL;
654         }
655
656         info_handler( "Received class to init_server_class: %s", server_class );
657         node->current_server_node = init_server_node( remote_id );
658         if( node->current_server_node == NULL ) {
659                 fatal_handler( "init_server_class(): NULL server_node for %s", remote_id );
660                 return NULL;
661         }
662
663
664         if( ! j_connect( node->jabber ) ) {
665                 fatal_handler( "Unable to init server class %s", node->server_class );
666                 return NULL;
667         }
668
669         info_handler( "Jabber address in init for %s : address %x : username %s : resource %s", 
670                         node->server_class, node->jabber->t_client->session->sock_obj->sock_fd, 
671                         node->jabber->username,  node->jabber->resource );
672
673         return node;
674
675 }
676
677 /* builds a new server_node to be added to the ring of server_nodes */
678 server_node* init_server_node(  char* remote_id ) {
679
680         info_handler( "Initing server node for %s", remote_id );
681         server_node* current_server_node;
682         size_t size = sizeof( server_node);
683         current_server_node = (server_node*) safe_malloc( size );
684
685         current_server_node->remote_id = strdup(remote_id);
686         if( current_server_node->remote_id == NULL ) {
687                 fatal_handler("init_server_class(): Out of Memory for %s", remote_id );
688                 return NULL;
689         }
690         
691         current_server_node->reg_time = time(NULL);     
692         current_server_node->available = 1;
693         current_server_node->next = current_server_node;
694         current_server_node->prev = current_server_node;
695
696
697         return current_server_node;
698
699 }
700
701 int  server_class_handle_msg( transport_router_registrar* router, 
702                 server_class_node* s_node, transport_message* msg ) {
703
704         if( s_node->current_server_node == NULL ) {
705                 /* return error to client ??!*/
706                 /* WE have no one to send the message to */
707                 warning_handler( "We no longer have any servers for %s : " 
708                                 "no one to send the message to. Sending error message to %s", s_node->server_class, msg->sender );
709                 free( msg->recipient );  
710
711                 char* rec = strdup( msg->sender );
712                 if( rec == NULL ) {
713                         fatal_handler( "class msg_handler: out of memory");
714                         return 0;
715                 }
716
717                 info_handler( "Building error message to return for %s", s_node->server_class);
718                 msg->recipient = rec;
719                 set_msg_error(msg, "cancel", 501);
720
721                 client_send_message( s_node->jabber->t_client, msg );
722                 message_free( msg );
723
724                 remove_server_class( router, s_node );
725                 debug_handler( "Successfully removed server class" ); 
726
727                 return -1;
728         }
729
730         info_handler( "[%s] Received \nfrom: %s \nto: %s", 
731                         s_node->server_class, msg->sender, msg->recipient );
732
733         if( msg->is_error ) {
734                 warning_handler( "We've received an error message type: %s : code: %d", 
735                                 msg->error_type, msg->error_code );
736
737                 if( strcmp( msg->error_type, "cancel" ) == 0 ) {
738                         warning_handler( "Looks like we've lost a server!" );
739                         server_node* dead_node = find_server_node( s_node, msg->sender );
740
741                         if( dead_node != NULL ) { 
742                                 //message_free( msg );
743                                 transport_message* tmp = dead_node->last_sent;
744
745                                 /* copy over last sent, it will be freed in the unregister function */
746                                 transport_message* tmp2 = message_init( tmp->body, tmp->subject, tmp->thread,
747                                                 tmp->recipient, tmp->sender );
748                                         
749                                 message_set_router_info( tmp2, tmp->router_from,  
750                                                 tmp->router_to, tmp->router_class, tmp->router_command, tmp->broadcast );
751
752                                 if( ! unregister_server_node( s_node, dead_node->remote_id ) ) { 
753                                         /* WE have no one to send the message to */
754                                         warning_handler( "We no longer have any servers for %s : " 
755                                                         "no one to send the message to.", s_node->server_class );
756                                         free( msg->recipient );  
757
758                                         char* rec = strdup( msg->router_from );
759                                         if( rec == NULL ) {
760                                                 fatal_handler( "class msg_handler: out of memory");
761                                                 return 0;
762                                         }
763
764                                         info_handler( "Building error message to return for %s", s_node->server_class);
765                                         msg->recipient = rec;
766                                         client_send_message( s_node->jabber->t_client, msg );
767                                         message_free( tmp2 );
768                                         message_free( msg );
769                                         return 0;
770
771                                 } else {
772                                         msg = tmp2;
773                                 }
774                         }
775                 }
776         } 
777
778
779         server_node* c_node = s_node->current_server_node->next;
780
781         /* not implemented yet */
782         while( ! c_node->available ) {
783                 if( c_node == s_node->current_server_node ) {
784                         warning_handler("No server_node's are available for %s", s_node->server_class );
785                         /* XXX send error message to client */
786                         return 0;
787                 }
788                 c_node = c_node->next;
789         }
790         s_node->current_server_node = c_node;
791
792         transport_message * new_msg =
793                 message_init(   msg->body, msg->subject, msg->thread, 
794                                 s_node->current_server_node->remote_id, msg->sender );
795
796         message_set_router_info( new_msg, msg->sender, NULL, NULL, NULL, 0 );
797
798         info_handler( "[%s] Routing message from [%s]\nto [%s]", s_node->server_class, msg->sender, new_msg->recipient );
799         //info_handler( "New Message Details: sender:%s recipient: %s \nbody: %s", 
800         //              new_msg->sender, new_msg->recipient, new_msg->body );
801
802         message_free( s_node->current_server_node->last_sent );
803         s_node->current_server_node->last_sent = msg;
804
805         if ( new_msg != NULL && client_send_message( s_node->jabber->t_client, new_msg ) ) {
806                 s_node->current_server_node->serve_count++;
807                 s_node->current_server_node->la_time = time(NULL);
808                 message_free( new_msg ); // XXX
809                 return 1;
810         }
811         message_free( new_msg ); // XXX
812
813         return 0;
814 }
815
816
817 int router_return_server_info( 
818                 transport_router_registrar* router, transport_message* msg ) {
819
820         server_class_node* cur_class = router->server_class_list;
821         growing_buffer* buffer = buffer_init(1024);
822
823         while( cur_class != NULL ) {
824
825                 server_node* start_node = cur_class->current_server_node;
826                 server_node* cur_node = start_node;
827                 if( cur_node == NULL ) continue; 
828
829                 do {
830
831                         char tbuf[124];
832                         memset(tbuf,0,124);
833                         sprintf( tbuf, "%d", (int)cur_node->reg_time ); 
834                         buffer_add( buffer, tbuf );
835                         buffer_add( buffer, " | ");
836
837                         memset(tbuf,0,124);
838                         sprintf( tbuf, "%d", (int)cur_node->upd_time ); 
839                         buffer_add( buffer, tbuf );
840                         buffer_add( buffer, " | ");
841
842                         memset(tbuf,0,124);
843                         sprintf( tbuf, "%d", (int)cur_node->la_time );  
844                         buffer_add( buffer, tbuf );
845                         buffer_add( buffer, " | ");
846
847
848                         char sbuf[64];
849                         memset(sbuf,0,64);
850                         sprintf(sbuf,"%d",cur_node->serve_count);
851
852                         buffer_add( buffer, "#" ); 
853                         buffer_add( buffer, sbuf ); 
854                         buffer_add( buffer, " | ");
855
856                         buffer_add( buffer, cur_class->server_class );
857                         buffer_add( buffer, " | ");
858
859                         buffer_add( buffer, cur_node->remote_id );
860
861                         buffer_add( buffer, "\n" );
862                         cur_node = cur_node->next;
863
864                 } while( cur_node != start_node );
865
866                 cur_class = cur_class->next;
867
868         }
869
870         info_handler( "Router returning servers query command: %s", buffer->buf );
871
872         transport_message* new_msg; 
873
874         if( buffer->buf == NULL || strlen(buffer->buf) == 0 )
875                 new_msg = message_init( "0", NULL, NULL, msg->sender, NULL );
876         else
877                 new_msg = message_init( buffer->buf, NULL, NULL, msg->sender, NULL );
878
879         client_send_message( router->jabber->t_client, new_msg );
880         message_free( new_msg );
881
882         return 1;
883
884 }
885
886 int router_registrar_handle_app_request( 
887                 transport_router_registrar* router, transport_message* msg ) {
888
889         osrf_message* arr[ROUTER_MAX_MSGS_PER_PACKET];
890         memset(arr, 0, ROUTER_MAX_MSGS_PER_PACKET );
891         int num_msgs = osrf_message_from_xml( msg->body, arr );
892
893         int i;
894         for( i = 0; i != num_msgs; i++ ) {
895
896                 osrf_message* omsg = arr[i];
897                 osrf_message* success = NULL;
898                 osrf_message** result = NULL;
899                 int num_responses;
900
901                 char* newxml =  osrf_message_to_xml(omsg);
902                 debug_handler( "Received potential app request from client:\n%s\n", newxml ); 
903                 free(newxml);
904
905                 if(omsg->m_type == CONNECT) {
906
907                         success = osrf_message_init( 
908                                         STATUS, omsg->thread_trace, omsg->protocol );
909
910                         osrf_message_set_status_info( 
911                                         success, "oilsConnectStatus", "Connection Successful", OSRF_STATUS_OK );
912
913                 } else if( omsg->m_type == REQUEST ) {
914
915                         result = router_registrar_process_app_request( router, omsg, &num_responses );
916                         
917                 } else if(omsg->m_type == DISCONNECT) { 
918                         success = NULL;
919
920                 } else {
921
922                         success = osrf_message_init( 
923                                         STATUS, omsg->thread_trace, omsg->protocol );
924                         osrf_message_set_status_info( 
925                                         success, "oilsMethodException", "Method Not Found", OSRF_STATUS_NOTFOUND );
926                 }
927
928
929                 /* now send our new message back */
930                 if(success) {
931
932                         char* xml =  osrf_message_to_xml(success);
933                         debug_handler( "Sending XML to client app request:\n%s\n", xml );
934                         transport_message* return_m = message_init( 
935                                 xml, "", msg->thread, msg->sender, "" );
936
937
938                         client_send_message(router->jabber->t_client, return_m);
939
940                         free(xml);
941                         osrf_message_free(success);
942                 } else if(result) {
943                         int i;
944
945                         for(i=0; i!= num_responses; i++){
946                                 char* xml =  osrf_message_to_xml(result[i]);
947                                 debug_handler( "Sending XML to client app request:\n%s\n", xml );
948                                 transport_message* return_m = message_init( 
949                                         xml, "", msg->thread, msg->sender, "" );
950
951
952                                 client_send_message(router->jabber->t_client, return_m);
953
954                                 free(xml);
955                                 osrf_message_free(result[i]);
956                         }
957
958                         osrf_message* complete = osrf_message_init(
959                                 STATUS, result[i-1]->thread_trace, result[i-1]->protocol );
960                         osrf_message_set_status_info( complete, 
961                                         "oilsConnectStatus", "Request Complete", OSRF_STATUS_COMPLETE );
962                         char* complete_xml = osrf_message_to_xml(complete);
963                         transport_message* complete_m = message_init( 
964                                         complete_xml, "", msg->thread, msg->sender, "" );
965                         client_send_message(router->jabber->t_client, complete_m);
966                         free(complete_xml);
967                         osrf_message_free(complete);
968                         free(result);
969
970                 }
971
972         }
973
974         return 1;
975
976 }
977
978
979
980
981 osrf_message** router_registrar_process_app_request( 
982                 transport_router_registrar* router, osrf_message* omsg, int* num_responses ) {
983
984
985         if( omsg->method_name == NULL )
986                 return NULL;
987
988         osrf_message** result_array = NULL;
989
990
991         debug_handler( "Received method from client: %s", omsg->method_name );
992
993         if(!strcmp(omsg->method_name,"opensrf.router.info.class.list")) {
994
995                 object* result_content = json_parse_string("[]");
996
997                 debug_handler("Processing opensrf.router.info.class.list request");
998
999                 server_class_node* cur_class = router->server_class_list;
1000                 while( cur_class != NULL ) {
1001
1002                         debug_handler("Adding %s to request list", cur_class->server_class);
1003
1004                         result_content->push(result_content, new_object(cur_class->server_class));
1005                         cur_class = cur_class->next;
1006                 }
1007                 result_array = safe_malloc(sizeof(osrf_message*));
1008                 *num_responses = 1;
1009
1010                 result_array[0] = osrf_message_init(
1011                         RESULT, omsg->thread_trace, omsg->protocol );
1012
1013                 osrf_message_set_result_content( result_array[0], object_to_json(result_content));
1014                 free_object(result_content);
1015
1016
1017         } else if(!strcmp(omsg->method_name,"opensrf.router.info.stats")) {
1018
1019                 /* we have a server_class array which holds an array of node_objects.
1020                         each node_object contains an array of stats
1021                         */
1022
1023                 debug_handler("Processing opensrf.router.info.stats request");
1024
1025                 object* result_content = json_parse_string("{}");
1026
1027                 server_class_node* cur_class = router->server_class_list;
1028
1029                 while( cur_class != NULL ) {
1030
1031                         server_node* start_node = cur_class->current_server_node;
1032                         server_node* cur_node = start_node;
1033                         if( cur_node == NULL ) continue; 
1034
1035                         object* server_object = json_parse_string("{}");
1036
1037                         do {
1038
1039                                 object* node_stats_array = json_parse_string("[]");
1040
1041                                 object* json_reg_time = json_parse_string("{}");
1042
1043                                 object_add_key( json_reg_time, "reg_time", 
1044                                         new_int_object((int) cur_node->reg_time));
1045
1046                                 object_push(  node_stats_array, json_reg_time );
1047
1048                                 object* json_upd_time = json_parse_string("{}");
1049
1050
1051                                 object_add_key( json_upd_time, "upd_time", 
1052                                         new_int_object((int)cur_node->upd_time));
1053
1054
1055
1056                                 object_push( node_stats_array, json_upd_time );
1057
1058
1059
1060                                 object* json_la_time = json_parse_string("{}");
1061
1062
1063
1064                                 object_add_key( json_la_time, "la_time", 
1065                                                 new_int_object((int)cur_node->la_time));
1066
1067
1068                                 object_push( node_stats_array, json_la_time );
1069
1070                                 object* json_serve_count = json_parse_string("{}");
1071
1072
1073                                 object_add_key( json_serve_count, "serve_count", 
1074                                         new_int_object((int)cur_node->serve_count));
1075
1076                                 
1077                                 object_push( node_stats_array, json_serve_count );
1078
1079
1080                                 object_add_key( server_object, cur_node->remote_id, node_stats_array );
1081
1082                                 cur_node = cur_node->next;
1083         
1084                         } while( cur_node != start_node );
1085
1086                         object_add_key( result_content, cur_class->server_class, server_object );
1087         
1088                         cur_class = cur_class->next;
1089
1090                                 
1091                 }
1092
1093                 result_array = safe_malloc(sizeof(osrf_message*));
1094                 *num_responses = 1;
1095
1096                 result_array[0] = osrf_message_init(
1097                         RESULT, omsg->thread_trace, omsg->protocol );
1098
1099                 osrf_message_set_result_content(result_array[0], object_to_json(result_content));
1100
1101                 free_object(result_content);
1102
1103
1104         } else if(!strcmp(omsg->method_name,"opensrf.system.method.all")) {
1105
1106                 object* content = json_parse_string("{}");
1107                 object_add_key(content, "api_level", new_object("1"));
1108                 object_add_key(content, "api_name", new_object("opensrf.router.info.class.list"));
1109                 object_add_key(content, "server_class", new_object("router"));
1110                 object_add_key(content, "stream", new_object("0"));
1111
1112                 object* content2 = json_parse_string("{}");
1113                 object_add_key(content2, "api_level", new_object("1"));
1114                 object_add_key(content2, "api_name", new_object("opensrf.router.info.stats"));
1115                 object_add_key(content2, "server_class", new_object("router"));
1116                 object_add_key(content2, "stream", new_object("0"));
1117
1118                 object* content3 = json_parse_string("{}");
1119                 object_add_key(content3, "api_level", new_object("1"));
1120                 object_add_key(content3, "api_name", new_object("opensrf.system.method.all"));
1121                 object_add_key(content3, "server_class", new_object("router"));
1122                 object_add_key(content3, "stream", new_object("1"));
1123
1124                 result_array = safe_malloc(3*sizeof(osrf_message*));
1125                 *num_responses = 3;
1126
1127                 result_array[0] = osrf_message_init(
1128                         RESULT, omsg->thread_trace, omsg->protocol );
1129
1130                 osrf_message_set_result_content( result_array[0], object_to_json(content));
1131                 free_object(content);
1132
1133                 result_array[1] = osrf_message_init(
1134                         RESULT, omsg->thread_trace, omsg->protocol );
1135                 osrf_message_set_result_content( result_array[1], object_to_json(content2) );
1136                 free_object(content2);
1137
1138                 result_array[2] = osrf_message_init(
1139                         RESULT, omsg->thread_trace, omsg->protocol );
1140                 osrf_message_set_result_content( result_array[1], object_to_json(content3) );
1141                 free_object(content3);
1142
1143
1144         }
1145         
1146         
1147         if( result_array == NULL || result_array[0] == NULL ) 
1148                 return NULL;
1149
1150         return result_array;
1151 }
1152
1153
1154
1155
1156 int router_registrar_free( transport_router_registrar* router_registrar ) {
1157         if( router_registrar == NULL ) return 0;
1158         jabber_connect_free( router_registrar->jabber );
1159
1160         /* free the server_class list XXX */
1161         while( router_registrar->server_class_list != NULL ) {
1162                 remove_server_class(router_registrar, router_registrar->server_class_list);
1163                 debug_handler( "Removed server classes in registrar free");
1164         }
1165
1166         transport_router_registrar* router = router_registrar;
1167
1168         /* make this better 
1169         int i = 0;
1170         while(1) {
1171
1172                 if( router->trusted_servers[i] == NULL &&
1173                                 router->trusted_clients[i] == NULL )
1174                         break;
1175
1176                 if(router->trusted_servers[i] != NULL)
1177                         free(router->trusted_servers[i]);
1178                 if(router->trusted_clients[i] != NULL)
1179                         free(router->trusted_clients[i]);
1180                 i++;
1181         }
1182         */
1183
1184         free( router_registrar );
1185         return 1;
1186 }
1187
1188
1189 int server_class_node_free( server_class_node* node ) {
1190         if( node == NULL ) { return 0; }
1191         if( node->server_class != NULL ) 
1192                 free( node->server_class );
1193
1194         jabber_connect_free( node->jabber );
1195
1196         /* just in case, free the list */
1197         while( node->current_server_node != NULL ) {
1198                 unregister_server_node( node, node->current_server_node->remote_id );
1199         }
1200         free( node );
1201         return 1;
1202 }
1203
1204 int server_node_free( server_node* node ) {
1205         if( node == NULL ) { return 0; }
1206         message_free( node->last_sent );
1207         free( node->remote_id );
1208         free( node );
1209         return 1;
1210 }
1211
1212 int jabber_connect_free( jabber_connect* jabber ) {
1213         if( jabber == NULL ) { return 0; }
1214         client_free( jabber->t_client );
1215         free( jabber->username );
1216         free( jabber->password );
1217         free( jabber->resource );
1218         free( jabber->server );
1219         free( jabber );
1220         return 1;
1221 }
1222
1223