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