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