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