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