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