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