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