b58677acbc40f5de35ac8696382d4495e62ff893
[OpenSRF.git] / src / srfsh / srfsh.c
1 #include <opensrf/transport_client.h>
2 #include <opensrf/osrf_message.h>
3 #include <opensrf/osrf_app_session.h>
4 #include <time.h>
5 #include <ctype.h>
6 #include <sys/timeb.h>
7 #include <sys/types.h>
8 #include <sys/wait.h>
9
10 #include <opensrf/utils.h>
11 #include <opensrf/log.h>
12
13 #include <signal.h>
14
15 #include <stdio.h>
16 #include <readline/readline.h>
17 #include <readline/history.h>
18
19 #define SRFSH_PORT 5222
20 #define COMMAND_BUFSIZE 4096
21
22
23 /* shell prompt */
24 static const char* prompt = "srfsh# ";
25
26 static char* history_file = NULL;
27
28 //static int child_dead = 0;
29
30 static char* login_session = NULL;
31
32 /* true if we're pretty printing json results */
33 static int pretty_print = 1;
34 /* true if we're bypassing 'less' */
35 static int raw_print = 0;
36
37 /* our jabber connection */
38 static transport_client* client = NULL; 
39
40 /* the last result we received */
41 static osrf_message* last_result = NULL;
42
43 /* functions */
44 static int parse_request( char* request );
45
46 /* handles router requests */
47 static int handle_router( char* words[] );
48
49 /* utility method for print time data */
50 static int handle_time( char* words[] ); 
51
52 /* handles app level requests */
53 static int handle_request( char* words[], int relay );
54 static int handle_set( char* words[]);
55 static int handle_print( char* words[]);
56 static int send_request( char* server, 
57                                   char* method, growing_buffer* buffer, int relay );
58 static int parse_error( char* words[] );
59 static int router_query_servers( const char* server );
60 static int print_help( void );
61
62 //static int srfsh_client_connect();
63 //static char* tabs(int count);
64 //static void sig_child_handler( int s );
65 //static void sig_int_handler( int s );
66
67 static int load_history( void );
68 static int handle_math( char* words[] );
69 static int do_math( int count, int style );
70 static int handle_introspect(char* words[]);
71 static int handle_login( char* words[]);
72
73 static int recv_timeout = 120;
74 static int is_from_script = 0;
75
76 int main( int argc, char* argv[] ) {
77
78         /* --------------------------------------------- */
79         /* see if they have a .srfsh.xml in their home directory */
80         char* home = getenv("HOME");
81         int l = strlen(home) + 36;
82         char fbuf[l];
83         memset(fbuf, 0, l);
84         sprintf(fbuf,"%s/.srfsh.xml",home);
85         
86         if(!access(fbuf, R_OK)) {
87                 if( ! osrf_system_bootstrap_client(fbuf, "srfsh") ) {
88                         fprintf(stderr,"Unable to bootstrap client for requests\n");
89                         osrfLogError( OSRF_LOG_MARK,  "Unable to bootstrap client for requests");
90                         return -1;
91                 }
92
93         } else {
94                 fprintf(stderr,"No Config file found at %s\n", fbuf ); 
95                 return -1;
96         }
97
98         if(argc > 1) {
99                 /* for now.. the first arg is used as a script file for processing */
100                 int f;
101                 if( (f = open(argv[1], O_RDONLY)) == -1 ) {
102                         osrfLogError( OSRF_LOG_MARK, "Unable to open file %s for reading, exiting...", argv[1]);
103                         return -1;
104                 }
105
106                 if(dup2(f, STDIN_FILENO) == -1) {
107                         osrfLogError( OSRF_LOG_MARK, "Unable to duplicate STDIN, exiting...");
108                         return -1;
109                 }
110
111                 close(f);
112                 is_from_script = 1;
113         }
114                 
115         /* --------------------------------------------- */
116         load_history();
117
118
119         client = osrf_system_get_transport_client();
120
121         /* main process loop */
122         int newline_needed = 1;  /* used as boolean */
123         char* request;
124         while((request=readline(prompt))) {
125
126                 // Find first non-whitespace character
127                 
128                 char * cmd = request;
129                 while( isspace( (unsigned char) *cmd ) )
130                         ++cmd;
131
132                 // ignore comments and empty lines
133
134                 if( '\0' == *cmd || '#' == *cmd )
135                         continue;
136
137                 // Remove trailing whitespace.  We know at this point that
138                 // there is at least one non-whitespace character somewhere,
139                 // or we would have already skipped this line.  Hence we
140                 // needn't check to make sure that we don't back up past
141                 // the beginning.
142
143                 {
144                         // The curly braces limit the scope of the end variable
145                         
146                         char * end = cmd + strlen(cmd) - 1;
147                         while( isspace( (unsigned char) *end ) )
148                                 --end;
149                         end[1] = '\0';
150                 }
151
152                 if( !strcasecmp(cmd, "exit") || !strcasecmp(cmd, "quit"))
153                 {
154                         newline_needed = 0;
155                         break; 
156                 }
157                 
158                 char* req_copy = strdup(cmd);
159
160                 parse_request( req_copy ); 
161                 if( request && *cmd ) {
162                         add_history(request);
163                 }
164
165                 free(request);
166                 free(req_copy);
167
168                 fflush(stderr);
169                 fflush(stdout);
170         }
171
172         if( newline_needed ) {
173                 
174                 // We left the readline loop after seeing an EOF, not after
175                 // seeing "quit" or "exit".  So we issue a newline in order
176                 // to avoid leaving a dangling prompt.
177
178                 putchar( '\n' );
179         }
180
181         if(history_file != NULL )
182                 write_history(history_file);
183
184         free(request);
185         free(login_session);
186
187         osrf_system_shutdown();
188         return 0;
189 }
190
191 static int load_history( void ) {
192
193         char* home = getenv("HOME");
194         int l = strlen(home) + 24;
195         char fbuf[l];
196
197         memset(fbuf, 0, l);
198         sprintf(fbuf,"%s/.srfsh_history",home);
199         history_file = strdup(fbuf);
200
201         if(!access(history_file, W_OK | R_OK )) {
202                 history_length = 5000;
203                 read_history(history_file);
204         }
205         return 1;
206 }
207
208
209 static int parse_error( char* words[] ) {
210
211         if( ! words )
212                 return 0;
213
214         growing_buffer * gbuf = buffer_init( 64 );
215         buffer_add( gbuf, *words );
216         while( *++words ) {
217                 buffer_add( gbuf, " " );
218                 buffer_add( gbuf, *words );
219         }
220         fprintf( stderr, "???: %s\n", gbuf->buf );
221         buffer_free( gbuf );
222         
223         return 0;
224
225 }
226
227
228 static int parse_request( char* request ) {
229
230         if( request == NULL )
231                 return 0;
232
233         char* original_request = strdup( request );
234         char* words[COMMAND_BUFSIZE]; 
235         
236         int ret_val = 0;
237         int i = 0;
238
239
240         char* req = request;
241         char* cur_tok = strtok( req, " " );
242
243         if( cur_tok == NULL )
244         {
245                 free( original_request );
246                 return 0;
247         }
248
249         /* Load an array with pointers to    */
250         /* the tokens as defined by strtok() */
251         
252         while(cur_tok != NULL) {
253                 if( i < COMMAND_BUFSIZE - 1 ) {
254                         words[i++] = cur_tok;
255                         cur_tok = strtok( NULL, " " );
256                 } else {
257                         fprintf( stderr, "Too many tokens in command\n" );
258                         free( original_request );
259                         return 1;
260                 }
261         }
262
263         words[i] = NULL;
264         
265         /* pass off to the top level command */
266         if( !strcmp(words[0],"router") ) 
267                 ret_val = handle_router( words );
268
269         else if( !strcmp(words[0],"time") ) 
270                 ret_val = handle_time( words );
271
272         else if (!strcmp(words[0],"request"))
273                 ret_val = handle_request( words, 0 );
274
275         else if (!strcmp(words[0],"relay"))
276                 ret_val = handle_request( words, 1 );
277
278         else if (!strcmp(words[0],"help"))
279                 ret_val = print_help();
280
281         else if (!strcmp(words[0],"set"))
282                 ret_val = handle_set(words);
283
284         else if (!strcmp(words[0],"print"))
285                 ret_val = handle_print(words);
286
287         else if (!strcmp(words[0],"math_bench"))
288                 ret_val = handle_math(words);
289
290         else if (!strcmp(words[0],"introspect"))
291                 ret_val = handle_introspect(words);
292
293         else if (!strcmp(words[0],"login"))
294                 ret_val = handle_login(words);
295
296         else if (words[0][0] == '!') {
297                 system( original_request + 1 );
298                 ret_val = 1;
299         }
300         
301         free( original_request );
302         
303         if(!ret_val)
304                 return parse_error( words );
305         else
306                 return 1;
307 }
308
309
310 static int handle_introspect(char* words[]) {
311
312         if( ! words[1] )
313                 return 0;
314
315         fprintf(stderr, "--> %s\n", words[1]);
316
317         // Build a command in a suitably-sized
318         // buffer and then parse it
319         
320         size_t len;
321         if( words[2] ) {
322                 static const char text[] = "request %s opensrf.system.method %s";
323                 len = sizeof( text ) + strlen( words[1] ) + strlen( words[2] );
324                 char buf[len];
325                 sprintf( buf, text, words[1], words[2] );
326                 return parse_request( buf );
327
328         } else {
329                 static const char text[] = "request %s opensrf.system.method.all";
330                 len = sizeof( text ) + strlen( words[1] );
331                 char buf[len];
332                 sprintf( buf, text, words[1] );
333                 return parse_request( buf );
334
335         }
336 }
337
338
339 static int handle_login( char* words[]) {
340
341         if( words[1] && words[2]) {
342
343                 char* username          = words[1];
344                 char* password          = words[2];
345                 char* type                      = words[3];
346                 char* orgloc            = words[4];
347                 char* workstation       = words[5];
348                 int orgloci = (orgloc) ? atoi(orgloc) : 0;
349                 if(!type) type = "opac";
350
351                 char login_text[] = "request open-ils.auth open-ils.auth.authenticate.init \"%s\"";
352                 size_t len = sizeof( login_text ) + strlen(username);
353
354                 char buf[len];
355                 buf[0] = '\0';
356                 sprintf( buf, login_text, username );
357                 parse_request(buf);
358
359                 const char* hash;
360                 if(last_result && last_result->_result_content) {
361                         jsonObject* r = last_result->_result_content;
362                         hash = jsonObjectGetString(r);
363                 } else return 0;
364
365
366                 char* pass_buf = md5sum(password);
367
368                 size_t both_len = strlen( hash ) + strlen( pass_buf ) + 1;
369                 char both_buf[both_len];
370                 both_buf[0] = '\0';
371                 sprintf(both_buf,"%s%s",hash, pass_buf);
372
373                 char* mess_buf = md5sum(both_buf);
374
375                 growing_buffer* argbuf = buffer_init(64);
376                 buffer_fadd(argbuf, 
377                                 "request open-ils.auth open-ils.auth.authenticate.complete "
378                                 "{ \"username\" : \"%s\", \"password\" : \"%s\"", username, mess_buf );
379
380                 if(type) buffer_fadd( argbuf, ", \"type\" : \"%s\"", type );
381                 if(orgloci) buffer_fadd( argbuf, ", \"org\" : %d", orgloci );
382                 if(workstation) buffer_fadd( argbuf, ", \"workstation\" : \"%s\"", workstation);
383                 buffer_add(argbuf, "}");
384
385                 free(pass_buf);
386                 free(mess_buf);
387
388                 parse_request( argbuf->buf );
389                 buffer_free(argbuf);
390
391                 if( login_session != NULL )
392                         free( login_session );
393
394                 const jsonObject* x = last_result->_result_content;
395                 double authtime = 0;
396                 if(x) {
397                         const char* authtoken = jsonObjectGetString(
398                                         jsonObjectGetKeyConst(jsonObjectGetKeyConst(x,"payload"), "authtoken"));
399                         authtime  = jsonObjectGetNumber(
400                                         jsonObjectGetKeyConst(jsonObjectGetKeyConst(x,"payload"), "authtime"));
401
402                         if(authtoken)
403                                 login_session = strdup(authtoken);
404                         else
405                                 login_session = NULL;
406                 }
407                 else login_session = NULL;
408
409                 printf("Login Session: %s.  Session timeout: %f\n",
410                            (login_session ? login_session : "(none)"), authtime );
411                 
412                 return 1;
413
414         }
415
416         return 0;
417 }
418
419 static int handle_set( char* words[]) {
420
421         char* variable;
422         if( (variable=words[1]) ) {
423
424                 char* val;
425                 if( (val=words[2]) ) {
426
427                         if(!strcmp(variable,"pretty_print")) {
428                                 if(!strcmp(val,"true")) {
429                                         pretty_print = 1;
430                                         printf("pretty_print = true\n");
431                                         return 1;
432                                 } 
433                                 if(!strcmp(val,"false")) {
434                                         pretty_print = 0;
435                                         printf("pretty_print = false\n");
436                                         return 1;
437                                 } 
438                         }
439
440                         if(!strcmp(variable,"raw_print")) {
441                                 if(!strcmp(val,"true")) {
442                                         raw_print = 1;
443                                         printf("raw_print = true\n");
444                                         return 1;
445                                 } 
446                                 if(!strcmp(val,"false")) {
447                                         raw_print = 0;
448                                         printf("raw_print = false\n");
449                                         return 1;
450                                 } 
451                         }
452
453                 }
454         }
455
456         return 0;
457 }
458
459
460 static int handle_print( char* words[]) {
461
462         char* variable;
463         if( (variable=words[1]) ) {
464                 if(!strcmp(variable,"pretty_print")) {
465                         if(pretty_print) {
466                                 printf("pretty_print = true\n");
467                                 return 1;
468                         } else {
469                                 printf("pretty_print = false\n");
470                                 return 1;
471                         }
472                 }
473
474                 if(!strcmp(variable,"raw_print")) {
475                         if(raw_print) {
476                                 printf("raw_print = true\n");
477                                 return 1;
478                         } else {
479                                 printf("raw_print = false\n");
480                                 return 1;
481                         }
482                 }
483
484                 if(!strcmp(variable,"login")) {
485                         printf("login session = %s\n",
486                                    login_session ? login_session : "(none)" );
487                         return 1;
488                 }
489
490         }
491         return 0;
492 }
493
494 static int handle_router( char* words[] ) {
495
496         if(!client)
497                 return 1;
498
499         int i;
500
501         if( words[1] ) { 
502                 if( !strcmp(words[1],"query") ) {
503                         
504                         if( words[2] && !strcmp(words[2],"servers") ) {
505                                 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {   
506                                         router_query_servers( words[i] );
507                                 }
508                                 return 1;
509                         }
510                         return 0;
511                 }
512                 return 0;
513         }
514         return 0;
515 }
516
517
518
519 static int handle_request( char* words[], int relay ) {
520
521         if(!client)
522                 return 1;
523
524         if(words[1]) {
525                 char* server = words[1];
526                 char* method = words[2];
527                 int i;
528                 growing_buffer* buffer = NULL;
529                 if(!relay) {
530                         buffer = buffer_init(128);
531                         buffer_add(buffer, "[");
532                         for(i = 3; words[i] != NULL; i++ ) {
533                                 /* removes trailing semicolon if user accidentally enters it */
534                                 if( words[i][strlen(words[i])-1] == ';' )
535                                         words[i][strlen(words[i])-1] = '\0';
536                                 buffer_add( buffer, words[i] );
537                                 buffer_add(buffer, " ");
538                         }
539                         buffer_add(buffer, "]");
540                 }
541
542                 return send_request( server, method, buffer, relay );
543         } 
544
545         return 0;
546 }
547
548 int send_request( char* server, 
549                 char* method, growing_buffer* buffer, int relay ) {
550         if( server == NULL || method == NULL )
551                 return 0;
552
553         jsonObject* params = NULL;
554         if( !relay ) {
555                 if( buffer != NULL && buffer->n_used > 0 ) 
556                         params = jsonParseString(buffer->buf);
557         } else {
558                 if(!last_result || ! last_result->_result_content) { 
559                         printf("We're not going to call 'relay' with no result params\n");
560                         return 1;
561                 }
562                 else {
563                         jsonObject* o = jsonNewObject(NULL);
564                         jsonObjectPush(o, last_result->_result_content );
565                         params = o;
566                 }
567         }
568
569
570         if(buffer->n_used > 0 && params == NULL) {
571                 fprintf(stderr, "JSON error detected, not executing\n");
572                 return 1;
573         }
574
575         osrf_app_session* session = osrf_app_client_session_init(server);
576
577         if(!osrf_app_session_connect(session)) {
578                 osrfLogWarning( OSRF_LOG_MARK,  "Unable to connect to remote service %s\n", server );
579                 return 1;
580         }
581
582         double start = get_timestamp_millis();
583         //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
584         int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
585
586
587         osrf_message* omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
588
589         if(!omsg) 
590                 printf("\nReceived no data from server\n");
591         
592         
593         signal(SIGPIPE, SIG_IGN);
594
595         FILE* less; 
596         if(!is_from_script) less = popen( "less -EX", "w");
597         else less = stdout;
598
599         if( less == NULL ) { less = stdout; }
600
601         growing_buffer* resp_buffer = buffer_init(4096);
602
603         while(omsg) {
604
605                 if(raw_print) {
606
607                         if(omsg->_result_content) {
608         
609                                 osrf_message_free(last_result);
610                                 last_result = omsg;
611         
612                                 char* content;
613         
614                                 if( pretty_print ) {
615                                         char* j = jsonObjectToJSON(omsg->_result_content);
616                                         //content = json_printer(j); 
617                                         content = jsonFormatString(j);
618                                         free(j);
619                                 } else {
620                                         const char * temp_content = jsonObjectGetString(omsg->_result_content);
621                                         if( ! temp_content )
622                                                 temp_content = "[null]";
623                                         content = strdup( temp_content );
624                                 }
625                                 
626                                 printf( "\nReceived Data: %s\n", content ); 
627                                 free(content);
628         
629                         } else {
630
631                                 char code[16];
632                                 memset(code, 0, 16);
633                                 sprintf( code, "%d", omsg->status_code );
634                                 buffer_add( resp_buffer, code );
635
636                                 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n", 
637                                                 omsg->status_name, omsg->status_text, code );
638
639                                 fflush(stdout);
640                         }
641
642                 } else {
643
644                         if(omsg->_result_content) {
645         
646                                 osrf_message_free(last_result);
647                                 last_result = omsg;
648         
649                                 char* content;
650         
651                                 if( pretty_print && omsg->_result_content ) {
652                                         char* j = jsonObjectToJSON(omsg->_result_content);
653                                         //content = json_printer(j); 
654                                         content = jsonFormatString(j);
655                                         free(j);
656                                 } else {
657                                         const char * temp_content = jsonObjectGetString(omsg->_result_content);
658                                         if( temp_content )
659                                                 content = strdup( temp_content );
660                                         else
661                                                 content = NULL;
662                                 }
663
664                                 buffer_add( resp_buffer, "\nReceived Data: " ); 
665                                 buffer_add( resp_buffer, content );
666                                 buffer_add( resp_buffer, "\n" );
667                                 free(content);
668         
669                         } else {
670         
671                                 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
672                                 buffer_add( resp_buffer, omsg->status_name );
673                                 buffer_add( resp_buffer, "\nStatus: " );
674                                 buffer_add( resp_buffer, omsg->status_text );
675                                 buffer_add( resp_buffer, "\nStatus: " );
676                                 char code[16];
677                                 memset(code, 0, 16);
678                                 sprintf( code, "%d", omsg->status_code );
679                                 buffer_add( resp_buffer, code );
680                         }
681                 }
682
683
684                 omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
685
686         }
687
688         double end = get_timestamp_millis();
689
690         fprintf( less, resp_buffer->buf );
691         buffer_free( resp_buffer );
692         fprintf( less, "\n------------------------------------\n");
693         if( osrf_app_session_request_complete( session, req_id ))
694                 fprintf(less, "Request Completed Successfully\n");
695
696
697         fprintf(less, "Request Time in seconds: %.6f\n", end - start );
698         fprintf(less, "------------------------------------\n");
699
700         pclose(less); 
701
702         osrf_app_session_request_finish( session, req_id );
703         osrf_app_session_disconnect( session );
704         osrf_app_session_destroy( session );
705
706
707         return 1;
708
709
710 }
711
712 static int handle_time( char* words[] ) {
713         if(!words[1]) {
714                 printf("%f\n", get_timestamp_millis());
715     } else {
716         time_t epoch = (time_t) atoi(words[1]);
717                 printf("%s", ctime(&epoch));
718     }
719         return 1;
720 }
721
722                 
723
724 static int router_query_servers( const char* router_server ) {
725
726         if( ! router_server || strlen(router_server) == 0 ) 
727                 return 0;
728
729         const static char router_text[] = "router@%s/router";
730         size_t len = sizeof( router_text ) + strlen( router_server );
731         char rbuf[len];
732         rbuf[0] = '\0';
733         sprintf(rbuf, router_text, router_server );
734                 
735         transport_message* send = 
736                 message_init( "servers", NULL, NULL, rbuf, NULL );
737         message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
738
739         client_send_message( client, send );
740         message_free( send );
741
742         transport_message* recv = client_recv( client, -1 );
743         if( recv == NULL ) {
744                 fprintf(stderr, "NULL message received from router\n");
745                 return 1;
746         }
747         
748         printf( 
749                         "---------------------------------------------------------------------------------\n"
750                         "Received from 'server' query on %s\n"
751                         "---------------------------------------------------------------------------------\n"
752                         "original reg time | latest reg time | last used time | class | server\n"
753                         "---------------------------------------------------------------------------------\n"
754                         "%s"
755                         "---------------------------------------------------------------------------------\n"
756                         , router_server, recv->body );
757
758         message_free( recv );
759         
760         return 1;
761 }
762
763 static int print_help( void ) {
764
765         printf(
766                         "---------------------------------------------------------------------------------\n"
767                         "Commands:\n"
768                         "---------------------------------------------------------------------------------\n"
769                         "help                   - Display this message\n"
770                         "!<command> [args]      - Forks and runs the given command in the shell\n"
771                 /*
772                         "time                   - Prints the current time\n"
773                         "time <timestamp>       - Formats seconds since epoch into readable format\n"
774                 */
775                         "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
776                         "print <variable>       - Displays the value of a srfsh variable\n"
777                         "---------------------------------------------------------------------------------\n"
778
779                         "router query servers <server1 [, server2, ...]>\n"
780                         "       - Returns stats on connected services\n"
781                         "\n"
782                         "\n"
783                         "request <service> <method> [ <json formatted string of params> ]\n"
784                         "       - Anything passed in will be wrapped in a json array,\n"
785                         "               so add commas if there is more than one param\n"
786                         "\n"
787                         "\n"
788                         "relay <service> <method>\n"
789                         "       - Performs the requested query using the last received result as the param\n"
790                         "\n"
791                         "\n"
792                         "math_bench <num_batches> [0|1|2]\n"
793                         "       - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
794                         "                2 means reconnect after every request\n"
795                         "\n"
796                         "introspect <service>\n"
797                         "       - prints the API for the service\n"
798                         "\n"
799                         "\n"
800                         "---------------------------------------------------------------------------------\n"
801                         " Commands for Open-ILS\n"
802                         "---------------------------------------------------------------------------------\n"
803                         "login <username> <password>\n"
804                         "       - Logs into the 'server' and displays the session id\n"
805                         "       - To view the session id later, enter: print login\n"
806                         "---------------------------------------------------------------------------------\n"
807                         "\n"
808                         "\n"
809                         "Note: long output is piped through 'less'. To search in 'less', type: /<search>\n"
810                         "---------------------------------------------------------------------------------\n"
811                         "\n"
812                         );
813
814         return 1;
815 }
816
817
818 /*
819 static char* tabs(int count) {
820         growing_buffer* buf = buffer_init(24);
821         int i;
822         for(i=0;i!=count;i++)
823                 buffer_add(buf, "  ");
824
825         char* final = buffer_data( buf );
826         buffer_free( buf );
827         return final;
828 }
829 */
830
831
832 static int handle_math( char* words[] ) {
833         if( words[1] )
834                 return do_math( atoi(words[1]), 0 );
835         return 0;
836 }
837
838
839 static int do_math( int count, int style ) {
840
841         osrf_app_session* session = osrf_app_client_session_init(  "opensrf.math" );
842         osrf_app_session_connect(session);
843
844         jsonObject* params = jsonParseString("[]");
845         jsonObjectPush(params,jsonNewObject("1"));
846         jsonObjectPush(params,jsonNewObject("2"));
847
848         char* methods[] = { "add", "sub", "mult", "div" };
849         char* answers[] = { "3", "-1", "2", "0.500000" };
850
851         float times[ count * 4 ];
852         memset(times,0,count*4);
853
854         int k;
855         for(k=0;k!=100;k++) {
856                 if(!(k%10)) 
857                         fprintf(stderr,"|");
858                 else
859                         fprintf(stderr,".");
860         }
861
862         fprintf(stderr,"\n\n");
863
864         int running = 0;
865         int i;
866         for(i=0; i!= count; i++) {
867
868                 int j;
869                 for(j=0; j != 4; j++) {
870
871                         ++running;
872
873                         double start = get_timestamp_millis();
874                         int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
875                         osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
876                         double end = get_timestamp_millis();
877
878                         times[(4*i) + j] = end - start;
879
880                         if(omsg) {
881         
882                                 if(omsg->_result_content) {
883                                         char* jsn = jsonObjectToJSON(omsg->_result_content);
884                                         if(!strcmp(jsn, answers[j]))
885                                                 fprintf(stderr, "+");
886                                         else
887                                                 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
888                                         free(jsn);
889                                 }
890
891
892                                 osrf_message_free(omsg);
893                 
894                         } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
895
896                         osrf_app_session_request_finish( session, req_id );
897
898                         if(style == 2)
899                                 osrf_app_session_disconnect( session );
900
901                         if(!(running%100))
902                                 fprintf(stderr,"\n");
903                 }
904
905                 if(style==1)
906                         osrf_app_session_disconnect( session );
907         }
908
909         osrf_app_session_destroy( session );
910         jsonObjectFree(params);
911
912         int c;
913         float total = 0;
914         for(c=0; c!= count*4; c++) 
915                 total += times[c];
916
917         float avg = total / (count*4); 
918         fprintf(stderr, "\n      Average round trip time: %f\n", avg );
919
920         return 1;
921 }