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