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