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