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