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