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