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