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