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