Added a few casts to make C++ happy.
[yaz-moved-to-github.git] / client / client.c
1 /*
2  * Copyright (c) 1995-1998, Index Data.
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: client.c,v $
7  * Revision 1.63  1998-03-05 08:05:10  adam
8  * Added a few casts to make C++ happy.
9  *
10  * Revision 1.62  1998/02/11 11:53:33  adam
11  * Changed code so that it compiles as C++.
12  *
13  * Revision 1.61  1998/02/10 11:03:06  adam
14  * Implemented command refid. Client prints reference-ID's, when present,
15  * in responses.
16  *
17  * Revision 1.60  1998/01/29 14:08:52  adam
18  * Better sort diagnostics.
19  *
20  * Revision 1.59  1998/01/29 13:17:56  adam
21  * Added sort.
22  *
23  * Revision 1.58  1998/01/07 13:51:45  adam
24  * Minor change.
25  *
26  * Revision 1.57  1998/01/07 12:58:22  adam
27  * Using fgets instead of gets.
28  *
29  * Revision 1.56  1997/11/05 09:18:31  adam
30  * The client handles records with no associated syntax.
31  *
32  * Revision 1.55  1997/10/31 12:20:08  adam
33  * Improved memory debugging for xmalloc/nmem.c. References to NMEM
34  * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
35  * Bug fix: missing fclose in data1_read_espec1.
36  *
37  * Revision 1.54  1997/10/27 13:52:46  adam
38  * Header yaz-util includes all YAZ utility header files.
39  *
40  * Revision 1.53  1997/09/29 13:18:59  adam
41  * Added function, oid_ent_to_oid, to replace the function
42  * oid_getoidbyent, which is not thread safe.
43  *
44  * Revision 1.52  1997/09/29 07:20:31  adam
45  * Client code uses nmem_init.
46  *
47  * Revision 1.51  1997/09/26 09:41:55  adam
48  * Updated client to handle multiple diagnostics.
49  *
50  * Revision 1.50  1997/09/17 12:10:29  adam
51  * YAZ version 1.4.
52  *
53  * Revision 1.49  1997/09/04 13:45:17  adam
54  * Added UNImarc to list of available syntaxes.
55  *
56  * Revision 1.48  1997/09/01 08:48:44  adam
57  * New windows NT/95 port using MSV5.0. Only a few changes made
58  * to avoid warnings. Sub project created: client.dsp.
59  *
60  * Revision 1.47  1997/07/01 13:49:56  adam
61  * Take care of case when invalid target is specified on command line.
62  *
63  * Revision 1.46  1997/06/23 10:30:18  adam
64  * Added call to ccl_rpn_delete in search. Added ODR stream "out"
65  * as parameter to ccl_rpn_query to release RPN query.
66  *
67  * Revision 1.45  1997/05/14 06:53:29  adam
68  * C++ support.
69  *
70  * Revision 1.44  1997/05/05 11:20:35  adam
71  * Client uses "options" utility and marc dump filename may be specified
72  * as an option (-m <file>).
73  *
74  * Revision 1.43  1996/11/08 11:03:26  adam
75  * Client accepts multiple database names.
76  *
77  * Revision 1.42  1996/10/08 10:44:57  quinn
78  * Resolved conflicts.
79  *
80  * Revision 1.41  1996/10/07  15:29:03  quinn
81  * Work
82  *
83  * Revision 1.40  1996/08/29  14:19:34  quinn
84  * Fixed conflict (CVS)
85  *
86  * Revision 1.39  1996/08/27  10:43:22  quinn
87  * Made select() optional
88  *
89  * Revision 1.38  1996/08/12  14:09:11  adam
90  * Default prefix query attribute set defined by using p_query_attset.
91  *
92  * Revision 1.37  1996/07/06  19:58:29  quinn
93  * System headerfiles gathered in yconfig
94  *
95  * Revision 1.36  1996/06/10  08:53:47  quinn
96  * Added Summary
97  *
98  * Revision 1.35  1996/06/03  09:45:50  quinn
99  * Added display of OIDs in the GRS routine.
100  *
101  * Revision 1.34  1996/05/09  07:26:49  quinn
102  * *** empty log message ***
103  *
104  * Revision 1.33  1996/05/09  07:25:22  quinn
105  * Small
106  *
107  * Revision 1.32  1996/03/15  11:05:33  adam
108  * The user can set the preferred query type (prefix, ccl, ..) with the
109  * querytype command.
110  *
111  * Revision 1.31  1996/02/20  12:51:54  quinn
112  * Fixed problems with EXTERNAL.
113  *
114  * Revision 1.30  1996/02/12  18:18:09  quinn
115  * Fidgeting.
116  *
117  * Revision 1.29  1996/01/02  08:57:25  quinn
118  * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
119  *
120  * Revision 1.28  1995/12/14  11:09:31  quinn
121  * Added Explain record syntax to the format command.
122  *
123  * Revision 1.27  1995/12/12  16:37:02  quinn
124  * Added destroy element to data1_node.
125  *
126  * Revision 1.26  1995/12/12  14:11:00  quinn
127  * Minimal.
128  *
129  * Revision 1.25  1995/11/13  09:27:22  quinn
130  * Fiddling with the variant stuff.
131  *
132  * Revision 1.24  1995/10/30  12:41:13  quinn
133  * Added hostname lookup for server.
134  *
135  * Revision 1.23  1995/10/18  16:12:30  quinn
136  * Better diagnostics.
137  *
138  * Revision 1.22  1995/10/11  14:49:12  quinn
139  * Smallish.
140  *
141  * Revision 1.21  1995/09/29  17:01:47  quinn
142  * More Windows work
143  *
144  * Revision 1.20  1995/08/29  14:24:13  quinn
145  * Added second half of close-handshake
146  *
147  * Revision 1.19  1995/08/29  11:17:28  quinn
148  * Added code to receive close
149  *
150  * Revision 1.18  1995/08/28  12:21:27  quinn
151  * Client can now ask for simple element set names.
152  *
153  * Revision 1.17  1995/08/17  12:45:02  quinn
154  * Fixed minor problems with GRS-1. Added support in c&s.
155  *
156  * Revision 1.16  1995/08/15  12:00:04  quinn
157  * Updated External
158  *
159  * Revision 1.15  1995/06/22  09:28:03  quinn
160  * Fixed bug in SUTRS processing.
161  *
162  * Revision 1.14  1995/06/19  12:37:41  quinn
163  * Added BER dumper.
164  *
165  * Revision 1.13  1995/06/16  10:29:11  quinn
166  * *** empty log message ***
167  *
168  * Revision 1.12  1995/06/15  07:44:57  quinn
169  * Moving to v3.
170  *
171  * Revision 1.11  1995/06/14  15:26:40  quinn
172  * *** empty log message ***
173  *
174  * Revision 1.10  1995/06/06  14:56:58  quinn
175  * Better diagnostics.
176  *
177  * Revision 1.9  1995/06/06  08:15:19  quinn
178  * Cosmetic.
179  *
180  * Revision 1.8  1995/06/05  10:52:22  quinn
181  * Added SCAN.
182  *
183  * Revision 1.7  1995/06/02  09:50:09  quinn
184  * Smallish.
185  *
186  * Revision 1.6  1995/05/31  08:29:21  quinn
187  * Nothing significant.
188  *
189  * Revision 1.5  1995/05/29  08:10:47  quinn
190  * Moved oid.c to util.
191  *
192  * Revision 1.4  1995/05/22  15:30:13  adam
193  * Client uses prefix query notation.
194  *
195  * Revision 1.3  1995/05/22  15:06:53  quinn
196  * *** empty log message ***
197  *
198  * Revision 1.2  1995/05/22  14:56:40  quinn
199  * *** empty log message ***
200  *
201  * Revision 1.1  1995/05/22  11:30:31  quinn
202  * Added prettier client.
203  *
204  *
205  */
206
207 /*
208  * This is the obligatory little toy client, whose primary purpose is
209  * to illustrate the use of the YAZ service-level API.
210  */
211
212 #include <stdio.h>
213 #include <stdlib.h>
214 #include <time.h>
215 #include <assert.h>
216
217 #include <yaz-util.h>
218
219 #include <comstack.h>
220 #include <tcpip.h>
221 #ifdef USE_XTIMOSI
222 #include <xmosi.h>
223 #endif
224
225 #include <proto.h>
226 #include <marcdisp.h>
227 #include <diagbib1.h>
228
229 #include <pquery.h>
230
231 #if CCL2RPN
232 #include <yaz-ccl.h>
233 #endif
234
235 #define C_PROMPT "Z> "
236
237 static ODR out, in, print;              /* encoding and decoding streams */
238 static COMSTACK conn = 0;               /* our z-association */
239 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
240 static char *databaseNames[128];
241 static int num_databaseNames = 0;
242 static int setnumber = 0;               /* current result set number */
243 static int smallSetUpperBound = 0;
244 static int largeSetLowerBound = 1;
245 static int mediumSetPresentNumber = 0;
246 static Z_ElementSetNames *elementSetNames = 0; 
247 static int setno = 1;                   /* current set offset */
248 static int protocol = PROTO_Z3950;      /* current app protocol */
249 static int recordsyntax = VAL_USMARC;
250 static int sent_close = 0;
251 static ODR_MEM session_mem;             /* memory handle for init-response */
252 static Z_InitResponse *session = 0;     /* session parameters */
253 static char last_scan[512] = "0";
254 static char last_cmd[100] = "?";
255 static FILE *marcdump = 0;
256 static char *refid = NULL;
257
258 typedef enum {
259     QueryType_Prefix,
260     QueryType_CCL,
261     QueryType_CCL2RPN
262 } QueryType;
263
264 static QueryType queryType = QueryType_Prefix;
265
266 #if CCL2RPN
267 static CCL_bibset bibset;               /* CCL bibset handle */
268 #endif
269
270 static void send_apdu(Z_APDU *a)
271 {
272     char *buf;
273     int len;
274
275     if (!z_APDU(out, &a, 0))
276     {
277         odr_perror(out, "Encoding APDU");
278         exit(1);
279     }
280     buf = odr_getbuf(out, &len, 0);
281     if (cs_put(conn, buf, len) < 0)
282     {
283         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
284         exit(1);
285     }
286     odr_reset(out); /* release the APDU structure  */
287 }
288
289 static void print_refid (Z_ReferenceId *id)
290 {
291     if (id)
292     {
293         printf ("ReferenceId: '%.*s'\n", id->len, id->buf);
294     }
295 }
296
297 static Z_ReferenceId *set_refid (ODR out)
298 {
299     Z_ReferenceId *id;
300     if (!refid)
301         return 0;
302     id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
303     id->size = id->len = strlen(refid);
304     id->buf = (unsigned char *) odr_malloc (out, id->len);
305     memcpy (id->buf, refid, id->len);
306     return id;
307 }   
308
309 /* INIT SERVICE ------------------------------- */
310
311 static void send_initRequest()
312 {
313     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
314     Z_InitRequest *req = apdu->u.initRequest;
315
316     ODR_MASK_SET(req->options, Z_Options_search);
317     ODR_MASK_SET(req->options, Z_Options_present);
318     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
319     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
320     ODR_MASK_SET(req->options, Z_Options_scan);
321     ODR_MASK_SET(req->options, Z_Options_sort);
322
323     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
324     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
325     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
326
327     *req->maximumRecordSize = 1024*1024;
328
329     req->idAuthentication = auth;
330
331     send_apdu(apdu);
332     printf("Sent initrequest.\n");
333 }
334
335 static int process_initResponse(Z_InitResponse *res)
336 {
337     /* save session parameters for later use */
338     session_mem = odr_extract_mem(in);
339     session = res;
340
341     if (!*res->result)
342         printf("Connection rejected by target.\n");
343     else
344         printf("Connection accepted by target.\n");
345     if (res->implementationId)
346         printf("ID     : %s\n", res->implementationId);
347     if (res->implementationName)
348         printf("Name   : %s\n", res->implementationName);
349     if (res->implementationVersion)
350         printf("Version: %s\n", res->implementationVersion);
351     if (res->userInformationField)
352     {
353         printf("UserInformationfield:\n");
354         if (!z_External(print, (Z_External**)&res-> userInformationField,
355             0))
356         {
357             odr_perror(print, "Printing userinfo\n");
358             odr_reset(print);
359         }
360         if (res->userInformationField->which == Z_External_octet)
361         {
362             printf("Guessing visiblestring:\n");
363             printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
364         }
365     }
366     return 0;
367 }
368
369 int cmd_open(char *arg)
370 {
371     void *add;
372     char type[100], addr[100];
373     CS_TYPE t;
374
375     if (conn)
376     {
377         printf("Already connected.\n");
378         return 0;
379     }
380     if (!*arg || sscanf(arg, "%[^:]:%s", type, addr) < 2)
381     {
382         fprintf(stderr, "Usage: open (osi|tcp) ':' [tsel '/']host[':'port]\n");
383         return 0;
384     }
385     if (!strcmp(type, "tcp"))
386     {
387         t = tcpip_type;
388         protocol = PROTO_Z3950;
389     }
390     else
391 #ifdef USE_XTIMOSI
392     if (!strcmp(type, "osi"))
393     {
394         t = mosi_type;
395         protocol = PROTO_SR;
396     }
397     else
398 #endif
399     {
400         fprintf(stderr, "Bad type: %s\n", type);
401         return 0;
402     }
403     if (!(conn = cs_create(t, 1, protocol)))
404     {
405         perror("cs_create");
406         return 0;
407     }
408     if (!(add = cs_straddr(conn, addr)))
409     {
410         perror(arg);
411         return 0;
412     }
413     printf("Connecting...");
414     fflush(stdout);
415     if (cs_connect(conn, add) < 0)
416     {
417         perror("connect");
418         cs_close(conn);
419         conn = 0;
420         return 0;
421     }
422     printf("Ok.\n");
423     send_initRequest();
424     return 2;
425 }
426
427 int cmd_authentication(char *arg)
428 {
429     static Z_IdAuthentication au;
430     static char open[256];
431
432     if (!*arg)
433     {
434         printf("Auth field set to null\n");
435         auth = 0;
436         return 1;
437     }
438     auth = &au;
439     au.which = Z_IdAuthentication_open;
440     au.u.open = open;
441     strcpy(open, arg);
442     return 1;
443 }
444
445 /* SEARCH SERVICE ------------------------------ */
446
447 static void display_variant(Z_Variant *v, int level)
448 {
449     int i;
450
451     for (i = 0; i < v->num_triples; i++)
452     {
453         printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
454             *v->triples[i]->type);
455         if (v->triples[i]->which == Z_Triple_internationalString)
456             printf(",value=%s\n", v->triples[i]->value.internationalString);
457         else
458             printf("\n");
459     }
460 }
461
462 static void display_grs1(Z_GenericRecord *r, int level)
463 {
464     int i;
465
466     if (!r)
467         return;
468     for (i = 0; i < r->num_elements; i++)
469     {
470         Z_TaggedElement *t;
471
472         printf("%*s", level * 4, "");
473         t = r->elements[i];
474         printf("(");
475         if (t->tagType)
476             printf("%d,", *t->tagType);
477         else
478             printf("?,");
479         if (t->tagValue->which == Z_StringOrNumeric_numeric)
480             printf("%d) ", *t->tagValue->u.numeric);
481         else
482             printf("%s) ", t->tagValue->u.string);
483         if (t->content->which == Z_ElementData_subtree)
484         {
485             printf("\n");
486             display_grs1(t->content->u.subtree, level+1);
487         }
488         else if (t->content->which == Z_ElementData_string)
489             printf("%s\n", t->content->u.string);
490         else if (t->content->which == Z_ElementData_numeric)
491             printf("%d\n", *t->content->u.numeric);
492         else if (t->content->which == Z_ElementData_oid)
493         {
494             int *ip = t->content->u.oid;
495             oident *oent;
496
497             if ((oent = oid_getentbyoid(t->content->u.oid)))
498                 printf("OID: %s\n", oent->desc);
499             else
500             {
501                 printf("{");
502                 while (ip && *ip >= 0)
503                     printf(" %d", *(ip++));
504                 printf(" }\n");
505             }
506         }
507         else if (t->content->which == Z_ElementData_noDataRequested)
508             printf("[No data requested]\n");
509         else if (t->content->which == Z_ElementData_elementEmpty)
510             printf("[Element empty]\n");
511         else if (t->content->which == Z_ElementData_elementNotThere)
512             printf("[Element not there]\n");
513         else
514             printf("??????\n");
515         if (t->appliedVariant)
516             display_variant(t->appliedVariant, level+1);
517         if (t->metaData && t->metaData->supportedVariants)
518         {
519             int c;
520
521             printf("%*s---- variant list\n", (level+1)*4, "");
522             for (c = 0; c < t->metaData->num_supportedVariants; c++)
523             {
524                 printf("%*svariant #%d\n", (level+1)*4, "", c);
525                 display_variant(t->metaData->supportedVariants[c], level + 2);
526             }
527         }
528     }
529 }
530
531 static void display_record(Z_DatabaseRecord *p)
532 {
533     Z_External *r = (Z_External*) p;
534     oident *ent = oid_getentbyoid(r->direct_reference);
535
536     /*
537      * Tell the user what we got.
538      */
539     if (r->direct_reference)
540     {
541         printf("Record type: ");
542         if (ent)
543             printf("%s\n", ent->desc);
544         else if (!odr_oid(print, &r->direct_reference, 0))
545         {
546             odr_perror(print, "print oid");
547             odr_reset(print);
548         }
549     }
550     /* Check if this is a known, ASN.1 type tucked away in an octet string */
551     if (ent && r->which == Z_External_octet)
552     {
553         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
554         void *rr;
555
556         if (type)
557         {
558             /*
559              * Call the given decoder to process the record.
560              */
561             odr_setbuf(in, (char*)p->u.octet_aligned->buf,
562                 p->u.octet_aligned->len, 0);
563             if (!(*type->fun)(in, (char **)&rr, 0))
564             {
565                 odr_perror(in, "Decoding constructed record.");
566                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
567                 fprintf(stderr, "Packet dump:\n---------\n");
568                 odr_dumpBER(stderr, (char*)p->u.octet_aligned->buf,
569                     p->u.octet_aligned->len);
570                 fprintf(stderr, "---------\n");
571                 exit(1);
572             }
573             /*
574              * Note: we throw away the original, BER-encoded record here.
575              * Do something else with it if you want to keep it.
576              */
577             r->u.sutrs = (Odr_oct *)rr;    /* we don't actually check the type here. */
578             r->which = type->what;
579         }
580     }
581     if (ent && ent->value == VAL_SOIF)
582         printf("%.*s", r->u.octet_aligned->len, r->u.octet_aligned->buf);
583     else if (r->which == Z_External_octet && p->u.octet_aligned->len)
584     {
585         const char *marc_buf = (char*)p->u.octet_aligned->buf;
586         marc_display (marc_buf, NULL);
587         if (marcdump)
588             fwrite (marc_buf, strlen (marc_buf), 1, marcdump);
589     }
590     else if (ent && ent->value == VAL_SUTRS)
591     {
592         if (r->which != Z_External_sutrs)
593         {
594             printf("Expecting single SUTRS type for SUTRS.\n");
595             return;
596         }
597         printf("%.*s", r->u.sutrs->len, r->u.sutrs->buf);
598     }
599     else if (ent && ent->value == VAL_GRS1)
600     {
601         if (r->which != Z_External_grs1)
602         {
603             printf("Expecting single GRS type for GRS.\n");
604             return;
605         }
606         display_grs1(r->u.grs1, 0);
607     }
608     else 
609     {
610         printf("Unknown record representation.\n");
611         if (!z_External(print, &r, 0))
612         {
613             odr_perror(print, "Printing external");
614             odr_reset(print);
615         }
616     }
617 }
618
619
620 static void display_diagrecs(Z_DiagRec **pp, int num)
621 {
622     int i;
623     oident *ent;
624     Z_DefaultDiagFormat *r;
625
626     printf("Diagnostic message(s) from database:\n");
627     for (i = 0; i<num; i++)
628     {
629         Z_DiagRec *p = pp[i];
630         if (p->which != Z_DiagRec_defaultFormat)
631         {
632             printf("Diagnostic record not in default format.\n");
633             return;
634         }
635         else
636             r = p->u.defaultFormat;
637         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
638             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
639             printf("Missing or unknown diagset\n");
640         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
641         if (r->addinfo && *r->addinfo)
642             printf(" -- '%s'\n", r->addinfo);
643         else
644             printf("\n");
645     }
646 }
647
648
649 static void display_nameplusrecord(Z_NamePlusRecord *p)
650 {
651     if (p->databaseName)
652         printf("[%s]", p->databaseName);
653     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
654         display_diagrecs(&p->u.surrogateDiagnostic, 1);
655     else
656         display_record(p->u.databaseRecord);
657 }
658
659 static void display_records(Z_Records *p)
660 {
661     int i;
662
663     if (p->which == Z_Records_NSD)
664         display_diagrecs (&p->u.nonSurrogateDiagnostic, 1);
665     else if (p->which == Z_Records_multipleNSD)
666         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
667                           p->u.multipleNonSurDiagnostics->num_diagRecs);
668     else 
669     {
670         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
671         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
672             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
673     }
674 }
675
676 static int send_searchRequest(char *arg)
677 {
678     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
679     Z_SearchRequest *req = apdu->u.searchRequest;
680     Z_Query query;
681     int oid[OID_SIZE];
682 #if CCL2RPN
683     struct ccl_rpn_node *rpn;
684     int error, pos;
685     oident bib1;
686 #endif
687     char setstring[100];
688     Z_RPNQuery *RPNquery;
689     Odr_oct ccl_query;
690
691 #if CCL2RPN
692     if (queryType == QueryType_CCL2RPN)
693     {
694         rpn = ccl_find_str(bibset, arg, &error, &pos);
695         if (error)
696         {
697             printf("CCL ERROR: %s\n", ccl_err_msg(error));
698             return 0;
699         }
700     }
701 #endif
702     req->referenceId = set_refid (out);
703     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
704     {
705         static unsigned char big[2100];
706         static Odr_oct bigo;
707
708         /* send a very big referenceid to test transport stack etc. */
709         memset(big, 'A', 2100);
710         bigo.len = bigo.size = 2100;
711         bigo.buf = big;
712         req->referenceId = &bigo;
713     }
714     
715     if (setnumber >= 0)
716     {
717         sprintf(setstring, "%d", ++setnumber);
718         req->resultSetName = setstring;
719     }
720     *req->smallSetUpperBound = smallSetUpperBound;
721     *req->largeSetLowerBound = largeSetLowerBound;
722     *req->mediumSetPresentNumber = mediumSetPresentNumber;
723     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
724         mediumSetPresentNumber > 0))
725     {
726         oident prefsyn;
727
728         prefsyn.proto = protocol;
729         prefsyn.oclass = CLASS_RECSYN;
730         prefsyn.value = recordsyntax;
731         req->preferredRecordSyntax =
732             odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
733         req->smallSetElementSetNames =
734             req->mediumSetElementSetNames = elementSetNames;
735     }
736     req->num_databaseNames = num_databaseNames;
737     req->databaseNames = databaseNames;
738
739     req->query = &query;
740
741     switch (queryType)
742     {
743     case QueryType_Prefix:
744         query.which = Z_Query_type_1;
745         RPNquery = p_query_rpn (out, protocol, arg);
746         if (!RPNquery)
747         {
748             printf("Prefix query error\n");
749             return 0;
750         }
751         query.u.type_1 = RPNquery;
752         break;
753     case QueryType_CCL:
754         query.which = Z_Query_type_2;
755         query.u.type_2 = &ccl_query;
756         ccl_query.buf = (unsigned char*) arg;
757         ccl_query.len = strlen(arg);
758         break;
759 #if CCL2RPN
760     case QueryType_CCL2RPN:
761         query.which = Z_Query_type_1;
762         assert((RPNquery = ccl_rpn_query(out, rpn)));
763         bib1.proto = protocol;
764         bib1.oclass = CLASS_ATTSET;
765         bib1.value = VAL_BIB1;
766         RPNquery->attributeSetId = oid_ent_to_oid(&bib1, oid);
767         query.u.type_1 = RPNquery;
768         ccl_rpn_delete (rpn);
769         break;
770 #endif
771     default:
772         printf ("Unsupported query type\n");
773         return 0;
774     }
775     send_apdu(apdu);
776     setno = 1;
777     printf("Sent searchRequest.\n");
778     return 2;
779 }
780
781 static int process_searchResponse(Z_SearchResponse *res)
782 {
783     printf ("Received SearchResponse.\n");
784     print_refid (res->referenceId);
785     if (*res->searchStatus)
786         printf("Search was a success.\n");
787     else
788         printf("Search was a bloomin' failure.\n");
789     printf("Number of hits: %d, setno %d\n",
790         *res->resultCount, setnumber);
791     printf("records returned: %d\n",
792         *res->numberOfRecordsReturned);
793     setno += *res->numberOfRecordsReturned;
794     if (res->records)
795         display_records(res->records);
796     return 0;
797 }
798
799 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
800 {
801     printf ("Received ResourceControlRequest.\n");
802     print_refid (req->referenceId);
803     return 0;
804 }
805
806 static int cmd_find(char *arg)
807 {
808     if (!*arg)
809     {
810         printf("Find what?\n");
811         return 0;
812     }
813     if (!conn)
814     {
815         printf("Not connected yet\n");
816         return 0;
817     }
818     if (!send_searchRequest(arg))
819         return 0;
820     return 2;
821 }
822
823 static int cmd_ssub(char *arg)
824 {
825     if (!(smallSetUpperBound = atoi(arg)))
826         return 0;
827     return 1;
828 }
829
830 static int cmd_lslb(char *arg)
831 {
832     if (!(largeSetLowerBound = atoi(arg)))
833         return 0;
834     return 1;
835 }
836
837 static int cmd_mspn(char *arg)
838 {
839     if (!(mediumSetPresentNumber = atoi(arg)))
840         return 0;
841     return 1;
842 }
843
844 static int cmd_status(char *arg)
845 {
846     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
847     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
848     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
849     return 1;
850 }
851
852 static int cmd_base(char *arg)
853 {
854     int i;
855     char *cp;
856
857     if (!*arg)
858     {
859         printf("Usage: base <database> <database> ...\n");
860         return 0;
861     }
862     for (i = 0; i<num_databaseNames; i++)
863         xfree (databaseNames[i]);
864     num_databaseNames = 0;
865     while (1)
866     {
867         if (!(cp = strchr(arg, ' ')))
868             cp = arg + strlen(arg);
869         if (cp - arg < 1)
870             break;
871         databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
872         memcpy (databaseNames[num_databaseNames], arg, cp - arg);
873         databaseNames[num_databaseNames++][cp - arg] = '\0';
874         if (!*cp)
875             break;
876         arg = cp+1;
877     }
878     return 1;
879 }
880
881 static int cmd_setnames(char *arg)
882 {
883     if (setnumber < 0)
884     {
885         printf("Set numbering enabled.\n");
886         setnumber = 0;
887     }
888     else
889     {
890         printf("Set numbering disabled.\n");
891         setnumber = -1;
892     }
893     return 1;
894 }
895
896 /* PRESENT SERVICE ----------------------------- */
897
898 static int send_presentRequest(char *arg)
899 {
900     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
901     Z_PresentRequest *req = apdu->u.presentRequest;
902     Z_RecordComposition compo;
903     oident prefsyn;
904     int nos = 1;
905     int oid[OID_SIZE];
906     char *p;
907     char setstring[100];
908
909     req->referenceId = set_refid (out);
910     if ((p = strchr(arg, '+')))
911     {
912         nos = atoi(p + 1);
913         *p = 0;
914     }
915     if (*arg)
916         setno = atoi(arg);
917     if (p && (p=strchr(p+1, '+')))
918     {
919         strcpy (setstring, p+1);
920         req->resultSetId = setstring;
921     }
922     else if (setnumber >= 0)
923     {
924         sprintf(setstring, "%d", setnumber);
925         req->resultSetId = setstring;
926     }
927 #if 0
928     if (1)
929     {
930         static Z_Range range;
931         static Z_Range *rangep = &range;
932     req->num_ranges = 1;
933 #endif
934     req->resultSetStartPoint = &setno;
935     req->numberOfRecordsRequested = &nos;
936     prefsyn.proto = protocol;
937     prefsyn.oclass = CLASS_RECSYN;
938     prefsyn.value = recordsyntax;
939     req->preferredRecordSyntax = oid_ent_to_oid(&prefsyn, oid);
940
941     if (elementSetNames)
942     {
943         req->recordComposition = &compo;
944         compo.which = Z_RecordComp_simple;
945         compo.u.simple = elementSetNames;
946     }
947     send_apdu(apdu);
948     printf("Sent presentRequest (%d+%d).\n", setno, nos);
949     return 2;
950 }
951
952 void process_close(Z_Close *req)
953 {
954     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
955     Z_Close *res = apdu->u.close;
956
957     static char *reasons[] =
958     {
959         "finished",
960         "shutdown",
961         "system problem",
962         "cost limit reached",
963         "resources",
964         "security violation",
965         "protocolError",
966         "lack of activity",
967         "peer abort",
968         "unspecified"
969     };
970
971     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
972         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
973     if (sent_close)
974     {
975         printf("Goodbye.\n");
976         exit(0);
977     }
978     *res->closeReason = Z_Close_finished;
979     send_apdu(apdu);
980     printf("Sent response.\n");
981     sent_close = 1;
982 }
983
984 static int cmd_show(char *arg)
985 {
986     if (!send_presentRequest(arg))
987         return 0;
988     return 2;
989 }
990
991 int cmd_quit(char *arg)
992 {
993     printf("See you later, alligator.\n");
994     exit(0);
995     return 0;
996 }
997
998 int cmd_cancel(char *arg)
999 {
1000     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1001     Z_TriggerResourceControlRequest *req =
1002         apdu->u.triggerResourceControlRequest;
1003     bool_t rfalse = 0;
1004     
1005     if (!session)
1006     {
1007         printf("Session not initialized yet\n");
1008         return 0;
1009     }
1010     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1011     {
1012         printf("Target doesn't support cancel (trigger resource ctrl)\n");
1013         return 0;
1014     }
1015     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1016     req->resultSetWanted = &rfalse;
1017
1018     send_apdu(apdu);
1019     printf("Sent cancel request\n");
1020     return 2;
1021 }
1022
1023 int send_scanrequest(char *string, int pp, int num)
1024 {
1025     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1026     Z_ScanRequest *req = apdu->u.scanRequest;
1027
1028     req->referenceId = set_refid (out);
1029     req->num_databaseNames = num_databaseNames;
1030     req->databaseNames = databaseNames;
1031     req->termListAndStartPoint = p_query_scan(out, protocol,
1032                                               &req->attributeSet, string);
1033     req->numberOfTermsRequested = &num;
1034     req->preferredPositionInResponse = &pp;
1035     send_apdu(apdu);
1036     return 2;
1037 }
1038
1039 int send_sortrequest(char *arg, int newset)
1040 {
1041     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1042     Z_SortRequest *req = apdu->u.sortRequest;
1043     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)odr_malloc (out, sizeof(*sksl));
1044     char setstring[32];
1045     char sort_string[32], sort_flags[32];
1046     int off;
1047     int oid[OID_SIZE];
1048     oident bib1;
1049
1050     if (setnumber >= 0)
1051         sprintf (setstring, "%d", setnumber);
1052     else
1053         sprintf (setstring, "default");
1054
1055     req->referenceId = set_refid (out);
1056
1057     req->inputResultSetNames =
1058         (Z_StringList *)odr_malloc (out, sizeof(*req->inputResultSetNames));
1059     req->inputResultSetNames->num_strings = 1;
1060     req->inputResultSetNames->strings =
1061         (char **)odr_malloc (out, sizeof(*req->inputResultSetNames->strings));
1062     req->inputResultSetNames->strings[0] =
1063         (char *)odr_malloc (out, strlen(setstring)+1);
1064     strcpy (req->inputResultSetNames->strings[0], setstring);
1065
1066     if (newset && setnumber >= 0)
1067         sprintf (setstring, "%d", ++setnumber);
1068
1069     req->sortedResultSetName = (char *)odr_malloc (out, strlen(setstring)+1);
1070     strcpy (req->sortedResultSetName, setstring);
1071
1072     req->sortSequence = sksl;
1073     sksl->num_specs = 0;
1074     sksl->specs = (Z_SortKeySpec **)odr_malloc (out, sizeof(sksl->specs) * 20);
1075     
1076     bib1.proto = protocol;
1077     bib1.oclass = CLASS_ATTSET;
1078     bib1.value = VAL_BIB1;
1079     while ((sscanf (arg, "%31s %31s%n", sort_string, sort_flags, &off)) == 2 
1080            && off > 1)
1081     {
1082         int i;
1083         char *sort_string_sep;
1084         Z_SortKeySpec *sks = (Z_SortKeySpec *)odr_malloc (out, sizeof(*sks));
1085         Z_SortKey *sk = (Z_SortKey *)odr_malloc (out, sizeof(*sk));
1086
1087         arg += off;
1088         sksl->specs[sksl->num_specs++] = sks;
1089         sks->sortElement = (Z_SortElement *)odr_malloc (out, sizeof(*sks->sortElement));
1090         sks->sortElement->which = Z_SortElement_generic;
1091         sks->sortElement->u.generic = sk;
1092         
1093         if ((sort_string_sep = strchr (sort_string, '=')))
1094         {
1095             Z_AttributeElement *el = (Z_AttributeElement *)odr_malloc (out, sizeof(*el));
1096             sk->which = Z_SortKey_sortAttributes;
1097             sk->u.sortAttributes =
1098                 (Z_SortAttributes *)odr_malloc (out, sizeof(*sk->u.sortAttributes));
1099             sk->u.sortAttributes->id = oid_ent_to_oid(&bib1, oid);
1100             sk->u.sortAttributes->list =
1101                 (Z_AttributeList *)odr_malloc (out, sizeof(*sk->u.sortAttributes->list));
1102             sk->u.sortAttributes->list->num_attributes = 1;
1103             sk->u.sortAttributes->list->attributes =
1104                 (Z_AttributeElement **)odr_malloc (out,
1105                             sizeof(*sk->u.sortAttributes->list->attributes));
1106             sk->u.sortAttributes->list->attributes[0] = el;
1107             el->attributeSet = 0;
1108             el->attributeType = (int *)odr_malloc (out, sizeof(*el->attributeType));
1109             *el->attributeType = atoi (sort_string);
1110             el->which = Z_AttributeValue_numeric;
1111             el->value.numeric = (int *)odr_malloc (out, sizeof(*el->value.numeric));
1112             *el->value.numeric = atoi (sort_string_sep + 1);
1113         }
1114         else
1115         {
1116             sk->which = Z_SortKey_sortField;
1117             sk->u.sortField = (char *)odr_malloc (out, strlen(sort_string)+1);
1118             strcpy (sk->u.sortField, sort_string);
1119         }
1120         sks->sortRelation = (int *)odr_malloc (out, sizeof(*sks->sortRelation));
1121         *sks->sortRelation = Z_SortRelation_ascending;
1122         sks->caseSensitivity = (int *)odr_malloc (out, sizeof(*sks->caseSensitivity));
1123         *sks->caseSensitivity = Z_SortCase_caseSensitive;
1124
1125         sks->missingValueAction = NULL;
1126
1127         for (i = 0; sort_flags[i]; i++)
1128         {
1129             switch (sort_flags[i])
1130             {
1131             case 'a':
1132             case 'A':
1133             case '>':
1134                 *sks->sortRelation = Z_SortRelation_ascending;
1135                 break;
1136             case 'd':
1137             case 'D':
1138             case '<':
1139                 *sks->sortRelation = Z_SortRelation_descending;
1140                 break;
1141             case 'i':
1142             case 'I':
1143                 *sks->caseSensitivity = Z_SortCase_caseInsensitive;
1144                 break;
1145             case 'S':
1146             case 's':
1147                 *sks->caseSensitivity = Z_SortCase_caseSensitive;
1148                 break;
1149             }
1150         }
1151     }
1152     if (!sksl->num_specs)
1153     {
1154         printf ("Missing sort specifications\n");
1155         return -1;
1156     }
1157     send_apdu(apdu);
1158     return 2;
1159 }
1160
1161 void display_term(Z_TermInfo *t)
1162 {
1163     if (t->term->which == Z_Term_general)
1164     {
1165         printf("%.*s (%d)\n", t->term->u.general->len, t->term->u.general->buf,
1166             t->globalOccurrences ? *t->globalOccurrences : -1);
1167         sprintf(last_scan, "%.*s", t->term->u.general->len,
1168             t->term->u.general->buf);
1169     }
1170     else
1171         printf("Term type not general.\n");
1172 }
1173
1174 void process_scanResponse(Z_ScanResponse *res)
1175 {
1176     int i;
1177    
1178     printf("Received ScanResponse\n"); 
1179     print_refid (res->referenceId);
1180     printf("%d entries", *res->numberOfEntriesReturned);
1181     if (res->positionOfTerm)
1182         printf (", position=%d", *res->positionOfTerm); 
1183     printf ("\n");
1184     if (*res->scanStatus != Z_Scan_success)
1185         printf("Scan returned code %d\n", *res->scanStatus);
1186     if (!res->entries)
1187         return;
1188     if (res->entries->which == Z_ListEntries_entries)
1189     {
1190         Z_Entries *ent = res->entries->u.entries;
1191
1192         for (i = 0; i < ent->num_entries; i++)
1193             if (ent->entries[i]->which == Z_Entry_termInfo)
1194             {
1195                 printf("%c ", i + 1 == *res->positionOfTerm ? '*' : ' ');
1196                 display_term(ent->entries[i]->u.termInfo);
1197             }
1198             else
1199                 display_diagrecs(&ent->entries[i]->u.surrogateDiagnostic, 1);
1200     }
1201     else
1202         display_diagrecs(&res->entries->
1203                          u.nonSurrogateDiagnostics->diagRecs[0], 1);
1204 }
1205
1206 void process_sortResponse(Z_SortResponse *res)
1207 {
1208     printf("Received SortResponse: status=");
1209     switch (*res->sortStatus)
1210     {
1211     case Z_SortStatus_success:
1212         printf ("success"); break;
1213     case Z_SortStatus_partial_1:
1214         printf ("partial"); break;
1215     case Z_SortStatus_failure:
1216         printf ("failure"); break;
1217     default:
1218         printf ("unknown (%d)", *res->sortStatus);
1219     }
1220     printf ("\n");
1221     print_refid (res->referenceId);
1222     if (res->diagnostics)
1223         display_diagrecs(res->diagnostics->diagRecs,
1224                          res->diagnostics->num_diagRecs);
1225 }
1226
1227 int cmd_sort_generic(char *arg, int newset)
1228 {
1229     if (!session)
1230     {
1231         printf("Session not initialized yet\n");
1232         return 0;
1233     }
1234     if (!ODR_MASK_GET(session->options, Z_Options_sort))
1235     {
1236         printf("Target doesn't support sort\n");
1237         return 0;
1238     }
1239     if (*arg)
1240     {
1241         if (send_sortrequest(arg, newset) < 0)
1242             return 0;
1243         return 2;
1244     }
1245     return 0;
1246 }
1247
1248 int cmd_sort(char *arg)
1249 {
1250     return cmd_sort_generic (arg, 0);
1251 }
1252
1253 int cmd_sort_newset (char *arg)
1254 {
1255     return cmd_sort_generic (arg, 1);
1256 }
1257
1258 int cmd_scan(char *arg)
1259 {
1260     if (!session)
1261     {
1262         printf("Session not initialized yet\n");
1263         return 0;
1264     }
1265     if (!ODR_MASK_GET(session->options, Z_Options_scan))
1266     {
1267         printf("Target doesn't support scan\n");
1268         return 0;
1269     }
1270     if (*arg)
1271     {
1272         if (send_scanrequest(arg, 5, 20) < 0)
1273             return 0;
1274     }
1275     else
1276         if (send_scanrequest(last_scan, 1, 20) < 0)
1277             return 0;
1278     return 2;
1279 }
1280
1281 int cmd_format(char *arg)
1282 {
1283     if (!arg || !*arg)
1284     {
1285         printf("Usage: format <recordsyntax>\n");
1286         return 0;
1287     }
1288     recordsyntax = oid_getvalbyname (arg);
1289     if (recordsyntax == VAL_NONE)
1290     {
1291         printf ("unknown record syntax\n");
1292         return 0;
1293     }
1294     return 1;
1295 }
1296
1297 int cmd_elements(char *arg)
1298 {
1299     static Z_ElementSetNames esn;
1300     static char what[100];
1301
1302     if (!arg || !*arg)
1303     {
1304         printf("Usage: elements <esn>\n");
1305         return 0;
1306     }
1307     strcpy(what, arg);
1308     esn.which = Z_ElementSetNames_generic;
1309     esn.u.generic = what;
1310     elementSetNames = &esn;
1311     return 1;
1312 }
1313
1314 int cmd_attributeset(char *arg)
1315 {
1316     char what[100];
1317
1318     if (!arg || !*arg)
1319     {
1320         printf("Usage: attributeset <setname>\n");
1321         return 0;
1322     }
1323     sscanf(arg, "%s", what);
1324     if (p_query_attset (what))
1325     {
1326         printf("Unknown attribute set name\n");
1327         return 0;
1328     }
1329     return 1;
1330 }
1331
1332 int cmd_querytype (char *arg)
1333 {
1334     if (!strcmp (arg, "ccl"))
1335         queryType = QueryType_CCL;
1336     else if (!strcmp (arg, "prefix"))
1337         queryType = QueryType_Prefix;
1338 #if CCL2RPN
1339     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
1340         queryType = QueryType_CCL2RPN;
1341 #endif
1342     else
1343     {
1344         printf ("Querytype must be one of:\n");
1345         printf (" prefix         - Prefix query\n");
1346         printf (" ccl            - CCL query\n");
1347 #if CCL2RPN
1348         printf (" ccl2rpn        - CCL query converted to RPN\n");
1349 #endif
1350         return 0;
1351     }
1352     return 1;
1353 }
1354
1355 int cmd_refid (char *arg)
1356 {
1357     xfree (refid);
1358     refid = NULL;
1359     if (*arg)
1360     {
1361         refid = (char *) xmalloc (strlen(arg)+1);
1362         strcpy (refid, arg);
1363     }
1364     return 1;
1365 }
1366
1367 int cmd_close(char *arg)
1368 {
1369     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1370     Z_Close *req = apdu->u.close;
1371
1372     *req->closeReason = Z_Close_finished;
1373     send_apdu(apdu);
1374     printf("Sent close request.\n");
1375     sent_close = 1;
1376     return 2;
1377 }
1378
1379 static void initialize(void)
1380 {
1381 #if CCL2RPN
1382     FILE *inf;
1383 #endif
1384     nmem_init();
1385     if (!(out = odr_createmem(ODR_ENCODE)) ||
1386         !(in = odr_createmem(ODR_DECODE)) ||
1387         !(print = odr_createmem(ODR_PRINT)))
1388     {
1389         fprintf(stderr, "failed to allocate ODR streams\n");
1390         exit(1);
1391     }
1392     setvbuf(stdout, 0, _IONBF, 0);
1393
1394 #if CCL2RPN
1395     bibset = ccl_qual_mk (); 
1396     inf = fopen ("default.bib", "r");
1397     if (inf)
1398     {
1399         ccl_qual_file (bibset, inf);
1400         fclose (inf);
1401     }
1402 #endif
1403 }
1404
1405 static int client(int wait)
1406 {
1407     static struct {
1408         char *cmd;
1409         int (*fun)(char *arg);
1410         char *ad;
1411     } cmd[] = {
1412         {"open", cmd_open, "('tcp'|'osi')':'[<tsel>'/']<host>[':'<port>]"},
1413         {"quit", cmd_quit, ""},
1414         {"find", cmd_find, "<query>"},
1415         {"base", cmd_base, "<base-name>"},
1416         {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]"},
1417         {"scan", cmd_scan, "<term>"},
1418         {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ..."},
1419         {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ..."},
1420         {"authentication", cmd_authentication, "<acctstring>"},
1421         {"lslb", cmd_lslb, "<largeSetLowerBound>"},
1422         {"ssub", cmd_ssub, "<smallSetUpperBound>"},
1423         {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
1424         {"status", cmd_status, ""},
1425         {"setnames", cmd_setnames, ""},
1426         {"cancel", cmd_cancel, ""},
1427         {"format", cmd_format, "<recordsyntax>"},
1428         {"elements", cmd_elements, "<elementSetName>"},
1429         {"close", cmd_close, ""},
1430         {"attributeset", cmd_attributeset, "<attrset>"},
1431         {"querytype", cmd_querytype, "<type>"},
1432         {"refid", cmd_refid, "<id>"},
1433         {0,0}
1434     };
1435     char *netbuffer= 0;
1436     int netbufferlen = 0;
1437     int i;
1438     Z_APDU *apdu;
1439
1440     while (1)
1441     {
1442         int res;
1443 #ifdef USE_SELECT
1444         fd_set input;
1445 #endif
1446         char line[1024], word[1024], arg[1024];
1447         
1448 #ifdef USE_SELECT
1449         FD_ZERO(&input);
1450         FD_SET(0, &input);
1451         if (conn)
1452             FD_SET(cs_fileno(conn), &input);
1453         if ((res = select(20, &input, 0, 0, 0)) < 0)
1454         {
1455             perror("select");
1456             exit(1);
1457         }
1458         if (!res)
1459             continue;
1460         if (!wait && FD_ISSET(0, &input))
1461 #else
1462         if (!wait)
1463 #endif
1464             {
1465             /* quick & dirty way to get a command line. */
1466                 char *end_p;
1467                 if (!fgets(line, 1023, stdin))
1468                     break;
1469                 if ((end_p = strchr (line, '\n')))
1470                     *end_p = '\0';
1471             if ((res = sscanf(line, "%s %[^;]", word, arg)) <= 0)
1472             {
1473                 strcpy(word, last_cmd);
1474                 *arg = '\0';
1475             }
1476             else if (res == 1)
1477                 *arg = 0;
1478             strcpy(last_cmd, word);
1479             for (i = 0; cmd[i].cmd; i++)
1480                 if (!strncmp(cmd[i].cmd, word, strlen(word)))
1481                 {
1482                     res = (*cmd[i].fun)(arg);
1483                     break;
1484                 }
1485             if (!cmd[i].cmd) /* dump our help-screen */
1486             {
1487                 printf("Unknown command: %s.\n", word);
1488                 printf("Currently recognized commands:\n");
1489                 for (i = 0; cmd[i].cmd; i++)
1490                     printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
1491                 res = 1;
1492             }
1493             if (res < 2)
1494             {
1495                 printf(C_PROMPT);
1496                 continue;
1497             }
1498         }
1499         wait = 0;
1500 #ifdef USE_SELECT
1501         if (conn && FD_ISSET(cs_fileno(conn), &input))
1502 #endif
1503         {
1504             do
1505             {
1506                 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
1507                 {
1508                     perror("cs_get");
1509                     exit(1);
1510                 }
1511                 if (!res)
1512                 {
1513                     printf("Target closed connection.\n");
1514                     exit(1);
1515                 }
1516                 odr_reset(in); /* release APDU from last round */
1517                 odr_setbuf(in, netbuffer, res, 0);
1518                 if (!z_APDU(in, &apdu, 0))
1519                 {
1520                     odr_perror(in, "Decoding incoming APDU");
1521                     fprintf(stderr, "[Near %d]\n", odr_offset(in));
1522                     fprintf(stderr, "Packet dump:\n---------\n");
1523                     odr_dumpBER(stderr, netbuffer, res);
1524                     fprintf(stderr, "---------\n");
1525                     exit(1);
1526                 }
1527 #if 0
1528                 if (!z_APDU(print, &apdu, 0))
1529                 {
1530                     odr_perror(print, "Failed to print incoming APDU");
1531                     odr_reset(print);
1532                     continue;
1533                 }
1534 #endif
1535                 switch(apdu->which)
1536                 {
1537                 case Z_APDU_initResponse:
1538                     process_initResponse(apdu->u.initResponse);
1539                     break;
1540                 case Z_APDU_searchResponse:
1541                     process_searchResponse(apdu->u.searchResponse);
1542                     break;
1543                 case Z_APDU_scanResponse:
1544                     process_scanResponse(apdu->u.scanResponse);
1545                     break;
1546                 case Z_APDU_presentResponse:
1547                     print_refid (apdu->u.presentResponse->referenceId);
1548                     setno +=
1549                         *apdu->u.presentResponse->numberOfRecordsReturned;
1550                     if (apdu->u.presentResponse->records)
1551                         display_records(apdu->u.presentResponse->records);
1552                     else
1553                         printf("No records.\n");
1554                     break;
1555                 case Z_APDU_sortResponse:
1556                     process_sortResponse(apdu->u.sortResponse);
1557                     break;
1558                 case Z_APDU_close:
1559                     printf("Target has closed the association.\n");
1560                     process_close(apdu->u.close);
1561                     break;
1562                 case Z_APDU_resourceControlRequest:
1563                     process_resourceControlRequest
1564                         (apdu->u.resourceControlRequest);
1565                     break;
1566                 default:
1567                     printf("Received unknown APDU type (%d).\n", 
1568                            apdu->which);
1569                     exit(1);
1570                 }
1571             }
1572             while (cs_more(conn));
1573             printf(C_PROMPT);
1574             fflush(stdout);
1575         }
1576     }
1577     return 0;
1578 }
1579
1580 int main(int argc, char **argv)
1581 {
1582     char *prog = *argv;
1583     char *arg;
1584     int ret;
1585     int opened = 0;
1586
1587     initialize();
1588     cmd_base("Default");
1589
1590     while ((ret = options("m:", argv, argc, &arg)) != -2)
1591     {
1592         switch (ret)
1593         {
1594         case 0:
1595             if (cmd_open (arg) == 2)
1596                 opened = 1;
1597             break;
1598         case 'm':
1599             if (!(marcdump = fopen (arg, "a")))
1600             {
1601                 perror (arg);
1602                 exit (1);
1603             }
1604             break;
1605         default:
1606             fprintf (stderr, "Usage: %s [-m <marclog>] [<server-addr>]\n",
1607                      prog);
1608             exit (1);
1609         }
1610     }
1611     if (!opened)
1612         printf (C_PROMPT);
1613     return client (opened);
1614 }