Implemented upper-limit on proxy-to-target sessions.
[yazpp-moved-to-github.git] / src / yaz-client.cpp
1 /*
2  * Copyright (c) 1998-2000, Index Data.
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  * 
6  * $Log: yaz-client.cpp,v $
7  * Revision 1.11  2000-07-04 13:48:49  adam
8  * Implemented upper-limit on proxy-to-target sessions.
9  *
10  * Revision 1.10  2000/05/30 03:12:27  ian
11  * minor change to stop g++ 2.95.2 complaining about taking the address
12  * of a member function.
13  *
14  * Revision 1.9  1999/12/06 13:52:45  adam
15  * Modified for new location of YAZ header files. Experimental threaded
16  * operation.
17  *
18  * Revision 1.8  1999/11/10 10:02:34  adam
19  * Work on proxy.
20  *
21  * Revision 1.7  1999/04/21 12:09:01  adam
22  * Many improvements. Modified to proxy server to work with "sessions"
23  * based on cookies.
24  *
25  * Revision 1.6  1999/04/20 10:30:05  adam
26  * Implemented various stuff for client and proxy. Updated calls
27  * to ODR to reflect new name parameter.
28  *
29  * Revision 1.5  1999/04/09 11:46:57  adam
30  * Added object Yaz_Z_Assoc. Much more functional client.
31  *
32  * Revision 1.4  1999/03/23 14:17:57  adam
33  * More work on timeout handling. Work on yaz-client.
34  *
35  * Revision 1.3  1999/02/02 14:01:18  adam
36  * First WIN32 port of YAZ++.
37  *
38  * Revision 1.2  1999/01/28 13:08:42  adam
39  * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
40  * yaz-socket-manager.cc.
41  *
42  * Revision 1.1.1.1  1999/01/28 09:41:07  adam
43  * First implementation of YAZ++.
44  *
45  */
46
47 #include <yaz/log.h>
48 #include <yaz/options.h>
49 #include <yaz/diagbib1.h>
50 #include <yaz-ir-assoc.h>
51 #include <yaz-pdu-assoc.h>
52 #include <yaz-socket-manager.h>
53
54 extern "C" {
55 #if HAVE_READLINE_READLINE_H
56 #include <readline/readline.h>
57 #endif
58 #if HAVE_READLINE_HISTORY_H
59 #include <readline/history.h>
60 #endif
61 }
62
63 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
64 private:
65     int m_interactive_flag;
66     char m_thisCommand[1024];
67     char m_lastCommand[1024];
68     int m_setOffset;
69     Yaz_SocketManager *m_socketManager;
70 public:
71     MyClient(IYaz_PDU_Observable *the_PDU_Observable,
72              Yaz_SocketManager *the_SocketManager);
73     IYaz_PDU_Observer *clone(IYaz_PDU_Observable *the_PDU_Observable);
74     int args(Yaz_SocketManager *socketManager, int argc, char **argv);
75     int interactive(Yaz_SocketManager *socketManager);
76     int wait();
77     void recv_initResponse(Z_InitResponse *initResponse);
78     void recv_searchResponse(Z_SearchResponse *searchResponse);
79     void recv_presentResponse(Z_PresentResponse *presentResponse);
80     void recv_records (Z_Records *records);
81     void recv_diagrecs(Z_DiagRec **pp, int num);
82     void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
83     void recv_record(Z_DatabaseRecord *record, int offset,
84                      const char *databaseName);
85     void recv_textRecord(int type, const char *buf, size_t len);
86     void recv_genericRecord(Z_GenericRecord *r);
87     void display_genericRecord(Z_GenericRecord *r, int level);
88     void display_variant(Z_Variant *v, int level);
89     void connectNotify();
90     void failNotify();
91     void timeoutNotify();
92     char *get_cookie (Z_OtherInformation **oi);
93     int processCommand(const char *cmd);
94     const char *MyClient::getCommand();
95     int cmd_open(char *host);
96     int cmd_connect(char *host);
97     int cmd_quit(char *args);
98     int cmd_close(char *args);
99     int cmd_find(char *args);
100     int cmd_show(char *args);
101     int cmd_cookie(char *args);
102     int cmd_init(char *args);
103     int cmd_format(char *args);
104     int cmd_proxy(char *args);
105 };
106
107
108 void MyClient::connectNotify()
109 {
110     printf ("Connection accepted by target\n");
111     set_lastReceived(-1);
112 }
113
114 void MyClient::timeoutNotify()
115 {
116     printf ("Connection timeout\n");
117     close();
118 }
119
120 void MyClient::failNotify()
121 {
122     printf ("Connection closed by target\n");
123     set_lastReceived(-1);
124 }
125
126 IYaz_PDU_Observer *MyClient::clone(IYaz_PDU_Observable *the_PDU_Observable)
127
128     return new MyClient(the_PDU_Observable, m_socketManager);
129 }
130
131 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
132                    Yaz_SocketManager *the_socketManager) :
133     Yaz_IR_Assoc (the_PDU_Observable)
134 {
135     m_setOffset = 1;
136     m_interactive_flag = 1;
137     m_thisCommand[0] = '\0';
138     m_lastCommand[0] = '\0';
139     m_socketManager = the_socketManager;
140 }
141
142 void usage(char *prog)
143 {
144     fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
145     exit (1);
146 }
147
148 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
149 {
150     int oid[OID_SIZE];
151     Z_OtherInformationUnit *oi;
152     struct oident ent;
153     ent.proto = PROTO_Z3950;
154     ent.oclass = CLASS_USERINFO;
155     ent.value = (oid_value) VAL_COOKIE;
156
157     if (oid_ent_to_oid (&ent, oid) && 
158         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
159         oi->which == Z_OtherInfo_characterInfo)
160         return oi->information.characterInfo;
161     return 0;
162 }
163
164 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
165 {
166     printf ("Got InitResponse. Status ");
167     if (*initResponse->result)
168     {
169         printf ("Ok\n");
170
171         const char *p = get_cookie (&initResponse->otherInfo);
172         if (p)
173         {
174             printf ("cookie = %s\n", p);
175             set_cookie(p);
176         }
177     }
178     else
179         printf ("Fail\n");
180 }
181
182 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
183 {
184     int i;
185     oident *ent;
186     Z_DefaultDiagFormat *r;
187
188     printf("Diagnostic message(s) from database:\n");
189     for (i = 0; i<num; i++)
190     {
191         Z_DiagRec *p = pp[i];
192         if (p->which != Z_DiagRec_defaultFormat)
193         {
194             printf("Diagnostic record not in default format.\n");
195             return;
196         }
197         else
198             r = p->u.defaultFormat;
199         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
200             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
201             printf("Missing or unknown diagset\n");
202         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
203 #ifdef ASN_COMPILED
204         switch (r->which)
205         {
206         case Z_DefaultDiagFormat_v2Addinfo:
207             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
208             break;
209         case Z_DefaultDiagFormat_v3Addinfo:
210             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
211             break;
212         }
213 #else
214         if (r->addinfo && *r->addinfo)
215             printf(" -- '%s'\n", r->addinfo);
216         else
217             printf("\n");
218 #endif
219     }
220 }
221
222 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
223 {
224     fwrite (buf, 1, len, stdout);
225     fputc ('\n', stdout);
226 }
227
228 void MyClient::display_variant(Z_Variant *v, int level)
229 {
230     int i;
231
232     for (i = 0; i < v->num_triples; i++)
233     {
234         printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
235             *v->triples[i]->type);
236         if (v->triples[i]->which == Z_Triple_internationalString)
237             printf(",value=%s\n", v->triples[i]->value.internationalString);
238         else
239             printf("\n");
240     }
241 }
242
243 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
244 {
245     int i;
246
247     if (!r)
248         return;
249     for (i = 0; i < r->num_elements; i++)
250     {
251         Z_TaggedElement *t;
252
253         printf("%*s", level * 4, "");
254         t = r->elements[i];
255         printf("(");
256         if (t->tagType)
257             printf("%d,", *t->tagType);
258         else
259             printf("?,");
260         if (t->tagValue->which == Z_StringOrNumeric_numeric)
261             printf("%d) ", *t->tagValue->u.numeric);
262         else
263             printf("%s) ", t->tagValue->u.string);
264         if (t->content->which == Z_ElementData_subtree)
265         {
266             printf("\n");
267             display_genericRecord(t->content->u.subtree, level+1);
268         }
269         else if (t->content->which == Z_ElementData_string)
270             printf("%s\n", t->content->u.string);
271         else if (t->content->which == Z_ElementData_numeric)
272             printf("%d\n", *t->content->u.numeric);
273         else if (t->content->which == Z_ElementData_oid)
274         {
275             int *ip = t->content->u.oid;
276             oident *oent;
277
278             if ((oent = oid_getentbyoid(t->content->u.oid)))
279                 printf("OID: %s\n", oent->desc);
280             else
281             {
282                 printf("{");
283                 while (ip && *ip >= 0)
284                     printf(" %d", *(ip++));
285                 printf(" }\n");
286             }
287         }
288         else if (t->content->which == Z_ElementData_noDataRequested)
289             printf("[No data requested]\n");
290         else if (t->content->which == Z_ElementData_elementEmpty)
291             printf("[Element empty]\n");
292         else if (t->content->which == Z_ElementData_elementNotThere)
293             printf("[Element not there]\n");
294         else
295             printf("??????\n");
296         if (t->appliedVariant)
297             display_variant(t->appliedVariant, level+1);
298         if (t->metaData && t->metaData->supportedVariants)
299         {
300             int c;
301
302             printf("%*s---- variant list\n", (level+1)*4, "");
303             for (c = 0; c < t->metaData->num_supportedVariants; c++)
304             {
305                 printf("%*svariant #%d\n", (level+1)*4, "", c);
306                 display_variant(t->metaData->supportedVariants[c], level + 2);
307             }
308         }
309     }
310 }
311
312 void MyClient::recv_genericRecord(Z_GenericRecord *r)
313 {
314     display_genericRecord(r, 0);
315 }
316
317 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
318                            const char *databaseName)
319 {
320     Z_External *r = (Z_External*) record;
321     oident *ent = oid_getentbyoid(r->direct_reference);
322
323     /*
324      * Tell the user what we got.
325      */
326     if (r->direct_reference)
327     {
328         printf("Record type: ");
329         if (ent)
330             printf("%s\n", ent->desc);
331     }
332     /* Check if this is a known, ASN.1 type tucked away in an octet string */
333     Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
334     if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
335         && (etype = z_ext_getentbyref(ent->value)))
336
337     {
338         void *rr;
339         /*
340          * Call the given decoder to process the record.
341          */
342         odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
343                    record->u.octet_aligned->len, 0);
344         if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
345         {
346             odr_perror(odr_decode(), "Decoding constructed record.");
347             fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
348             fprintf(stderr, "Packet dump:\n---------\n");
349             odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
350                         record->u.octet_aligned->len);
351             fprintf(stderr, "---------\n");
352         }
353         if (etype->what == Z_External_sutrs)
354         {
355             Z_SUTRS *sutrs = (Z_SUTRS *) rr;
356             recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
357                              (size_t) sutrs->len);
358         }
359         return;
360     }
361     if (r->which == Z_External_octet && record->u.octet_aligned->len)
362     {
363         recv_textRecord((int) ent->value,
364                         (const char *) record->u.octet_aligned->buf,
365                         (size_t) record->u.octet_aligned->len);
366     }
367     else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
368         recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
369                         (size_t) r->u.sutrs->len);
370     else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
371         recv_genericRecord(r->u.grs1);
372     else 
373     {
374         printf("Unknown record representation.\n");
375         if (!z_External(odr_print(), &r, 0, 0))
376         {
377             odr_perror(odr_print(), "Printing external");
378             odr_reset(odr_print());
379         }
380     }    
381 }
382
383 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
384 {
385     if (zpr->databaseName)
386         printf("[%s]", zpr->databaseName);
387     if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
388         recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
389     else
390         recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
391 }
392
393 void MyClient::recv_records (Z_Records *records)
394 {
395 #ifdef ASN_COMPILED
396     Z_DiagRec dr, *dr_p = &dr;
397 #endif
398     if (!records)
399         return;
400     int i;
401     switch (records->which)
402     {
403     case Z_Records_DBOSD:
404         for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
405             recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
406                                 records[i], i + m_setOffset);
407         m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
408         break;
409     case Z_Records_NSD:
410 #ifdef ASN_COMPILED
411         dr.which = Z_DiagRec_defaultFormat;
412         dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
413         recv_diagrecs (&dr_p, 1);
414 #else
415         recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
416 #endif
417         break;
418     case Z_Records_multipleNSD:
419         recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
420                        records->u.multipleNonSurDiagnostics->num_diagRecs);
421         break;
422     }
423 }
424
425 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
426 {
427     printf ("Got SearchResponse. Status ");
428     if (!*searchResponse->searchStatus)
429     {
430         printf ("Fail\n");
431         return;
432     }
433     printf ("Ok\n");
434     printf ("Hits: %d\n", *searchResponse->resultCount);
435     recv_records (searchResponse->records);
436 }
437
438 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
439 {
440     printf ("Got PresentResponse\n");
441     recv_records (presentResponse->records);
442 }
443
444 int MyClient::wait()
445 {
446     set_lastReceived(0);
447     while (m_socketManager->processEvent() > 0)
448     {
449         if (get_lastReceived())
450             return 1;
451     }
452     return 0;
453 }
454
455 #define C_PROMPT "Z>"
456
457 int MyClient::cmd_connect(char *host)
458 {
459     client (host);
460     timeout (10);
461     wait ();
462     timeout (0);
463     return 1;
464 }
465
466 int MyClient::cmd_open(char *host)
467 {
468     client (host);
469     timeout (10);
470     wait ();
471     timeout (0);
472     send_initRequest();
473     wait ();
474     return 1;
475 }
476
477 int MyClient::cmd_init(char *args)
478 {
479     if (send_initRequest() >= 0)
480         wait();
481     else
482         close();
483     return 1;
484 }
485
486 int MyClient::cmd_quit(char *args)
487 {
488     return 0;
489 }
490
491 int MyClient::cmd_close(char *args)
492 {
493     close();
494     return 1;
495 }
496
497 int MyClient::cmd_find(char *args)
498 {
499     Yaz_Z_Query query;
500
501     if (query.set_rpn(args) <= 0)
502     {
503         printf ("Bad RPN query\n");
504         return 1;
505     }
506     if (send_searchRequest(&query) >= 0)
507         wait();
508     else
509         printf ("Not connected\n");
510     return 1;
511 }
512
513 int MyClient::cmd_show(char *args)
514 {
515     int start = m_setOffset, number = 1;
516
517     sscanf (args, "%d %d", &start, &number);
518     m_setOffset = start;
519     if (send_presentRequest(start, number) >= 0)
520         wait();
521     else
522         printf ("Not connected\n");
523     return 1;
524 }
525
526 int MyClient::cmd_cookie(char *args)
527 {
528     set_cookie(*args ? args : 0);
529     return 1;
530 }
531
532 int MyClient::cmd_format(char *args)
533 {
534     set_preferredRecordSyntax(args);
535     return 1;
536 }
537
538 int MyClient::cmd_proxy(char *args)
539 {
540     set_proxy(args);
541     return 1;
542 }
543
544 int MyClient::processCommand(const char *commandLine)
545 {
546     char cmdStr[1024], cmdArgs[1024];
547     cmdArgs[0] = '\0';
548     cmdStr[0] = '\0';
549     static struct {
550         char *cmd;
551         int (MyClient::*fun)(char *arg);
552         char *ad;
553     } cmd[] = {
554         {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
555         {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
556         {"quit", &MyClient::cmd_quit, ""},
557         {"close", &MyClient::cmd_close, ""},
558         {"find", &MyClient::cmd_find, "<query>"},
559         {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
560         {"cookie", &MyClient::cmd_cookie, "<cookie>"},
561         {"init", &MyClient::cmd_init, ""},
562         {"format", &MyClient::cmd_format, "<record-syntax>"},
563         {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
564         {0,0,0}
565     };
566     
567     if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
568         return 1;
569     int i;
570     for (i = 0; cmd[i].cmd; i++)
571         if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
572             break;
573     
574     int res = 1;
575     if (cmd[i].cmd) // Invoke command handler
576         res = (this->*cmd[i].fun)(cmdArgs);
577     else            // Dump help screen
578     {
579         printf("Unknown command: %s.\n", cmdStr);
580         printf("Currently recognized commands:\n");
581         for (i = 0; cmd[i].cmd; i++)
582             printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
583     }
584     return res;
585 }
586
587 const char *MyClient::getCommand()
588 {
589 #if HAVE_READLINE_READLINE_H
590     // Read using GNU readline
591     char *line_in;
592     line_in=readline(C_PROMPT);
593     if (!line_in)
594         return 0;
595 #if HAVE_READLINE_HISTORY_H
596     if (*line_in)
597         add_history(line_in);
598 #endif
599     strncpy(m_thisCommand,line_in, 1023);
600     m_thisCommand[1023] = '\0';
601     free (line_in);
602 #else    
603     // Read using fgets(3)
604     printf (C_PROMPT);
605     fflush(stdout);
606     if (!fgets(m_thisCommand, 1023, stdin))
607         return 0;
608 #endif
609     // Remove trailing whitespace
610     char *cp = m_thisCommand + strlen(m_thisCommand);
611     while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
612         cp--;
613     *cp = '\0';
614     cp = m_thisCommand;
615     // Remove leading spaces...
616     while (*cp && strchr ("\t \n", *cp))
617         cp++;
618     // Save command if non-empty
619     if (*cp != '\0')
620         strcpy (m_lastCommand, cp);
621     return m_lastCommand;
622 }
623
624 int MyClient::interactive(Yaz_SocketManager *socketManager)
625 {
626     const char *cmd;
627     if (!m_interactive_flag)
628         return 0;
629     while ((cmd = getCommand()))
630     {
631         if (!processCommand(cmd))
632             break;
633     }
634     return 0;
635 }
636
637 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
638 {
639     char *host = 0;
640     char *proxy = 0;
641     char *arg;
642     char *prog = argv[0];
643     int ret;
644
645     while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
646     {
647         switch (ret)
648         {
649         case 0:
650             if (host)
651             {
652                 usage(prog);
653                 return 1;
654             }
655             host = arg;
656             break;
657         case 'p':
658             if (proxy)
659             {
660                 usage(prog);
661                 return 1;
662             }
663             set_proxy(arg);
664             break;
665         case 'c':
666             set_cookie(arg);
667             break;
668         case 'v':
669             log_init_level (log_mask_str(arg));
670             break;
671         case 'q':
672             m_interactive_flag = 0;
673             break;
674         default:
675             usage(prog);
676             return 1;
677         }
678     }
679     if (host)
680     {
681         client (host);
682         timeout (10);
683         wait ();
684         timeout (0);
685         send_initRequest();
686         wait ();
687     }
688     return 0;
689 }
690
691 int main(int argc, char **argv)
692 {
693     Yaz_SocketManager mySocketManager;
694     Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
695
696     MyClient z(some, &mySocketManager);
697
698     if (z.args(&mySocketManager, argc, argv))
699         exit (1);
700     if (z.interactive(&mySocketManager))
701         exit (1);
702 }