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