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