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