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