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