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