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