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