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