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