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