Attempted to encode the oclc-specific login info.
[yaz-moved-to-github.git] / util / yaz-illclient.c
1 /*
2  * Copyright (C) 1995-2006, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: yaz-illclient.c,v 1.2 2007-04-17 13:23:02 heikki Exp $
6  */
7
8 /* NOTE - This is work in progress - not at all ready */
9
10 /** \file yaz-illclient.c
11  *  \brief client for ILL requests (ISO 10161-1)
12  *
13  *  This is a test client for handling ISO 10161-1 ILL requests.
14  *  Those are not directly Z39.50, but the protocol is quite similar
15  *  and yaz already provides the APDUS for it.
16  *
17  *  This is not an interactive client like yaz-client, but driven by command-
18  *  line arguments. Its output is a return code, and possibly some text on 
19  *  stdout.
20  *
21  *  Exit codes  (note, the program exits as soon as it finds a good reason)
22  *     0   ok
23  *     1   errors in arguments
24  *     2   Internal errors in creating objects (comstack, odr...)
25  *         mostly programming errors.
26  *     3   could not connect
27  *     4   could not send request
28  *     5   No reponse received
29  *     6   Error decoding response packet
30  *     7   Server returned an error (see log or stdout)
31  *
32  *
33  *
34  *
35  */
36
37 #include <stdlib.h>
38 #include <stdio.h>
39
40 #if HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43 #if HAVE_SYS_STAT_H
44 #include <sys/stat.h>
45 #endif
46 #if HAVE_SYS_TIME_H
47 #include <sys/time.h>
48 #endif
49
50
51 #include <yaz/yaz-util.h>
52 #include <yaz/proto.h>
53 #include <yaz/comstack.h>
54 #include <yaz/tcpip.h>
55 #include <yaz/unix.h>
56 #include <yaz/odr.h>
57 #include <yaz/log.h>
58 #include <yaz/ill.h>
59
60 /* A structure for storing all the arguments */
61 struct prog_args {
62     char *host;
63     char *auth_userid;
64     char *auth_passwd;
65 } ;
66
67
68 /* Call-back to be called for every field in the ill-request */
69 /* It can set values to any field, perhaps from the prog_args */
70 const char *get_ill_element(void *clientData, const char *element) {
71     struct prog_args *args = clientData;
72     char *ret=0;
73     if (!strcmp(element,"foo")) {
74         ret=args->host;
75     } else if (!strcmp(element,"ill,protocol-version-num")) {
76         ret="2";
77     } else if (!strcmp(element,"ill,transaction-id,initial-requester-id,person-or-institution-symbol,institution")) {
78         ret="IndexData";
79     } 
80     yaz_log(YLOG_DEBUG,"get_ill_element: '%s' -> '%s' ", element, ret );
81     return ret;
82 }
83
84
85 /* * * * * * * * * * * * * * * * * */
86 /** \brief  Parse program arguments */
87 void parseargs( int argc, char * argv[],  struct prog_args *args) {
88     int ret;
89     char *arg;
90     char *prog=*argv;
91     char *version="$Id: yaz-illclient.c,v 1.2 2007-04-17 13:23:02 heikki Exp $"; /* from cvs */
92
93     /* default values */
94     args->host = 0; /* not known (yet) */
95 #if 0    
96     args->auth_userid = "100-228-301" ; /* FIXME - get from cmd line */
97     args->auth_passwd = "dxg5magxc" ;   /* FIXME - get from cmd line */
98 #else
99     args->auth_userid = "100070049" ; /* FIXME - get from cmd line */
100     args->auth_passwd = "cowgirl" ;   /* FIXME - get from cmd line */
101 #endif
102
103
104     while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
105     {
106         switch (ret)
107         {
108         case 0:
109             if (!args->host)
110             {
111                 args->host = xstrdup (arg);
112             }
113             else
114             {
115                 fprintf(stderr, "%s: Specify most one server address\n",
116                         prog);
117                 exit(1);
118             }
119             break;
120         case 'v':
121             yaz_log_init(yaz_log_mask_str(arg), "", 0);
122             break;
123         case 'V':
124             printf("%s %s",prog, version );
125             break;
126         default:
127             fprintf (stderr, "Usage: %s "
128                      " [-v loglevel...]"
129                      " [-V]"
130                      " <server-addr>\n",
131                      prog);
132             exit (1);
133         }
134     }
135 } /* parseargs */
136
137 /* * * * * * * * * * * */
138 /** \brief  Validate the arguments make sense */
139 void validateargs( struct prog_args *args) {
140     if (!args->host) {
141         fprintf(stderr, "Specify a connection address, "
142                         "as in 'bagel.indexdata.dk:210' \n");
143         exit(1);
144     }
145 } /* validateargs */
146
147
148 /* * * * * * * * * * * * * * * */
149 /** \brief  Connect to the target */
150 COMSTACK connect_to( char *hostaddr ){
151     COMSTACK stack;
152     void *server_address_ip;
153     int status;
154
155     yaz_log(YLOG_DEBUG,"Connecting to '%s'", hostaddr);
156     stack = cs_create_host(hostaddr, 1, &server_address_ip );
157     if (!stack) {
158         yaz_log(YLOG_FATAL,"Error in creating the comstack '%s' ",
159                  hostaddr );
160         exit(2);
161     }
162     
163     yaz_log(YLOG_DEBUG,"Created stack ok ");
164
165     status = cs_connect(stack, server_address_ip);
166     if (status != 0) {
167         yaz_log(YLOG_FATAL|YLOG_ERRNO,"Can not connect '%s' ",
168                  hostaddr );
169         exit(3);
170     }
171     yaz_log(YLOG_DEBUG,"Connected OK to '%s'", hostaddr);
172     return stack;
173 }
174
175
176 /* * * * * * * * * * * * * * * */
177 /* Makes a Z39.50-like prompt package with username and password */
178 Z_PromptObject1 *makeprompt(struct prog_args *args, ODR odr) {
179     Z_PromptObject1 *p = odr_malloc(odr, sizeof(*p) );
180     p->which=Z_PromptObject1_response;
181     p->u.response = odr_malloc(odr, sizeof(*(p->u.response)) );
182     p->u.response->num=2;
183     p->u.response->elements=odr_malloc(odr, 
184              p->u.response->num*sizeof(*(p->u.response->elements)) );
185     /* user id, aka "oclc authorization number" */
186     Z_ResponseUnit1 *ru = odr_malloc(odr, sizeof(*ru) );
187     p->u.response->elements[0] = ru;
188     ru->promptId = odr_malloc(odr, sizeof(*(ru->promptId) ));
189     ru->promptId->which = Z_PromptId_enumeratedPrompt;
190     ru->promptId->u.enumeratedPrompt =  
191         odr_malloc(odr, sizeof(*(ru->promptId->u.enumeratedPrompt) ));
192     ru->promptId->u.enumeratedPrompt->type = 
193          odr_intdup(odr,Z_PromptIdEnumeratedPrompt_userId);
194     ru->promptId->u.enumeratedPrompt->suggestedString = 0 ;
195     ru->which = Z_ResponseUnit1_string ;
196     ru->u.string = odr_strdup(odr, args->auth_userid);
197     /* password */
198     ru = odr_malloc(odr, sizeof(*ru) );
199     p->u.response->elements[1] = ru;
200     ru->promptId = odr_malloc(odr, sizeof(*(ru->promptId) ));
201     ru->promptId->which = Z_PromptId_enumeratedPrompt;
202     ru->promptId->u.enumeratedPrompt =  
203         odr_malloc(odr, sizeof(*(ru->promptId->u.enumeratedPrompt) ));
204     ru->promptId->u.enumeratedPrompt->type = 
205          odr_intdup(odr,Z_PromptIdEnumeratedPrompt_password);
206     ru->promptId->u.enumeratedPrompt->suggestedString = 0 ;
207     ru->which = Z_ResponseUnit1_string ;
208     ru->u.string = odr_strdup(odr, args->auth_passwd);
209     return p;
210 } /* makeprompt */
211
212 ILL_Extension *makepromptextension(struct prog_args *args, ODR odr) {
213     ODR odr_ext = odr_createmem(ODR_ENCODE);
214     ODR odr_prt = odr_createmem(ODR_PRINT);
215     ILL_Extension *e = odr_malloc(odr, sizeof(*e));
216     Z_PromptObject1 *p = makeprompt(args,odr_ext);
217     char * buf;
218     int siz;
219     Z_External *ext = odr_malloc(odr, sizeof(*ext));
220     ext->direct_reference = odr_getoidbystr(odr,"1.2.840.10003.8.1");
221     ext->indirect_reference=0;
222     ext->descriptor=0;
223     ext->which=Z_External_single;
224     if ( ! z_PromptObject1(odr_ext, &p, 0,0 ) ) {
225         yaz_log(YLOG_FATAL,"Encoding of z_PromptObject1 failed ");
226         exit (6);
227     }
228     
229     z_PromptObject1(odr_prt, &p, 0,0 ); /*!*/
230
231     buf= odr_getbuf(odr_ext,&siz,0);
232     ext->u.single_ASN1_type=odr_malloc(odr,sizeof(*ext->u.single_ASN1_type));
233     ext->u.single_ASN1_type->buf= odr_malloc(odr, siz);
234     memcpy(ext->u.single_ASN1_type->buf,buf, siz );
235     ext->u.single_ASN1_type->len = ext->u.single_ASN1_type->size = siz;
236     odr_reset(odr_ext);
237
238     e->identifier = odr_intdup(odr,1);
239     e->critical = odr_intdup(odr,0);
240     e->item=odr_malloc(odr,sizeof(*e->item));
241     if ( ! z_External(odr_ext, &ext,0,0) ) {
242         yaz_log(YLOG_FATAL,"Encoding of z_External failed ");
243         exit (6);
244     }
245     buf= odr_getbuf(odr_ext,&siz,0); 
246     e->item->buf= odr_malloc(odr, siz);
247     memcpy(e->item->buf,buf, siz );
248     e->item->len = e->item->size = siz;
249
250     return e;
251 } /* makepromptextension */
252
253 ILL_APDU *createrequest( struct prog_args *args, ODR odr) {
254     struct ill_get_ctl ctl;
255     ILL_APDU *apdu;
256     ILL_Request *req;
257
258     ctl.odr = odr;
259     ctl.clientData = & args;
260     ctl.f = get_ill_element;
261     apdu = odr_malloc( odr, sizeof(*apdu) );
262     apdu->which=ILL_APDU_ILL_Request;
263     req = ill_get_ILLRequest(&ctl, "ill", 0);
264     apdu->u.illRequest=req;
265     req->num_iLL_request_extensions=1;
266     req->iLL_request_extensions=
267         odr_malloc(odr, req->num_iLL_request_extensions*sizeof(*req->iLL_request_extensions));
268     req->iLL_request_extensions[0]=makepromptextension(args,odr);
269     if (!req) {
270         yaz_log(YLOG_FATAL,"Could not create ill request");
271         exit(2);
272     }
273     return apdu;
274 } /* createrequest */
275
276
277 /* * * * * * * * * * * * * * * */
278 /** \brief Send the request */
279 void sendrequest(ILL_APDU *apdu, ODR odr, COMSTACK stack ) {
280     char *buf_out;
281     int len_out;
282     int res;
283     if (!ill_APDU  (odr, &apdu, 0, 0)) { 
284         yaz_log(YLOG_FATAL,"ill_Apdu failed");
285         exit(2);
286     }
287     buf_out = odr_getbuf(odr, &len_out, 0);
288     if (0) {
289         yaz_log(YLOG_DEBUG,"Request PDU Dump");
290         odr_dumpBER(yaz_log_file(), buf_out, len_out);
291     }
292     if (!buf_out) {
293         yaz_log(YLOG_FATAL,"Encoding failed. Len=%d", len_out);
294         odr_perror(odr, "encoding failed");
295         exit(2);
296     }
297     yaz_log(YLOG_DEBUG,"About to send the request. Len=%d", len_out);
298     res = cs_put(stack, buf_out, len_out);
299     if ( res<0 ) {
300         yaz_log(YLOG_FATAL,"Could not send packet. code %d",res );
301         exit (4);
302     }
303 } /* sendrequest */
304
305 /* * * * * * * * * * * * * * * */
306 /** \brief  Get a response */
307 ILL_APDU *getresponse( COMSTACK stack, ODR in_odr ){
308     ILL_APDU *resp;
309     int res;
310     char *buf_in=0;
311     int len_in=0;
312     yaz_log(YLOG_DEBUG,"About to wait for a response");
313     res = cs_get(stack, &buf_in, &len_in);
314     yaz_log(YLOG_DEBUG,"Got a response of %d bytes at %x. res=%d", len_in,buf_in, res);
315     if (res<0) {
316         yaz_log(YLOG_FATAL,"Could not receive packet. code %d",res );
317         yaz_log(YLOG_DEBUG,"%02x %02x %02x %02x %02x %02x %02x %02x ...", 
318                 buf_in[0], buf_in[1], buf_in[2], buf_in[3],
319                 buf_in[4], buf_in[5], buf_in[6], buf_in[7]  );
320         yaz_log(YLOG_DEBUG,"PDU Dump:");
321         odr_dumpBER(yaz_log_file(), buf_in, len_in);
322         exit (5);
323     }
324     odr_setbuf(in_odr, buf_in, res, 0);
325     if (!ill_APDU (in_odr, &resp, 0, 0))
326     {
327         int x;
328         int err = odr_geterrorx(in_odr, &x);
329         char msg[60];
330         const char *element = odr_getelement(in_odr);
331         sprintf(msg, "ODR code %d:%d element=%-20s",
332                 err, x, element ? element : "<unknown>");
333         yaz_log(YLOG_FATAL,"Error decoding incoming packet: %s",msg);
334         yaz_log(YLOG_DEBUG,"%02x %02x %02x %02x %02x %02x %02x %02x ...", 
335                 buf_in[0], buf_in[1], buf_in[2], buf_in[3],
336                 buf_in[4], buf_in[5], buf_in[6], buf_in[7]  );
337         yaz_log(YLOG_DEBUG,"PDU Dump:");
338         odr_dumpBER(yaz_log_file(), buf_in, len_in);
339         yaz_log(YLOG_FATAL,"Error decoding incoming packet: %s",msg);
340         exit(6);
341     }
342     return resp;
343 } /* getresponse */
344
345
346 /** \brief Dump a apdu */
347 void dumpapdu( ILL_APDU *apdu) {
348     ODR print_odr = odr_createmem(ODR_PRINT);
349     ill_APDU (print_odr, &apdu, 0, 0);
350     odr_destroy(print_odr);
351 } /* dumpapdu */
352
353 /** \brief  Check apdu type and extract the status_or_error */
354 ILL_Status_Or_Error_Report *getstaterr( ILL_APDU *resp, ODR in_odr ) {
355     if (resp->which != ILL_APDU_Status_Or_Error_Report ) {
356         const char *element = odr_getelement(in_odr);
357         if (!element) 
358             element="unknown";
359         printf("Server returned wrong packet type: %d\n", resp->which);
360         yaz_log(YLOG_FATAL,"Server returned a (%d) and "
361                  "not a 'Status_Or_Error_Report' (%d) ",
362                  resp->which, ILL_APDU_Status_Or_Error_Report);
363         exit(6);
364     }
365     return resp->u.Status_Or_Error_Report;
366 } /* getstaterr */
367
368 /** \brief  Return a printable string from an ILL_String */
369 char *getillstring( ILL_String *s) {
370     if (s->which == ILL_String_GeneralString ) 
371         return s->u.GeneralString;
372     else if (s->which == ILL_String_EDIFACTString ) 
373         return s->u.EDIFACTString;
374     else {
375         yaz_log(YLOG_FATAL,"Invalid ILL_String ");
376         exit (6);
377     }
378 } /* getillstring */
379
380 /** \brief Check if the status was an error packet */
381 /* The presence of an error_report indicates it was an error */
382 /* Then the problem is to find the right message. We dig around */
383 /* until we find the first message, print that, and exit the program */
384 void checkerr( ILL_Status_Or_Error_Report *staterr ) {
385     yaz_log(YLOG_DEBUG, "err= %x ",staterr->error_report );
386     if (staterr->error_report) {
387         ILL_Error_Report *err= staterr->error_report;
388         if ( err->user_error_report) {
389             ILL_User_Error_Report *uerr= err->user_error_report;
390             switch( uerr->which ) {
391                 case ILL_User_Error_Report_already_forwarded:
392                     printf("Already forwarded: \n");
393                     break;
394                 case ILL_User_Error_Report_intermediary_problem:
395                     printf("Intermediary problem: %d\n", 
396                         uerr->u.intermediary_problem);
397                     break;
398                 case ILL_User_Error_Report_security_problem:
399                     printf("Security problem: %s\n", 
400                         getillstring(uerr->u.security_problem));
401                     break;
402                 case ILL_User_Error_Report_unable_to_perform:
403                     printf("Unable to perform: %d\n", 
404                           uerr->u.unable_to_perform);
405                     break;
406                 default:
407                     printf("Unknown problem");
408             }
409             exit(7);
410         }
411         if ( err->provider_error_report) {
412             ILL_Provider_Error_Report *perr= err->provider_error_report;
413             switch( perr->which ) {
414                 case ILL_Provider_Error_Report_general_problem:
415                     printf("General Problem: %d\n", 
416                           perr->u.general_problem);
417                     break;
418                 case ILL_Provider_Error_Report_transaction_id_problem:
419                     printf("Transaction Id Problem: %d\n", 
420                           perr->u.general_problem);
421                     break;
422                 case ILL_Provider_Error_Report_state_transition_prohibited:
423                     printf("State Transition prohibited \n");
424                     break;
425             }
426             exit(7);
427         } 
428         /* fallbacks */
429         if ( staterr->note ) 
430             printf("%s", getillstring(staterr->note));
431         else 
432             printf("Unknown error type");
433         exit(7);
434     }
435 } /* checkerr */
436
437
438
439 /* * * * * * * * * * * * * * * */
440
441 /** \brief Main program 
442  *
443  * Parse arguments
444  * Validate arguments
445  * Establish connection
446  * Build a request
447  * Send a request
448  * Get a reply
449  * Parse reply
450  * Produce output
451  */
452
453 int main (int argc, char * argv[]) {
454     struct prog_args args;
455     COMSTACK stack;
456     ODR out_odr = odr_createmem(ODR_ENCODE);
457     ODR in_odr = odr_createmem(ODR_DECODE);
458     ILL_APDU *apdu;
459     ILL_APDU *resp;
460     ILL_Status_Or_Error_Report *staterr;
461
462     parseargs( argc, argv,  &args);
463     validateargs(&args);
464     stack = connect_to(args.host);
465     apdu = createrequest(&args, out_odr);
466     if (1) 
467         dumpapdu(apdu);
468     sendrequest(apdu, out_odr, stack ); 
469     resp = getresponse(stack, in_odr );
470     if (1) 
471         dumpapdu(resp);
472     staterr=getstaterr(resp, in_odr);
473     checkerr(staterr);
474
475
476     printf ("Ok\n"); /* while debugging */
477     exit (0);
478 }
479
480 /*
481  * Local variables:
482  * c-basic-offset: 4
483  * indent-tabs-mode: nil
484  * End:
485  * vim: shiftwidth=4 tabstop=8 expandtab
486  */
487