System headerfiles gathered in yconfig
[yaz-moved-to-github.git] / client / client.c
1 /*
2  * Copyright (c) 1995, Index Data.
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: client.c,v $
7  * Revision 1.37  1996-07-06 19:58:29  quinn
8  * System headerfiles gathered in yconfig
9  *
10  * Revision 1.36  1996/06/10  08:53:47  quinn
11  * Added Summary
12  *
13  * Revision 1.35  1996/06/03  09:45:50  quinn
14  * Added display of OIDs in the GRS routine.
15  *
16  * Revision 1.34  1996/05/09  07:26:49  quinn
17  * *** empty log message ***
18  *
19  * Revision 1.33  1996/05/09  07:25:22  quinn
20  * Small
21  *
22  * Revision 1.32  1996/03/15  11:05:33  adam
23  * The user can set the preferred query type (prefix, ccl, ..) with the
24  * querytype command.
25  *
26  * Revision 1.31  1996/02/20  12:51:54  quinn
27  * Fixed problems with EXTERNAL.
28  *
29  * Revision 1.30  1996/02/12  18:18:09  quinn
30  * Fidgeting.
31  *
32  * Revision 1.29  1996/01/02  08:57:25  quinn
33  * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
34  *
35  * Revision 1.28  1995/12/14  11:09:31  quinn
36  * Added Explain record syntax to the format command.
37  *
38  * Revision 1.27  1995/12/12  16:37:02  quinn
39  * Added destroy element to data1_node.
40  *
41  * Revision 1.26  1995/12/12  14:11:00  quinn
42  * Minimal.
43  *
44  * Revision 1.25  1995/11/13  09:27:22  quinn
45  * Fiddling with the variant stuff.
46  *
47  * Revision 1.24  1995/10/30  12:41:13  quinn
48  * Added hostname lookup for server.
49  *
50  * Revision 1.23  1995/10/18  16:12:30  quinn
51  * Better diagnostics.
52  *
53  * Revision 1.22  1995/10/11  14:49:12  quinn
54  * Smallish.
55  *
56  * Revision 1.21  1995/09/29  17:01:47  quinn
57  * More Windows work
58  *
59  * Revision 1.20  1995/08/29  14:24:13  quinn
60  * Added second half of close-handshake
61  *
62  * Revision 1.19  1995/08/29  11:17:28  quinn
63  * Added code to receive close
64  *
65  * Revision 1.18  1995/08/28  12:21:27  quinn
66  * Client can now ask for simple element set names.
67  *
68  * Revision 1.17  1995/08/17  12:45:02  quinn
69  * Fixed minor problems with GRS-1. Added support in c&s.
70  *
71  * Revision 1.16  1995/08/15  12:00:04  quinn
72  * Updated External
73  *
74  * Revision 1.15  1995/06/22  09:28:03  quinn
75  * Fixed bug in SUTRS processing.
76  *
77  * Revision 1.14  1995/06/19  12:37:41  quinn
78  * Added BER dumper.
79  *
80  * Revision 1.13  1995/06/16  10:29:11  quinn
81  * *** empty log message ***
82  *
83  * Revision 1.12  1995/06/15  07:44:57  quinn
84  * Moving to v3.
85  *
86  * Revision 1.11  1995/06/14  15:26:40  quinn
87  * *** empty log message ***
88  *
89  * Revision 1.10  1995/06/06  14:56:58  quinn
90  * Better diagnostics.
91  *
92  * Revision 1.9  1995/06/06  08:15:19  quinn
93  * Cosmetic.
94  *
95  * Revision 1.8  1995/06/05  10:52:22  quinn
96  * Added SCAN.
97  *
98  * Revision 1.7  1995/06/02  09:50:09  quinn
99  * Smallish.
100  *
101  * Revision 1.6  1995/05/31  08:29:21  quinn
102  * Nothing significant.
103  *
104  * Revision 1.5  1995/05/29  08:10:47  quinn
105  * Moved oid.c to util.
106  *
107  * Revision 1.4  1995/05/22  15:30:13  adam
108  * Client uses prefix query notation.
109  *
110  * Revision 1.3  1995/05/22  15:06:53  quinn
111  * *** empty log message ***
112  *
113  * Revision 1.2  1995/05/22  14:56:40  quinn
114  * *** empty log message ***
115  *
116  * Revision 1.1  1995/05/22  11:30:31  quinn
117  * Added prettier client.
118  *
119  *
120  */
121
122 /*
123  * This is the obligatory little toy client, whose primary purpose is
124  * to illustrate the use of the YAZ service-level API.
125  */
126
127 #include <yconfig.h>
128 #include <stdio.h>
129 #include <stdlib.h>
130 #include <time.h>
131 #include <assert.h>
132
133 #include <comstack.h>
134 #include <tcpip.h>
135 #ifdef USE_XTIMOSI
136 #include <xmosi.h>
137 #endif
138
139 #include <proto.h>
140 #include <marcdisp.h>
141 #include <diagbib1.h>
142
143 #include <pquery.h>
144
145 #if CCL2RPN
146 #include <yaz-ccl.h>
147 #endif
148
149 #define C_PROMPT "Z> "
150
151 static ODR out, in, print;              /* encoding and decoding streams */
152 static COMSTACK conn = 0;               /* our z-association */
153 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
154 static char database[512] = "Default";  /* Database name */
155 static int setnumber = 0;               /* current result set number */
156 static int smallSetUpperBound = 0;
157 static int largeSetLowerBound = 1;
158 static int mediumSetPresentNumber = 0;
159 static Z_ElementSetNames *elementSetNames = 0; 
160 static int setno = 1;                   /* current set offset */
161 static int protocol = PROTO_Z3950;      /* current app protocol */
162 static int recordsyntax = VAL_USMARC;
163 static int sent_close = 0;
164 static ODR_MEM session_mem;             /* memory handle for init-response */
165 static Z_InitResponse *session = 0;     /* session parameters */
166 static char last_scan[512] = "0";
167 static char last_cmd[100] = "?";
168 static oid_value attributeset = VAL_BIB1;
169 static FILE *marcdump = 0;
170 static char marcdump_file[512] = "marc.out";
171
172 typedef enum {
173     QueryType_Prefix,
174     QueryType_CCL,
175     QueryType_CCL2RPN
176 } QueryType;
177
178 static QueryType queryType = QueryType_Prefix;
179
180 #if CCL2RPN
181 static CCL_bibset bibset;               /* CCL bibset handle */
182 #endif
183
184 static void send_apdu(Z_APDU *a)
185 {
186     char *buf;
187     int len;
188
189     if (!z_APDU(out, &a, 0))
190     {
191         odr_perror(out, "Encoding APDU");
192         exit(1);
193     }
194     buf = odr_getbuf(out, &len, 0);
195     odr_reset(out); /* release the APDU structure  */
196     if (cs_put(conn, buf, len) < 0)
197     {
198         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
199         exit(1);
200     }
201 }
202
203 /* INIT SERVICE ------------------------------- */
204
205 static void send_initRequest()
206 {
207     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
208     Z_InitRequest *req = apdu->u.initRequest;
209
210     ODR_MASK_SET(req->options, Z_Options_search);
211     ODR_MASK_SET(req->options, Z_Options_present);
212     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
213     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
214     ODR_MASK_SET(req->options, Z_Options_scan);
215
216     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
217     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
218     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
219
220     *req->maximumRecordSize = 1024*1024;
221
222     req->idAuthentication = auth;
223
224     send_apdu(apdu);
225     printf("Sent initrequest.\n");
226 }
227
228 static int process_initResponse(Z_InitResponse *res)
229 {
230     /* save session parameters for later use */
231     session_mem = odr_extract_mem(in);
232     session = res;
233
234     if (!*res->result)
235         printf("Connection rejected by target.\n");
236     else
237         printf("Connection accepted by target.\n");
238     if (res->implementationId)
239         printf("ID     : %s\n", res->implementationId);
240     if (res->implementationName)
241         printf("Name   : %s\n", res->implementationName);
242     if (res->implementationVersion)
243         printf("Version: %s\n", res->implementationVersion);
244     if (res->userInformationField)
245     {
246         printf("UserInformationfield:\n");
247         if (!z_External(print, (Z_External**)&res-> userInformationField,
248             0))
249         {
250             odr_perror(print, "Printing userinfo\n");
251             odr_reset(print);
252         }
253         if (res->userInformationField->which == Z_External_octet)
254         {
255             printf("Guessing visiblestring:\n");
256             printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
257         }
258     }
259     return 0;
260 }
261
262 int cmd_open(char *arg)
263 {
264     void *add;
265     char type[100], addr[100];
266     CS_TYPE t;
267
268     if (conn)
269     {
270         printf("Already connected.\n");
271         return 0;
272     }
273     if (!*arg || sscanf(arg, "%[^:]:%s", type, addr) < 2)
274     {
275         fprintf(stderr, "Usage: open (osi|tcp) ':' [tsel '/']host[':'port]\n");
276         return 0;
277     }
278 #ifdef USE_XTIMOSI
279     if (!strcmp(type, "osi"))
280     {
281         if (!(add = mosi_strtoaddr(addr)))
282         {
283             perror(arg);
284             return 0;
285         }
286         t = mosi_type;
287         protocol = PROTO_SR;
288     }
289     else
290 #endif
291     if (!strcmp(type, "tcp"))
292     {
293         if (!(add = tcpip_strtoaddr(addr)))
294         {
295             perror(arg);
296             return 0;
297         }
298         t = tcpip_type;
299         protocol = PROTO_Z3950;
300     }
301     else
302     {
303         fprintf(stderr, "Bad type: %s\n", type);
304         return 0;
305     }
306     if (!(conn = cs_create(t, 1, protocol)))
307     {
308         perror("cs_create");
309         return 0;
310     }
311     printf("Connecting...");
312     fflush(stdout);
313     if (cs_connect(conn, add) < 0)
314     {
315         perror("connect");
316         cs_close(conn);
317         conn = 0;
318         return 0;
319     }
320     printf("Ok.\n");
321     send_initRequest();
322     return 2;
323 }
324
325 int cmd_authentication(char *arg)
326 {
327     static Z_IdAuthentication au;
328     static char open[256];
329
330     if (!*arg)
331     {
332         printf("Auth field set to null\n");
333         auth = 0;
334         return 1;
335     }
336     auth = &au;
337     au.which = Z_IdAuthentication_open;
338     au.u.open = open;
339     strcpy(open, arg);
340     return 1;
341 }
342
343 /* SEARCH SERVICE ------------------------------ */
344
345 static void display_variant(Z_Variant *v, int level)
346 {
347     int i;
348
349     for (i = 0; i < v->num_triples; i++)
350     {
351         printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->class,
352             *v->triples[i]->type);
353         if (v->triples[i]->which == Z_Triple_internationalString)
354             printf(",value=%s\n", v->triples[i]->value.internationalString);
355         else
356             printf("\n");
357     }
358 }
359
360 static void display_grs1(Z_GenericRecord *r, int level)
361 {
362     int i;
363
364     if (!r)
365         return;
366     for (i = 0; i < r->num_elements; i++)
367     {
368         Z_TaggedElement *t;
369
370         printf("%*s", level * 4, "");
371         t = r->elements[i];
372         printf("(");
373         if (t->tagType)
374             printf("%d,", *t->tagType);
375         else
376             printf("?,");
377         if (t->tagValue->which == Z_StringOrNumeric_numeric)
378             printf("%d) ", *t->tagValue->u.numeric);
379         else
380             printf("%s) ", t->tagValue->u.string);
381         if (t->content->which == Z_ElementData_subtree)
382         {
383             printf("\n");
384             display_grs1(t->content->u.subtree, level+1);
385         }
386         else if (t->content->which == Z_ElementData_string)
387             printf("%s\n", t->content->u.string);
388         else if (t->content->which == Z_ElementData_numeric)
389             printf("%d\n", *t->content->u.numeric);
390         else if (t->content->which == Z_ElementData_oid)
391         {
392             int *ip = t->content->u.oid;
393             oident *oent;
394
395             if ((oent = oid_getentbyoid(t->content->u.oid)))
396                 printf("OID: %s\n", oent->desc);
397             else
398             {
399                 printf("{");
400                 while (ip && *ip >= 0)
401                     printf(" %d", *(ip++));
402                 printf(" }\n");
403             }
404         }
405         else if (t->content->which == Z_ElementData_noDataRequested)
406             printf("[No data requested]\n");
407         else if (t->content->which == Z_ElementData_elementEmpty)
408             printf("[Element empty]\n");
409         else if (t->content->which == Z_ElementData_elementNotThere)
410             printf("[Element not there]\n");
411         else
412             printf("??????\n");
413         if (t->appliedVariant)
414             display_variant(t->appliedVariant, level+1);
415         if (t->metaData && t->metaData->supportedVariants)
416         {
417             int c;
418
419             printf("%*s---- variant list\n", (level+1)*4, "");
420             for (c = 0; c < t->metaData->num_supportedVariants; c++)
421             {
422                 printf("%*svariant #%d\n", (level+1)*4, "", c);
423                 display_variant(t->metaData->supportedVariants[c], level + 2);
424             }
425         }
426     }
427 }
428
429 static void display_record(Z_DatabaseRecord *p)
430 {
431     Z_External *r = (Z_External*) p;
432     oident *ent = oid_getentbyoid(r->direct_reference);
433
434     /*
435      * Tell the user what we got.
436      */
437     if (r->direct_reference)
438     {
439         printf("Record type: ");
440         if (ent)
441             printf("%s\n", ent->desc);
442         else if (!odr_oid(print, &r->direct_reference, 0))
443         {
444             odr_perror(print, "print oid");
445             odr_reset(print);
446         }
447     }
448
449     /* Check if this is a known, ASN.1 type tucked away in an octet string */
450     if (ent && r->which == Z_External_octet)
451     {
452         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
453         void *rr;
454
455         if (type)
456         {
457             /*
458              * Call the given decoder to process the record.
459              */
460             odr_setbuf(in, (char*)p->u.octet_aligned->buf,
461                 p->u.octet_aligned->len, 0);
462             if (!(*type->fun)(in, &rr, 0))
463             {
464                 odr_perror(in, "Decoding constructed record.");
465                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
466                 fprintf(stderr, "Packet dump:\n---------\n");
467                 odr_dumpBER(stderr, (char*)p->u.octet_aligned->buf,
468                     p->u.octet_aligned->len);
469                 fprintf(stderr, "---------\n");
470                 exit(1);
471             }
472             /*
473              * Note: we throw away the original, BER-encoded record here.
474              * Do something else with it if you want to keep it.
475              */
476             r->u.sutrs = rr;    /* we don't actually check the type here. */
477             r->which = type->what;
478         }
479     }
480     if (r->which == Z_External_octet && p->u.octet_aligned->len)
481         marc_display ((char*)p->u.octet_aligned->buf, stdout);
482     else if (ent->value == VAL_SUTRS)
483     {
484         if (r->which != Z_External_sutrs)
485         {
486             printf("Expecting single SUTRS type for SUTRS.\n");
487             return;
488         }
489         printf("%.*s", r->u.sutrs->len, r->u.sutrs->buf);
490     }
491     else if (ent->value == VAL_GRS1)
492     {
493         if (r->which != Z_External_grs1)
494         {
495             printf("Expecting single GRS type for GRS.\n");
496             return;
497         }
498         display_grs1(r->u.grs1, 0);
499     }
500     else 
501     {
502         printf("Unknown record representation.\n");
503         if (!z_External(print, &r, 0))
504         {
505             odr_perror(print, "Printing external");
506             odr_reset(print);
507         }
508     }
509 }
510
511 static void display_diagrec(Z_DiagRec *p)
512 {
513     oident *ent;
514 #ifdef Z_95
515     Z_DefaultDiagFormat *r;
516 #else
517     Z_DiagRec *r = p;
518 #endif
519
520     printf("Diagnostic message from database:\n");
521 #ifdef Z_95
522     if (p->which != Z_DiagRec_defaultFormat)
523     {
524         printf("Diagnostic record not in default format.\n");
525         return;
526     }
527     else
528         r = p->u.defaultFormat;
529 #endif
530     if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
531         ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
532         printf("Missing or unknown diagset\n");
533     printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
534     if (r->addinfo && *r->addinfo)
535         printf(" -- '%s'\n", r->addinfo);
536     else
537         printf("\n");
538 }
539
540 static void display_nameplusrecord(Z_NamePlusRecord *p)
541 {
542     if (p->databaseName)
543         printf("[%s]", p->databaseName);
544     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
545         display_diagrec(p->u.surrogateDiagnostic);
546     else
547         display_record(p->u.databaseRecord);
548 }
549
550 static void display_records(Z_Records *p)
551 {
552     int i;
553
554     if (p->which == Z_Records_NSD)
555         display_diagrec(p->u.nonSurrogateDiagnostic);
556     else
557     {
558         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
559         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
560             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
561     }
562 }
563
564 static int send_searchRequest(char *arg)
565 {
566     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
567     Z_SearchRequest *req = apdu->u.searchRequest;
568     char *databaseNames = database;
569     Z_Query query;
570 #if CCL2RPN
571     struct ccl_rpn_node *rpn;
572     int error, pos;
573     oident bib1;
574 #endif
575     char setstring[100];
576     Z_RPNQuery *RPNquery;
577     Odr_oct ccl_query;
578
579 #if CCL2RPN
580     if (queryType == QueryType_CCL2RPN)
581     {
582         rpn = ccl_find_str(bibset, arg, &error, &pos);
583         if (error)
584         {
585             printf("CCL ERROR: %s\n", ccl_err_msg(error));
586             return 0;
587         }
588     }
589 #endif
590
591     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
592     {
593         static unsigned char big[2100];
594         static Odr_oct bigo;
595
596         /* send a very big referenceid to test transport stack etc. */
597         memset(big, 'A', 2100);
598         bigo.len = bigo.size = 2100;
599         bigo.buf = big;
600         req->referenceId = &bigo;
601     }
602
603     if (setnumber >= 0)
604     {
605         sprintf(setstring, "%d", ++setnumber);
606         req->resultSetName = setstring;
607     }
608     *req->smallSetUpperBound = smallSetUpperBound;
609     *req->largeSetLowerBound = largeSetLowerBound;
610     *req->mediumSetPresentNumber = mediumSetPresentNumber;
611     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
612         mediumSetPresentNumber > 0))
613     {
614         oident prefsyn;
615
616         prefsyn.proto = protocol;
617         prefsyn.oclass = CLASS_RECSYN;
618         prefsyn.value = recordsyntax;
619         req->preferredRecordSyntax =
620             odr_oiddup(out, oid_getoidbyent(&prefsyn));
621         req->smallSetElementSetNames =
622             req->mediumSetElementSetNames = elementSetNames;
623     }
624     req->num_databaseNames = 1;
625     req->databaseNames = &databaseNames;
626
627     req->query = &query;
628
629     switch (queryType)
630     {
631     case QueryType_Prefix:
632         query.which = Z_Query_type_1;
633         RPNquery = p_query_rpn (out, protocol, arg);
634         if (!RPNquery)
635         {
636             printf("Prefix query error\n");
637             return 0;
638         }
639         query.u.type_1 = RPNquery;
640         break;
641     case QueryType_CCL:
642         query.which = Z_Query_type_2;
643         query.u.type_2 = &ccl_query;
644         ccl_query.buf = (unsigned char*) arg;
645         ccl_query.len = strlen(arg);
646         break;
647 #if CCL2RPN
648     case QueryType_CCL2RPN:
649         query.which = Z_Query_type_1;
650         assert((RPNquery = ccl_rpn_query(rpn)));
651         bib1.proto = protocol;
652         bib1.oclass = CLASS_ATTSET;
653         bib1.value = attributeset;
654         RPNquery->attributeSetId = oid_getoidbyent(&bib1);
655         query.u.type_1 = RPNquery;
656         break;
657 #endif
658     default:
659         printf ("Unsupported query type\n");
660         return 0;
661     }
662     send_apdu(apdu);
663     setno = 1;
664     printf("Sent searchRequest.\n");
665     return 2;
666 }
667
668 static int process_searchResponse(Z_SearchResponse *res)
669 {
670     if (*res->searchStatus)
671         printf("Search was a success.\n");
672     else
673         printf("Search was a bloomin' failure.\n");
674     printf("Number of hits: %d, setno %d\n",
675         *res->resultCount, setnumber);
676     printf("records returned: %d\n",
677         *res->numberOfRecordsReturned);
678     setno += *res->numberOfRecordsReturned;
679     if (res->records)
680         display_records(res->records);
681     return 0;
682 }
683
684 static int cmd_find(char *arg)
685 {
686     if (!*arg)
687     {
688         printf("Find what?\n");
689         return 0;
690     }
691     if (!conn)
692     {
693         printf("Not connected yet\n");
694         return 0;
695     }
696     if (!send_searchRequest(arg))
697         return 0;
698     return 2;
699 }
700
701 static int cmd_ssub(char *arg)
702 {
703     if (!(smallSetUpperBound = atoi(arg)))
704         return 0;
705     return 1;
706 }
707
708 static int cmd_lslb(char *arg)
709 {
710     if (!(largeSetLowerBound = atoi(arg)))
711         return 0;
712     return 1;
713 }
714
715 static int cmd_mspn(char *arg)
716 {
717     if (!(mediumSetPresentNumber = atoi(arg)))
718         return 0;
719     return 1;
720 }
721
722 static int cmd_status(char *arg)
723 {
724     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
725     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
726     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
727     return 1;
728 }
729
730 static int cmd_base(char *arg)
731 {
732     if (!*arg)
733     {
734         printf("Usage: base <database>\n");
735         return 0;
736     }
737     strcpy(database, arg);
738     return 1;
739 }
740
741 static int cmd_setnames(char *arg)
742 {
743     if (setnumber < 0)
744     {
745         printf("Set numbering enabled.\n");
746         setnumber = 0;
747     }
748     else
749     {
750         printf("Set numbering disabled.\n");
751         setnumber = -1;
752     }
753     return 1;
754 }
755
756 /* PRESENT SERVICE ----------------------------- */
757
758 static int send_presentRequest(char *arg)
759 {
760     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
761     Z_PresentRequest *req = apdu->u.presentRequest;
762     Z_RecordComposition compo;
763     oident prefsyn;
764     int nos = 1;
765     char *p;
766     char setstring[100];
767
768     if ((p = strchr(arg, '+')))
769     {
770         nos = atoi(p + 1);
771         *p = 0;
772     }
773     if (*arg)
774         setno = atoi(arg);
775
776     if (setnumber >= 0)
777     {
778         sprintf(setstring, "%d", setnumber);
779         req->resultSetId = setstring;
780     }
781
782
783 #if 0
784     if (1)
785     {
786         static Z_Range range;
787         static Z_Range *rangep = &range;
788     req->num_ranges = 1;
789 #endif
790
791
792
793
794
795
796
797
798
799     req->resultSetStartPoint = &setno;
800     req->numberOfRecordsRequested = &nos;
801     prefsyn.proto = protocol;
802     prefsyn.oclass = CLASS_RECSYN;
803     prefsyn.value = recordsyntax;
804     req->preferredRecordSyntax = oid_getoidbyent(&prefsyn);
805     if (elementSetNames)
806     {
807         req->recordComposition = &compo;
808         compo.which = Z_RecordComp_simple;
809         compo.u.simple = elementSetNames;
810     }
811     send_apdu(apdu);
812     printf("Sent presentRequest (%d+%d).\n", setno, nos);
813     return 2;
814 }
815
816 void process_close(Z_Close *req)
817 {
818     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
819     Z_Close *res = apdu->u.close;
820
821     static char *reasons[] =
822     {
823         "finished",
824         "shutdown",
825         "system problem",
826         "cost limit reached",
827         "resources",
828         "security violation",
829         "protocolError",
830         "lack of activity",
831         "peer abort",
832         "unspecified"
833     };
834
835     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
836         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
837     if (sent_close)
838     {
839         printf("Goodbye.\n");
840         exit(0);
841     }
842     *res->closeReason = Z_Close_finished;
843     send_apdu(apdu);
844     printf("Sent response.\n");
845     sent_close = 1;
846 }
847
848 static int cmd_show(char *arg)
849 {
850     if (!send_presentRequest(arg))
851         return 0;
852     return 2;
853 }
854
855 int cmd_quit(char *arg)
856 {
857     printf("See you later, alligator.\n");
858     exit(0);
859 }
860
861 int cmd_cancel(char *arg)
862 {
863     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
864     Z_TriggerResourceControlRequest *req =
865         apdu->u.triggerResourceControlRequest;
866     bool_t false = 0;
867     
868     if (!session)
869     {
870         printf("Session not initialized yet\n");
871         return 0;
872     }
873     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
874     {
875         printf("Target doesn't support cancel (trigger resource ctrl)\n");
876         return 0;
877     }
878     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
879     req->resultSetWanted = &false;
880
881     send_apdu(apdu);
882     printf("Sent cancel request\n");
883     return 2;
884 }
885
886 int send_scanrequest(char *string, int pp, int num)
887 {
888     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
889     Z_ScanRequest *req = apdu->u.scanRequest;
890     char *db = database;
891
892     req->num_databaseNames = 1;
893     req->databaseNames = &db;
894     req->termListAndStartPoint = p_query_scan(out, protocol,
895                                               &req->attributeSet, string);
896     req->numberOfTermsRequested = &num;
897     req->preferredPositionInResponse = &pp;
898     send_apdu(apdu);
899     return 2;
900 }
901
902 void display_term(Z_TermInfo *t)
903 {
904     if (t->term->which == Z_Term_general)
905     {
906         printf("%.*s (%d)\n", t->term->u.general->len, t->term->u.general->buf,
907             t->globalOccurrences ? *t->globalOccurrences : -1);
908         sprintf(last_scan, "%.*s", t->term->u.general->len,
909             t->term->u.general->buf);
910     }
911     else
912         printf("Term type not general.\n");
913 }
914
915 void process_scanResponse(Z_ScanResponse *res)
916 {
917     int i;
918
919     printf("SCAN: %d entries, position=%d\n", *res->numberOfEntriesReturned,
920         *res->positionOfTerm);
921     if (*res->scanStatus != Z_Scan_success)
922         printf("Scan returned code %d\n", *res->scanStatus);
923     if (!res->entries)
924         return;
925     if (res->entries->which == Z_ListEntries_entries)
926     {
927         Z_Entries *ent = res->entries->u.entries;
928
929         for (i = 0; i < ent->num_entries; i++)
930             if (ent->entries[i]->which == Z_Entry_termInfo)
931             {
932                 printf("%c ", i + 1 == *res->positionOfTerm ? '*' : ' ');
933                 display_term(ent->entries[i]->u.termInfo);
934             }
935             else
936                 display_diagrec(ent->entries[i]->u.surrogateDiagnostic);
937     }
938     else
939         display_diagrec(res->entries->u.nonSurrogateDiagnostics->diagRecs[0]);
940 }
941
942 int cmd_scan(char *arg)
943 {
944     if (!session)
945     {
946         printf("Session not initialized yet\n");
947         return 0;
948     }
949     if (!ODR_MASK_GET(session->options, Z_Options_scan))
950     {
951         printf("Target doesn't support scan\n");
952         return 0;
953     }
954     if (*arg)
955     {
956         if (send_scanrequest(arg, 5, 20) < 0)
957             return 0;
958     }
959     else
960         if (send_scanrequest(last_scan, 1, 20) < 0)
961             return 0;
962     return 2;
963 }
964
965 int cmd_format(char *arg)
966 {
967     if (!arg || !*arg)
968     {
969         printf("Usage: format <recordsyntax>\n");
970         return 0;
971     }
972     if (!strcmp(arg, "sutrs"))
973     {
974         printf("Preferred format is SUTRS.\n");
975         recordsyntax = VAL_SUTRS;
976         return 1;
977     }
978     else if (!strcmp(arg, "usmarc"))
979     {
980         printf("Preferred format is USMARC\n");
981         recordsyntax = VAL_USMARC;
982         return 1;
983     }
984     else if (!strcmp(arg, "danmarc"))
985     {
986         printf("Preferred format is DANMARC\n");
987         recordsyntax = VAL_DANMARC;
988         return 1;
989     }
990     else if (!strcmp(arg, "grs1"))
991     {
992         printf("Preferred format is GRS1\n");
993         recordsyntax = VAL_GRS1;
994         return 1;
995     }
996     else if (!strcmp(arg, "summary"))
997     {
998         printf("Preferred format is Summary\n");
999         recordsyntax = VAL_SUMMARY;
1000         return 1;
1001     }
1002     else if (!strcmp(arg, "explain"))
1003     {
1004         printf("Preferred format is Explain\n");
1005         recordsyntax = VAL_EXPLAIN;
1006         return 1;
1007     }
1008     else
1009     {
1010         printf("Specify one of {sutrs,usmarc,danmarc,grs1}.\n");
1011         return 0;
1012     }
1013 }
1014
1015 int cmd_elements(char *arg)
1016 {
1017     static Z_ElementSetNames esn;
1018     static char what[100];
1019
1020     if (!arg || !*arg)
1021     {
1022         printf("Usage: elements <esn>\n");
1023         return 0;
1024     }
1025     strcpy(what, arg);
1026     esn.which = Z_ElementSetNames_generic;
1027     esn.u.generic = what;
1028     elementSetNames = &esn;
1029     return 1;
1030 }
1031
1032 int cmd_attributeset(char *arg)
1033 {
1034     char what[100];
1035     oid_value v;
1036
1037     if (!arg || !*arg)
1038     {
1039         printf("Usage: attributeset <setname>\n");
1040         return 0;
1041     }
1042     sscanf(arg, "%s", what);
1043     if ((v = oid_getvalbyname(what)) == VAL_NONE)
1044     {
1045         printf("Unknown attribute set name\n");
1046         return 0;
1047     }
1048     attributeset = v;
1049     return 1;
1050 }
1051
1052 int cmd_querytype (char *arg)
1053 {
1054     if (!strcmp (arg, "ccl"))
1055         queryType = QueryType_CCL;
1056     else if (!strcmp (arg, "prefix"))
1057         queryType = QueryType_Prefix;
1058 #if CCL2RPN
1059     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
1060         queryType = QueryType_CCL2RPN;
1061 #endif
1062     else
1063     {
1064         printf ("Querytype must be one of:\n");
1065         printf (" prefix         - Prefix query\n");
1066         printf (" ccl            - CCL query\n");
1067 #if CCL2RPN
1068         printf (" ccl2rpn        - CCL query converted to RPN\n");
1069 #endif
1070         return 0;
1071     }
1072     return 1;
1073 }
1074
1075 int cmd_close(char *arg)
1076 {
1077     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1078     Z_Close *req = apdu->u.close;
1079
1080     *req->closeReason = Z_Close_finished;
1081     send_apdu(apdu);
1082     printf("Sent close request.\n");
1083     sent_close = 1;
1084     return 2;
1085 }
1086
1087 static void initialize(void)
1088 {
1089 #if CCL2RPN
1090     FILE *inf;
1091 #endif
1092
1093     if (!(out = odr_createmem(ODR_ENCODE)) ||
1094         !(in = odr_createmem(ODR_DECODE)) ||
1095         !(print = odr_createmem(ODR_PRINT)))
1096     {
1097         fprintf(stderr, "failed to allocate ODR streams\n");
1098         exit(1);
1099     }
1100     setvbuf(stdout, 0, _IONBF, 0);
1101
1102 #if CCL2RPN
1103     bibset = ccl_qual_mk (); 
1104     inf = fopen ("default.bib", "r");
1105     if (inf)
1106     {
1107         ccl_qual_file (bibset, inf);
1108         fclose (inf);
1109     }
1110 #endif
1111 }
1112
1113 static int client(void)
1114 {
1115     static struct {
1116         char *cmd;
1117         int (*fun)(char *arg);
1118         char *ad;
1119     } cmd[] = {
1120         {"open", cmd_open, "('tcp'|'osi')':'[<tsel>'/']<host>[':'<port>]"},
1121         {"quit", cmd_quit, ""},
1122         {"find", cmd_find, "<query>"},
1123         {"base", cmd_base, "<base-name>"},
1124         {"show", cmd_show, "<rec#>['+'<#recs>]"},
1125         {"scan", cmd_scan, "<term>"},
1126         {"authentication", cmd_authentication, "<acctstring>"},
1127         {"lslb", cmd_lslb, "<largeSetLowerBound>"},
1128         {"ssub", cmd_ssub, "<smallSetUpperBound>"},
1129         {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
1130         {"status", cmd_status, ""},
1131         {"setnames", cmd_setnames, ""},
1132         {"cancel", cmd_cancel, ""},
1133         {"format", cmd_format, "<recordsyntax>"},
1134         {"elements", cmd_elements, "<elementSetName>"},
1135         {"close", cmd_close, ""},
1136         {"attributeset", cmd_attributeset, "<attrset>"},
1137         {"querytype", cmd_querytype, "<type>"},
1138         {0,0}
1139     };
1140     char *netbuffer= 0;
1141     int netbufferlen = 0;
1142     int i;
1143     Z_APDU *apdu;
1144
1145     while (1)
1146     {
1147         int res;
1148         fd_set input;
1149         char line[1024], word[1024], arg[1024];
1150
1151         FD_ZERO(&input);
1152         FD_SET(0, &input);
1153         if (conn)
1154             FD_SET(cs_fileno(conn), &input);
1155         if ((res = select(20, &input, 0, 0, 0)) < 0)
1156         {
1157             perror("select");
1158             exit(1);
1159         }
1160         if (!res)
1161             continue;
1162         if (FD_ISSET(0, &input))
1163         {
1164             /* quick & dirty way to get a command line. */
1165             if (!gets(line))
1166                 break;
1167             if ((res = sscanf(line, "%s %[^;]", word, arg)) <= 0)
1168             {
1169                 strcpy(word, last_cmd);
1170                 *arg = '\0';
1171             }
1172             else if (res == 1)
1173                 *arg = 0;
1174             strcpy(last_cmd, word);
1175             for (i = 0; cmd[i].cmd; i++)
1176                 if (!strncmp(cmd[i].cmd, word, strlen(word)))
1177                 {
1178                     res = (*cmd[i].fun)(arg);
1179                     break;
1180                 }
1181             if (!cmd[i].cmd) /* dump our help-screen */
1182             {
1183                 printf("Unknown command: %s.\n", word);
1184                 printf("Currently recognized commands:\n");
1185                 for (i = 0; cmd[i].cmd; i++)
1186                     printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
1187                 res = 1;
1188             }
1189             if (res < 2)
1190                 printf(C_PROMPT);
1191         }
1192         if (conn && FD_ISSET(cs_fileno(conn), &input))
1193         {
1194             do
1195             {
1196                 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
1197                 {
1198                     perror("cs_get");
1199                     exit(1);
1200                 }
1201                 if (!res)
1202                 {
1203                     printf("Target closed connection.\n");
1204                     exit(1);
1205                 }
1206                 odr_reset(in); /* release APDU from last round */
1207                 odr_setbuf(in, netbuffer, res, 0);
1208                 if (!z_APDU(in, &apdu, 0))
1209                 {
1210                     odr_perror(in, "Decoding incoming APDU");
1211                     fprintf(stderr, "[Near %d]\n", odr_offset(in));
1212                     fprintf(stderr, "Packet dump:\n---------\n");
1213                     odr_dumpBER(stderr, netbuffer, res);
1214                     fprintf(stderr, "---------\n");
1215                     exit(1);
1216                 }
1217 #if 0
1218                 if (!z_APDU(print, &apdu, 0))
1219                 {
1220                     odr_perror(print, "Failed to print incoming APDU");
1221                     odr_reset(print);
1222                     continue;
1223                 }
1224 #endif
1225                 switch(apdu->which)
1226                 {
1227                     case Z_APDU_initResponse:
1228                         process_initResponse(apdu->u.initResponse);
1229                         break;
1230                     case Z_APDU_searchResponse:
1231                         process_searchResponse(apdu->u.searchResponse);
1232                         break;
1233                     case Z_APDU_scanResponse:
1234                         process_scanResponse(apdu->u.scanResponse);
1235                         break;
1236                     case Z_APDU_presentResponse:
1237                         printf("Received presentResponse.\n");
1238                         setno +=
1239                             *apdu->u.presentResponse->numberOfRecordsReturned;
1240                         if (apdu->u.presentResponse->records)
1241                             display_records(apdu->u.presentResponse->records);
1242                         else
1243                             printf("No records.\n");
1244                         break;
1245                     case Z_APDU_close:
1246                         printf("Target has closed the association.\n");
1247                         process_close(apdu->u.close);
1248                         break;
1249                     default:
1250                         printf("Received unknown APDU type (%d).\n", 
1251                             apdu->which);
1252                         exit(1);
1253                 }
1254                 printf(C_PROMPT);
1255                 fflush(stdout);
1256             }
1257             while (cs_more(conn));
1258         }
1259     }
1260     return 0;
1261 }
1262
1263 int main(int argc, char **argv)
1264 {
1265     initialize();
1266     if (argc > 1)
1267         cmd_open(argv[1]);
1268     else
1269         printf(C_PROMPT);
1270     if (*marcdump_file && !(marcdump = fopen(marcdump_file, "a")))
1271     {
1272         perror(marcdump_file);
1273         exit(1);
1274     }
1275     return client();
1276 }