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