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