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