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