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