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