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