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