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