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