f9a94620dcbfa7c54018a247be78db4de4d8382a
[yazpp-moved-to-github.git] / src / yaz-my-client.cpp
1 /*
2  * Copyright (c) 1998-2004, Index Data.
3  * See the file LICENSE for details.
4  * 
5  * $Id: yaz-my-client.cpp,v 1.26 2007-04-10 12:14:04 adam Exp $
6  */
7
8 #include <stdlib.h>
9 #include <yaz/log.h>
10 #include <yaz/options.h>
11 #include <yaz/diagbib1.h>
12 #include <yaz/marcdisp.h>
13 #include <yazpp/ir-assoc.h>
14 #include <yazpp/pdu-assoc.h>
15 #include <yazpp/socket-manager.h>
16
17 extern "C" {
18 #if HAVE_READLINE_READLINE_H
19 #include <readline/readline.h>
20 #endif
21 #if HAVE_READLINE_HISTORY_H
22 #include <readline/history.h>
23 #endif
24 }
25
26 using namespace yazpp_1;
27
28 class YAZ_EXPORT MyClient : public IR_Assoc {
29 private:
30     int m_interactive_flag;
31     char m_thisCommand[1024];
32     char m_lastCommand[1024];
33     int m_setOffset;
34     SocketManager *m_socketManager;
35 public:
36     MyClient(IPDU_Observable *the_PDU_Observable,
37              SocketManager *the_SocketManager);
38     IPDU_Observer *sessionNotify(
39         IPDU_Observable *the_PDU_Observable, int fd);
40     int args(SocketManager *socketManager, int argc, char **argv);
41     int interactive(SocketManager *socketManager);
42     int wait();
43     void recv_initResponse(Z_InitResponse *initResponse);
44     void recv_searchResponse(Z_SearchResponse *searchResponse);
45     void recv_presentResponse(Z_PresentResponse *presentResponse);
46     void recv_records (Z_Records *records);
47     void recv_diagrecs(Z_DiagRec **pp, int num);
48     void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
49     void recv_record(Z_DatabaseRecord *record, int offset,
50                      const char *databaseName);
51     void recv_textRecord(int type, const char *buf, size_t len);
52     void recv_genericRecord(Z_GenericRecord *r);
53     void display_genericRecord(Z_GenericRecord *r, int level);
54     void display_variant(Z_Variant *v, int level);
55     void connectNotify();
56     void failNotify();
57     void timeoutNotify();
58     char *get_cookie (Z_OtherInformation **oi);
59     int processCommand(const char *cmd);
60     const char *getCommand();
61     int cmd_open(char *host);
62     int cmd_connect(char *host);
63     int cmd_quit(char *args);
64     int cmd_close(char *args);
65     int cmd_find(char *args);
66     int cmd_show(char *args);
67     int cmd_cookie(char *args);
68     int cmd_init(char *args);
69     int cmd_format(char *args);
70     int cmd_proxy(char *args);
71 };
72
73
74 void MyClient::connectNotify()
75 {
76     printf ("Connection accepted by target\n");
77     set_lastReceived(-1);
78 }
79
80 void MyClient::timeoutNotify()
81 {
82     printf ("Connection timeout\n");
83     close();
84 }
85
86 void MyClient::failNotify()
87 {
88     printf ("Connection closed by target\n");
89     set_lastReceived(-1);
90 }
91
92 IPDU_Observer *MyClient::sessionNotify(IPDU_Observable *the_PDU_Observable,
93                                        int fd)
94
95     return new MyClient(the_PDU_Observable, m_socketManager);
96 }
97
98 MyClient::MyClient(IPDU_Observable *the_PDU_Observable,
99                    SocketManager *the_socketManager) :
100     IR_Assoc (the_PDU_Observable)
101 {
102     m_setOffset = 1;
103     m_interactive_flag = 1;
104     m_thisCommand[0] = '\0';
105     m_lastCommand[0] = '\0';
106     m_socketManager = the_socketManager;
107 }
108
109 void usage(char *prog)
110 {
111     fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
112     exit (1);
113 }
114
115 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
116 {
117     int oid[OID_SIZE];
118     Z_OtherInformationUnit *oi;
119     struct oident ent;
120     ent.proto = PROTO_Z3950;
121     ent.oclass = CLASS_USERINFO;
122     ent.value = (oid_value) VAL_COOKIE;
123
124     if (oid_ent_to_oid (&ent, oid) && 
125         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
126         oi->which == Z_OtherInfo_characterInfo)
127         return oi->information.characterInfo;
128     return 0;
129 }
130
131 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
132 {
133     printf ("Got InitResponse. Status ");
134     if (*initResponse->result)
135     {
136         printf ("Ok\n");
137
138         const char *p = get_cookie (&initResponse->otherInfo);
139         if (p)
140         {
141             printf ("cookie = %s\n", p);
142             set_cookie(p);
143         }
144     }
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     if (r->which == Z_External_octet && record->u.octet_aligned->len)
300     {
301         yaz_marc_t mt = yaz_marc_create();
302         switch (ent->value)
303         {
304         case VAL_ISO2709:
305         case VAL_UNIMARC:
306         case VAL_INTERMARC:
307         case VAL_USMARC:
308         case VAL_UKMARC:
309         case VAL_NORMARC:
310         case VAL_LIBRISMARC:
311         case VAL_DANMARC:
312         case VAL_FINMARC:
313         case VAL_MAB:
314         case VAL_CANMARC:
315         case VAL_SBN:
316         case VAL_PICAMARC:
317         case VAL_AUSMARC:
318         case VAL_IBERMARC:
319         case VAL_CATMARC:
320         case VAL_MALMARC:
321         case VAL_JPMARC:
322         case VAL_SWEMARC:
323         case VAL_SIGLEMARC:
324         case VAL_ISDSMARC:
325         case VAL_RUSMARC:
326             const char *result_buf;
327             size_t result_size;
328             yaz_marc_decode_buf(mt, (const char *)
329                                 record->u.octet_aligned->buf,
330                                 record->u.octet_aligned->len,
331                                 &result_buf, &result_size);
332             fwrite(result_buf, 1, result_size, stdout);
333             break;
334         default:
335             recv_textRecord((int) ent->value,
336                             (const char *) record->u.octet_aligned->buf,
337                             (size_t) record->u.octet_aligned->len);
338         }
339         yaz_marc_destroy(mt);
340     }
341     else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
342         recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
343                         (size_t) r->u.sutrs->len);
344     else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
345         recv_genericRecord(r->u.grs1);
346     else 
347     {
348         printf("Unknown record representation.\n");
349         if (!z_External(odr_print(), &r, 0, 0))
350         {
351             odr_perror(odr_print(), "Printing external");
352             odr_reset(odr_print());
353         }
354     }    
355 }
356
357 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
358 {
359     if (zpr->databaseName)
360         printf("[%s]", zpr->databaseName);
361     if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
362         recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
363     else
364         recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
365 }
366
367 void MyClient::recv_records (Z_Records *records)
368 {
369 #ifdef ASN_COMPILED
370     Z_DiagRec dr, *dr_p = &dr;
371 #endif
372     if (!records)
373         return;
374     int i;
375     switch (records->which)
376     {
377     case Z_Records_DBOSD:
378         for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
379             recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
380                                 records[i], i + m_setOffset);
381         m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
382         break;
383     case Z_Records_NSD:
384 #ifdef ASN_COMPILED
385         dr.which = Z_DiagRec_defaultFormat;
386         dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
387         recv_diagrecs (&dr_p, 1);
388 #else
389         recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
390 #endif
391         break;
392     case Z_Records_multipleNSD:
393         recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
394                        records->u.multipleNonSurDiagnostics->num_diagRecs);
395         break;
396     }
397 }
398
399 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
400 {
401     printf ("Got SearchResponse. Status ");
402     if (!*searchResponse->searchStatus)
403     {
404         printf ("Fail\n");
405     }
406     else
407     {
408         printf ("Ok\n");
409         printf ("Hits: %d\n", *searchResponse->resultCount);
410     }
411     recv_records (searchResponse->records);
412 }
413
414 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
415 {
416     printf ("Got PresentResponse\n");
417     recv_records (presentResponse->records);
418 }
419
420 int MyClient::wait()
421 {
422     set_lastReceived(0);
423     while (m_socketManager->processEvent() > 0)
424     {
425         if (get_lastReceived())
426             return 1;
427     }
428     return 0;
429 }
430
431
432 #define C_PROMPT "Z>"
433
434 int MyClient::cmd_connect(char *host)
435 {
436     client (host);
437     timeout (10);
438     wait ();
439     timeout (-1);
440     return 1;
441 }
442
443 int MyClient::cmd_open(char *host)
444 {
445     client (host);
446     timeout (10);
447     wait ();
448     timeout (-1);
449     send_initRequest();
450     wait ();
451     return 1;
452 }
453
454 int MyClient::cmd_init(char *args)
455 {
456     if (send_initRequest() >= 0)
457         wait();
458     else
459         close();
460     return 1;
461 }
462
463 int MyClient::cmd_quit(char *args)
464 {
465     return 0;
466 }
467
468 int MyClient::cmd_close(char *args)
469 {
470     close();
471     return 1;
472 }
473
474 int MyClient::cmd_find(char *args)
475 {
476     Yaz_Z_Query query;
477
478     if (query.set_rpn(args) <= 0)
479     {
480         printf ("Bad RPN query\n");
481         return 1;
482     }
483     if (send_searchRequest(&query) >= 0)
484         wait();
485     else
486         printf ("Not connected\n");
487     return 1;
488 }
489
490 int MyClient::cmd_show(char *args)
491 {
492     int start = m_setOffset, number = 1;
493
494     sscanf (args, "%d %d", &start, &number);
495     m_setOffset = start;
496     if (send_presentRequest(start, number) >= 0)
497         wait();
498     else
499         printf ("Not connected\n");
500     return 1;
501 }
502
503 int MyClient::cmd_cookie(char *args)
504 {
505     set_cookie(*args ? args : 0);
506     return 1;
507 }
508
509 int MyClient::cmd_format(char *args)
510 {
511     set_preferredRecordSyntax(args);
512     return 1;
513 }
514
515 int MyClient::cmd_proxy(char *args)
516 {
517     set_proxy(args);
518     return 1;
519 }
520
521 int MyClient::processCommand(const char *commandLine)
522 {
523     char cmdStr[1024], cmdArgs[1024];
524     cmdArgs[0] = '\0';
525     cmdStr[0] = '\0';
526     static struct {
527         const char *cmd;
528         int (MyClient::*fun)(char *arg);
529         const char *ad;
530     } cmd[] = {
531         {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
532         {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
533         {"quit", &MyClient::cmd_quit, ""},
534         {"close", &MyClient::cmd_close, ""},
535         {"find", &MyClient::cmd_find, "<query>"},
536         {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
537         {"cookie", &MyClient::cmd_cookie, "<cookie>"},
538         {"init", &MyClient::cmd_init, ""},
539         {"format", &MyClient::cmd_format, "<record-syntax>"},
540         {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
541         {0,0,0}
542     };
543     
544     if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
545         return 1;
546     int i;
547     for (i = 0; cmd[i].cmd; i++)
548         if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
549             break;
550     
551     int res = 1;
552     if (cmd[i].cmd) // Invoke command handler
553         res = (this->*cmd[i].fun)(cmdArgs);
554     else            // Dump help screen
555     {
556         printf("Unknown command: %s.\n", cmdStr);
557         printf("Currently recognized commands:\n");
558         for (i = 0; cmd[i].cmd; i++)
559             printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
560     }
561     return res;
562 }
563
564 const char *MyClient::getCommand()
565 {
566 #if HAVE_READLINE_READLINE_H
567     // Read using GNU readline
568     char *line_in;
569     line_in=readline(C_PROMPT);
570     if (!line_in)
571         return 0;
572 #if HAVE_READLINE_HISTORY_H
573     if (*line_in)
574         add_history(line_in);
575 #endif
576     strncpy(m_thisCommand,line_in, 1023);
577     m_thisCommand[1023] = '\0';
578     free (line_in);
579 #else    
580     // Read using fgets(3)
581     printf (C_PROMPT);
582     fflush(stdout);
583     if (!fgets(m_thisCommand, 1023, stdin))
584         return 0;
585 #endif
586     // Remove trailing whitespace
587     char *cp = m_thisCommand + strlen(m_thisCommand);
588     while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
589         cp--;
590     *cp = '\0';
591     cp = m_thisCommand;
592     // Remove leading spaces...
593     while (*cp && strchr ("\t \n", *cp))
594         cp++;
595     // Save command if non-empty
596     if (*cp != '\0')
597         strcpy (m_lastCommand, cp);
598     return m_lastCommand;
599 }
600
601 int MyClient::interactive(SocketManager *socketManager)
602 {
603     const char *cmd;
604     if (!m_interactive_flag)
605         return 0;
606     while ((cmd = getCommand()))
607     {
608         if (!processCommand(cmd))
609             break;
610     }
611     return 0;
612 }
613
614 int MyClient::args(SocketManager *socketManager, int argc, char **argv)
615 {
616     char *host = 0;
617     char *proxy = 0;
618     char *arg;
619     char *prog = argv[0];
620     int ret;
621
622     while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
623     {
624         switch (ret)
625         {
626         case 0:
627             if (host)
628             {
629                 usage(prog);
630                 return 1;
631             }
632             host = arg;
633             break;
634         case 'p':
635             if (proxy)
636             {
637                 usage(prog);
638                 return 1;
639             }
640             set_proxy(arg);
641             break;
642         case 'c':
643             set_cookie(arg);
644             break;
645         case 'v':
646             yaz_log_init_level (yaz_log_mask_str(arg));
647             break;
648         case 'q':
649             m_interactive_flag = 0;
650             break;
651         default:
652             usage(prog);
653             return 1;
654         }
655     }
656     if (host)
657     {
658         client (host);
659         timeout (10);
660         wait ();
661         timeout (-1);
662         send_initRequest();
663         wait ();
664     }
665     return 0;
666 }
667
668 int main(int argc, char **argv)
669 {
670     SocketManager mySocketManager;
671     PDU_Assoc *some = new PDU_Assoc(&mySocketManager);
672
673     MyClient z(some, &mySocketManager);
674
675     if (z.args(&mySocketManager, argc, argv))
676         exit (1);
677     if (z.interactive(&mySocketManager))
678         exit (1);
679     return 0;
680 }
681 /*
682  * Local variables:
683  * c-basic-offset: 4
684  * indent-tabs-mode: nil
685  * End:
686  * vim: shiftwidth=4 tabstop=8 expandtab
687  */
688