Patch from Scott McKellar to repair srfsh buffer overflow:
[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
186         osrf_system_shutdown();
187         return 0;
188 }
189
190 /*
191 static void sig_child_handler( int s ) {
192         child_dead = 1;
193 }
194 */
195
196 /*
197 void sig_int_handler( int s ) {
198         printf("\n");
199         caught_sigint = 1;
200         signal(SIGINT,sig_int_handler);
201 }
202 */
203
204 static int load_history( void ) {
205
206         char* home = getenv("HOME");
207         int l = strlen(home) + 24;
208         char fbuf[l];
209
210         memset(fbuf, 0, l);
211         sprintf(fbuf,"%s/.srfsh_history",home);
212         history_file = strdup(fbuf);
213
214         if(!access(history_file, W_OK | R_OK )) {
215                 history_length = 5000;
216                 read_history(history_file);
217         }
218         return 1;
219 }
220
221
222 static int parse_error( char* words[] ) {
223
224         if( ! words )
225                 return 0;
226
227         growing_buffer * gbuf = buffer_init( 64 );
228         buffer_add( gbuf, *words );
229         while( *++words ) {
230                 buffer_add( gbuf, " " );
231                 buffer_add( gbuf, *words );
232         }
233         fprintf( stderr, "???: %s\n", gbuf->buf );
234         buffer_free( gbuf );
235         
236         return 0;
237
238 }
239
240
241 static int parse_request( char* request ) {
242
243         if( request == NULL )
244                 return 0;
245
246         char* original_request = strdup( request );
247         char* words[COMMAND_BUFSIZE]; 
248         
249         int ret_val = 0;
250         int i = 0;
251
252
253         char* req = request;
254         char* cur_tok = strtok( req, " " );
255
256         if( cur_tok == NULL )
257         {
258                 free( original_request );
259                 return 0;
260         }
261
262         /* Load an array with pointers to    */
263         /* the tokens as defined by strtok() */
264         
265         while(cur_tok != NULL) {
266                 if( i < COMMAND_BUFSIZE - 1 ) {
267                         words[i++] = cur_tok;
268                         cur_tok = strtok( NULL, " " );
269                 } else {
270                         fprintf( stderr, "Too many tokens in command\n" );
271                         free( original_request );
272                         return 1;
273                 }
274         }
275
276         words[i] = NULL;
277         
278         /* pass off to the top level command */
279         if( !strcmp(words[0],"router") ) 
280                 ret_val = handle_router( words );
281
282         /*
283         else if( !strcmp(words[0],"time") ) 
284                 ret_val = handle_time( words );
285                 */
286
287         else if (!strcmp(words[0],"request"))
288                 ret_val = handle_request( words, 0 );
289
290         else if (!strcmp(words[0],"relay"))
291                 ret_val = handle_request( words, 1 );
292
293         else if (!strcmp(words[0],"help"))
294                 ret_val = print_help();
295
296         else if (!strcmp(words[0],"set"))
297                 ret_val = handle_set(words);
298
299         else if (!strcmp(words[0],"print"))
300                 ret_val = handle_print(words);
301
302         else if (!strcmp(words[0],"math_bench"))
303                 ret_val = handle_math(words);
304
305         else if (!strcmp(words[0],"introspect"))
306                 ret_val = handle_introspect(words);
307
308         else if (!strcmp(words[0],"login"))
309                 ret_val = handle_login(words);
310
311         else if (words[0][0] == '!') {
312                 system( original_request + 1 );
313                 ret_val = 1;
314         }
315         
316         free( original_request );
317         
318         if(!ret_val)
319                 return parse_error( words );
320         else
321                 return 1;
322 }
323
324
325 static int handle_introspect(char* words[]) {
326
327         if( ! words[1] )
328                 return 0;
329
330         fprintf(stderr, "--> %s\n", words[1]);
331
332         // Build a command in a suitably-sized
333         // buffer and then parse it
334         
335         size_t len;
336         if( words[2] ) {
337                 static const char text[] = "request %s opensrf.system.method %s";
338                 len = sizeof( text ) + strlen( words[1] ) + strlen( words[2] );
339                 char buf[len];
340                 sprintf( buf, text, words[1], words[2] );
341                 return parse_request( buf );
342
343         } else {
344                 static const char text[] = "request %s opensrf.system.method.all";
345                 len = sizeof( text ) + strlen( words[1] );
346                 char buf[len];
347                 sprintf( buf, text, words[1] );
348                 return parse_request( buf );
349
350         }
351 }
352
353
354 static int handle_login( char* words[]) {
355
356         if( words[1] && words[2]) {
357
358                 char* username          = words[1];
359                 char* password          = words[2];
360                 char* type                      = words[3];
361                 char* orgloc            = words[4];
362                 char* workstation       = words[5];
363                 int orgloci = (orgloc) ? atoi(orgloc) : 0;
364                 if(!type) type = "opac";
365
366                 char buf[256];
367                 memset(buf,0,256);
368
369                 char buf2[256];
370                 memset(buf2,0,256);
371
372                 sprintf( buf, 
373                                 "request open-ils.auth open-ils.auth.authenticate.init \"%s\"", username );
374                 parse_request(buf); 
375
376                 char* hash;
377                 if(last_result && last_result->_result_content) {
378                         jsonObject* r = last_result->_result_content;
379                         hash = jsonObjectGetString(r);
380                 } else return 0;
381
382
383                 char* pass_buf = md5sum(password);
384
385                 char both_buf[256];
386                 memset(both_buf,0,256);
387                 sprintf(both_buf,"%s%s",hash, pass_buf);
388
389                 char* mess_buf = md5sum(both_buf);
390
391                 /*
392                 sprintf( buf2, "request open-ils.auth open-ils.auth.authenticate.complete "
393                                 "{ \"username\" : \"%s\", \"password\" : \"%s\", "
394                                 "\"type\" : \"%s\", \"org\" : %d, \"workstation\": \"%s\"}", 
395                                 username, mess_buf, type, orgloci, workstation );
396                                 */
397
398                 growing_buffer* argbuf = buffer_init(64);
399                 buffer_fadd(argbuf, 
400                                 "request open-ils.auth open-ils.auth.authenticate.complete "
401                                 "{ \"username\" : \"%s\", \"password\" : \"%s\"", username, mess_buf );
402
403                 if(type) buffer_fadd( argbuf, ", \"type\" : \"%s\"", type );
404                 if(orgloci) buffer_fadd( argbuf, ", \"org\" : %d", orgloci );
405                 if(workstation) buffer_fadd( argbuf, ", \"workstation\" : \"%s\"", workstation);
406                 buffer_add(argbuf, "}");
407
408                 free(pass_buf);
409                 free(mess_buf);
410
411                 parse_request( argbuf->buf );
412                 buffer_free(argbuf);
413
414                 jsonObject* x = last_result->_result_content;
415                 double authtime = 0;
416                 if(x) {
417                         char* authtoken = jsonObjectGetString(
418                                         jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtoken"));
419                         authtime  = jsonObjectGetNumber(
420                                         jsonObjectGetKey(jsonObjectGetKey(x,"payload"), "authtime"));
421                         if(authtoken) login_session = strdup(authtoken);
422                         else login_session = NULL;
423                 }
424                 else login_session = NULL;
425
426                 printf("Login Session: %s.  Session timeout: %f\n", login_session, authtime );
427                 
428                 return 1;
429
430         }
431
432         return 0;
433 }
434
435 static int handle_set( char* words[]) {
436
437         char* variable;
438         if( (variable=words[1]) ) {
439
440                 char* val;
441                 if( (val=words[2]) ) {
442
443                         if(!strcmp(variable,"pretty_print")) {
444                                 if(!strcmp(val,"true")) {
445                                         pretty_print = 1;
446                                         printf("pretty_print = true\n");
447                                         return 1;
448                                 } 
449                                 if(!strcmp(val,"false")) {
450                                         pretty_print = 0;
451                                         printf("pretty_print = false\n");
452                                         return 1;
453                                 } 
454                         }
455
456                         if(!strcmp(variable,"raw_print")) {
457                                 if(!strcmp(val,"true")) {
458                                         raw_print = 1;
459                                         printf("raw_print = true\n");
460                                         return 1;
461                                 } 
462                                 if(!strcmp(val,"false")) {
463                                         raw_print = 0;
464                                         printf("raw_print = false\n");
465                                         return 1;
466                                 } 
467                         }
468
469                 }
470         }
471
472         return 0;
473 }
474
475
476 static int handle_print( char* words[]) {
477
478         char* variable;
479         if( (variable=words[1]) ) {
480                 if(!strcmp(variable,"pretty_print")) {
481                         if(pretty_print) {
482                                 printf("pretty_print = true\n");
483                                 return 1;
484                         } else {
485                                 printf("pretty_print = false\n");
486                                 return 1;
487                         }
488                 }
489
490                 if(!strcmp(variable,"login")) {
491                         printf("login session = %s\n", login_session );
492                         return 1;
493                 }
494
495         }
496         return 0;
497 }
498
499 static int handle_router( char* words[] ) {
500
501         if(!client)
502                 return 1;
503
504         int i;
505
506         if( words[1] ) { 
507                 if( !strcmp(words[1],"query") ) {
508                         
509                         if( words[2] && !strcmp(words[2],"servers") ) {
510                                 for(i=3; i < COMMAND_BUFSIZE - 3 && words[i]; i++ ) {   
511                                         router_query_servers( words[i] );
512                                 }
513                                 return 1;
514                         }
515                         return 0;
516                 }
517                 return 0;
518         }
519         return 0;
520 }
521
522
523
524 static int handle_request( char* words[], int relay ) {
525
526         if(!client)
527                 return 1;
528
529         if(words[1]) {
530                 char* server = words[1];
531                 char* method = words[2];
532                 int i;
533                 growing_buffer* buffer = NULL;
534                 if(!relay) {
535                         buffer = buffer_init(128);
536                         buffer_add(buffer, "[");
537                         for(i = 3; words[i] != NULL; i++ ) {
538                                 /* removes trailing semicolon if user accidentally enters it */
539                                 if( words[i][strlen(words[i])-1] == ';' )
540                                         words[i][strlen(words[i])-1] = '\0';
541                                 buffer_add( buffer, words[i] );
542                                 buffer_add(buffer, " ");
543                         }
544                         buffer_add(buffer, "]");
545                 }
546
547                 return send_request( server, method, buffer, relay );
548         } 
549
550         return 0;
551 }
552
553 int send_request( char* server, 
554                 char* method, growing_buffer* buffer, int relay ) {
555         if( server == NULL || method == NULL )
556                 return 0;
557
558         jsonObject* params = NULL;
559         if( !relay ) {
560                 if( buffer != NULL && buffer->n_used > 0 ) 
561                         params = json_parse_string(buffer->buf);
562         } else {
563                 if(!last_result || ! last_result->_result_content) { 
564                         printf("We're not going to call 'relay' with no result params\n");
565                         return 1;
566                 }
567                 else {
568                         jsonObject* o = jsonNewObject(NULL);
569                         jsonObjectPush(o, last_result->_result_content );
570                         params = o;
571                 }
572         }
573
574
575         if(buffer->n_used > 0 && params == NULL) {
576                 fprintf(stderr, "JSON error detected, not executing\n");
577                 return 1;
578         }
579
580         osrf_app_session* session = osrf_app_client_session_init(server);
581
582         if(!osrf_app_session_connect(session)) {
583                 osrfLogWarning( OSRF_LOG_MARK,  "Unable to connect to remote service %s\n", server );
584                 return 1;
585         }
586
587         double start = get_timestamp_millis();
588         //int req_id = osrf_app_session_make_request( session, params, method, 1, NULL );
589         int req_id = osrf_app_session_make_req( session, params, method, 1, NULL );
590
591
592         osrf_message* omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
593
594         if(!omsg) 
595                 printf("\nReceived no data from server\n");
596         
597         
598         signal(SIGPIPE, SIG_IGN);
599
600         FILE* less; 
601         if(!is_from_script) less = popen( "less -EX", "w");
602         else less = stdout;
603
604         if( less == NULL ) { less = stdout; }
605
606         growing_buffer* resp_buffer = buffer_init(4096);
607
608         while(omsg) {
609
610                 if(raw_print) {
611
612                         if(omsg->_result_content) {
613         
614                                 osrf_message_free(last_result);
615                                 last_result = omsg;
616         
617                                 char* content;
618         
619                                 if( pretty_print && omsg->_result_content ) {
620                                         char* j = jsonObjectToJSON(omsg->_result_content);
621                                         //content = json_printer(j); 
622                                         content = jsonFormatString(j);
623                                         free(j);
624                                 } else
625                                         content = jsonObjectGetString(omsg->_result_content);
626         
627                                 printf( "\nReceived Data: %s\n", content ); 
628                                 free(content);
629         
630                         } else {
631
632                                 char code[16];
633                                 memset(code, 0, 16);
634                                 sprintf( code, "%d", omsg->status_code );
635                                 buffer_add( resp_buffer, code );
636
637                                 printf( "\nReceived Exception:\nName: %s\nStatus: %s\nStatus: %s\n", 
638                                                 omsg->status_name, omsg->status_text, code );
639
640                                 fflush(stdout);
641                         }
642
643                 } else {
644
645                         if(omsg->_result_content) {
646         
647                                 osrf_message_free(last_result);
648                                 last_result = omsg;
649         
650                                 char* content;
651         
652                                 if( pretty_print && omsg->_result_content ) {
653                                         char* j = jsonObjectToJSON(omsg->_result_content);
654                                         //content = json_printer(j); 
655                                         content = jsonFormatString(j);
656                                         free(j);
657                                 } else
658                                         content = jsonObjectGetString(omsg->_result_content);
659         
660                                 buffer_add( resp_buffer, "\nReceived Data: " ); 
661                                 buffer_add( resp_buffer, content );
662                                 buffer_add( resp_buffer, "\n" );
663                                 free(content);
664         
665                         } else {
666         
667                                 buffer_add( resp_buffer, "\nReceived Exception:\nName: " );
668                                 buffer_add( resp_buffer, omsg->status_name );
669                                 buffer_add( resp_buffer, "\nStatus: " );
670                                 buffer_add( resp_buffer, omsg->status_text );
671                                 buffer_add( resp_buffer, "\nStatus: " );
672                                 char code[16];
673                                 memset(code, 0, 16);
674                                 sprintf( code, "%d", omsg->status_code );
675                                 buffer_add( resp_buffer, code );
676                         }
677                 }
678
679
680                 omsg = osrf_app_session_request_recv( session, req_id, recv_timeout );
681
682         }
683
684         double end = get_timestamp_millis();
685
686         fprintf( less, resp_buffer->buf );
687         buffer_free( resp_buffer );
688         fprintf( less, "\n------------------------------------\n");
689         if( osrf_app_session_request_complete( session, req_id ))
690                 fprintf(less, "Request Completed Successfully\n");
691
692
693         fprintf(less, "Request Time in seconds: %.6f\n", end - start );
694         fprintf(less, "------------------------------------\n");
695
696         pclose(less); 
697
698         osrf_app_session_request_finish( session, req_id );
699         osrf_app_session_disconnect( session );
700         osrf_app_session_destroy( session );
701
702
703         return 1;
704
705
706 }
707
708 /*
709 static int handle_time( char* words[] ) {
710
711         if( ! words[1] ) {
712
713                 char buf[36];
714                 memset(buf,0,36);
715                 get_timestamp(buf);
716                 printf( "%s\n", buf );
717                 return 1;
718         }
719
720         if( words[1] ) {
721                 time_t epoch = (time_t)atoi( words[1] );
722                 char* localtime = strdup( ctime( &epoch ) );
723                 printf( "%s => %s", words[1], localtime );
724                 free(localtime);
725                 return 1;
726         }
727
728         return 0;
729
730 }
731 */
732
733                 
734
735 static int router_query_servers( const char* router_server ) {
736
737         if( ! router_server || strlen(router_server) == 0 ) 
738                 return 0;
739
740         char rbuf[256];
741         memset(rbuf,0,256);
742         sprintf(rbuf,"router@%s/router", router_server );
743                 
744         transport_message* send = 
745                 message_init( "servers", NULL, NULL, rbuf, NULL );
746         message_set_router_info( send, NULL, NULL, NULL, "query", 0 );
747
748         client_send_message( client, send );
749         message_free( send );
750
751         transport_message* recv = client_recv( client, -1 );
752         if( recv == NULL ) {
753                 fprintf(stderr, "NULL message received from router\n");
754                 return 1;
755         }
756         
757         printf( 
758                         "---------------------------------------------------------------------------------\n"
759                         "Received from 'server' query on %s\n"
760                         "---------------------------------------------------------------------------------\n"
761                         "original reg time | latest reg time | last used time | class | server\n"
762                         "---------------------------------------------------------------------------------\n"
763                         "%s"
764                         "---------------------------------------------------------------------------------\n"
765                         , router_server, recv->body );
766
767         message_free( recv );
768         
769         return 1;
770 }
771
772 static int print_help( void ) {
773
774         printf(
775                         "---------------------------------------------------------------------------------\n"
776                         "Commands:\n"
777                         "---------------------------------------------------------------------------------\n"
778                         "help                   - Display this message\n"
779                         "!<command> [args] - Forks and runs the given command in the shell\n"
780                 /*
781                         "time                   - Prints the current time\n"
782                         "time <timestamp>       - Formats seconds since epoch into readable format\n"   
783                 */
784                         "set <variable> <value> - set a srfsh variable (e.g. set pretty_print true )\n"
785                         "print <variable>               - Displays the value of a srfsh variable\n"
786                         "---------------------------------------------------------------------------------\n"
787
788                         "router query servers <server1 [, server2, ...]>\n"
789                         "       - Returns stats on connected services\n"
790                         "\n"
791                         "\n"
792                         "request <service> <method> [ <json formatted string of params> ]\n"
793                         "       - Anything passed in will be wrapped in a json array,\n"
794                         "               so add commas if there is more than one param\n"
795                         "\n"
796                         "\n"
797                         "relay <service> <method>\n"
798                         "       - Performs the requested query using the last received result as the param\n"
799                         "\n"
800                         "\n"
801                         "math_bench <num_batches> [0|1|2]\n"
802                         "       - 0 means don't reconnect, 1 means reconnect after each batch of 4, and\n"
803                         "                2 means reconnect after every request\n"
804                         "\n"
805                         "introspect <service>\n"
806                         "       - prints the API for the service\n"
807                         "\n"
808                         "\n"
809                         "---------------------------------------------------------------------------------\n"
810                         " Commands for Open-ILS\n"
811                         "---------------------------------------------------------------------------------\n"
812                         "login <username> <password>\n"
813                         "       -       Logs into the 'server' and displays the session id\n"
814                         "       - To view the session id later, enter: print login\n"
815                         "---------------------------------------------------------------------------------\n"
816                         "\n"
817                         "\n"
818                         "Note: long output is piped through 'less'.  To search in 'less', type: /<search>\n"
819                         "---------------------------------------------------------------------------------\n"
820                         "\n"
821                         );
822
823         return 1;
824 }
825
826
827 /*
828 static char* tabs(int count) {
829         growing_buffer* buf = buffer_init(24);
830         int i;
831         for(i=0;i!=count;i++)
832                 buffer_add(buf, "  ");
833
834         char* final = buffer_data( buf );
835         buffer_free( buf );
836         return final;
837 }
838 */
839
840
841 static int handle_math( char* words[] ) {
842         if( words[1] )
843                 return do_math( atoi(words[1]), 0 );
844         return 0;
845 }
846
847
848 static int do_math( int count, int style ) {
849
850         osrf_app_session* session = osrf_app_client_session_init(  "opensrf.math" );
851         osrf_app_session_connect(session);
852
853         jsonObject* params = json_parse_string("[]");
854         jsonObjectPush(params,jsonNewObject("1"));
855         jsonObjectPush(params,jsonNewObject("2"));
856
857         char* methods[] = { "add", "sub", "mult", "div" };
858         char* answers[] = { "3", "-1", "2", "0.500000" };
859
860         float times[ count * 4 ];
861         memset(times,0,count*4);
862
863         int k;
864         for(k=0;k!=100;k++) {
865                 if(!(k%10)) 
866                         fprintf(stderr,"|");
867                 else
868                         fprintf(stderr,".");
869         }
870
871         fprintf(stderr,"\n\n");
872
873         int running = 0;
874         int i;
875         for(i=0; i!= count; i++) {
876
877                 int j;
878                 for(j=0; j != 4; j++) {
879
880                         ++running;
881
882                         double start = get_timestamp_millis();
883                         int req_id = osrf_app_session_make_req( session, params, methods[j], 1, NULL );
884                         osrf_message* omsg = osrf_app_session_request_recv( session, req_id, 5 );
885                         double end = get_timestamp_millis();
886
887                         times[(4*i) + j] = end - start;
888
889                         if(omsg) {
890         
891                                 if(omsg->_result_content) {
892                                         char* jsn = jsonObjectToJSON(omsg->_result_content);
893                                         if(!strcmp(jsn, answers[j]))
894                                                 fprintf(stderr, "+");
895                                         else
896                                                 fprintf(stderr, "\n![%s] - should be %s\n", jsn, answers[j] );
897                                         free(jsn);
898                                 }
899
900
901                                 osrf_message_free(omsg);
902                 
903                         } else { fprintf( stderr, "\nempty message for tt: %d\n", req_id ); }
904
905                         osrf_app_session_request_finish( session, req_id );
906
907                         if(style == 2)
908                                 osrf_app_session_disconnect( session );
909
910                         if(!(running%100))
911                                 fprintf(stderr,"\n");
912                 }
913
914                 if(style==1)
915                         osrf_app_session_disconnect( session );
916         }
917
918         osrf_app_session_destroy( session );
919         jsonObjectFree(params);
920
921         int c;
922         float total = 0;
923         for(c=0; c!= count*4; c++) 
924                 total += times[c];
925
926         float avg = total / (count*4); 
927         fprintf(stderr, "\n      Average round trip time: %f\n", avg );
928
929         return 1;
930 }