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