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