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