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