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