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