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