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