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