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