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