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