8aeede66bb5a368355960f59ddc932b003aa9c59
[yaz-moved-to-github.git] / client / client.c
1 /*
2  * Copyright (c) 1995-2001, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Log: client.c,v $
6  * Revision 1.119  2001-04-05 13:08:48  adam
7  * New configure options: --enable-module.
8  *
9  * Revision 1.118  2001/03/27 14:48:06  adam
10  * Fixed scan for bad CCL.
11  *
12  * Revision 1.117  2001/03/25 21:55:12  adam
13  * Added odr_intdup. Ztest server returns TaskPackage for ItemUpdate.
14  *
15  * Revision 1.116  2001/03/21 12:43:36  adam
16  * Implemented cs_create_host. Better error reporting for SSL comstack.
17  *
18  * Revision 1.115  2001/03/13 18:10:58  adam
19  * Added option -c to set CCL config file.
20  *
21  * Revision 1.114  2001/02/21 13:46:53  adam
22  * C++ fixes.
23  *
24  * Revision 1.113  2001/02/21 09:41:15  adam
25  * Fixed problem with old codecs.
26  *
27  * Revision 1.112  2001/02/20 11:25:32  adam
28  * Added ill_get_APDU and ill_get_Cancel.
29  *
30  * Revision 1.111  2001/01/30 15:52:48  ja7
31  * added command for setting packageName in ES packages!
32  * command is named packagename default is NULL for server suplyed package name
33  *
34  * Revision 1.110  2001/01/29 11:19:05  adam
35  * Clients prints options in InitResponse.
36  *
37  * Revision 1.109  2001/01/22 10:41:47  adam
38  * Multiple attribute may be specified for sorging.
39  *
40  * Revision 1.108  2000/11/23 10:58:32  adam
41  * SSL comstack support. Separate POSIX thread support library.
42  *
43  * Revision 1.107  2000/11/16 13:11:07  adam
44  * Changed because ccl_rpn_query sets attribute set.
45  *
46  * Revision 1.106  2000/11/13 09:44:59  adam
47  * Work on SCAN: RPN2CCL conversion and proper "next" scan.
48  *
49  * Revision 1.105  2000/10/02 11:07:44  adam
50  * Added peer_name member for bend_init handler. Changed the YAZ
51  * client so that tcp: can be avoided in target spec.
52  *
53  * Revision 1.104  2000/09/04 08:58:15  adam
54  * Added prefix yaz_ for most logging utility functions.
55  *
56  * Revision 1.103  2000/08/10 08:41:26  adam
57  * Fixes for ILL.
58  *
59  * Revision 1.102  2000/05/18 11:57:04  adam
60  * Client display time elapsed.
61  *
62  * Revision 1.101  2000/04/05 07:39:54  adam
63  * Added shared library support (libtool).
64  *
65  * Revision 1.100  2000/03/20 19:29:59  adam
66  * Minor change.
67  *
68  * Revision 1.99  2000/03/20 19:06:25  adam
69  * Added Segment request for fronend server. Work on admin for client.
70  *
71  * Revision 1.98  2000/03/16 13:55:49  ian
72  * Added commands for sending shutdown and startup admin requests via the admin ES.
73  *
74  * Revision 1.97  2000/03/14 14:06:04  ian
75  * Minor change to order of debugging output for send_apdu,
76  * fixed encoding of admin request.
77  *
78  * Revision 1.96  2000/03/14 09:27:07  ian
79  * Added code to enable sending of admin extended service requests
80  *
81  * Revision 1.95  2000/02/28 11:20:05  adam
82  * Using autoconf. New definitions: YAZ_BEGIN_CDECL/YAZ_END_CDECL.
83  *
84  * Revision 1.94  2000/01/31 13:15:21  adam
85  * Removed uses of assert(3). Cleanup of ODR. CCL parser update so
86  * that some characters are not surrounded by spaces in resulting term.
87  * ILL-code updates.
88  *
89  * Revision 1.93  2000/01/15 09:39:50  adam
90  * Implemented ill_get_ILLRequest. More ILL testing for client.
91  *
92  * Revision 1.92  1999/12/21 16:24:48  adam
93  * More robust ISO2709 handling (in case of real bad formats).
94  *
95  * Revision 1.91  1999/12/16 23:36:19  adam
96  * Implemented ILL protocol. Minor updates ASN.1 compiler.
97  *
98  * Revision 1.90  1999/11/30 13:47:11  adam
99  * Improved installation. Moved header files to include/yaz.
100  *
101  * Revision 1.89  1999/11/04 14:58:44  adam
102  * Added status elements for backend delete result set handler.
103  * Updated delete result result set command for client.
104  *
105  * Revision 1.88  1999/10/11 10:00:29  adam
106  * Modified printing of records.
107  *
108  * Revision 1.87  1999/08/27 09:40:32  adam
109  * Renamed logf function to yaz_log. Removed VC++ project files.
110  *
111  * Revision 1.86  1999/07/06 12:13:35  adam
112  * Added "schema" command.
113  *
114  * Revision 1.85  1999/06/16 11:55:24  adam
115  * Added APDU log to client.
116  *
117  * Revision 1.84  1999/06/01 14:29:11  adam
118  * Work on Extended Services.
119  *
120  * Revision 1.83  1999/05/26 15:24:26  adam
121  * Fixed minor bugs regarding DB Update (introduced by previous commit).
122  *
123  * Revision 1.82  1999/05/26 13:49:12  adam
124  * DB Update implemented in client (very basic).
125  *
126  * Revision 1.81  1999/04/20 09:56:48  adam
127  * Added 'name' paramter to encoder/decoder routines (typedef Odr_fun).
128  * Modified all encoders/decoders to reflect this change.
129  *
130  * Revision 1.80  1999/03/31 11:18:24  adam
131  * Implemented odr_strdup. Added Reference ID to backend server API.
132  *
133  * Revision 1.79  1999/03/23 14:14:25  adam
134  * Yet another fix.
135  *
136  * Revision 1.78  1999/03/18 12:57:18  adam
137  * Minor fix.
138  *
139  * Revision 1.77  1999/03/11 15:26:51  adam
140  * Fixed bug (introduced by previous commit).
141  *
142  * Revision 1.76  1999/03/11 11:12:07  adam
143  * Added GNU readline support. HTML display in client.
144  *
145  * Revision 1.75  1999/02/01 15:37:32  adam
146  * Fixed minor bug introduced by previous commit.
147  *
148  * Revision 1.74  1999/02/01 15:35:21  adam
149  * Added XML display.
150  *
151  * Revision 1.73  1998/10/20 13:55:43  quinn
152  * Fixed Scan bug in asn and client
153  *
154  * Revision 1.72  1998/10/20 13:23:15  quinn
155  * changed preferred pos to 1
156  *
157  * Revision 1.71  1998/10/20 13:21:43  adam
158  * Fixed scan response handler.
159  *
160  * Revision 1.70  1998/09/22 09:40:37  adam
161  * Minor changes in sort spec.
162  *
163  * Revision 1.69  1998/08/19 16:10:06  adam
164  * Changed som member names of DeleteResultSetRequest/Response.
165  *
166  * Revision 1.68  1998/07/20 12:37:06  adam
167  * Added 'delete <resultset>' command. Changed open command so that
168  * it reconnects if already connected.
169  *
170  * Revision 1.67  1998/06/09 13:55:06  adam
171  * Minor changes.
172  *
173  * Revision 1.66  1998/05/18 13:06:53  adam
174  * Changed the way attribute sets are handled by the retriaval module.
175  * Extended Explain conversion / schema.
176  * Modified server and client to work with ASN.1 compiled protocol handlers.
177  *
178  * Revision 1.65  1998/03/31 15:13:19  adam
179  * Development towards compiled ASN.1.
180  *
181  * Revision 1.64  1998/03/31 11:07:44  adam
182  * Furhter work on UNIverse resource report.
183  * Added Extended Services handling in frontend server.
184  *
185  * Revision 1.63  1998/03/05 08:05:10  adam
186  * Added a few casts to make C++ happy.
187  *
188  * Revision 1.62  1998/02/11 11:53:33  adam
189  * Changed code so that it compiles as C++.
190  *
191  * Revision 1.61  1998/02/10 11:03:06  adam
192  * Implemented command refid. Client prints reference-ID's, when present,
193  * in responses.
194  *
195  * Revision 1.60  1998/01/29 14:08:52  adam
196  * Better sort diagnostics.
197  *
198  * Revision 1.59  1998/01/29 13:17:56  adam
199  * Added sort.
200  *
201  * Revision 1.58  1998/01/07 13:51:45  adam
202  * Minor change.
203  *
204  * Revision 1.57  1998/01/07 12:58:22  adam
205  * Using fgets instead of gets.
206  *
207  * Revision 1.56  1997/11/05 09:18:31  adam
208  * The client handles records with no associated syntax.
209  *
210  * Revision 1.55  1997/10/31 12:20:08  adam
211  * Improved memory debugging for xmalloc/nmem.c. References to NMEM
212  * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
213  * Bug fix: missing fclose in data1_read_espec1.
214  *
215  * Revision 1.54  1997/10/27 13:52:46  adam
216  * Header yaz-util includes all YAZ utility header files.
217  *
218  * Revision 1.53  1997/09/29 13:18:59  adam
219  * Added function, oid_ent_to_oid, to replace the function
220  * oid_getoidbyent, which is not thread safe.
221  *
222  * Revision 1.52  1997/09/29 07:20:31  adam
223  * Client code uses nmem_init.
224  *
225  * Revision 1.51  1997/09/26 09:41:55  adam
226  * Updated client to handle multiple diagnostics.
227  *
228  * Revision 1.50  1997/09/17 12:10:29  adam
229  * YAZ version 1.4.
230  *
231  * Revision 1.49  1997/09/04 13:45:17  adam
232  * Added UNImarc to list of available syntaxes.
233  *
234  * Revision 1.48  1997/09/01 08:48:44  adam
235  * New windows NT/95 port using MSV5.0. Only a few changes made
236  * to avoid warnings. Sub project created: client.dsp.
237  *
238  * Revision 1.47  1997/07/01 13:49:56  adam
239  * Take care of case when invalid target is specified on command line.
240  *
241  * Revision 1.46  1997/06/23 10:30:18  adam
242  * Added call to ccl_rpn_delete in search. Added ODR stream "out"
243  * as parameter to ccl_rpn_query to release RPN query.
244  *
245  * Revision 1.45  1997/05/14 06:53:29  adam
246  * C++ support.
247  *
248  * Revision 1.44  1997/05/05 11:20:35  adam
249  * Client uses "options" utility and marc dump filename may be specified
250  * as an option (-m <file>).
251  *
252  * Revision 1.43  1996/11/08 11:03:26  adam
253  * Client accepts multiple database names.
254  *
255  * Revision 1.42  1996/10/08 10:44:57  quinn
256  * Resolved conflicts.
257  *
258  * Revision 1.41  1996/10/07  15:29:03  quinn
259  * Work
260  *
261  * Revision 1.40  1996/08/29  14:19:34  quinn
262  * Fixed conflict (CVS)
263  *
264  * Revision 1.39  1996/08/27  10:43:22  quinn
265  * Made select() optional
266  *
267  * Revision 1.38  1996/08/12  14:09:11  adam
268  * Default prefix query attribute set defined by using p_query_attset.
269  *
270  * Revision 1.37  1996/07/06  19:58:29  quinn
271  * System headerfiles gathered in yconfig
272  *
273  * Revision 1.36  1996/06/10  08:53:47  quinn
274  * Added Summary
275  *
276  * Revision 1.35  1996/06/03  09:45:50  quinn
277  * Added display of OIDs in the GRS routine.
278  *
279  * Revision 1.34  1996/05/09  07:26:49  quinn
280  * *** empty log message ***
281  *
282  * Revision 1.33  1996/05/09  07:25:22  quinn
283  * Small
284  *
285  * Revision 1.32  1996/03/15  11:05:33  adam
286  * The user can set the preferred query type (prefix, ccl, ..) with the
287  * querytype command.
288  *
289  * Revision 1.31  1996/02/20  12:51:54  quinn
290  * Fixed problems with EXTERNAL.
291  *
292  * Revision 1.30  1996/02/12  18:18:09  quinn
293  * Fidgeting.
294  *
295  * Revision 1.29  1996/01/02  08:57:25  quinn
296  * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
297  *
298  * Revision 1.28  1995/12/14  11:09:31  quinn
299  * Added Explain record syntax to the format command.
300  *
301  * Revision 1.27  1995/12/12  16:37:02  quinn
302  * Added destroy element to data1_node.
303  *
304  * Revision 1.26  1995/12/12  14:11:00  quinn
305  * Minimal.
306  *
307  * Revision 1.25  1995/11/13  09:27:22  quinn
308  * Fiddling with the variant stuff.
309  *
310  * Revision 1.24  1995/10/30  12:41:13  quinn
311  * Added hostname lookup for server.
312  *
313  * Revision 1.23  1995/10/18  16:12:30  quinn
314  * Better diagnostics.
315  *
316  * Revision 1.22  1995/10/11  14:49:12  quinn
317  * Smallish.
318  *
319  * Revision 1.21  1995/09/29  17:01:47  quinn
320  * More Windows work
321  *
322  * Revision 1.20  1995/08/29  14:24:13  quinn
323  * Added second half of close-handshake
324  *
325  * Revision 1.19  1995/08/29  11:17:28  quinn
326  * Added code to receive close
327  *
328  * Revision 1.18  1995/08/28  12:21:27  quinn
329  * Client can now ask for simple element set names.
330  *
331  * Revision 1.17  1995/08/17  12:45:02  quinn
332  * Fixed minor problems with GRS-1. Added support in c&s.
333  *
334  * Revision 1.16  1995/08/15  12:00:04  quinn
335  * Updated External
336  *
337  * Revision 1.15  1995/06/22  09:28:03  quinn
338  * Fixed bug in SUTRS processing.
339  *
340  * Revision 1.14  1995/06/19  12:37:41  quinn
341  * Added BER dumper.
342  *
343  * Revision 1.13  1995/06/16  10:29:11  quinn
344  * *** empty log message ***
345  *
346  * Revision 1.12  1995/06/15  07:44:57  quinn
347  * Moving to v3.
348  *
349  * Revision 1.11  1995/06/14  15:26:40  quinn
350  * *** empty log message ***
351  *
352  * Revision 1.10  1995/06/06  14:56:58  quinn
353  * Better diagnostics.
354  *
355  * Revision 1.9  1995/06/06  08:15:19  quinn
356  * Cosmetic.
357  *
358  * Revision 1.8  1995/06/05  10:52:22  quinn
359  * Added SCAN.
360  *
361  * Revision 1.7  1995/06/02  09:50:09  quinn
362  * Smallish.
363  *
364  * Revision 1.6  1995/05/31  08:29:21  quinn
365  * Nothing significant.
366  *
367  * Revision 1.5  1995/05/29  08:10:47  quinn
368  * Moved oid.c to util.
369  *
370  * Revision 1.4  1995/05/22  15:30:13  adam
371  * Client uses prefix query notation.
372  *
373  * Revision 1.3  1995/05/22  15:06:53  quinn
374  * *** empty log message ***
375  *
376  * Revision 1.2  1995/05/22  14:56:40  quinn
377  * *** empty log message ***
378  *
379  * Revision 1.1  1995/05/22  11:30:31  quinn
380  * Added prettier client.
381  *
382  *
383  */
384
385 /*
386  * This is the obligatory little toy client, whose primary purpose is
387  * to illustrate the use of the YAZ service-level API.
388  */
389
390 #include <stdio.h>
391 #include <stdlib.h>
392 #include <time.h>
393
394 #include <yaz/yaz-util.h>
395
396 #include <yaz/tcpip.h>
397 #ifdef USE_XTIMOSI
398 #include <yaz/xmosi.h>
399 #endif
400
401 #include <yaz/proto.h>
402 #include <yaz/marcdisp.h>
403 #include <yaz/diagbib1.h>
404
405 #include <yaz/pquery.h>
406
407 #if YAZ_MODULE_ill
408 #include <yaz/ill.h>
409 #endif
410
411 #if CCL2RPN
412 #include <yaz/yaz-ccl.h>
413 #endif
414
415 #if HAVE_READLINE_READLINE_H
416 #include <readline/readline.h>
417 #endif
418 #if HAVE_READLINE_HISTORY_H
419 #include <readline/history.h>
420 #endif
421
422 #include "admin.h"
423
424 #define C_PROMPT "Z> "
425
426 static ODR out, in, print;              /* encoding and decoding streams */
427 static FILE *apdu_file = 0;
428 static COMSTACK conn = 0;               /* our z-association */
429 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
430 char *databaseNames[128];
431 int num_databaseNames = 0;
432 static Z_External *record_last = 0;
433 static int setnumber = 0;               /* current result set number */
434 static int smallSetUpperBound = 0;
435 static int largeSetLowerBound = 1;
436 static int mediumSetPresentNumber = 0;
437 static Z_ElementSetNames *elementSetNames = 0; 
438 static int setno = 1;                   /* current set offset */
439 static enum oid_proto protocol = PROTO_Z3950;      /* current app protocol */
440 static enum oid_value recordsyntax = VAL_USMARC;
441 static enum oid_value schema = VAL_NONE;
442 static int sent_close = 0;
443 static NMEM session_mem = NULL;      /* memory handle for init-response */
444 static Z_InitResponse *session = 0;     /* session parameters */
445 static char last_scan_line[512] = "0";
446 static char last_scan_query[512] = "0";
447 static char ccl_fields[512] = "default.bib";
448 char* esPackageName = 0;
449
450 static char last_cmd[100] = "?";
451 static FILE *marcdump = 0;
452 static char *refid = NULL;
453
454 typedef enum {
455     QueryType_Prefix,
456     QueryType_CCL,
457     QueryType_CCL2RPN
458 } QueryType;
459
460 static QueryType queryType = QueryType_Prefix;
461
462 #if CCL2RPN
463 static CCL_bibset bibset;               /* CCL bibset handle */
464 #endif
465
466 ODR getODROutputStream()
467 {
468     return out;
469 }
470
471 void send_apdu(Z_APDU *a)
472 {
473     char *buf;
474     int len;
475
476     if (apdu_file)
477     {
478         z_APDU(print, &a, 0, 0);
479         odr_reset(print);
480     }
481     if (!z_APDU(out, &a, 0, 0))
482     {
483         odr_perror(out, "Encoding APDU");
484         exit(1);
485     }
486     buf = odr_getbuf(out, &len, 0);
487     /* printf ("sending APDU of size %d\n", len); */
488     if (cs_put(conn, buf, len) < 0)
489     {
490         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
491         exit(1);
492     }
493     odr_reset(out); /* release the APDU structure  */
494 }
495
496 static void print_refid (Z_ReferenceId *id)
497 {
498     if (id)
499     {
500         printf ("ReferenceId: '%.*s'\n", id->len, id->buf);
501     }
502 }
503
504 static Z_ReferenceId *set_refid (ODR out)
505 {
506     Z_ReferenceId *id;
507     if (!refid)
508         return 0;
509     id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
510     id->size = id->len = strlen(refid);
511     id->buf = (unsigned char *) odr_malloc (out, id->len);
512     memcpy (id->buf, refid, id->len);
513     return id;
514 }   
515
516 /* INIT SERVICE ------------------------------- */
517
518 static void send_initRequest()
519 {
520     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
521     Z_InitRequest *req = apdu->u.initRequest;
522
523     ODR_MASK_SET(req->options, Z_Options_search);
524     ODR_MASK_SET(req->options, Z_Options_present);
525     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
526     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
527     ODR_MASK_SET(req->options, Z_Options_scan);
528     ODR_MASK_SET(req->options, Z_Options_sort);
529     ODR_MASK_SET(req->options, Z_Options_extendedServices);
530     ODR_MASK_SET(req->options, Z_Options_delSet);
531
532     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
533     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
534     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
535
536     *req->maximumRecordSize = 1024*1024;
537     *req->preferredMessageSize = 1024*1024;
538
539     req->idAuthentication = auth;
540
541     send_apdu(apdu);
542     printf("Sent initrequest.\n");
543 }
544
545 static int process_initResponse(Z_InitResponse *res)
546 {
547     /* save session parameters for later use */
548     session_mem = odr_extract_mem(in);
549     session = res;
550
551     if (!*res->result)
552         printf("Connection rejected by target.\n");
553     else
554         printf("Connection accepted by target.\n");
555     if (res->implementationId)
556         printf("ID     : %s\n", res->implementationId);
557     if (res->implementationName)
558         printf("Name   : %s\n", res->implementationName);
559     if (res->implementationVersion)
560         printf("Version: %s\n", res->implementationVersion);
561     if (res->userInformationField)
562     {
563         printf("UserInformationfield:\n");
564         if (!z_External(print, (Z_External**)&res-> userInformationField,
565             0, 0))
566         {
567             odr_perror(print, "Printing userinfo\n");
568             odr_reset(print);
569         }
570         if (res->userInformationField->which == Z_External_octet)
571         {
572             printf("Guessing visiblestring:\n");
573             printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
574         }
575         odr_reset (print);
576     }
577     printf ("Options:");
578     if (ODR_MASK_GET(res->options, Z_Options_search))
579         printf (" search");
580     if (ODR_MASK_GET(res->options, Z_Options_present))
581         printf (" present");
582     if (ODR_MASK_GET(res->options, Z_Options_delSet))
583         printf (" delSet");
584     if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
585         printf (" resourceReport");
586     if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
587         printf (" resourceCtrl");
588     if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
589         printf (" accessCtrl");
590     if (ODR_MASK_GET(res->options, Z_Options_scan))
591         printf (" scan");
592     if (ODR_MASK_GET(res->options, Z_Options_sort))
593         printf (" sort");
594     if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
595         printf (" extendedServices");
596     if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
597         printf (" level1Segmentation");
598     if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
599         printf (" level2Segmentation");
600     if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
601         printf (" concurrentOperations");
602     if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
603         printf (" namedResultSets");
604     printf ("\n");
605     fflush (stdout);
606     return 0;
607 }
608
609 static int cmd_base(char *arg)
610 {
611     int i;
612     char *cp;
613
614     if (!*arg)
615     {
616         printf("Usage: base <database> <database> ...\n");
617         return 0;
618     }
619     for (i = 0; i<num_databaseNames; i++)
620         xfree (databaseNames[i]);
621     num_databaseNames = 0;
622     while (1)
623     {
624         if (!(cp = strchr(arg, ' ')))
625             cp = arg + strlen(arg);
626         if (cp - arg < 1)
627             break;
628         databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
629         memcpy (databaseNames[num_databaseNames], arg, cp - arg);
630         databaseNames[num_databaseNames++][cp - arg] = '\0';
631         if (!*cp)
632             break;
633         arg = cp+1;
634     }
635     return 1;
636 }
637
638
639 int cmd_open(char *arg)
640 {
641     void *add;
642     char type_and_host[101], base[101];
643     CS_TYPE t;
644
645     if (conn)
646     {
647         printf("Already connected.\n");
648
649         cs_close (conn);
650         conn = NULL;
651         if (session_mem)
652         {
653             nmem_destroy (session_mem);
654             session_mem = NULL;
655         }
656     }
657     t = tcpip_type;
658     base[0] = '\0';
659     if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
660         return 0;
661
662     conn = cs_create_host(type_and_host, 1, &add);
663     if (!conn)
664     {
665         printf ("Couldn't create comstack\n");
666         return 0;
667     }
668     printf("Connecting...");
669     fflush(stdout);
670     if (cs_connect(conn, add) < 0)
671     {
672         printf ("error = %s\n", cs_strerror(conn));
673         if (conn->cerrno == CSYSERR)
674             perror("system");
675         cs_close(conn);
676         conn = 0;
677         return 0;
678     }
679     printf("Ok.\n");
680     send_initRequest();
681     if (*base)
682         cmd_base (base);
683     return 2;
684 }
685
686 int cmd_authentication(char *arg)
687 {
688     static Z_IdAuthentication au;
689     static char open[256];
690
691     if (!*arg)
692     {
693         printf("Auth field set to null\n");
694         auth = 0;
695         return 1;
696     }
697     auth = &au;
698     au.which = Z_IdAuthentication_open;
699     au.u.open = open;
700     strcpy(open, arg);
701     return 1;
702 }
703
704 /* SEARCH SERVICE ------------------------------ */
705
706 static void display_variant(Z_Variant *v, int level)
707 {
708     int i;
709
710     for (i = 0; i < v->num_triples; i++)
711     {
712         printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
713             *v->triples[i]->type);
714         if (v->triples[i]->which == Z_Triple_internationalString)
715             printf(",value=%s\n", v->triples[i]->value.internationalString);
716         else
717             printf("\n");
718     }
719 }
720
721 static void display_grs1(Z_GenericRecord *r, int level)
722 {
723     int i;
724
725     if (!r)
726         return;
727     for (i = 0; i < r->num_elements; i++)
728     {
729         Z_TaggedElement *t;
730
731         printf("%*s", level * 4, "");
732         t = r->elements[i];
733         printf("(");
734         if (t->tagType)
735             printf("%d,", *t->tagType);
736         else
737             printf("?,");
738         if (t->tagValue->which == Z_StringOrNumeric_numeric)
739             printf("%d) ", *t->tagValue->u.numeric);
740         else
741             printf("%s) ", t->tagValue->u.string);
742         if (t->content->which == Z_ElementData_subtree)
743         {
744             printf("\n");
745             display_grs1(t->content->u.subtree, level+1);
746         }
747         else if (t->content->which == Z_ElementData_string)
748             printf("%s\n", t->content->u.string);
749         else if (t->content->which == Z_ElementData_numeric)
750             printf("%d\n", *t->content->u.numeric);
751         else if (t->content->which == Z_ElementData_oid)
752         {
753             int *ip = t->content->u.oid;
754             oident *oent;
755
756             if ((oent = oid_getentbyoid(t->content->u.oid)))
757                 printf("OID: %s\n", oent->desc);
758             else
759             {
760                 printf("{");
761                 while (ip && *ip >= 0)
762                     printf(" %d", *(ip++));
763                 printf(" }\n");
764             }
765         }
766         else if (t->content->which == Z_ElementData_noDataRequested)
767             printf("[No data requested]\n");
768         else if (t->content->which == Z_ElementData_elementEmpty)
769             printf("[Element empty]\n");
770         else if (t->content->which == Z_ElementData_elementNotThere)
771             printf("[Element not there]\n");
772         else
773             printf("??????\n");
774         if (t->appliedVariant)
775             display_variant(t->appliedVariant, level+1);
776         if (t->metaData && t->metaData->supportedVariants)
777         {
778             int c;
779
780             printf("%*s---- variant list\n", (level+1)*4, "");
781             for (c = 0; c < t->metaData->num_supportedVariants; c++)
782             {
783                 printf("%*svariant #%d\n", (level+1)*4, "", c);
784                 display_variant(t->metaData->supportedVariants[c], level + 2);
785             }
786         }
787     }
788 }
789
790 static void print_record(const unsigned char *buf, size_t len)
791 {
792    size_t i;
793    for (i = 0; i<len; i++)
794        if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
795            fputc (buf[i], stdout);
796        else
797            printf ("\\X%02X", buf[i]);
798    /* add newline if not already added ... */
799    if (i <= 0 || buf[i-1] != '\n')
800        fputc ('\n', stdout);
801 }
802
803 static void display_record(Z_DatabaseRecord *p)
804 {
805     Z_External *r = (Z_External*) p;
806     oident *ent = oid_getentbyoid(r->direct_reference);
807
808     record_last = r;
809     /*
810      * Tell the user what we got.
811      */
812     if (r->direct_reference)
813     {
814         printf("Record type: ");
815         if (ent)
816             printf("%s\n", ent->desc);
817         else if (!odr_oid(print, &r->direct_reference, 0, 0))
818         {
819             odr_perror(print, "print oid");
820             odr_reset(print);
821         }
822     }
823     /* Check if this is a known, ASN.1 type tucked away in an octet string */
824     if (ent && r->which == Z_External_octet)
825     {
826         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
827         void *rr;
828
829         if (type)
830         {
831             /*
832              * Call the given decoder to process the record.
833              */
834             odr_setbuf(in, (char*)p->u.octet_aligned->buf,
835                 p->u.octet_aligned->len, 0);
836             if (!(*type->fun)(in, (char **)&rr, 0, 0))
837             {
838                 odr_perror(in, "Decoding constructed record.");
839                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
840                 fprintf(stderr, "Packet dump:\n---------\n");
841                 odr_dumpBER(stderr, (char*)p->u.octet_aligned->buf,
842                     p->u.octet_aligned->len);
843                 fprintf(stderr, "---------\n");
844                 exit(1);
845             }
846             /*
847              * Note: we throw away the original, BER-encoded record here.
848              * Do something else with it if you want to keep it.
849              */
850             r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
851             r->which = type->what;
852         }
853     }
854     if (ent && ent->value == VAL_SOIF)
855         print_record((const unsigned char *) r->u.octet_aligned->buf, r->u.octet_aligned->len);
856     else if (r->which == Z_External_octet && p->u.octet_aligned->len)
857     {
858         const char *octet_buf = (char*)p->u.octet_aligned->buf;
859         if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
860             ent->value == VAL_HTML)
861             print_record((const unsigned char *) octet_buf,
862                          p->u.octet_aligned->len);
863         else
864         {
865             if (marc_display (octet_buf, NULL) <= 0)
866             {
867                 printf ("ISO2709 decoding failed, dumping record as is:\n");
868                 print_record((const unsigned char*) octet_buf,
869                               p->u.octet_aligned->len);
870             }
871         }
872         if (marcdump)
873             fwrite (octet_buf, 1, p->u.octet_aligned->len, marcdump);
874     }
875     else if (ent && ent->value == VAL_SUTRS)
876     {
877         if (r->which != Z_External_sutrs)
878         {
879             printf("Expecting single SUTRS type for SUTRS.\n");
880             return;
881         }
882         print_record(r->u.sutrs->buf, r->u.sutrs->len);
883     }
884     else if (ent && ent->value == VAL_GRS1)
885     {
886         if (r->which != Z_External_grs1)
887         {
888             printf("Expecting single GRS type for GRS.\n");
889             return;
890         }
891         display_grs1(r->u.grs1, 0);
892     }
893     else 
894     {
895         printf("Unknown record representation.\n");
896         if (!z_External(print, &r, 0, 0))
897         {
898             odr_perror(print, "Printing external");
899             odr_reset(print);
900         }
901     }
902 }
903
904
905 static void display_diagrecs(Z_DiagRec **pp, int num)
906 {
907     int i;
908     oident *ent;
909     Z_DefaultDiagFormat *r;
910
911     printf("Diagnostic message(s) from database:\n");
912     for (i = 0; i<num; i++)
913     {
914         Z_DiagRec *p = pp[i];
915         if (p->which != Z_DiagRec_defaultFormat)
916         {
917             printf("Diagnostic record not in default format.\n");
918             return;
919         }
920         else
921             r = p->u.defaultFormat;
922         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
923             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
924             printf("Missing or unknown diagset\n");
925         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
926 #ifdef ASN_COMPILED
927         switch (r->which)
928         {
929         case Z_DefaultDiagFormat_v2Addinfo:
930             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
931             break;
932         case Z_DefaultDiagFormat_v3Addinfo:
933             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
934             break;
935         }
936 #else
937         if (r->addinfo && *r->addinfo)
938             printf(" -- '%s'\n", r->addinfo);
939         else
940             printf("\n");
941 #endif
942     }
943 }
944
945
946 static void display_nameplusrecord(Z_NamePlusRecord *p)
947 {
948     if (p->databaseName)
949         printf("[%s]", p->databaseName);
950     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
951         display_diagrecs(&p->u.surrogateDiagnostic, 1);
952     else if (p->which == Z_NamePlusRecord_databaseRecord)
953         display_record(p->u.databaseRecord);
954 }
955
956 static void display_records(Z_Records *p)
957 {
958     int i;
959
960     if (p->which == Z_Records_NSD)
961     {
962 #ifdef ASN_COMPILED
963         Z_DiagRec dr, *dr_p = &dr;
964         dr.which = Z_DiagRec_defaultFormat;
965         dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
966         display_diagrecs (&dr_p, 1);
967 #else
968         display_diagrecs (&p->u.nonSurrogateDiagnostic, 1);
969 #endif
970     }
971     else if (p->which == Z_Records_multipleNSD)
972         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
973                           p->u.multipleNonSurDiagnostics->num_diagRecs);
974     else 
975     {
976         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
977         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
978             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
979     }
980 }
981
982 static int send_deleteResultSetRequest(char *arg)
983 {
984     char names[8][32];
985     int i;
986
987     Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
988     Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
989
990     req->referenceId = set_refid (out);
991
992     req->num_resultSetList =
993         sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
994                 names[0], names[1], names[2], names[3],
995                 names[4], names[5], names[6], names[7]);
996
997     req->deleteFunction = (int *)
998         odr_malloc (out, sizeof(*req->deleteFunction));
999     if (req->num_resultSetList > 0)
1000     {
1001         *req->deleteFunction = Z_DeleteRequest_list;
1002         req->resultSetList = (char **)
1003             odr_malloc (out, sizeof(*req->resultSetList)*
1004                         req->num_resultSetList);
1005         for (i = 0; i<req->num_resultSetList; i++)
1006             req->resultSetList[i] = names[i];
1007     }
1008     else
1009     {
1010         *req->deleteFunction = Z_DeleteRequest_all;
1011         req->resultSetList = 0;
1012     }
1013     
1014     send_apdu(apdu);
1015     printf("Sent deleteResultSetRequest.\n");
1016     return 2;
1017 }
1018
1019 static int send_searchRequest(char *arg)
1020 {
1021     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1022     Z_SearchRequest *req = apdu->u.searchRequest;
1023     Z_Query query;
1024     int oid[OID_SIZE];
1025 #if CCL2RPN
1026     struct ccl_rpn_node *rpn = NULL;
1027     int error, pos;
1028 #endif
1029     char setstring[100];
1030     Z_RPNQuery *RPNquery;
1031     Odr_oct ccl_query;
1032
1033 #if CCL2RPN
1034     if (queryType == QueryType_CCL2RPN)
1035     {
1036         rpn = ccl_find_str(bibset, arg, &error, &pos);
1037         if (error)
1038         {
1039             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1040             return 0;
1041         }
1042     }
1043 #endif
1044     req->referenceId = set_refid (out);
1045     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1046     {
1047         static unsigned char big[2100];
1048         static Odr_oct bigo;
1049
1050         /* send a very big referenceid to test transport stack etc. */
1051         memset(big, 'A', 2100);
1052         bigo.len = bigo.size = 2100;
1053         bigo.buf = big;
1054         req->referenceId = &bigo;
1055     }
1056     
1057     if (setnumber >= 0)
1058     {
1059         sprintf(setstring, "%d", ++setnumber);
1060         req->resultSetName = setstring;
1061     }
1062     *req->smallSetUpperBound = smallSetUpperBound;
1063     *req->largeSetLowerBound = largeSetLowerBound;
1064     *req->mediumSetPresentNumber = mediumSetPresentNumber;
1065     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1066         mediumSetPresentNumber > 0))
1067     {
1068         oident prefsyn;
1069
1070         prefsyn.proto = protocol;
1071         prefsyn.oclass = CLASS_RECSYN;
1072         prefsyn.value = recordsyntax;
1073         req->preferredRecordSyntax =
1074             odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1075         req->smallSetElementSetNames =
1076             req->mediumSetElementSetNames = elementSetNames;
1077     }
1078     req->num_databaseNames = num_databaseNames;
1079     req->databaseNames = databaseNames;
1080
1081     req->query = &query;
1082
1083     switch (queryType)
1084     {
1085     case QueryType_Prefix:
1086         query.which = Z_Query_type_1;
1087         RPNquery = p_query_rpn (out, protocol, arg);
1088         if (!RPNquery)
1089         {
1090             printf("Prefix query error\n");
1091             return 0;
1092         }
1093         query.u.type_1 = RPNquery;
1094         break;
1095     case QueryType_CCL:
1096         query.which = Z_Query_type_2;
1097         query.u.type_2 = &ccl_query;
1098         ccl_query.buf = (unsigned char*) arg;
1099         ccl_query.len = strlen(arg);
1100         break;
1101 #if CCL2RPN
1102     case QueryType_CCL2RPN:
1103         query.which = Z_Query_type_1;
1104         RPNquery = ccl_rpn_query(out, rpn);
1105         if (!RPNquery)
1106         {
1107             printf ("Couldn't convert from CCL to RPN\n");
1108             return 0;
1109         }
1110         query.u.type_1 = RPNquery;
1111         ccl_rpn_delete (rpn);
1112         break;
1113 #endif
1114     default:
1115         printf ("Unsupported query type\n");
1116         return 0;
1117     }
1118     send_apdu(apdu);
1119     setno = 1;
1120     printf("Sent searchRequest.\n");
1121     return 2;
1122 }
1123
1124 static int process_searchResponse(Z_SearchResponse *res)
1125 {
1126     printf ("Received SearchResponse.\n");
1127     print_refid (res->referenceId);
1128     if (*res->searchStatus)
1129         printf("Search was a success.\n");
1130     else
1131         printf("Search was a bloomin' failure.\n");
1132     printf("Number of hits: %d, setno %d\n",
1133         *res->resultCount, setnumber);
1134     printf("records returned: %d\n",
1135         *res->numberOfRecordsReturned);
1136     setno += *res->numberOfRecordsReturned;
1137     if (res->records)
1138         display_records(res->records);
1139     return 0;
1140 }
1141
1142 static void print_level(int iLevel)
1143 {
1144     int i;
1145     for (i = 0; i < iLevel * 4; i++)
1146         printf(" ");
1147 }
1148
1149 static void print_int(int iLevel, const char *pTag, int *pInt)
1150 {
1151     if (pInt != NULL)
1152     {
1153         print_level(iLevel);
1154         printf("%s: %d\n", pTag, *pInt);
1155     }
1156 }
1157
1158 static void print_string(int iLevel, const char *pTag, const char *pString)
1159 {
1160     if (pString != NULL)
1161     {
1162         print_level(iLevel);
1163         printf("%s: %s\n", pTag, pString);
1164     }
1165 }
1166
1167 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1168 {
1169     if (pOid != NULL)
1170     {
1171         int *pInt = pOid;
1172
1173         print_level(iLevel);
1174         printf("%s:", pTag);
1175         for (; *pInt != -1; pInt++)
1176             printf(" %d", *pInt);
1177         printf("\n");
1178     }
1179 }
1180
1181 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1182 {
1183     if (referenceId != NULL)
1184     {
1185         int i;
1186
1187         print_level(iLevel);
1188         printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1189         for (i = 0; i < referenceId->len; i++)
1190             printf("%c", referenceId->buf[i]);
1191         printf("\n");
1192     }
1193 }
1194
1195 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1196 {
1197     if (pStringNumeric != NULL)
1198     {
1199         switch (pStringNumeric->which)
1200         {
1201             case Z_StringOrNumeric_string:
1202                 print_string(iLevel, pTag, pStringNumeric->u.string);
1203                 break;
1204
1205             case Z_StringOrNumeric_numeric:
1206                 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1207                 break;
1208
1209             default:
1210                 print_level(iLevel);
1211                 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1212                 break;
1213         }
1214     }
1215 }
1216
1217 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1218 {
1219     if (pUniverseReportDuplicate != NULL)
1220     {
1221         print_level(iLevel);
1222         printf("Universe Report Duplicate: \n");
1223         iLevel++;
1224         print_string_or_numeric(iLevel, "Hit No", pUniverseReportDuplicate->hitno);
1225     }
1226 }
1227
1228 static void print_universe_report_hits(int iLevel, Z_UniverseReportHits *pUniverseReportHits)
1229 {
1230     if (pUniverseReportHits != NULL)
1231     {
1232         print_level(iLevel);
1233         printf("Universe Report Hits: \n");
1234         iLevel++;
1235         print_string_or_numeric(iLevel, "Database", pUniverseReportHits->database);
1236         print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1237     }
1238 }
1239
1240 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1241 {
1242     if (pUniverseReport != NULL)
1243     {
1244         print_level(iLevel);
1245         printf("Universe Report: \n");
1246         iLevel++;
1247         print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1248         switch (pUniverseReport->which)
1249         {
1250             case Z_UniverseReport_databaseHits:
1251                 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
1252                 break;
1253
1254             case Z_UniverseReport_duplicate:
1255                 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
1256                 break;
1257
1258             default:
1259                 print_level(iLevel);
1260                 printf("Type: %d\n", pUniverseReport->which);
1261                 break;
1262         }
1263     }
1264 }
1265
1266 static void print_external(int iLevel, Z_External *pExternal)
1267 {
1268     if (pExternal != NULL)
1269     {
1270         print_level(iLevel);
1271         printf("External: \n");
1272         iLevel++;
1273         print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1274         print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1275         print_string(iLevel, "Descriptor", pExternal->descriptor);
1276         switch (pExternal->which)
1277         {
1278             case Z_External_universeReport:
1279                 print_universe_report(iLevel, pExternal->u.universeReport);
1280                 break;
1281
1282             default:
1283                 print_level(iLevel);
1284                 printf("Type: %d\n", pExternal->which);
1285                 break;
1286         }
1287     }
1288 }
1289
1290 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1291 {
1292     printf ("Received ResourceControlRequest.\n");
1293     print_referenceId(1, req->referenceId);
1294     print_int(1, "Suspended Flag", req->suspendedFlag);
1295     print_int(1, "Partial Results Available", req->partialResultsAvailable);
1296     print_int(1, "Response Required", req->responseRequired);
1297     print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1298     print_external(1, req->resourceReport);
1299     return 0;
1300 }
1301
1302 void process_ESResponse(Z_ExtendedServicesResponse *res)
1303 {
1304     printf("process_ESResponse status=");
1305     switch (*res->operationStatus)
1306     {
1307     case Z_ExtendedServicesResponse_done:
1308         printf ("done\n");
1309         break;
1310     case Z_ExtendedServicesResponse_accepted:
1311         printf ("accepted\n");
1312         break;
1313     case Z_ExtendedServicesResponse_failure:
1314         printf ("failure\n");
1315         display_diagrecs(res->diagnostics, res->num_diagnostics);
1316         break;
1317     }
1318 }
1319
1320 #if YAZ_MODULE_ill
1321
1322 const char *get_ill_element (void *clientData, const char *element)
1323 {
1324     printf ("%s\n", element);
1325     return 0;
1326 }
1327
1328 static Z_External *create_external_itemRequest()
1329 {
1330     struct ill_get_ctl ctl;
1331     ILL_ItemRequest *req;
1332     Z_External *r = 0;
1333     int item_request_size = 0;
1334     char *item_request_buf = 0;
1335
1336     ctl.odr = out;
1337     ctl.clientData = 0;
1338     ctl.f = get_ill_element;
1339
1340     req = ill_get_ItemRequest(&ctl, "ill", 0);
1341     if (!req)
1342         printf ("ill_get_ItemRequest failed\n");
1343         
1344     if (!ill_ItemRequest (out, &req, 0, 0))
1345     {
1346         if (apdu_file)
1347         {
1348             ill_ItemRequest(print, &req, 0, 0);
1349             odr_reset(print);
1350         }
1351         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1352         if (item_request_buf)
1353             odr_setbuf (out, item_request_buf, item_request_size, 1);
1354         printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1355         return 0;
1356     }
1357     else
1358     {
1359         oident oid;
1360         
1361         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1362         oid.proto = PROTO_GENERAL;
1363         oid.oclass = CLASS_GENERAL;
1364         oid.value = VAL_ISO_ILL_1;
1365         
1366         r = (Z_External *) odr_malloc (out, sizeof(*r));
1367         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1368         r->indirect_reference = 0;
1369         r->descriptor = 0;
1370         r->which = Z_External_single;
1371         
1372         r->u.single_ASN1_type = (Odr_oct *)
1373             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1374         r->u.single_ASN1_type->buf = (unsigned char *)
1375             odr_malloc (out, item_request_size);
1376         r->u.single_ASN1_type->len = item_request_size;
1377         r->u.single_ASN1_type->size = item_request_size;
1378         memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1379                 item_request_size);
1380         printf ("len = %d\n", item_request_size);
1381     }
1382     return r;
1383 }
1384 #endif
1385
1386 #ifdef YAZ_MODULE_ill
1387 static Z_External *create_external_ILL_APDU(int which)
1388 {
1389     struct ill_get_ctl ctl;
1390     ILL_APDU *ill_apdu;
1391     Z_External *r = 0;
1392     int ill_request_size = 0;
1393     char *ill_request_buf = 0;
1394         
1395     ctl.odr = out;
1396     ctl.clientData = 0;
1397     ctl.f = get_ill_element;
1398
1399     ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1400
1401     if (!ill_APDU (out, &ill_apdu, 0, 0))
1402     {
1403         if (apdu_file)
1404         {
1405             printf ("-------------------\n");
1406             ill_APDU(print, &ill_apdu, 0, 0);
1407             odr_reset(print);
1408             printf ("-------------------\n");
1409         }
1410         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1411         if (ill_request_buf)
1412             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1413         printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1414         return 0;
1415     }
1416     else
1417     {
1418         oident oid;
1419         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1420         
1421         oid.proto = PROTO_GENERAL;
1422         oid.oclass = CLASS_GENERAL;
1423         oid.value = VAL_ISO_ILL_1;
1424         
1425         r = (Z_External *) odr_malloc (out, sizeof(*r));
1426         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1427         r->indirect_reference = 0;
1428         r->descriptor = 0;
1429         r->which = Z_External_single;
1430         
1431         r->u.single_ASN1_type = (Odr_oct *)
1432             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1433         r->u.single_ASN1_type->buf = (unsigned char *)
1434             odr_malloc (out, ill_request_size);
1435         r->u.single_ASN1_type->len = ill_request_size;
1436         r->u.single_ASN1_type->size = ill_request_size;
1437         memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1438         printf ("len = %d\n", ill_request_size);
1439     }
1440     return r;
1441 }
1442 #endif
1443
1444
1445 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1446 {
1447     Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1448     oident ItemOrderRequest;
1449   
1450     ItemOrderRequest.proto = PROTO_Z3950;
1451     ItemOrderRequest.oclass = CLASS_EXTSERV;
1452     ItemOrderRequest.value = VAL_ITEMORDER;
1453  
1454     r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest)); 
1455     r->indirect_reference = 0;
1456     r->descriptor = 0;
1457
1458     r->which = Z_External_itemOrder;
1459
1460     r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1461     memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1462 #ifdef ASN_COMPILED
1463     r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1464 #else
1465     r->u.itemOrder->which=Z_ItemOrder_esRequest;
1466 #endif
1467
1468     r->u.itemOrder->u.esRequest = (Z_IORequest *) 
1469         odr_malloc(out,sizeof(Z_IORequest));
1470     memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1471
1472     r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1473         odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1474     memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1475     r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1476         odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1477     memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1478
1479     r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1480     r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1481     r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1482
1483     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1484         (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1485     memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1486     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1487
1488     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1489         (int *) odr_malloc(out, sizeof(int));
1490     *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1491
1492 #if YAZ_MODULE_ill
1493     if (!strcmp (type, "item") || !strcmp(type, "2"))
1494     {
1495         printf ("using item-request\n");
1496         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1497             create_external_itemRequest();
1498     }
1499     else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1500     {
1501         printf ("using ILL-request\n");
1502         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1503             create_external_ILL_APDU(ILL_APDU_ILL_Request);
1504     }
1505     else
1506         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1507
1508 #else
1509     r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1510 #endif
1511     return r;
1512 }
1513
1514 static int send_itemorder(const char *type, int itemno)
1515 {
1516     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1517     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1518     oident ItemOrderRequest;
1519
1520     ItemOrderRequest.proto = PROTO_Z3950;
1521     ItemOrderRequest.oclass = CLASS_EXTSERV;
1522     ItemOrderRequest.value = VAL_ITEMORDER;
1523     req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1524     req->packageName = esPackageName;
1525
1526     req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1527
1528     send_apdu(apdu);
1529     return 0;
1530 }
1531
1532 static int cmd_update(char *arg)
1533 {
1534     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1535     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1536     Z_External *r;
1537     int oid[OID_SIZE];
1538     Z_IUOriginPartToKeep *toKeep;
1539     Z_IUSuppliedRecords *notToKeep;
1540     oident update_oid;
1541     printf ("Update request\n");
1542     fflush(stdout);
1543
1544     if (!record_last)
1545         return 0;
1546     update_oid.proto = PROTO_Z3950;
1547     update_oid.oclass = CLASS_EXTSERV;
1548     update_oid.value = VAL_DBUPDATE;
1549     oid_ent_to_oid (&update_oid, oid);
1550     req->packageType = odr_oiddup(out,oid);
1551     req->packageName = esPackageName;
1552
1553     r = req->taskSpecificParameters = (Z_External *)
1554         odr_malloc (out, sizeof(*r));
1555     r->direct_reference = odr_oiddup(out,oid);
1556     r->indirect_reference = 0;
1557     r->descriptor = 0;
1558     r->which = Z_External_update;
1559     r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1560     r->u.update->which = Z_IUUpdate_esRequest;
1561     r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1562         odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1563     toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1564         odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1565     toKeep->databaseName = databaseNames[0];
1566     toKeep->schema = 0;
1567     toKeep->elementSetName = 0;
1568     toKeep->actionQualifier = 0;
1569     toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1570     *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1571
1572     notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1573         odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1574     notToKeep->num = 1;
1575     notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1576         odr_malloc(out, sizeof(*notToKeep->elements));
1577     notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1578         odr_malloc(out, sizeof(**notToKeep->elements));
1579     notToKeep->elements[0]->u.number = 0;
1580     notToKeep->elements[0]->supplementalId = 0;
1581     notToKeep->elements[0]->correlationInfo = 0;
1582     notToKeep->elements[0]->record = record_last;
1583     
1584     send_apdu(apdu);
1585
1586     return 2;
1587 }
1588
1589 /* II : Added to do DALI Item Order Extended services request */
1590 static int cmd_itemorder(char *arg)
1591 {
1592     char type[12];
1593     int itemno;
1594
1595     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1596         return 0;
1597
1598     printf("Item order request\n");
1599     fflush(stdout);
1600     send_itemorder(type, itemno);
1601     return(2);
1602 }
1603
1604 static int cmd_find(char *arg)
1605 {
1606     if (!*arg)
1607     {
1608         printf("Find what?\n");
1609         return 0;
1610     }
1611     if (!conn)
1612     {
1613         printf("Not connected yet\n");
1614         return 0;
1615     }
1616     if (!send_searchRequest(arg))
1617         return 0;
1618     return 2;
1619 }
1620
1621 static int cmd_delete(char *arg)
1622 {
1623     if (!conn)
1624     {
1625         printf("Not connected yet\n");
1626         return 0;
1627     }
1628     if (!send_deleteResultSetRequest(arg))
1629         return 0;
1630     return 2;
1631 }
1632
1633 static int cmd_ssub(char *arg)
1634 {
1635     if (!(smallSetUpperBound = atoi(arg)))
1636         return 0;
1637     return 1;
1638 }
1639
1640 static int cmd_lslb(char *arg)
1641 {
1642     if (!(largeSetLowerBound = atoi(arg)))
1643         return 0;
1644     return 1;
1645 }
1646
1647 static int cmd_mspn(char *arg)
1648 {
1649     if (!(mediumSetPresentNumber = atoi(arg)))
1650         return 0;
1651     return 1;
1652 }
1653
1654 static int cmd_status(char *arg)
1655 {
1656     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1657     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1658     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1659     return 1;
1660 }
1661
1662 static int cmd_setnames(char *arg)
1663 {
1664     if (setnumber < 0)
1665     {
1666         printf("Set numbering enabled.\n");
1667         setnumber = 0;
1668     }
1669     else
1670     {
1671         printf("Set numbering disabled.\n");
1672         setnumber = -1;
1673     }
1674     return 1;
1675 }
1676
1677 /* PRESENT SERVICE ----------------------------- */
1678
1679 static int send_presentRequest(char *arg)
1680 {
1681     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1682     Z_PresentRequest *req = apdu->u.presentRequest;
1683     Z_RecordComposition compo;
1684     oident prefsyn;
1685     int nos = 1;
1686     int oid[OID_SIZE];
1687     char *p;
1688     char setstring[100];
1689
1690     req->referenceId = set_refid (out);
1691     if ((p = strchr(arg, '+')))
1692     {
1693         nos = atoi(p + 1);
1694         *p = 0;
1695     }
1696     if (*arg)
1697         setno = atoi(arg);
1698     if (p && (p=strchr(p+1, '+')))
1699     {
1700         strcpy (setstring, p+1);
1701         req->resultSetId = setstring;
1702     }
1703     else if (setnumber >= 0)
1704     {
1705         sprintf(setstring, "%d", setnumber);
1706         req->resultSetId = setstring;
1707     }
1708 #if 0
1709     if (1)
1710     {
1711         static Z_Range range;
1712         static Z_Range *rangep = &range;
1713     req->num_ranges = 1;
1714 #endif
1715     req->resultSetStartPoint = &setno;
1716     req->numberOfRecordsRequested = &nos;
1717     prefsyn.proto = protocol;
1718     prefsyn.oclass = CLASS_RECSYN;
1719     prefsyn.value = recordsyntax;
1720     req->preferredRecordSyntax =
1721         odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1722
1723     if (schema != VAL_NONE)
1724     {
1725         oident prefschema;
1726
1727         prefschema.proto = protocol;
1728         prefschema.oclass = CLASS_SCHEMA;
1729         prefschema.value = schema;
1730
1731         req->recordComposition = &compo;
1732         compo.which = Z_RecordComp_complex;
1733         compo.u.complex = (Z_CompSpec *)
1734             odr_malloc(out, sizeof(*compo.u.complex));
1735         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
1736             odr_malloc(out, sizeof(bool_t));
1737         *compo.u.complex->selectAlternativeSyntax = 0;
1738
1739         compo.u.complex->generic = (Z_Specification *)
1740             odr_malloc(out, sizeof(*compo.u.complex->generic));
1741         compo.u.complex->generic->schema = (Odr_oid *)
1742             odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1743         if (!compo.u.complex->generic->schema)
1744         {
1745             /* OID wasn't a schema! Try record syntax instead. */
1746             prefschema.oclass = CLASS_RECSYN;
1747             compo.u.complex->generic->schema = (Odr_oid *)
1748                 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1749         }
1750         if (!elementSetNames)
1751             compo.u.complex->generic->elementSpec = 0;
1752         else
1753         {
1754             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1755                 odr_malloc(out, sizeof(Z_ElementSpec));
1756             compo.u.complex->generic->elementSpec->which =
1757                 Z_ElementSpec_elementSetName;
1758             compo.u.complex->generic->elementSpec->u.elementSetName =
1759                 elementSetNames->u.generic;
1760         }
1761         compo.u.complex->num_dbSpecific = 0;
1762         compo.u.complex->dbSpecific = 0;
1763         compo.u.complex->num_recordSyntax = 0;
1764         compo.u.complex->recordSyntax = 0;
1765     }
1766     else if (elementSetNames)
1767     {
1768         req->recordComposition = &compo;
1769         compo.which = Z_RecordComp_simple;
1770         compo.u.simple = elementSetNames;
1771     }
1772     send_apdu(apdu);
1773     printf("Sent presentRequest (%d+%d).\n", setno, nos);
1774     return 2;
1775 }
1776
1777 void process_close(Z_Close *req)
1778 {
1779     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1780     Z_Close *res = apdu->u.close;
1781
1782     static char *reasons[] =
1783     {
1784         "finished",
1785         "shutdown",
1786         "system problem",
1787         "cost limit reached",
1788         "resources",
1789         "security violation",
1790         "protocolError",
1791         "lack of activity",
1792         "peer abort",
1793         "unspecified"
1794     };
1795
1796     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1797         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1798     if (sent_close)
1799     {
1800         cs_close (conn);
1801         conn = NULL;
1802         if (session_mem)
1803         {
1804             nmem_destroy (session_mem);
1805             session_mem = NULL;
1806         }
1807         sent_close = 0;
1808     }
1809     else
1810     {
1811         *res->closeReason = Z_Close_finished;
1812         send_apdu(apdu);
1813         printf("Sent response.\n");
1814         sent_close = 1;
1815     }
1816 }
1817
1818 static int cmd_show(char *arg)
1819 {
1820     if (!conn)
1821     {
1822         printf("Not connected yet\n");
1823         return 0;
1824     }
1825     if (!send_presentRequest(arg))
1826         return 0;
1827     return 2;
1828 }
1829
1830 int cmd_quit(char *arg)
1831 {
1832     printf("See you later, alligator.\n");
1833     exit(0);
1834     return 0;
1835 }
1836
1837 int cmd_cancel(char *arg)
1838 {
1839     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1840     Z_TriggerResourceControlRequest *req =
1841         apdu->u.triggerResourceControlRequest;
1842     bool_t rfalse = 0;
1843     
1844     if (!conn)
1845     {
1846         printf("Session not initialized yet\n");
1847         return 0;
1848     }
1849     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1850     {
1851         printf("Target doesn't support cancel (trigger resource ctrl)\n");
1852         return 0;
1853     }
1854     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1855     req->resultSetWanted = &rfalse;
1856
1857     send_apdu(apdu);
1858     printf("Sent cancel request\n");
1859     return 2;
1860 }
1861
1862 int send_scanrequest(const char *query, int pp, int num, const char *term)
1863 {
1864     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1865     Z_ScanRequest *req = apdu->u.scanRequest;
1866     int use_rpn = 1;
1867     int oid[OID_SIZE];
1868     
1869 #if CCL2RPN
1870     if (queryType == QueryType_CCL2RPN)
1871     {
1872         oident bib1;
1873         int error, pos;
1874         struct ccl_rpn_node *rpn;
1875
1876         rpn = ccl_find_str (bibset,  query, &error, &pos);
1877         if (error)
1878         {
1879             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1880             return -1;
1881         }
1882         use_rpn = 0;
1883         bib1.proto = PROTO_Z3950;
1884         bib1.oclass = CLASS_ATTSET;
1885         bib1.value = VAL_BIB1;
1886         req->attributeSet = oid_ent_to_oid (&bib1, oid);
1887         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1888         {
1889             printf("Couldn't convert CCL to Scan term\n");
1890             return -1;
1891         }
1892         ccl_rpn_delete (rpn);
1893     }
1894 #endif
1895     if (use_rpn && !(req->termListAndStartPoint =
1896                      p_query_scan(out, protocol, &req->attributeSet, query)))
1897     {
1898         printf("Prefix query error\n");
1899         return -1;
1900     }
1901     if (term && *term)
1902     {
1903         if (req->termListAndStartPoint->term &&
1904             req->termListAndStartPoint->term->which == Z_Term_general &&
1905             req->termListAndStartPoint->term->u.general)
1906         {
1907             req->termListAndStartPoint->term->u.general->buf =
1908                 (unsigned char *) odr_strdup(out, term);
1909             req->termListAndStartPoint->term->u.general->len =
1910                 req->termListAndStartPoint->term->u.general->size =
1911                 strlen(term);
1912         }
1913     }
1914     req->referenceId = set_refid (out);
1915     req->num_databaseNames = num_databaseNames;
1916     req->databaseNames = databaseNames;
1917     req->numberOfTermsRequested = &num;
1918     req->preferredPositionInResponse = &pp;
1919     send_apdu(apdu);
1920     return 2;
1921 }
1922
1923 int send_sortrequest(char *arg, int newset)
1924 {
1925     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1926     Z_SortRequest *req = apdu->u.sortRequest;
1927     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1928         odr_malloc (out, sizeof(*sksl));
1929     char setstring[32];
1930     char sort_string_buf[32], sort_flags[32];
1931     int off;
1932     int oid[OID_SIZE];
1933     oident bib1;
1934
1935     if (setnumber >= 0)
1936         sprintf (setstring, "%d", setnumber);
1937     else
1938         sprintf (setstring, "default");
1939
1940     req->referenceId = set_refid (out);
1941
1942 #ifdef ASN_COMPILED
1943     req->num_inputResultSetNames = 1;
1944     req->inputResultSetNames = (Z_InternationalString **)
1945         odr_malloc (out, sizeof(*req->inputResultSetNames));
1946     req->inputResultSetNames[0] = odr_strdup (out, setstring);
1947 #else
1948     req->inputResultSetNames =
1949         (Z_StringList *)odr_malloc (out, sizeof(*req->inputResultSetNames));
1950     req->inputResultSetNames->num_strings = 1;
1951     req->inputResultSetNames->strings =
1952         (char **)odr_malloc (out, sizeof(*req->inputResultSetNames->strings));
1953     req->inputResultSetNames->strings[0] =
1954         odr_strdup (out, setstring);
1955 #endif
1956
1957     if (newset && setnumber >= 0)
1958         sprintf (setstring, "%d", ++setnumber);
1959
1960     req->sortedResultSetName = odr_strdup (out, setstring);
1961
1962     req->sortSequence = sksl;
1963     sksl->num_specs = 0;
1964     sksl->specs = (Z_SortKeySpec **)odr_malloc (out, sizeof(sksl->specs) * 20);
1965     
1966     bib1.proto = protocol;
1967     bib1.oclass = CLASS_ATTSET;
1968     bib1.value = VAL_BIB1;
1969     while ((sscanf (arg, "%31s %31s%n", sort_string_buf, sort_flags, &off)) == 2 
1970            && off > 1)
1971     {
1972         int i;
1973         char *sort_string_sep;
1974         char *sort_string = sort_string_buf;
1975         Z_SortKeySpec *sks = (Z_SortKeySpec *)odr_malloc (out, sizeof(*sks));
1976         Z_SortKey *sk = (Z_SortKey *)odr_malloc (out, sizeof(*sk));
1977
1978         arg += off;
1979         sksl->specs[sksl->num_specs++] = sks;
1980         sks->sortElement = (Z_SortElement *)odr_malloc (out, sizeof(*sks->sortElement));
1981         sks->sortElement->which = Z_SortElement_generic;
1982         sks->sortElement->u.generic = sk;
1983         
1984         if ((sort_string_sep = strchr (sort_string, '=')))
1985         {
1986             int i = 0;
1987             sk->which = Z_SortKey_sortAttributes;
1988             sk->u.sortAttributes =
1989                 (Z_SortAttributes *)odr_malloc (out, sizeof(*sk->u.sortAttributes));
1990             sk->u.sortAttributes->id = oid_ent_to_oid(&bib1, oid);
1991             sk->u.sortAttributes->list =
1992                 (Z_AttributeList *)odr_malloc (out, sizeof(*sk->u.sortAttributes->list));
1993             sk->u.sortAttributes->list->attributes =
1994                 (Z_AttributeElement **)
1995                 odr_malloc (out, 10 *
1996                             sizeof(*sk->u.sortAttributes->list->attributes));
1997             while (i < 10 && sort_string && sort_string_sep)
1998             {
1999                 Z_AttributeElement *el = (Z_AttributeElement *)
2000                     odr_malloc (out, sizeof(*el));
2001                 sk->u.sortAttributes->list->attributes[i] = el;
2002                 el->attributeSet = 0;
2003                 el->attributeType = (int *)odr_malloc (out, sizeof(*el->attributeType));
2004                 *el->attributeType = atoi (sort_string);
2005                 el->which = Z_AttributeValue_numeric;
2006                 el->value.numeric = (int *)odr_malloc (out, sizeof(*el->value.numeric));
2007                 *el->value.numeric = atoi (sort_string_sep + 1);
2008                 i++;
2009                 sort_string = strchr(sort_string, ',');
2010                 if (sort_string)
2011                 {
2012                     sort_string++;
2013                     sort_string_sep = strchr (sort_string, '=');
2014                 }
2015             }
2016             sk->u.sortAttributes->list->num_attributes = i;
2017         }
2018         else
2019         {
2020             sk->which = Z_SortKey_sortField;
2021             sk->u.sortField = odr_strdup (out, sort_string);
2022         }
2023         sks->sortRelation = (int *)odr_malloc (out, sizeof(*sks->sortRelation));
2024         *sks->sortRelation = Z_SortRelation_ascending;
2025         sks->caseSensitivity = (int *)odr_malloc (out, sizeof(*sks->caseSensitivity));
2026         *sks->caseSensitivity = Z_SortCase_caseSensitive;
2027
2028 #ifdef ASN_COMPILED
2029         sks->which = Z_SortKeySpec_null;
2030         sks->u.null = odr_nullval ();
2031 #else
2032         sks->missingValueAction = NULL;
2033 #endif
2034
2035         for (i = 0; sort_flags[i]; i++)
2036         {
2037             switch (sort_flags[i])
2038             {
2039             case 'a':
2040             case 'A':
2041             case '>':
2042                 *sks->sortRelation = Z_SortRelation_descending;
2043                 break;
2044             case 'd':
2045             case 'D':
2046             case '<':
2047                 *sks->sortRelation = Z_SortRelation_ascending;
2048                 break;
2049             case 'i':
2050             case 'I':
2051                 *sks->caseSensitivity = Z_SortCase_caseInsensitive;
2052                 break;
2053             case 'S':
2054             case 's':
2055                 *sks->caseSensitivity = Z_SortCase_caseSensitive;
2056                 break;
2057             }
2058         }
2059     }
2060     if (!sksl->num_specs)
2061     {
2062         printf ("Missing sort specifications\n");
2063         return -1;
2064     }
2065     send_apdu(apdu);
2066     return 2;
2067 }
2068
2069 void display_term(Z_TermInfo *t)
2070 {
2071     if (t->term->which == Z_Term_general)
2072     {
2073         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2074         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2075             t->term->u.general->buf);
2076     }
2077     else
2078         printf("Term (not general)");
2079     if (t->globalOccurrences)
2080         printf (" (%d)\n", *t->globalOccurrences);
2081     else
2082         printf ("\n");
2083 }
2084
2085 void process_scanResponse(Z_ScanResponse *res)
2086 {
2087     int i;
2088     Z_Entry **entries = NULL;
2089     int num_entries = 0;
2090    
2091     printf("Received ScanResponse\n"); 
2092     print_refid (res->referenceId);
2093     printf("%d entries", *res->numberOfEntriesReturned);
2094     if (res->positionOfTerm)
2095         printf (", position=%d", *res->positionOfTerm); 
2096     printf ("\n");
2097     if (*res->scanStatus != Z_Scan_success)
2098         printf("Scan returned code %d\n", *res->scanStatus);
2099     if (!res->entries)
2100         return;
2101     if ((entries = res->entries->entries))
2102         num_entries = res->entries->num_entries;
2103     for (i = 0; i < num_entries; i++)
2104     {
2105         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2106         if (entries[i]->which == Z_Entry_termInfo)
2107         {
2108             printf("%c ", i + 1 == pos_term ? '*' : ' ');
2109             display_term(entries[i]->u.termInfo);
2110         }
2111         else
2112             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2113     }
2114     if (res->entries->nonsurrogateDiagnostics)
2115         display_diagrecs (res->entries->nonsurrogateDiagnostics,
2116                           res->entries->num_nonsurrogateDiagnostics);
2117 }
2118
2119 void process_sortResponse(Z_SortResponse *res)
2120 {
2121     printf("Received SortResponse: status=");
2122     switch (*res->sortStatus)
2123     {
2124     case Z_SortStatus_success:
2125         printf ("success"); break;
2126     case Z_SortStatus_partial_1:
2127         printf ("partial"); break;
2128     case Z_SortStatus_failure:
2129         printf ("failure"); break;
2130     default:
2131         printf ("unknown (%d)", *res->sortStatus);
2132     }
2133     printf ("\n");
2134     print_refid (res->referenceId);
2135 #ifdef ASN_COMPILED
2136     if (res->diagnostics)
2137         display_diagrecs(res->diagnostics,
2138                          res->num_diagnostics);
2139 #else
2140     if (res->diagnostics)
2141         display_diagrecs(res->diagnostics->diagRecs,
2142                          res->diagnostics->num_diagRecs);
2143 #endif
2144 }
2145
2146 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2147 {
2148     printf("Got deleteResultSetResponse status=%d\n",
2149            *res->deleteOperationStatus);
2150     if (res->deleteListStatuses)
2151     {
2152         int i;
2153         for (i = 0; i < res->deleteListStatuses->num; i++)
2154         {
2155             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2156                     *res->deleteListStatuses->elements[i]->status);
2157         }
2158     }
2159 }
2160
2161 int cmd_sort_generic(char *arg, int newset)
2162 {
2163     if (!conn)
2164     {
2165         printf("Session not initialized yet\n");
2166         return 0;
2167     }
2168     if (!ODR_MASK_GET(session->options, Z_Options_sort))
2169     {
2170         printf("Target doesn't support sort\n");
2171         return 0;
2172     }
2173     if (*arg)
2174     {
2175         if (send_sortrequest(arg, newset) < 0)
2176             return 0;
2177         return 2;
2178     }
2179     return 0;
2180 }
2181
2182 int cmd_sort(char *arg)
2183 {
2184     return cmd_sort_generic (arg, 0);
2185 }
2186
2187 int cmd_sort_newset (char *arg)
2188 {
2189     return cmd_sort_generic (arg, 1);
2190 }
2191
2192 int cmd_scan(char *arg)
2193 {
2194     if (!conn)
2195     {
2196         printf("Session not initialized yet\n");
2197         return 0;
2198     }
2199     if (!ODR_MASK_GET(session->options, Z_Options_scan))
2200     {
2201         printf("Target doesn't support scan\n");
2202         return 0;
2203     }
2204     if (*arg)
2205     {
2206         strcpy (last_scan_query, arg);
2207         if (send_scanrequest(arg, 1, 20, 0) < 0)
2208             return 0;
2209     }
2210     else
2211     {
2212         if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2213             return 0;
2214     }
2215     return 2;
2216 }
2217
2218 int cmd_schema(char *arg)
2219 {
2220     if (!arg || !*arg)
2221     {
2222         schema = VAL_NONE;
2223         return 1;
2224     }
2225     schema = oid_getvalbyname (arg);
2226     if (schema == VAL_NONE)
2227     {
2228         printf ("unknown schema\n");
2229         return 0;
2230     }
2231     return 1;
2232 }
2233
2234 int cmd_format(char *arg)
2235 {
2236     if (!arg || !*arg)
2237     {
2238         printf("Usage: format <recordsyntax>\n");
2239         return 0;
2240     }
2241     recordsyntax = oid_getvalbyname (arg);
2242     if (recordsyntax == VAL_NONE)
2243     {
2244         printf ("unknown record syntax\n");
2245         return 0;
2246     }
2247     return 1;
2248 }
2249
2250 int cmd_elements(char *arg)
2251 {
2252     static Z_ElementSetNames esn;
2253     static char what[100];
2254
2255     if (!arg || !*arg)
2256     {
2257         elementSetNames = 0;
2258         return 1;
2259     }
2260     strcpy(what, arg);
2261     esn.which = Z_ElementSetNames_generic;
2262     esn.u.generic = what;
2263     elementSetNames = &esn;
2264     return 1;
2265 }
2266
2267 int cmd_attributeset(char *arg)
2268 {
2269     char what[100];
2270
2271     if (!arg || !*arg)
2272     {
2273         printf("Usage: attributeset <setname>\n");
2274         return 0;
2275     }
2276     sscanf(arg, "%s", what);
2277     if (p_query_attset (what))
2278     {
2279         printf("Unknown attribute set name\n");
2280         return 0;
2281     }
2282     return 1;
2283 }
2284
2285 int cmd_querytype (char *arg)
2286 {
2287     if (!strcmp (arg, "ccl"))
2288         queryType = QueryType_CCL;
2289     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2290         queryType = QueryType_Prefix;
2291 #if CCL2RPN
2292     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2293         queryType = QueryType_CCL2RPN;
2294 #endif
2295     else
2296     {
2297         printf ("Querytype must be one of:\n");
2298         printf (" prefix         - Prefix query\n");
2299         printf (" ccl            - CCL query\n");
2300 #if CCL2RPN
2301         printf (" ccl2rpn        - CCL query converted to RPN\n");
2302 #endif
2303         return 0;
2304     }
2305     return 1;
2306 }
2307
2308 int cmd_refid (char *arg)
2309 {
2310     xfree (refid);
2311     refid = NULL;
2312     if (*arg)
2313     {
2314         refid = (char *) xmalloc (strlen(arg)+1);
2315         strcpy (refid, arg);
2316     }
2317     return 1;
2318 }
2319
2320 int cmd_close(char *arg)
2321 {
2322     Z_APDU *apdu;
2323     Z_Close *req;
2324     if (!conn)
2325         return 0;
2326
2327     apdu = zget_APDU(out, Z_APDU_close);
2328     req = apdu->u.close;
2329     *req->closeReason = Z_Close_finished;
2330     send_apdu(apdu);
2331     printf("Sent close request.\n");
2332     sent_close = 1;
2333     return 2;
2334 }
2335
2336 int cmd_packagename(char* arg) {
2337     xfree (esPackageName);
2338     esPackageName = NULL;
2339     if (*arg)
2340     {
2341         esPackageName = (char *) xmalloc (strlen(arg)+1);
2342         strcpy (esPackageName, arg);
2343     }
2344     return 1;
2345 };
2346
2347 static void initialize(void)
2348 {
2349 #if CCL2RPN
2350     FILE *inf;
2351 #endif
2352     nmem_init();
2353     if (!(out = odr_createmem(ODR_ENCODE)) ||
2354         !(in = odr_createmem(ODR_DECODE)) ||
2355         !(print = odr_createmem(ODR_PRINT)))
2356     {
2357         fprintf(stderr, "failed to allocate ODR streams\n");
2358         exit(1);
2359     }
2360     setvbuf(stdout, 0, _IONBF, 0);
2361     if (apdu_file)
2362         odr_setprint(print, apdu_file);
2363
2364 #if CCL2RPN
2365     bibset = ccl_qual_mk (); 
2366     inf = fopen (ccl_fields, "r");
2367     if (inf)
2368     {
2369         ccl_qual_file (bibset, inf);
2370         fclose (inf);
2371     }
2372 #endif
2373     cmd_base("Default");
2374 }
2375
2376 static int client(int wait)
2377 {
2378     static struct {
2379         char *cmd;
2380         int (*fun)(char *arg);
2381         char *ad;
2382     } cmd[] = {
2383         {"open", cmd_open, "('tcp'|'osi')':'[<tsel>'/']<host>[':'<port>]"},
2384         {"quit", cmd_quit, ""},
2385         {"find", cmd_find, "<query>"},
2386         {"delete", cmd_delete, "<setname>"},
2387         {"base", cmd_base, "<base-name>"},
2388         {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]"},
2389         {"scan", cmd_scan, "<term>"},
2390         {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ..."},
2391         {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ..."},
2392         {"authentication", cmd_authentication, "<acctstring>"},
2393         {"lslb", cmd_lslb, "<largeSetLowerBound>"},
2394         {"ssub", cmd_ssub, "<smallSetUpperBound>"},
2395         {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
2396         {"status", cmd_status, ""},
2397         {"setnames", cmd_setnames, ""},
2398         {"cancel", cmd_cancel, ""},
2399         {"format", cmd_format, "<recordsyntax>"},
2400         {"schema", cmd_schema, "<schema>"},
2401         {"elements", cmd_elements, "<elementSetName>"},
2402         {"close", cmd_close, ""},
2403         {"attributeset", cmd_attributeset, "<attrset>"},
2404         {"querytype", cmd_querytype, "<type>"},
2405         {"refid", cmd_refid, "<id>"},
2406         {"itemorder", cmd_itemorder, "ill|item <itemno>"},
2407         {"update", cmd_update, "<item>"},
2408         {"packagename", cmd_packagename, "<packagename>"},
2409 #ifdef ASN_COMPILED
2410         /* Server Admin Functions */
2411         {"adm-reindex", cmd_adm_reindex, "<database-name>"},
2412         {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>"},
2413         {"adm-create", cmd_adm_create, ""},
2414         {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>"},
2415         {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>"},
2416         {"adm-refresh", cmd_adm_refresh, ""},
2417         {"adm-commit", cmd_adm_commit, ""},
2418         {"adm-shutdown", cmd_adm_shutdown, ""},
2419         {"adm-startup", cmd_adm_startup, ""},
2420 #endif
2421         {0,0}
2422     };
2423     char *netbuffer= 0;
2424     int netbufferlen = 0;
2425     int i;
2426     Z_APDU *apdu;
2427 #if HAVE_GETTIMEOFDAY
2428     struct timeval tv_start, tv_end;
2429     gettimeofday (&tv_start, 0);
2430 #endif
2431
2432     while (1)
2433     {
2434         int res;
2435 #ifdef USE_SELECT
2436         fd_set input;
2437 #endif
2438         char line[1024], word[1024], arg[1024];
2439         
2440 #ifdef USE_SELECT
2441         FD_ZERO(&input);
2442         FD_SET(0, &input);
2443         if (conn)
2444             FD_SET(cs_fileno(conn), &input);
2445         if ((res = select(20, &input, 0, 0, 0)) < 0)
2446         {
2447             perror("select");
2448             exit(1);
2449         }
2450         if (!res)
2451             continue;
2452         if (!wait && FD_ISSET(0, &input))
2453 #else
2454         if (!wait)
2455 #endif
2456         {
2457 #if HAVE_READLINE_READLINE_H
2458             char* line_in;
2459             line_in=readline(C_PROMPT);
2460             if (!line_in)
2461                 break;
2462 #if HAVE_READLINE_HISTORY_H
2463             if (*line_in)
2464                 add_history(line_in);
2465 #endif
2466             strcpy(line,line_in);
2467             free (line_in);
2468 #else    
2469             char *end_p;
2470             printf (C_PROMPT);
2471             fflush(stdout);
2472             if (!fgets(line, 1023, stdin))
2473                 break;
2474             if ((end_p = strchr (line, '\n')))
2475                 *end_p = '\0';
2476 #endif 
2477 #if HAVE_GETTIMEOFDAY
2478             gettimeofday (&tv_start, 0);
2479 #endif
2480
2481             if ((res = sscanf(line, "%s %[^;]", word, arg)) <= 0)
2482             {
2483                 strcpy(word, last_cmd);
2484                 *arg = '\0';
2485             }
2486             else if (res == 1)
2487                 *arg = 0;
2488             strcpy(last_cmd, word);
2489             for (i = 0; cmd[i].cmd; i++)
2490                 if (!strncmp(cmd[i].cmd, word, strlen(word)))
2491                 {
2492                     res = (*cmd[i].fun)(arg);
2493                     break;
2494                 }
2495             if (!cmd[i].cmd) /* dump our help-screen */
2496             {
2497                 printf("Unknown command: %s.\n", word);
2498                 printf("Currently recognized commands:\n");
2499                 for (i = 0; cmd[i].cmd; i++)
2500                     printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
2501                 res = 1;
2502             }
2503             if (res < 2)
2504             {
2505                 continue;
2506             }
2507         }
2508         wait = 0;
2509         if (conn
2510 #ifdef USE_SELECT
2511             && FD_ISSET(cs_fileno(conn), &input)
2512 #endif
2513             )
2514         {
2515             do
2516             {
2517                 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2518                 {
2519                     perror("cs_get");
2520                     exit(1);
2521                 }
2522                 if (!res)
2523                 {
2524                     printf("Target closed connection.\n");
2525                     exit(1);
2526                 }
2527                 odr_reset(in); /* release APDU from last round */
2528                 record_last = 0;
2529                 odr_setbuf(in, netbuffer, res, 0);
2530                 if (!z_APDU(in, &apdu, 0, 0))
2531                 {
2532                     odr_perror(in, "Decoding incoming APDU");
2533                     fprintf(stderr, "[Near %d]\n", odr_offset(in));
2534                     fprintf(stderr, "Packet dump:\n---------\n");
2535                     odr_dumpBER(stderr, netbuffer, res);
2536                     fprintf(stderr, "---------\n");
2537                     if (apdu_file)
2538                         z_APDU(print, &apdu, 0, 0);
2539                     exit(1);
2540                 }
2541                 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2542                 {
2543                     odr_perror(print, "Failed to print incoming APDU");
2544                     odr_reset(print);
2545                     continue;
2546                 }
2547                 switch(apdu->which)
2548                 {
2549                 case Z_APDU_initResponse:
2550                     process_initResponse(apdu->u.initResponse);
2551                     break;
2552                 case Z_APDU_searchResponse:
2553                     process_searchResponse(apdu->u.searchResponse);
2554                     break;
2555                 case Z_APDU_scanResponse:
2556                     process_scanResponse(apdu->u.scanResponse);
2557                     break;
2558                 case Z_APDU_presentResponse:
2559                     print_refid (apdu->u.presentResponse->referenceId);
2560                     setno +=
2561                         *apdu->u.presentResponse->numberOfRecordsReturned;
2562                     if (apdu->u.presentResponse->records)
2563                         display_records(apdu->u.presentResponse->records);
2564                     else
2565                         printf("No records.\n");
2566                     printf ("nextResultSetPosition = %d\n",
2567                         *apdu->u.presentResponse->nextResultSetPosition);
2568                     break;
2569                 case Z_APDU_sortResponse:
2570                     process_sortResponse(apdu->u.sortResponse);
2571                     break;
2572                 case Z_APDU_extendedServicesResponse:
2573                     printf("Got extended services response\n");
2574                     process_ESResponse(apdu->u.extendedServicesResponse);
2575                     break;
2576                 case Z_APDU_close:
2577                     printf("Target has closed the association.\n");
2578                     process_close(apdu->u.close);
2579                     break;
2580                 case Z_APDU_resourceControlRequest:
2581                     process_resourceControlRequest
2582                         (apdu->u.resourceControlRequest);
2583                     break;
2584                 case Z_APDU_deleteResultSetResponse:
2585                     process_deleteResultSetResponse(apdu->u.
2586                                                     deleteResultSetResponse);
2587                     break;
2588                 default:
2589                     printf("Received unknown APDU type (%d).\n", 
2590                            apdu->which);
2591                     exit(1);
2592                 }
2593             }
2594             while (conn && cs_more(conn));
2595 #if HAVE_GETTIMEOFDAY
2596             gettimeofday (&tv_end, 0);
2597             if (1)
2598             {
2599                 printf ("Elapsed: %.6f\n", (double) tv_end.tv_usec /
2600                                                 1e6 + tv_end.tv_sec -
2601                    ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2602             }
2603 #endif
2604         }
2605     }
2606     return 0;
2607 }
2608
2609 int main(int argc, char **argv)
2610 {
2611     char *prog = *argv;
2612     char *arg;
2613     int ret;
2614     int opened = 0;
2615
2616     while ((ret = options("c:a:m:v:", argv, argc, &arg)) != -2)
2617     {
2618         switch (ret)
2619         {
2620         case 0:
2621             if (!opened)
2622             {
2623                 initialize ();
2624                 if (cmd_open (arg) == 2)
2625                     opened = 1;
2626             }
2627             break;
2628         case 'm':
2629             if (!(marcdump = fopen (arg, "a")))
2630             {
2631                 perror (arg);
2632                 exit (1);
2633             }
2634             break;
2635         case 'c':
2636             strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
2637             ccl_fields[sizeof(ccl_fields)-1] = '\0';
2638             break;
2639         case 'a':
2640             if (!strcmp(arg, "-"))
2641                 apdu_file=stderr;
2642             else
2643                 apdu_file=fopen(arg, "a");
2644             break;
2645         case 'v':
2646             yaz_log_init (yaz_log_mask_str(arg), "", NULL);
2647             break;
2648         default:
2649             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
2650                              "[-c cclfields] [<server-addr>]\n",
2651                      prog);
2652             exit (1);
2653         }
2654     }
2655     if (!opened)
2656         initialize ();
2657     return client (opened);
2658 }