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