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