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