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