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