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