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