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