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