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