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