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