395a4cfe9dc865efd00906149109968de0a8f510
[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.6  1995-05-31 08:29:21  quinn
8  * Nothing significant.
9  *
10  * Revision 1.5  1995/05/29  08:10:47  quinn
11  * Moved oid.c to util.
12  *
13  * Revision 1.4  1995/05/22  15:30:13  adam
14  * Client uses prefix query notation.
15  *
16  * Revision 1.3  1995/05/22  15:06:53  quinn
17  * *** empty log message ***
18  *
19  * Revision 1.2  1995/05/22  14:56:40  quinn
20  * *** empty log message ***
21  *
22  * Revision 1.1  1995/05/22  11:30:31  quinn
23  * Added prettier client.
24  *
25  *
26  */
27
28 /*
29  * This is the obligatory little toy client, whose primary purpose is
30  * to illustrate the use of the YAZ service-level API.
31  */
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <sys/time.h>
36 #include <assert.h>
37
38 #include <comstack.h>
39 #include <tcpip.h>
40 #ifdef USE_XTIMOSI
41 #include <xmosi.h>
42 #endif
43
44 #include <proto.h>
45
46 #include <marcdisp.h>
47
48 #ifdef RPN_QUERY
49 #ifdef PREFIX_QUERY
50 #include <pquery.h>
51 #else
52 #include <yaz-ccl.h>
53 #endif
54 #endif
55
56 #include "../version.h"
57
58 #define C_PROMPT "Z> "
59
60 static ODR out, in, print;              /* encoding and decoding streams */
61 static COMSTACK conn = 0;               /* our z-association */
62 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
63 static char database[512] = "Default";  /* Database name */
64 static int setnumber = 0;               /* current result set number */
65 static int smallSetUpperBound = 0;
66 static int largeSetLowerBound = 1;
67 static int mediumSetPresentNumber = 0;
68 static int setno = 1;                   /* current set offset */
69 static int protocol = PROTO_Z3950;      /* current app protocol */
70 #ifdef RPN_QUERY
71 #ifndef PREFIX_QUERY
72 static CCL_bibset bibset;               /* CCL bibset handle */
73 #endif
74 #endif
75
76 static void send_apdu(Z_APDU *a)
77 {
78     char *buf;
79     int len;
80
81     if (!z_APDU(out, &a, 0))
82     {
83         odr_perror(out, "Encoding APDU");
84         exit(1);
85     }
86     buf = odr_getbuf(out, &len, 0);
87     odr_reset(out); /* release the APDU */
88     if (cs_put(conn, buf, len) < 0)
89     {
90         fprintf(stderr, "cs_put: %s", cs_errlist[cs_errno(conn)]);
91         exit(1);
92     }
93 }
94
95 /* INIT SERVICE ------------------------------- */
96
97 static void send_initRequest()
98 {
99     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
100     Z_InitRequest *req = apdu->u.initRequest;
101
102     ODR_MASK_SET(req->options, Z_Options_search);
103     ODR_MASK_SET(req->options, Z_Options_present);
104
105     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
106     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
107
108     req->idAuthentication = auth;
109
110     send_apdu(apdu);
111     printf("Sent initrequest.\n");
112 }
113
114 static int process_initResponse(Z_InitResponse *res)
115 {
116     if (!*res->result)
117         printf("Connection rejected by target.\n");
118     else
119         printf("Connection accepted by target.\n");
120     if (res->implementationId)
121         printf("ID     : %s\n", res->implementationId);
122     if (res->implementationName)
123         printf("Name   : %s\n", res->implementationName);
124     if (res->implementationVersion)
125         printf("Version: %s\n", res->implementationVersion);
126     if (res->userInformationField)
127     {
128         printf("UserInformationfield:\n");
129         if (!odr_external(print, (Odr_external**)&res-> userInformationField,
130             0))
131         {
132             odr_perror(print, "Printing userinfo\n");
133             odr_reset(print);
134         }
135         if (res->userInformationField->which == ODR_EXTERNAL_octet)
136         {
137             printf("Guessing visiblestring:\n");
138             printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
139         }
140     }
141     return 0;
142 }
143
144 int cmd_open(char *arg)
145 {
146     void *add;
147     char type[100], addr[100];
148     CS_TYPE t;
149
150     if (conn)
151     {
152         printf("Already connected.\n");
153         return 0;
154     }
155     if (!*arg || sscanf(arg, "%[^:]:%s", type, addr) < 2)
156     {
157         fprintf(stderr, "Usage: open (osi|tcp) ':' [tsel '/']host[':'port]\n");
158         return 0;
159     }
160 #ifdef USE_XTIMOSI
161     if (!strcmp(type, "osi"))
162     {
163         if (!(add = mosi_strtoaddr(addr)))
164         {
165             perror(arg);
166             return 0;
167         }
168         t = mosi_type;
169         protocol = PROTO_SR;
170     }
171     else
172 #endif
173     if (!strcmp(type, "tcp"))
174     {
175         if (!(add = tcpip_strtoaddr(addr)))
176         {
177             perror(arg);
178             return 0;
179         }
180         t = tcpip_type;
181         protocol = PROTO_Z3950;
182     }
183     else
184     {
185         fprintf(stderr, "Bad type: %s\n", type);
186         return 0;
187     }
188     if (!(conn = cs_create(t, 1, protocol)))
189     {
190         perror("cs_create");
191         return 0;
192     }
193     printf("Connecting...");
194     fflush(stdout);
195     if (cs_connect(conn, add) < 0)
196     {
197         perror("connect");
198         cs_close(conn);
199         conn = 0;
200         return 0;
201     }
202     printf("Ok!\n");
203     send_initRequest();
204     return 2;
205 }
206
207 int cmd_authentication(char *arg)
208 {
209     static Z_IdAuthentication au;
210     static char open[256];
211
212     if (!*arg)
213     {
214         printf("Auth field set to null\n");
215         auth = 0;
216         return 1;
217     }
218     auth = &au;
219     au.which = Z_IdAuthentication_open;
220     au.u.open = open;
221     strcpy(open, arg);
222     return 1;
223 }
224
225 /* SEARCH SERVICE ------------------------------ */
226
227 void display_record(Z_DatabaseRecord *p)
228 {
229     Odr_external *r = (Odr_external*) p;
230
231     if (r->direct_reference)
232     {
233         oident *ent = oid_getentbyoid(r->direct_reference);
234
235         printf("Record type: ");
236         if (ent)
237             printf("%s\n", ent->desc);
238         else if (!odr_oid(print, &r->direct_reference, 0))
239         {
240             odr_perror(print, "print oid");
241             odr_reset(print);
242         }
243     }
244 #if 1
245     if (r->which == ODR_EXTERNAL_octet && p->u.octet_aligned->len)
246     {
247 #if 1
248         marc_display ((char*)p->u.octet_aligned->buf, stdout);
249 #else
250         FILE *ofi = fopen("dump", "a");
251         assert(ofi);
252         fwrite(p->u.octet_aligned->buf, 1, p->u.octet_aligned->len, ofi);
253         fclose(ofi);
254         printf("dumped record\n");
255 #endif
256     }
257     else
258     {
259         printf("Unknown record representation.\n");
260         if (!odr_external(print, &r, 0))
261         {
262             odr_perror(print, "Printing external");
263             odr_reset(print);
264         }
265     }
266 #endif
267 }
268
269 static void display_diagrec(Z_DiagRec *p)
270 {
271     oident *ent;
272
273     printf("Diagnostic message from database.\n");
274     if (!(ent = oid_getentbyoid(p->diagnosticSetId)) ||
275         ent->class != CLASS_DIAGSET || ent->value != VAL_BIB1)
276         printf("Missing or unknown diagset\n");
277     printf("Error condition: %d", *p->condition);
278     printf(" -- %s\n", p->addinfo ? p->addinfo : "");
279 }
280
281 static void display_nameplusrecord(Z_NamePlusRecord *p)
282 {
283     if (p->databaseName)
284         printf("[%s]", p->databaseName);
285     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
286         display_diagrec(p->u.surrogateDiagnostic);
287     else
288         display_record(p->u.databaseRecord);
289 }
290
291 static void display_records(Z_Records *p)
292 {
293     int i;
294
295     if (p->which == Z_Records_NSD)
296         display_diagrec(p->u.nonSurrogateDiagnostic);
297     else
298     {
299         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
300         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
301             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
302     }
303 }
304
305 static int send_searchRequest(char *arg)
306 {
307     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
308     Z_SearchRequest *req = apdu->u.searchRequest;
309     char *databaseNames = database;
310     Z_Query query;
311 #ifdef RPN_QUERY
312 #ifndef PREFIX_QUERY
313     struct ccl_rpn_node *rpn;
314     int error, pos;
315 #endif
316 #endif
317     char setstring[100];
318 #ifdef RPN_QUERY
319     Z_RPNQuery *RPNquery;
320     oident bib1;
321 #else
322     Odr_oct ccl_query;
323 #endif
324
325 #ifdef RPN_QUERY
326 #ifndef PREFIX_QUERY
327     rpn = ccl_find_str(bibset, arg, &error, &pos);
328     if (error)
329     {
330         printf("CCL ERROR: %s\n", ccl_err_msg(error));
331         return 0;
332     }
333 #endif
334 #endif
335
336     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
337     {
338         static unsigned char big[2100];
339         static Odr_oct bigo;
340
341         /* send a very big referenceid to test transport stack etc. */
342         memset(big, 'A', 2100);
343         bigo.len = bigo.size = 2100;
344         bigo.buf = big;
345         req->referenceId = &bigo;
346     }
347
348     if (setnumber >= 0)
349     {
350         sprintf(setstring, "%d", ++setnumber);
351         req->resultSetName = setstring;
352     }
353     *req->smallSetUpperBound = smallSetUpperBound;
354     *req->largeSetLowerBound = largeSetLowerBound;
355     *req->mediumSetPresentNumber = mediumSetPresentNumber;
356     req->num_databaseNames = 1;
357     req->databaseNames = &databaseNames;
358
359     req->query = &query;
360
361 #ifdef RPN_QUERY
362     query.which = Z_Query_type_1;
363
364 #ifndef PREFIX_QUERY
365     assert((RPNquery = ccl_rpn_query(rpn)));
366 #else
367     RPNquery = p_query_rpn (out, arg);
368     if (!RPNquery)
369     {
370         printf("Prefix query error\n");
371         return 0;
372     }
373 #endif
374     bib1.proto = protocol;
375     bib1.class = CLASS_ATTSET;
376     bib1.value = VAL_BIB1;
377     RPNquery->attributeSetId = oid_getoidbyent(&bib1);
378     query.u.type_1 = RPNquery;
379 #else
380     query.which = Z_Query_type_2;
381     query.u.type_2 = &ccl_query;
382     ccl_query.buf = (unsigned char*) arg;
383     ccl_query.len = strlen(arg);
384 #endif
385
386     send_apdu(apdu);
387     setno = 1;
388     printf("Sent searchRequest.\n");
389     return 2;
390 }
391
392 static int process_searchResponse(Z_SearchResponse *res)
393 {
394     if (res->searchStatus)
395         printf("Search was a success.\n");
396     else
397         printf("Search was a bloomin' failure.\n");
398     printf("Number of hits: %d, setno %d\n",
399         *res->resultCount, setnumber);
400     printf("records returned: %d\n",
401         *res->numberOfRecordsReturned);
402     setno += *res->numberOfRecordsReturned;
403     if (res->records)
404         display_records(res->records);
405     return 0;
406 }
407
408 static int cmd_find(char *arg)
409 {
410     if (!*arg)
411     {
412         printf("Find what?\n");
413         return 0;
414     }
415     if (!conn)
416     {
417         printf("Not connected yet\n");
418         return 0;
419     }
420     if (!send_searchRequest(arg))
421         return 0;
422     return 2;
423 }
424
425 static int cmd_ssub(char *arg)
426 {
427     if (!(smallSetUpperBound = atoi(arg)))
428         return 0;
429     return 1;
430 }
431
432 static int cmd_lslb(char *arg)
433 {
434     if (!(largeSetLowerBound = atoi(arg)))
435         return 0;
436     return 1;
437 }
438
439 static int cmd_mspn(char *arg)
440 {
441     if (!(mediumSetPresentNumber = atoi(arg)))
442         return 0;
443     return 1;
444 }
445
446 static int cmd_status(char *arg)
447 {
448     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
449     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
450     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
451     return 1;
452 }
453
454 static int cmd_base(char *arg)
455 {
456     if (!*arg)
457     {
458         printf("Usage: base <database>\n");
459         return 0;
460     }
461     strcpy(database, arg);
462     return 1;
463 }
464
465 static int cmd_setnames(char *arg)
466 {
467     if (setnumber < 0)
468     {
469         printf("Set numbering enabled.\n");
470         setnumber = 0;
471     }
472     else
473     {
474         printf("Set numbering disabled.\n");
475         setnumber = -1;
476     }
477     return 1;
478 }
479
480 /* PRESENT SERVICE ----------------------------- */
481
482 static int send_presentRequest(char *arg)
483 {
484     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
485     Z_PresentRequest *req = apdu->u.presentRequest;
486     int nos = 1;
487     char *p;
488     char setstring[100];
489
490     if ((p = strchr(arg, '+')))
491     {
492         nos = atoi(p + 1);
493         *p = 0;
494     }
495     if (*arg)
496         setno = atoi(arg);
497
498     if (setnumber >= 0)
499     {
500         sprintf(setstring, "%d", setnumber);
501         req->resultSetId = setstring;
502     }
503     req->resultSetStartPoint = &setno;
504     req->numberOfRecordsRequested = &nos;
505     send_apdu(apdu);
506     printf("Sent presentRequest (%d+%d).\n", setno, nos);
507     return 2;
508 }
509
510 static int cmd_show(char *arg)
511 {
512     if (!send_presentRequest(arg))
513         return 0;
514     return 2;
515 }
516
517 int cmd_quit(char *arg)
518 {
519     printf("See you later, alligator.\n");
520     exit(0);
521 }
522
523 static void initialize(void)
524 {
525 #ifdef RPN_QUERY
526 #ifndef PREFIX_QUERY
527     FILE *inf;
528 #endif
529 #endif
530
531     if (!(out = odr_createmem(ODR_ENCODE)) ||
532         !(in = odr_createmem(ODR_DECODE)) ||
533         !(print = odr_createmem(ODR_PRINT)))
534     {
535         fprintf(stderr, "failed to allocate ODR streams\n");
536         exit(1);
537     }
538     setvbuf(stdout, 0, _IONBF, 0);
539
540 #ifdef RPN_QUERY
541 #ifndef PREFIX_QUERY
542     bibset = ccl_qual_mk (); 
543     inf = fopen ("default.bib", "r");
544     if (inf)
545     {
546         ccl_qual_file (bibset, inf);
547         fclose (inf);
548     }
549 #endif
550 #endif
551 }
552
553 static int client(void)
554 {
555     static struct {
556         char *cmd;
557         int (*fun)(char *arg);
558         char *ad;
559     } cmd[] = {
560         {"open", cmd_open, "('tcp'|'osi')':'[<TSEL>'/']<HOST>[':'<PORT>]"},
561         {"quit", cmd_quit, ""},
562         {"find", cmd_find, "<CCL-QUERY>"},
563         {"base", cmd_base, "<BASE-NAME>"},
564         {"show", cmd_show, "<REC#>['+'<#RECS>]"},
565         {"authentication", cmd_authentication, "<ACCTSTRING>"},
566         {"lslb", cmd_lslb, "<largeSetLowerBound>"},
567         {"ssub", cmd_ssub, "<smallSetUpperBound>"},
568         {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
569         {"status", cmd_status, ""},
570         {"setnames", cmd_setnames, ""},
571         {0,0}
572     };
573     char *netbuffer= 0;
574     int netbufferlen = 0;
575     int i;
576     Z_APDU *apdu;
577
578     while (1)
579     {
580         int res;
581         fd_set input;
582         char line[1024], word[1024], arg[1024];
583
584         FD_ZERO(&input);
585         FD_SET(0, &input);
586         if (conn)
587             FD_SET(cs_fileno(conn), &input);
588         if ((res = select(20, &input, 0, 0, 0)) < 0)
589         {
590             perror("select");
591             exit(1);
592         }
593         if (!res)
594             continue;
595         if (FD_ISSET(0, &input))
596         {
597             /* quick & dirty way to get a command line. */
598             if (!gets(line))
599                 break;
600             if ((res = sscanf(line, "%s %[^;]", word, arg)) <= 0)
601             {
602                 printf(C_PROMPT);
603                 continue;
604             }
605             if (res == 1)
606                 *arg = 0;
607             for (i = 0; cmd[i].cmd; i++)
608                 if (!strncmp(cmd[i].cmd, word, strlen(word)))
609                 {
610                     res = (*cmd[i].fun)(arg);
611                     break;
612                 }
613             if (!cmd[i].cmd) /* dump our help-screen */
614             {
615                 printf("Unknown command: %s.\n", word);
616                 printf("Currently recognized commands:\n");
617                 for (i = 0; cmd[i].cmd; i++)
618                     printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
619                 res = 1;
620             }
621             if (res < 2)
622                 printf(C_PROMPT);
623         }
624         if (conn && FD_ISSET(cs_fileno(conn), &input))
625         {
626             do
627             {
628                 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
629                 {
630                     perror("cs_get");
631                     exit(1);
632                 }
633                 if (!res)
634                 {
635                     printf("Target closed connection.\n");
636                     exit(1);
637                 }
638                 odr_reset(in); /* release APDU from last round */
639                 odr_setbuf(in, netbuffer, res, 0);
640                 if (!z_APDU(in, &apdu, 0))
641                 {
642                     odr_perror(in, "Decoding incoming APDU");
643                     exit(1);
644                 }
645 #if 0
646                 if (!z_APDU(print, &apdu, 0))
647                 {
648                     odr_perror(print, "Failed to print incoming APDU");
649                     odr_reset(print);
650                     continue;
651                 }
652 #endif
653                 switch(apdu->which)
654                 {
655                     case Z_APDU_initResponse:
656                         process_initResponse(apdu->u.initResponse);
657                         break;
658                     case Z_APDU_searchResponse:
659                         process_searchResponse(apdu->u.searchResponse);
660                         break;
661                     case Z_APDU_presentResponse:
662                         printf("Received presentResponse.\n");
663                         setno +=
664                             *apdu->u.presentResponse->numberOfRecordsReturned;
665                         if (apdu->u.presentResponse->records)
666                             display_records(apdu->u.presentResponse->records);
667                         else
668                             printf("No records.\n");
669                         break;
670                     default:
671                         printf("Received unknown APDU type (%d).\n", 
672                             apdu->which);
673                         exit(1);
674                 }
675                 printf("Z> ");
676                 fflush(stdout);
677             }
678             while (cs_more(conn));
679         }
680     }
681     return 0;
682 }
683
684 int main(int argc, char **argv)
685 {
686     initialize();
687     if (argc > 1)
688         cmd_open(argv[1]);
689     else
690         printf(C_PROMPT);
691     return client();
692 }