Furhter work on UNIverse resource report.
[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.64  1998-03-31 11:07:44  adam
8  * Furhter work on UNIverse resource report.
9  * Added Extended Services handling in frontend server.
10  *
11  * Revision 1.63  1998/03/05 08:05:10  adam
12  * Added a few casts to make C++ happy.
13  *
14  * Revision 1.62  1998/02/11 11:53:33  adam
15  * Changed code so that it compiles as C++.
16  *
17  * Revision 1.61  1998/02/10 11:03:06  adam
18  * Implemented command refid. Client prints reference-ID's, when present,
19  * in responses.
20  *
21  * Revision 1.60  1998/01/29 14:08:52  adam
22  * Better sort diagnostics.
23  *
24  * Revision 1.59  1998/01/29 13:17:56  adam
25  * Added sort.
26  *
27  * Revision 1.58  1998/01/07 13:51:45  adam
28  * Minor change.
29  *
30  * Revision 1.57  1998/01/07 12:58:22  adam
31  * Using fgets instead of gets.
32  *
33  * Revision 1.56  1997/11/05 09:18:31  adam
34  * The client handles records with no associated syntax.
35  *
36  * Revision 1.55  1997/10/31 12:20:08  adam
37  * Improved memory debugging for xmalloc/nmem.c. References to NMEM
38  * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
39  * Bug fix: missing fclose in data1_read_espec1.
40  *
41  * Revision 1.54  1997/10/27 13:52:46  adam
42  * Header yaz-util includes all YAZ utility header files.
43  *
44  * Revision 1.53  1997/09/29 13:18:59  adam
45  * Added function, oid_ent_to_oid, to replace the function
46  * oid_getoidbyent, which is not thread safe.
47  *
48  * Revision 1.52  1997/09/29 07:20:31  adam
49  * Client code uses nmem_init.
50  *
51  * Revision 1.51  1997/09/26 09:41:55  adam
52  * Updated client to handle multiple diagnostics.
53  *
54  * Revision 1.50  1997/09/17 12:10:29  adam
55  * YAZ version 1.4.
56  *
57  * Revision 1.49  1997/09/04 13:45:17  adam
58  * Added UNImarc to list of available syntaxes.
59  *
60  * Revision 1.48  1997/09/01 08:48:44  adam
61  * New windows NT/95 port using MSV5.0. Only a few changes made
62  * to avoid warnings. Sub project created: client.dsp.
63  *
64  * Revision 1.47  1997/07/01 13:49:56  adam
65  * Take care of case when invalid target is specified on command line.
66  *
67  * Revision 1.46  1997/06/23 10:30:18  adam
68  * Added call to ccl_rpn_delete in search. Added ODR stream "out"
69  * as parameter to ccl_rpn_query to release RPN query.
70  *
71  * Revision 1.45  1997/05/14 06:53:29  adam
72  * C++ support.
73  *
74  * Revision 1.44  1997/05/05 11:20:35  adam
75  * Client uses "options" utility and marc dump filename may be specified
76  * as an option (-m <file>).
77  *
78  * Revision 1.43  1996/11/08 11:03:26  adam
79  * Client accepts multiple database names.
80  *
81  * Revision 1.42  1996/10/08 10:44:57  quinn
82  * Resolved conflicts.
83  *
84  * Revision 1.41  1996/10/07  15:29:03  quinn
85  * Work
86  *
87  * Revision 1.40  1996/08/29  14:19:34  quinn
88  * Fixed conflict (CVS)
89  *
90  * Revision 1.39  1996/08/27  10:43:22  quinn
91  * Made select() optional
92  *
93  * Revision 1.38  1996/08/12  14:09:11  adam
94  * Default prefix query attribute set defined by using p_query_attset.
95  *
96  * Revision 1.37  1996/07/06  19:58:29  quinn
97  * System headerfiles gathered in yconfig
98  *
99  * Revision 1.36  1996/06/10  08:53:47  quinn
100  * Added Summary
101  *
102  * Revision 1.35  1996/06/03  09:45:50  quinn
103  * Added display of OIDs in the GRS routine.
104  *
105  * Revision 1.34  1996/05/09  07:26:49  quinn
106  * *** empty log message ***
107  *
108  * Revision 1.33  1996/05/09  07:25:22  quinn
109  * Small
110  *
111  * Revision 1.32  1996/03/15  11:05:33  adam
112  * The user can set the preferred query type (prefix, ccl, ..) with the
113  * querytype command.
114  *
115  * Revision 1.31  1996/02/20  12:51:54  quinn
116  * Fixed problems with EXTERNAL.
117  *
118  * Revision 1.30  1996/02/12  18:18:09  quinn
119  * Fidgeting.
120  *
121  * Revision 1.29  1996/01/02  08:57:25  quinn
122  * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
123  *
124  * Revision 1.28  1995/12/14  11:09:31  quinn
125  * Added Explain record syntax to the format command.
126  *
127  * Revision 1.27  1995/12/12  16:37:02  quinn
128  * Added destroy element to data1_node.
129  *
130  * Revision 1.26  1995/12/12  14:11:00  quinn
131  * Minimal.
132  *
133  * Revision 1.25  1995/11/13  09:27:22  quinn
134  * Fiddling with the variant stuff.
135  *
136  * Revision 1.24  1995/10/30  12:41:13  quinn
137  * Added hostname lookup for server.
138  *
139  * Revision 1.23  1995/10/18  16:12:30  quinn
140  * Better diagnostics.
141  *
142  * Revision 1.22  1995/10/11  14:49:12  quinn
143  * Smallish.
144  *
145  * Revision 1.21  1995/09/29  17:01:47  quinn
146  * More Windows work
147  *
148  * Revision 1.20  1995/08/29  14:24:13  quinn
149  * Added second half of close-handshake
150  *
151  * Revision 1.19  1995/08/29  11:17:28  quinn
152  * Added code to receive close
153  *
154  * Revision 1.18  1995/08/28  12:21:27  quinn
155  * Client can now ask for simple element set names.
156  *
157  * Revision 1.17  1995/08/17  12:45:02  quinn
158  * Fixed minor problems with GRS-1. Added support in c&s.
159  *
160  * Revision 1.16  1995/08/15  12:00:04  quinn
161  * Updated External
162  *
163  * Revision 1.15  1995/06/22  09:28:03  quinn
164  * Fixed bug in SUTRS processing.
165  *
166  * Revision 1.14  1995/06/19  12:37:41  quinn
167  * Added BER dumper.
168  *
169  * Revision 1.13  1995/06/16  10:29:11  quinn
170  * *** empty log message ***
171  *
172  * Revision 1.12  1995/06/15  07:44:57  quinn
173  * Moving to v3.
174  *
175  * Revision 1.11  1995/06/14  15:26:40  quinn
176  * *** empty log message ***
177  *
178  * Revision 1.10  1995/06/06  14:56:58  quinn
179  * Better diagnostics.
180  *
181  * Revision 1.9  1995/06/06  08:15:19  quinn
182  * Cosmetic.
183  *
184  * Revision 1.8  1995/06/05  10:52:22  quinn
185  * Added SCAN.
186  *
187  * Revision 1.7  1995/06/02  09:50:09  quinn
188  * Smallish.
189  *
190  * Revision 1.6  1995/05/31  08:29:21  quinn
191  * Nothing significant.
192  *
193  * Revision 1.5  1995/05/29  08:10:47  quinn
194  * Moved oid.c to util.
195  *
196  * Revision 1.4  1995/05/22  15:30:13  adam
197  * Client uses prefix query notation.
198  *
199  * Revision 1.3  1995/05/22  15:06:53  quinn
200  * *** empty log message ***
201  *
202  * Revision 1.2  1995/05/22  14:56:40  quinn
203  * *** empty log message ***
204  *
205  * Revision 1.1  1995/05/22  11:30:31  quinn
206  * Added prettier client.
207  *
208  *
209  */
210
211 /*
212  * This is the obligatory little toy client, whose primary purpose is
213  * to illustrate the use of the YAZ service-level API.
214  */
215
216 #include <stdio.h>
217 #include <stdlib.h>
218 #include <time.h>
219 #include <assert.h>
220
221 #include <yaz-util.h>
222
223 #include <comstack.h>
224 #include <tcpip.h>
225 #ifdef USE_XTIMOSI
226 #include <xmosi.h>
227 #endif
228
229 #include <proto.h>
230 #include <marcdisp.h>
231 #include <diagbib1.h>
232
233 #include <pquery.h>
234
235 #if CCL2RPN
236 #include <yaz-ccl.h>
237 #endif
238
239 #define C_PROMPT "Z> "
240
241 static ODR out, in, print;              /* encoding and decoding streams */
242 static COMSTACK conn = 0;               /* our z-association */
243 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
244 static char *databaseNames[128];
245 static int num_databaseNames = 0;
246 static int setnumber = 0;               /* current result set number */
247 static int smallSetUpperBound = 0;
248 static int largeSetLowerBound = 1;
249 static int mediumSetPresentNumber = 0;
250 static Z_ElementSetNames *elementSetNames = 0; 
251 static int setno = 1;                   /* current set offset */
252 static int protocol = PROTO_Z3950;      /* current app protocol */
253 static int recordsyntax = VAL_USMARC;
254 static int sent_close = 0;
255 static ODR_MEM session_mem;             /* memory handle for init-response */
256 static Z_InitResponse *session = 0;     /* session parameters */
257 static char last_scan[512] = "0";
258 static char last_cmd[100] = "?";
259 static FILE *marcdump = 0;
260 static char *refid = NULL;
261
262 typedef enum {
263     QueryType_Prefix,
264     QueryType_CCL,
265     QueryType_CCL2RPN
266 } QueryType;
267
268 static QueryType queryType = QueryType_Prefix;
269
270 #if CCL2RPN
271 static CCL_bibset bibset;               /* CCL bibset handle */
272 #endif
273
274 static void send_apdu(Z_APDU *a)
275 {
276     char *buf;
277     int len;
278
279     if (!z_APDU(out, &a, 0))
280     {
281         odr_perror(out, "Encoding APDU");
282         exit(1);
283     }
284     buf = odr_getbuf(out, &len, 0);
285     if (cs_put(conn, buf, len) < 0)
286     {
287         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
288         exit(1);
289     }
290     odr_reset(out); /* release the APDU structure  */
291 }
292
293 static void print_refid (Z_ReferenceId *id)
294 {
295     if (id)
296     {
297         printf ("ReferenceId: '%.*s'\n", id->len, id->buf);
298     }
299 }
300
301 static Z_ReferenceId *set_refid (ODR out)
302 {
303     Z_ReferenceId *id;
304     if (!refid)
305         return 0;
306     id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
307     id->size = id->len = strlen(refid);
308     id->buf = (unsigned char *) odr_malloc (out, id->len);
309     memcpy (id->buf, refid, id->len);
310     return id;
311 }   
312
313 /* INIT SERVICE ------------------------------- */
314
315 static void send_initRequest()
316 {
317     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
318     Z_InitRequest *req = apdu->u.initRequest;
319
320     ODR_MASK_SET(req->options, Z_Options_search);
321     ODR_MASK_SET(req->options, Z_Options_present);
322     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
323     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
324     ODR_MASK_SET(req->options, Z_Options_scan);
325     ODR_MASK_SET(req->options, Z_Options_sort);
326     ODR_MASK_SET(req->options, Z_Options_extendedServices);
327
328     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
329     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
330     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
331
332     *req->maximumRecordSize = 1024*1024;
333
334     req->idAuthentication = auth;
335
336     send_apdu(apdu);
337     printf("Sent initrequest.\n");
338 }
339
340 static int process_initResponse(Z_InitResponse *res)
341 {
342     /* save session parameters for later use */
343     session_mem = odr_extract_mem(in);
344     session = res;
345
346     if (!*res->result)
347         printf("Connection rejected by target.\n");
348     else
349         printf("Connection accepted by target.\n");
350     if (res->implementationId)
351         printf("ID     : %s\n", res->implementationId);
352     if (res->implementationName)
353         printf("Name   : %s\n", res->implementationName);
354     if (res->implementationVersion)
355         printf("Version: %s\n", res->implementationVersion);
356     if (res->userInformationField)
357     {
358         printf("UserInformationfield:\n");
359         if (!z_External(print, (Z_External**)&res-> userInformationField,
360             0))
361         {
362             odr_perror(print, "Printing userinfo\n");
363             odr_reset(print);
364         }
365         if (res->userInformationField->which == Z_External_octet)
366         {
367             printf("Guessing visiblestring:\n");
368             printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
369         }
370     }
371     return 0;
372 }
373
374 int cmd_open(char *arg)
375 {
376     void *add;
377     char type[100], addr[100];
378     CS_TYPE t;
379
380     if (conn)
381     {
382         printf("Already connected.\n");
383         return 0;
384     }
385     if (!*arg || sscanf(arg, "%[^:]:%s", type, addr) < 2)
386     {
387         fprintf(stderr, "Usage: open (osi|tcp) ':' [tsel '/']host[':'port]\n");
388         return 0;
389     }
390     if (!strcmp(type, "tcp"))
391     {
392         t = tcpip_type;
393         protocol = PROTO_Z3950;
394     }
395     else
396 #ifdef USE_XTIMOSI
397     if (!strcmp(type, "osi"))
398     {
399         t = mosi_type;
400         protocol = PROTO_SR;
401     }
402     else
403 #endif
404     {
405         fprintf(stderr, "Bad type: %s\n", type);
406         return 0;
407     }
408     if (!(conn = cs_create(t, 1, protocol)))
409     {
410         perror("cs_create");
411         return 0;
412     }
413     if (!(add = cs_straddr(conn, addr)))
414     {
415         perror(arg);
416         return 0;
417     }
418     printf("Connecting...");
419     fflush(stdout);
420     if (cs_connect(conn, add) < 0)
421     {
422         perror("connect");
423         cs_close(conn);
424         conn = 0;
425         return 0;
426     }
427     printf("Ok.\n");
428     send_initRequest();
429     return 2;
430 }
431
432 int cmd_authentication(char *arg)
433 {
434     static Z_IdAuthentication au;
435     static char open[256];
436
437     if (!*arg)
438     {
439         printf("Auth field set to null\n");
440         auth = 0;
441         return 1;
442     }
443     auth = &au;
444     au.which = Z_IdAuthentication_open;
445     au.u.open = open;
446     strcpy(open, arg);
447     return 1;
448 }
449
450 /* SEARCH SERVICE ------------------------------ */
451
452 static void display_variant(Z_Variant *v, int level)
453 {
454     int i;
455
456     for (i = 0; i < v->num_triples; i++)
457     {
458         printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
459             *v->triples[i]->type);
460         if (v->triples[i]->which == Z_Triple_internationalString)
461             printf(",value=%s\n", v->triples[i]->value.internationalString);
462         else
463             printf("\n");
464     }
465 }
466
467 static void display_grs1(Z_GenericRecord *r, int level)
468 {
469     int i;
470
471     if (!r)
472         return;
473     for (i = 0; i < r->num_elements; i++)
474     {
475         Z_TaggedElement *t;
476
477         printf("%*s", level * 4, "");
478         t = r->elements[i];
479         printf("(");
480         if (t->tagType)
481             printf("%d,", *t->tagType);
482         else
483             printf("?,");
484         if (t->tagValue->which == Z_StringOrNumeric_numeric)
485             printf("%d) ", *t->tagValue->u.numeric);
486         else
487             printf("%s) ", t->tagValue->u.string);
488         if (t->content->which == Z_ElementData_subtree)
489         {
490             printf("\n");
491             display_grs1(t->content->u.subtree, level+1);
492         }
493         else if (t->content->which == Z_ElementData_string)
494             printf("%s\n", t->content->u.string);
495         else if (t->content->which == Z_ElementData_numeric)
496             printf("%d\n", *t->content->u.numeric);
497         else if (t->content->which == Z_ElementData_oid)
498         {
499             int *ip = t->content->u.oid;
500             oident *oent;
501
502             if ((oent = oid_getentbyoid(t->content->u.oid)))
503                 printf("OID: %s\n", oent->desc);
504             else
505             {
506                 printf("{");
507                 while (ip && *ip >= 0)
508                     printf(" %d", *(ip++));
509                 printf(" }\n");
510             }
511         }
512         else if (t->content->which == Z_ElementData_noDataRequested)
513             printf("[No data requested]\n");
514         else if (t->content->which == Z_ElementData_elementEmpty)
515             printf("[Element empty]\n");
516         else if (t->content->which == Z_ElementData_elementNotThere)
517             printf("[Element not there]\n");
518         else
519             printf("??????\n");
520         if (t->appliedVariant)
521             display_variant(t->appliedVariant, level+1);
522         if (t->metaData && t->metaData->supportedVariants)
523         {
524             int c;
525
526             printf("%*s---- variant list\n", (level+1)*4, "");
527             for (c = 0; c < t->metaData->num_supportedVariants; c++)
528             {
529                 printf("%*svariant #%d\n", (level+1)*4, "", c);
530                 display_variant(t->metaData->supportedVariants[c], level + 2);
531             }
532         }
533     }
534 }
535
536 static void display_record(Z_DatabaseRecord *p)
537 {
538     Z_External *r = (Z_External*) p;
539     oident *ent = oid_getentbyoid(r->direct_reference);
540
541     /*
542      * Tell the user what we got.
543      */
544     if (r->direct_reference)
545     {
546         printf("Record type: ");
547         if (ent)
548             printf("%s\n", ent->desc);
549         else if (!odr_oid(print, &r->direct_reference, 0))
550         {
551             odr_perror(print, "print oid");
552             odr_reset(print);
553         }
554     }
555     /* Check if this is a known, ASN.1 type tucked away in an octet string */
556     if (ent && r->which == Z_External_octet)
557     {
558         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
559         void *rr;
560
561         if (type)
562         {
563             /*
564              * Call the given decoder to process the record.
565              */
566             odr_setbuf(in, (char*)p->u.octet_aligned->buf,
567                 p->u.octet_aligned->len, 0);
568             if (!(*type->fun)(in, (char **)&rr, 0))
569             {
570                 odr_perror(in, "Decoding constructed record.");
571                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
572                 fprintf(stderr, "Packet dump:\n---------\n");
573                 odr_dumpBER(stderr, (char*)p->u.octet_aligned->buf,
574                     p->u.octet_aligned->len);
575                 fprintf(stderr, "---------\n");
576                 exit(1);
577             }
578             /*
579              * Note: we throw away the original, BER-encoded record here.
580              * Do something else with it if you want to keep it.
581              */
582             r->u.sutrs = (Odr_oct *)rr;    /* we don't actually check the type here. */
583             r->which = type->what;
584         }
585     }
586     if (ent && ent->value == VAL_SOIF)
587         printf("%.*s", r->u.octet_aligned->len, r->u.octet_aligned->buf);
588     else if (r->which == Z_External_octet && p->u.octet_aligned->len)
589     {
590         const char *marc_buf = (char*)p->u.octet_aligned->buf;
591         marc_display (marc_buf, NULL);
592         if (marcdump)
593             fwrite (marc_buf, strlen (marc_buf), 1, marcdump);
594     }
595     else if (ent && ent->value == VAL_SUTRS)
596     {
597         if (r->which != Z_External_sutrs)
598         {
599             printf("Expecting single SUTRS type for SUTRS.\n");
600             return;
601         }
602         printf("%.*s", r->u.sutrs->len, r->u.sutrs->buf);
603     }
604     else if (ent && ent->value == VAL_GRS1)
605     {
606         if (r->which != Z_External_grs1)
607         {
608             printf("Expecting single GRS type for GRS.\n");
609             return;
610         }
611         display_grs1(r->u.grs1, 0);
612     }
613     else 
614     {
615         printf("Unknown record representation.\n");
616         if (!z_External(print, &r, 0))
617         {
618             odr_perror(print, "Printing external");
619             odr_reset(print);
620         }
621     }
622 }
623
624
625 static void display_diagrecs(Z_DiagRec **pp, int num)
626 {
627     int i;
628     oident *ent;
629     Z_DefaultDiagFormat *r;
630
631     printf("Diagnostic message(s) from database:\n");
632     for (i = 0; i<num; i++)
633     {
634         Z_DiagRec *p = pp[i];
635         if (p->which != Z_DiagRec_defaultFormat)
636         {
637             printf("Diagnostic record not in default format.\n");
638             return;
639         }
640         else
641             r = p->u.defaultFormat;
642         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
643             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
644             printf("Missing or unknown diagset\n");
645         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
646         if (r->addinfo && *r->addinfo)
647             printf(" -- '%s'\n", r->addinfo);
648         else
649             printf("\n");
650     }
651 }
652
653
654 static void display_nameplusrecord(Z_NamePlusRecord *p)
655 {
656     if (p->databaseName)
657         printf("[%s]", p->databaseName);
658     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
659         display_diagrecs(&p->u.surrogateDiagnostic, 1);
660     else
661         display_record(p->u.databaseRecord);
662 }
663
664 static void display_records(Z_Records *p)
665 {
666     int i;
667
668     if (p->which == Z_Records_NSD)
669         display_diagrecs (&p->u.nonSurrogateDiagnostic, 1);
670     else if (p->which == Z_Records_multipleNSD)
671         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
672                           p->u.multipleNonSurDiagnostics->num_diagRecs);
673     else 
674     {
675         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
676         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
677             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
678     }
679 }
680
681 static int send_searchRequest(char *arg)
682 {
683     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
684     Z_SearchRequest *req = apdu->u.searchRequest;
685     Z_Query query;
686     int oid[OID_SIZE];
687 #if CCL2RPN
688     struct ccl_rpn_node *rpn;
689     int error, pos;
690     oident bib1;
691 #endif
692     char setstring[100];
693     Z_RPNQuery *RPNquery;
694     Odr_oct ccl_query;
695
696 #if CCL2RPN
697     if (queryType == QueryType_CCL2RPN)
698     {
699         rpn = ccl_find_str(bibset, arg, &error, &pos);
700         if (error)
701         {
702             printf("CCL ERROR: %s\n", ccl_err_msg(error));
703             return 0;
704         }
705     }
706 #endif
707     req->referenceId = set_refid (out);
708     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
709     {
710         static unsigned char big[2100];
711         static Odr_oct bigo;
712
713         /* send a very big referenceid to test transport stack etc. */
714         memset(big, 'A', 2100);
715         bigo.len = bigo.size = 2100;
716         bigo.buf = big;
717         req->referenceId = &bigo;
718     }
719     
720     if (setnumber >= 0)
721     {
722         sprintf(setstring, "%d", ++setnumber);
723         req->resultSetName = setstring;
724     }
725     *req->smallSetUpperBound = smallSetUpperBound;
726     *req->largeSetLowerBound = largeSetLowerBound;
727     *req->mediumSetPresentNumber = mediumSetPresentNumber;
728     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
729         mediumSetPresentNumber > 0))
730     {
731         oident prefsyn;
732
733         prefsyn.proto = protocol;
734         prefsyn.oclass = CLASS_RECSYN;
735         prefsyn.value = recordsyntax;
736         req->preferredRecordSyntax =
737             odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
738         req->smallSetElementSetNames =
739             req->mediumSetElementSetNames = elementSetNames;
740     }
741     req->num_databaseNames = num_databaseNames;
742     req->databaseNames = databaseNames;
743
744     req->query = &query;
745
746     switch (queryType)
747     {
748     case QueryType_Prefix:
749         query.which = Z_Query_type_1;
750         RPNquery = p_query_rpn (out, protocol, arg);
751         if (!RPNquery)
752         {
753             printf("Prefix query error\n");
754             return 0;
755         }
756         query.u.type_1 = RPNquery;
757         break;
758     case QueryType_CCL:
759         query.which = Z_Query_type_2;
760         query.u.type_2 = &ccl_query;
761         ccl_query.buf = (unsigned char*) arg;
762         ccl_query.len = strlen(arg);
763         break;
764 #if CCL2RPN
765     case QueryType_CCL2RPN:
766         query.which = Z_Query_type_1;
767         assert((RPNquery = ccl_rpn_query(out, rpn)));
768         bib1.proto = protocol;
769         bib1.oclass = CLASS_ATTSET;
770         bib1.value = VAL_BIB1;
771         RPNquery->attributeSetId = oid_ent_to_oid(&bib1, oid);
772         query.u.type_1 = RPNquery;
773         ccl_rpn_delete (rpn);
774         break;
775 #endif
776     default:
777         printf ("Unsupported query type\n");
778         return 0;
779     }
780     send_apdu(apdu);
781     setno = 1;
782     printf("Sent searchRequest.\n");
783     return 2;
784 }
785
786 static int process_searchResponse(Z_SearchResponse *res)
787 {
788     printf ("Received SearchResponse.\n");
789     print_refid (res->referenceId);
790     if (*res->searchStatus)
791         printf("Search was a success.\n");
792     else
793         printf("Search was a bloomin' failure.\n");
794     printf("Number of hits: %d, setno %d\n",
795         *res->resultCount, setnumber);
796     printf("records returned: %d\n",
797         *res->numberOfRecordsReturned);
798     setno += *res->numberOfRecordsReturned;
799     if (res->records)
800         display_records(res->records);
801     return 0;
802 }
803
804 static void print_level(int iLevel)
805 {
806     int i;
807     for (i = 0; i < iLevel * 4; i++)
808         printf(" ");
809 }
810
811 static void print_int(int iLevel, const char *pTag, int *pInt)
812 {
813     if (pInt != NULL)
814     {
815         print_level(iLevel);
816         printf("%s: %d\n", pTag, *pInt);
817     }
818 }
819
820 static void print_string(int iLevel, const char *pTag, const char *pString)
821 {
822     if (pString != NULL)
823     {
824         print_level(iLevel);
825         printf("%s: %s\n", pTag, pString);
826     }
827 }
828
829 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
830 {
831     if (pOid != NULL)
832     {
833         int *pInt = pOid;
834
835         print_level(iLevel);
836         printf("%s:", pTag);
837         for (; *pInt != -1; pInt++)
838             printf(" %d", *pInt);
839         printf("\n");
840     }
841 }
842
843 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
844 {
845     if (referenceId != NULL)
846     {
847         int i;
848
849         print_level(iLevel);
850         printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
851         for (i = 0; i < referenceId->len; i++)
852             printf("%c", referenceId->buf[i]);
853         printf("\n");
854     }
855 }
856
857 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
858 {
859     if (pStringNumeric != NULL)
860     {
861         switch (pStringNumeric->which)
862         {
863             case Z_StringOrNumeric_string:
864                 print_string(iLevel, pTag, pStringNumeric->u.string);
865                 break;
866
867             case Z_StringOrNumeric_numeric:
868                 print_int(iLevel, pTag, pStringNumeric->u.numeric);
869                 break;
870
871             default:
872                 print_level(iLevel);
873                 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
874                 break;
875         }
876     }
877 }
878
879 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
880 {
881     if (pUniverseReportDuplicate != NULL)
882     {
883         print_level(iLevel);
884         printf("Universe Report Duplicate: \n");
885         iLevel++;
886         print_string_or_numeric(iLevel, "Hit No", pUniverseReportDuplicate->hitno);
887     }
888 }
889
890 static void print_universe_report_hits(int iLevel, Z_UniverseReportHits *pUniverseReportHits)
891 {
892     if (pUniverseReportHits != NULL)
893     {
894         print_level(iLevel);
895         printf("Universe Report Hits: \n");
896         iLevel++;
897         print_string_or_numeric(iLevel, "Database", pUniverseReportHits->database);
898         print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
899     }
900 }
901
902 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
903 {
904     if (pUniverseReport != NULL)
905     {
906         print_level(iLevel);
907         printf("Universe Report: \n");
908         iLevel++;
909         print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
910         switch (pUniverseReport->which)
911         {
912             case Z_UniverseReport_databaseHits:
913                 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
914                 break;
915
916             case Z_UniverseReport_duplicate:
917                 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
918                 break;
919
920             default:
921                 print_level(iLevel);
922                 printf("Type: %d\n", pUniverseReport->which);
923                 break;
924         }
925     }
926 }
927
928 static void print_external(int iLevel, Z_External *pExternal)
929 {
930     if (pExternal != NULL)
931     {
932         print_level(iLevel);
933         printf("External: \n");
934         iLevel++;
935         print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
936         print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
937         print_string(iLevel, "Descriptor", pExternal->descriptor);
938         switch (pExternal->which)
939         {
940             case Z_External_universeReport:
941                 print_universe_report(iLevel, pExternal->u.universeReport);
942                 break;
943
944             default:
945                 print_level(iLevel);
946                 printf("Type: %d\n", pExternal->which);
947                 break;
948         }
949     }
950 }
951
952 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
953 {
954     printf ("Received ResourceControlRequest.\n");
955     print_referenceId(1, req->referenceId);
956     print_int(1, "Suspended Flag", req->suspendedFlag);
957     print_int(1, "Partial Results Available", req->partialResultsAvailable);
958     print_int(1, "Response Required", req->responseRequired);
959     print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
960     print_external(1, req->resourceReport);
961     return 0;
962 }
963
964 void process_ESResponse(Z_ExtendedServicesResponse *res)
965 {
966     printf("process_ESResponse\n");
967 }
968
969 static Z_External *CreateItemOrderExternal(int itemno)
970 {
971     Z_External *r = odr_malloc(out, sizeof(Z_External));
972     oident ItemOrderRequest;
973   
974     ItemOrderRequest.proto = PROTO_Z3950;
975     ItemOrderRequest.oclass = CLASS_EXTSERV;
976     ItemOrderRequest.value = VAL_ITEMORDER;
977  
978     r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest)); 
979     r->indirect_reference = odr_malloc(out,sizeof(int));
980     *r->indirect_reference = 0;
981
982     r->descriptor = "Extended services item order";
983
984     r->which = Z_External_itemOrder;
985
986     r->u.itemOrder = odr_malloc(out,sizeof(Z_ItemOrder));
987     memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
988     r->u.itemOrder->which=Z_ItemOrder_esRequest;
989
990     r->u.itemOrder->u.esRequest = odr_malloc(out,sizeof(Z_IORequest));
991     memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
992
993     r->u.itemOrder->u.esRequest->toKeep = odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
994     memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
995     r->u.itemOrder->u.esRequest->notToKeep = odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
996     memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
997
998     r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
999     r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1000     r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1001
1002     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem = odr_malloc(out, sizeof(Z_IOResultSetItem));
1003     memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1004     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1005
1006     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = odr_malloc(out, sizeof(int));
1007     *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1008
1009     r->u.itemOrder->u.esRequest->notToKeep->itemRequest = NULL;
1010     return r;
1011 }
1012
1013 /* II : Added to do DALI Item Order Extended services request */
1014 static int send_itemorder(char *arg)
1015 {
1016     int itemno = -1;
1017     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1018     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1019     oident ItemOrderRequest;
1020
1021     if (*arg)
1022         itemno = atoi(arg);
1023
1024     /* Set up item order request */
1025
1026     /* Function being performed by this extended services request */
1027     req->function = odr_malloc(out, sizeof(int));
1028     *req->function = Z_ExtendedServicesRequest_create;
1029
1030     /* Package type, Using protocol ILL ( But that's not in the oid.h file yet */
1031     /* create an object of class Extended Service, value Item Order            */
1032     ItemOrderRequest.proto = PROTO_Z3950;
1033     ItemOrderRequest.oclass = CLASS_EXTSERV;
1034     ItemOrderRequest.value = VAL_ITEMORDER;
1035     req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1036     req->packageName = "1.Extendedserveq";
1037
1038     /* ** taskSpecificParameters ** */
1039     req->taskSpecificParameters = CreateItemOrderExternal(itemno);
1040
1041     /* waitAction - Create the ILL request and that's it */
1042     *req->waitAction = Z_ExtendedServicesRequest_wait;
1043
1044     send_apdu(apdu);
1045     return 0;
1046 }
1047
1048 /* II : Added to do DALI Item Order Extended services request */
1049 static int cmd_itemorder(char *arg)
1050 {
1051     printf("Item order request\n");
1052     fflush(stdout);
1053
1054     send_itemorder(arg);
1055     return(1);
1056 }
1057
1058 static int cmd_find(char *arg)
1059 {
1060     if (!*arg)
1061     {
1062         printf("Find what?\n");
1063         return 0;
1064     }
1065     if (!conn)
1066     {
1067         printf("Not connected yet\n");
1068         return 0;
1069     }
1070     if (!send_searchRequest(arg))
1071         return 0;
1072     return 2;
1073 }
1074
1075 static int cmd_ssub(char *arg)
1076 {
1077     if (!(smallSetUpperBound = atoi(arg)))
1078         return 0;
1079     return 1;
1080 }
1081
1082 static int cmd_lslb(char *arg)
1083 {
1084     if (!(largeSetLowerBound = atoi(arg)))
1085         return 0;
1086     return 1;
1087 }
1088
1089 static int cmd_mspn(char *arg)
1090 {
1091     if (!(mediumSetPresentNumber = atoi(arg)))
1092         return 0;
1093     return 1;
1094 }
1095
1096 static int cmd_status(char *arg)
1097 {
1098     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1099     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1100     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1101     return 1;
1102 }
1103
1104 static int cmd_base(char *arg)
1105 {
1106     int i;
1107     char *cp;
1108
1109     if (!*arg)
1110     {
1111         printf("Usage: base <database> <database> ...\n");
1112         return 0;
1113     }
1114     for (i = 0; i<num_databaseNames; i++)
1115         xfree (databaseNames[i]);
1116     num_databaseNames = 0;
1117     while (1)
1118     {
1119         if (!(cp = strchr(arg, ' ')))
1120             cp = arg + strlen(arg);
1121         if (cp - arg < 1)
1122             break;
1123         databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
1124         memcpy (databaseNames[num_databaseNames], arg, cp - arg);
1125         databaseNames[num_databaseNames++][cp - arg] = '\0';
1126         if (!*cp)
1127             break;
1128         arg = cp+1;
1129     }
1130     return 1;
1131 }
1132
1133 static int cmd_setnames(char *arg)
1134 {
1135     if (setnumber < 0)
1136     {
1137         printf("Set numbering enabled.\n");
1138         setnumber = 0;
1139     }
1140     else
1141     {
1142         printf("Set numbering disabled.\n");
1143         setnumber = -1;
1144     }
1145     return 1;
1146 }
1147
1148 /* PRESENT SERVICE ----------------------------- */
1149
1150 static int send_presentRequest(char *arg)
1151 {
1152     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1153     Z_PresentRequest *req = apdu->u.presentRequest;
1154     Z_RecordComposition compo;
1155     oident prefsyn;
1156     int nos = 1;
1157     int oid[OID_SIZE];
1158     char *p;
1159     char setstring[100];
1160
1161     req->referenceId = set_refid (out);
1162     if ((p = strchr(arg, '+')))
1163     {
1164         nos = atoi(p + 1);
1165         *p = 0;
1166     }
1167     if (*arg)
1168         setno = atoi(arg);
1169     if (p && (p=strchr(p+1, '+')))
1170     {
1171         strcpy (setstring, p+1);
1172         req->resultSetId = setstring;
1173     }
1174     else if (setnumber >= 0)
1175     {
1176         sprintf(setstring, "%d", setnumber);
1177         req->resultSetId = setstring;
1178     }
1179 #if 0
1180     if (1)
1181     {
1182         static Z_Range range;
1183         static Z_Range *rangep = &range;
1184     req->num_ranges = 1;
1185 #endif
1186     req->resultSetStartPoint = &setno;
1187     req->numberOfRecordsRequested = &nos;
1188     prefsyn.proto = protocol;
1189     prefsyn.oclass = CLASS_RECSYN;
1190     prefsyn.value = recordsyntax;
1191     req->preferredRecordSyntax = oid_ent_to_oid(&prefsyn, oid);
1192
1193     if (elementSetNames)
1194     {
1195         req->recordComposition = &compo;
1196         compo.which = Z_RecordComp_simple;
1197         compo.u.simple = elementSetNames;
1198     }
1199     send_apdu(apdu);
1200     printf("Sent presentRequest (%d+%d).\n", setno, nos);
1201     return 2;
1202 }
1203
1204 void process_close(Z_Close *req)
1205 {
1206     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1207     Z_Close *res = apdu->u.close;
1208
1209     static char *reasons[] =
1210     {
1211         "finished",
1212         "shutdown",
1213         "system problem",
1214         "cost limit reached",
1215         "resources",
1216         "security violation",
1217         "protocolError",
1218         "lack of activity",
1219         "peer abort",
1220         "unspecified"
1221     };
1222
1223     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1224         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1225     if (sent_close)
1226     {
1227         printf("Goodbye.\n");
1228         exit(0);
1229     }
1230     *res->closeReason = Z_Close_finished;
1231     send_apdu(apdu);
1232     printf("Sent response.\n");
1233     sent_close = 1;
1234 }
1235
1236 static int cmd_show(char *arg)
1237 {
1238     if (!send_presentRequest(arg))
1239         return 0;
1240     return 2;
1241 }
1242
1243 int cmd_quit(char *arg)
1244 {
1245     printf("See you later, alligator.\n");
1246     exit(0);
1247     return 0;
1248 }
1249
1250 int cmd_cancel(char *arg)
1251 {
1252     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1253     Z_TriggerResourceControlRequest *req =
1254         apdu->u.triggerResourceControlRequest;
1255     bool_t rfalse = 0;
1256     
1257     if (!session)
1258     {
1259         printf("Session not initialized yet\n");
1260         return 0;
1261     }
1262     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1263     {
1264         printf("Target doesn't support cancel (trigger resource ctrl)\n");
1265         return 0;
1266     }
1267     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1268     req->resultSetWanted = &rfalse;
1269
1270     send_apdu(apdu);
1271     printf("Sent cancel request\n");
1272     return 2;
1273 }
1274
1275 int send_scanrequest(char *string, int pp, int num)
1276 {
1277     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1278     Z_ScanRequest *req = apdu->u.scanRequest;
1279
1280     req->referenceId = set_refid (out);
1281     req->num_databaseNames = num_databaseNames;
1282     req->databaseNames = databaseNames;
1283     req->termListAndStartPoint = p_query_scan(out, protocol,
1284                                               &req->attributeSet, string);
1285     req->numberOfTermsRequested = &num;
1286     req->preferredPositionInResponse = &pp;
1287     send_apdu(apdu);
1288     return 2;
1289 }
1290
1291 int send_sortrequest(char *arg, int newset)
1292 {
1293     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1294     Z_SortRequest *req = apdu->u.sortRequest;
1295     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)odr_malloc (out, sizeof(*sksl));
1296     char setstring[32];
1297     char sort_string[32], sort_flags[32];
1298     int off;
1299     int oid[OID_SIZE];
1300     oident bib1;
1301
1302     if (setnumber >= 0)
1303         sprintf (setstring, "%d", setnumber);
1304     else
1305         sprintf (setstring, "default");
1306
1307     req->referenceId = set_refid (out);
1308
1309     req->inputResultSetNames =
1310         (Z_StringList *)odr_malloc (out, sizeof(*req->inputResultSetNames));
1311     req->inputResultSetNames->num_strings = 1;
1312     req->inputResultSetNames->strings =
1313         (char **)odr_malloc (out, sizeof(*req->inputResultSetNames->strings));
1314     req->inputResultSetNames->strings[0] =
1315         (char *)odr_malloc (out, strlen(setstring)+1);
1316     strcpy (req->inputResultSetNames->strings[0], setstring);
1317
1318     if (newset && setnumber >= 0)
1319         sprintf (setstring, "%d", ++setnumber);
1320
1321     req->sortedResultSetName = (char *)odr_malloc (out, strlen(setstring)+1);
1322     strcpy (req->sortedResultSetName, setstring);
1323
1324     req->sortSequence = sksl;
1325     sksl->num_specs = 0;
1326     sksl->specs = (Z_SortKeySpec **)odr_malloc (out, sizeof(sksl->specs) * 20);
1327     
1328     bib1.proto = protocol;
1329     bib1.oclass = CLASS_ATTSET;
1330     bib1.value = VAL_BIB1;
1331     while ((sscanf (arg, "%31s %31s%n", sort_string, sort_flags, &off)) == 2 
1332            && off > 1)
1333     {
1334         int i;
1335         char *sort_string_sep;
1336         Z_SortKeySpec *sks = (Z_SortKeySpec *)odr_malloc (out, sizeof(*sks));
1337         Z_SortKey *sk = (Z_SortKey *)odr_malloc (out, sizeof(*sk));
1338
1339         arg += off;
1340         sksl->specs[sksl->num_specs++] = sks;
1341         sks->sortElement = (Z_SortElement *)odr_malloc (out, sizeof(*sks->sortElement));
1342         sks->sortElement->which = Z_SortElement_generic;
1343         sks->sortElement->u.generic = sk;
1344         
1345         if ((sort_string_sep = strchr (sort_string, '=')))
1346         {
1347             Z_AttributeElement *el = (Z_AttributeElement *)odr_malloc (out, sizeof(*el));
1348             sk->which = Z_SortKey_sortAttributes;
1349             sk->u.sortAttributes =
1350                 (Z_SortAttributes *)odr_malloc (out, sizeof(*sk->u.sortAttributes));
1351             sk->u.sortAttributes->id = oid_ent_to_oid(&bib1, oid);
1352             sk->u.sortAttributes->list =
1353                 (Z_AttributeList *)odr_malloc (out, sizeof(*sk->u.sortAttributes->list));
1354             sk->u.sortAttributes->list->num_attributes = 1;
1355             sk->u.sortAttributes->list->attributes =
1356                 (Z_AttributeElement **)odr_malloc (out,
1357                             sizeof(*sk->u.sortAttributes->list->attributes));
1358             sk->u.sortAttributes->list->attributes[0] = el;
1359             el->attributeSet = 0;
1360             el->attributeType = (int *)odr_malloc (out, sizeof(*el->attributeType));
1361             *el->attributeType = atoi (sort_string);
1362             el->which = Z_AttributeValue_numeric;
1363             el->value.numeric = (int *)odr_malloc (out, sizeof(*el->value.numeric));
1364             *el->value.numeric = atoi (sort_string_sep + 1);
1365         }
1366         else
1367         {
1368             sk->which = Z_SortKey_sortField;
1369             sk->u.sortField = (char *)odr_malloc (out, strlen(sort_string)+1);
1370             strcpy (sk->u.sortField, sort_string);
1371         }
1372         sks->sortRelation = (int *)odr_malloc (out, sizeof(*sks->sortRelation));
1373         *sks->sortRelation = Z_SortRelation_ascending;
1374         sks->caseSensitivity = (int *)odr_malloc (out, sizeof(*sks->caseSensitivity));
1375         *sks->caseSensitivity = Z_SortCase_caseSensitive;
1376
1377         sks->missingValueAction = NULL;
1378
1379         for (i = 0; sort_flags[i]; i++)
1380         {
1381             switch (sort_flags[i])
1382             {
1383             case 'a':
1384             case 'A':
1385             case '>':
1386                 *sks->sortRelation = Z_SortRelation_ascending;
1387                 break;
1388             case 'd':
1389             case 'D':
1390             case '<':
1391                 *sks->sortRelation = Z_SortRelation_descending;
1392                 break;
1393             case 'i':
1394             case 'I':
1395                 *sks->caseSensitivity = Z_SortCase_caseInsensitive;
1396                 break;
1397             case 'S':
1398             case 's':
1399                 *sks->caseSensitivity = Z_SortCase_caseSensitive;
1400                 break;
1401             }
1402         }
1403     }
1404     if (!sksl->num_specs)
1405     {
1406         printf ("Missing sort specifications\n");
1407         return -1;
1408     }
1409     send_apdu(apdu);
1410     return 2;
1411 }
1412
1413 void display_term(Z_TermInfo *t)
1414 {
1415     if (t->term->which == Z_Term_general)
1416     {
1417         printf("%.*s (%d)\n", t->term->u.general->len, t->term->u.general->buf,
1418             t->globalOccurrences ? *t->globalOccurrences : -1);
1419         sprintf(last_scan, "%.*s", t->term->u.general->len,
1420             t->term->u.general->buf);
1421     }
1422     else
1423         printf("Term type not general.\n");
1424 }
1425
1426 void process_scanResponse(Z_ScanResponse *res)
1427 {
1428     int i;
1429    
1430     printf("Received ScanResponse\n"); 
1431     print_refid (res->referenceId);
1432     printf("%d entries", *res->numberOfEntriesReturned);
1433     if (res->positionOfTerm)
1434         printf (", position=%d", *res->positionOfTerm); 
1435     printf ("\n");
1436     if (*res->scanStatus != Z_Scan_success)
1437         printf("Scan returned code %d\n", *res->scanStatus);
1438     if (!res->entries)
1439         return;
1440     if (res->entries->which == Z_ListEntries_entries)
1441     {
1442         Z_Entries *ent = res->entries->u.entries;
1443
1444         for (i = 0; i < ent->num_entries; i++)
1445             if (ent->entries[i]->which == Z_Entry_termInfo)
1446             {
1447                 printf("%c ", i + 1 == *res->positionOfTerm ? '*' : ' ');
1448                 display_term(ent->entries[i]->u.termInfo);
1449             }
1450             else
1451                 display_diagrecs(&ent->entries[i]->u.surrogateDiagnostic, 1);
1452     }
1453     else
1454         display_diagrecs(&res->entries->
1455                          u.nonSurrogateDiagnostics->diagRecs[0], 1);
1456 }
1457
1458 void process_sortResponse(Z_SortResponse *res)
1459 {
1460     printf("Received SortResponse: status=");
1461     switch (*res->sortStatus)
1462     {
1463     case Z_SortStatus_success:
1464         printf ("success"); break;
1465     case Z_SortStatus_partial_1:
1466         printf ("partial"); break;
1467     case Z_SortStatus_failure:
1468         printf ("failure"); break;
1469     default:
1470         printf ("unknown (%d)", *res->sortStatus);
1471     }
1472     printf ("\n");
1473     print_refid (res->referenceId);
1474     if (res->diagnostics)
1475         display_diagrecs(res->diagnostics->diagRecs,
1476                          res->diagnostics->num_diagRecs);
1477 }
1478
1479 int cmd_sort_generic(char *arg, int newset)
1480 {
1481     if (!session)
1482     {
1483         printf("Session not initialized yet\n");
1484         return 0;
1485     }
1486     if (!ODR_MASK_GET(session->options, Z_Options_sort))
1487     {
1488         printf("Target doesn't support sort\n");
1489         return 0;
1490     }
1491     if (*arg)
1492     {
1493         if (send_sortrequest(arg, newset) < 0)
1494             return 0;
1495         return 2;
1496     }
1497     return 0;
1498 }
1499
1500 int cmd_sort(char *arg)
1501 {
1502     return cmd_sort_generic (arg, 0);
1503 }
1504
1505 int cmd_sort_newset (char *arg)
1506 {
1507     return cmd_sort_generic (arg, 1);
1508 }
1509
1510 int cmd_scan(char *arg)
1511 {
1512     if (!session)
1513     {
1514         printf("Session not initialized yet\n");
1515         return 0;
1516     }
1517     if (!ODR_MASK_GET(session->options, Z_Options_scan))
1518     {
1519         printf("Target doesn't support scan\n");
1520         return 0;
1521     }
1522     if (*arg)
1523     {
1524         if (send_scanrequest(arg, 5, 20) < 0)
1525             return 0;
1526     }
1527     else
1528         if (send_scanrequest(last_scan, 1, 20) < 0)
1529             return 0;
1530     return 2;
1531 }
1532
1533 int cmd_format(char *arg)
1534 {
1535     if (!arg || !*arg)
1536     {
1537         printf("Usage: format <recordsyntax>\n");
1538         return 0;
1539     }
1540     recordsyntax = oid_getvalbyname (arg);
1541     if (recordsyntax == VAL_NONE)
1542     {
1543         printf ("unknown record syntax\n");
1544         return 0;
1545     }
1546     return 1;
1547 }
1548
1549 int cmd_elements(char *arg)
1550 {
1551     static Z_ElementSetNames esn;
1552     static char what[100];
1553
1554     if (!arg || !*arg)
1555     {
1556         printf("Usage: elements <esn>\n");
1557         return 0;
1558     }
1559     strcpy(what, arg);
1560     esn.which = Z_ElementSetNames_generic;
1561     esn.u.generic = what;
1562     elementSetNames = &esn;
1563     return 1;
1564 }
1565
1566 int cmd_attributeset(char *arg)
1567 {
1568     char what[100];
1569
1570     if (!arg || !*arg)
1571     {
1572         printf("Usage: attributeset <setname>\n");
1573         return 0;
1574     }
1575     sscanf(arg, "%s", what);
1576     if (p_query_attset (what))
1577     {
1578         printf("Unknown attribute set name\n");
1579         return 0;
1580     }
1581     return 1;
1582 }
1583
1584 int cmd_querytype (char *arg)
1585 {
1586     if (!strcmp (arg, "ccl"))
1587         queryType = QueryType_CCL;
1588     else if (!strcmp (arg, "prefix"))
1589         queryType = QueryType_Prefix;
1590 #if CCL2RPN
1591     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
1592         queryType = QueryType_CCL2RPN;
1593 #endif
1594     else
1595     {
1596         printf ("Querytype must be one of:\n");
1597         printf (" prefix         - Prefix query\n");
1598         printf (" ccl            - CCL query\n");
1599 #if CCL2RPN
1600         printf (" ccl2rpn        - CCL query converted to RPN\n");
1601 #endif
1602         return 0;
1603     }
1604     return 1;
1605 }
1606
1607 int cmd_refid (char *arg)
1608 {
1609     xfree (refid);
1610     refid = NULL;
1611     if (*arg)
1612     {
1613         refid = (char *) xmalloc (strlen(arg)+1);
1614         strcpy (refid, arg);
1615     }
1616     return 1;
1617 }
1618
1619 int cmd_close(char *arg)
1620 {
1621     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1622     Z_Close *req = apdu->u.close;
1623
1624     *req->closeReason = Z_Close_finished;
1625     send_apdu(apdu);
1626     printf("Sent close request.\n");
1627     sent_close = 1;
1628     return 2;
1629 }
1630
1631 static void initialize(void)
1632 {
1633 #if CCL2RPN
1634     FILE *inf;
1635 #endif
1636     nmem_init();
1637     if (!(out = odr_createmem(ODR_ENCODE)) ||
1638         !(in = odr_createmem(ODR_DECODE)) ||
1639         !(print = odr_createmem(ODR_PRINT)))
1640     {
1641         fprintf(stderr, "failed to allocate ODR streams\n");
1642         exit(1);
1643     }
1644     setvbuf(stdout, 0, _IONBF, 0);
1645
1646 #if CCL2RPN
1647     bibset = ccl_qual_mk (); 
1648     inf = fopen ("default.bib", "r");
1649     if (inf)
1650     {
1651         ccl_qual_file (bibset, inf);
1652         fclose (inf);
1653     }
1654 #endif
1655 }
1656
1657 static int client(int wait)
1658 {
1659     static struct {
1660         char *cmd;
1661         int (*fun)(char *arg);
1662         char *ad;
1663     } cmd[] = {
1664         {"open", cmd_open, "('tcp'|'osi')':'[<tsel>'/']<host>[':'<port>]"},
1665         {"quit", cmd_quit, ""},
1666         {"find", cmd_find, "<query>"},
1667         {"base", cmd_base, "<base-name>"},
1668         {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]"},
1669         {"scan", cmd_scan, "<term>"},
1670         {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ..."},
1671         {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ..."},
1672         {"authentication", cmd_authentication, "<acctstring>"},
1673         {"lslb", cmd_lslb, "<largeSetLowerBound>"},
1674         {"ssub", cmd_ssub, "<smallSetUpperBound>"},
1675         {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
1676         {"status", cmd_status, ""},
1677         {"setnames", cmd_setnames, ""},
1678         {"cancel", cmd_cancel, ""},
1679         {"format", cmd_format, "<recordsyntax>"},
1680         {"elements", cmd_elements, "<elementSetName>"},
1681         {"close", cmd_close, ""},
1682         {"attributeset", cmd_attributeset, "<attrset>"},
1683         {"querytype", cmd_querytype, "<type>"},
1684         {"refid", cmd_refid, "<id>"},
1685         {"itemorder", cmd_itemorder, "<item>"},
1686         {0,0}
1687     };
1688     char *netbuffer= 0;
1689     int netbufferlen = 0;
1690     int i;
1691     Z_APDU *apdu;
1692
1693     while (1)
1694     {
1695         int res;
1696 #ifdef USE_SELECT
1697         fd_set input;
1698 #endif
1699         char line[1024], word[1024], arg[1024];
1700         
1701 #ifdef USE_SELECT
1702         FD_ZERO(&input);
1703         FD_SET(0, &input);
1704         if (conn)
1705             FD_SET(cs_fileno(conn), &input);
1706         if ((res = select(20, &input, 0, 0, 0)) < 0)
1707         {
1708             perror("select");
1709             exit(1);
1710         }
1711         if (!res)
1712             continue;
1713         if (!wait && FD_ISSET(0, &input))
1714 #else
1715         if (!wait)
1716 #endif
1717             {
1718             /* quick & dirty way to get a command line. */
1719                 char *end_p;
1720                 if (!fgets(line, 1023, stdin))
1721                     break;
1722                 if ((end_p = strchr (line, '\n')))
1723                     *end_p = '\0';
1724             if ((res = sscanf(line, "%s %[^;]", word, arg)) <= 0)
1725             {
1726                 strcpy(word, last_cmd);
1727                 *arg = '\0';
1728             }
1729             else if (res == 1)
1730                 *arg = 0;
1731             strcpy(last_cmd, word);
1732             for (i = 0; cmd[i].cmd; i++)
1733                 if (!strncmp(cmd[i].cmd, word, strlen(word)))
1734                 {
1735                     res = (*cmd[i].fun)(arg);
1736                     break;
1737                 }
1738             if (!cmd[i].cmd) /* dump our help-screen */
1739             {
1740                 printf("Unknown command: %s.\n", word);
1741                 printf("Currently recognized commands:\n");
1742                 for (i = 0; cmd[i].cmd; i++)
1743                     printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
1744                 res = 1;
1745             }
1746             if (res < 2)
1747             {
1748                 printf(C_PROMPT);
1749                 continue;
1750             }
1751         }
1752         wait = 0;
1753 #ifdef USE_SELECT
1754         if (conn && FD_ISSET(cs_fileno(conn), &input))
1755 #endif
1756         {
1757             do
1758             {
1759                 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
1760                 {
1761                     perror("cs_get");
1762                     exit(1);
1763                 }
1764                 if (!res)
1765                 {
1766                     printf("Target closed connection.\n");
1767                     exit(1);
1768                 }
1769                 odr_reset(in); /* release APDU from last round */
1770                 odr_setbuf(in, netbuffer, res, 0);
1771                 if (!z_APDU(in, &apdu, 0))
1772                 {
1773                     odr_perror(in, "Decoding incoming APDU");
1774                     fprintf(stderr, "[Near %d]\n", odr_offset(in));
1775                     fprintf(stderr, "Packet dump:\n---------\n");
1776                     odr_dumpBER(stderr, netbuffer, res);
1777                     fprintf(stderr, "---------\n");
1778                     exit(1);
1779                 }
1780 #if 0
1781                 if (!z_APDU(print, &apdu, 0))
1782                 {
1783                     odr_perror(print, "Failed to print incoming APDU");
1784                     odr_reset(print);
1785                     continue;
1786                 }
1787 #endif
1788                 switch(apdu->which)
1789                 {
1790                 case Z_APDU_initResponse:
1791                     process_initResponse(apdu->u.initResponse);
1792                     break;
1793                 case Z_APDU_searchResponse:
1794                     process_searchResponse(apdu->u.searchResponse);
1795                     break;
1796                 case Z_APDU_scanResponse:
1797                     process_scanResponse(apdu->u.scanResponse);
1798                     break;
1799                 case Z_APDU_presentResponse:
1800                     print_refid (apdu->u.presentResponse->referenceId);
1801                     setno +=
1802                         *apdu->u.presentResponse->numberOfRecordsReturned;
1803                     if (apdu->u.presentResponse->records)
1804                         display_records(apdu->u.presentResponse->records);
1805                     else
1806                         printf("No records.\n");
1807                     break;
1808                 case Z_APDU_sortResponse:
1809                     process_sortResponse(apdu->u.sortResponse);
1810                     break;
1811                 case Z_APDU_extendedServicesResponse:
1812                     printf("Got extended services response\n");
1813                     process_ESResponse(apdu->u.extendedServicesResponse);
1814                     break;
1815                 case Z_APDU_close:
1816                     printf("Target has closed the association.\n");
1817                     process_close(apdu->u.close);
1818                     break;
1819                 case Z_APDU_resourceControlRequest:
1820                     process_resourceControlRequest
1821                         (apdu->u.resourceControlRequest);
1822                     break;
1823                 default:
1824                     printf("Received unknown APDU type (%d).\n", 
1825                            apdu->which);
1826                     exit(1);
1827                 }
1828             }
1829             while (cs_more(conn));
1830             printf(C_PROMPT);
1831             fflush(stdout);
1832         }
1833     }
1834     return 0;
1835 }
1836
1837 int main(int argc, char **argv)
1838 {
1839     char *prog = *argv;
1840     char *arg;
1841     int ret;
1842     int opened = 0;
1843
1844     initialize();
1845     cmd_base("Default");
1846
1847     while ((ret = options("m:", argv, argc, &arg)) != -2)
1848     {
1849         switch (ret)
1850         {
1851         case 0:
1852             if (cmd_open (arg) == 2)
1853                 opened = 1;
1854             break;
1855         case 'm':
1856             if (!(marcdump = fopen (arg, "a")))
1857             {
1858                 perror (arg);
1859                 exit (1);
1860             }
1861             break;
1862         default:
1863             fprintf (stderr, "Usage: %s [-m <marclog>] [<server-addr>]\n",
1864                      prog);
1865             exit (1);
1866         }
1867     }
1868     if (!opened)
1869         printf (C_PROMPT);
1870     return client (opened);
1871 }
1872
1873