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