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