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