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