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