source: trunk/gsdl/packages/yaz/client/yaz_zclient.c@ 2640

Last change on this file since 2640 was 2547, checked in by jrm21, 23 years ago

don't add <a href> tags for USMARC field 856 (online access), as it is not
guaranteed to be a URL - just some text describing online access...

  • Property svn:keywords set to Author Date Id Revision
File size: 58.2 KB
Line 
1/*
2 * Copyright (c) 1995-2000, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
5 *
6 * $Log$
7 * Revision 1.3 2001/06/13 04:22:26 jrm21
8 * don't add <a href> tags for USMARC field 856 (online access), as it is not
9 * guaranteed to be a URL - just some text describing online access...
10 *
11 * Revision 1.2 2000/10/26 06:37:46 jrm21
12 * Now makes hyperlinks for MARC field 856 (Electronic Access/Location),
13 * so you too can point and click...
14 *
15 * Revision 1.1 2000/08/03 03:10:01 johnmcp
16 * Added the YAZ toolkit source to the packages directory (for z39.50 stuff)
17 *
18 * Revision 1.1.2.1 2000/05/24 23:24:29 johnmcp
19 * added some of the YAZ toolkit code for z39.50 client.
20 *
21 * Revision 1.95 2000/02/28 11:20:05 adam
22 * Using autoconf. New definitions: YAZ_BEGIN_CDECL/YAZ_END_CDECL.
23 *
24 */
25
26/* Modified for the GreenStone Digital Library project - johnmcp */
27
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
31#include <ctype.h> /* for isdigit() */
32#include <time.h>
33
34/* don't need functions from here, maybe only the other header files:
35function atoi_n needed by marc_display()
36#include <yaz/yconfig.h>
37#include <yaz/xmalloc.h>
38#include <yaz/log.h>
39#include <yaz/tpath.h>
40#include <yaz/options.h>
41#include <yaz/wrbuf.h>
42#include <yaz/nmem.h>
43#include <yaz/readconf.h>
44*/
45#include <yaz/yaz-util.h>
46
47#include <yaz/tcpip.h>
48
49#include <yaz/proto.h>
50
51/* only defines marc_display[_ex] (), which could be inline. May need
52 yaz/yconfig.h header file */
53#include <yaz/marcdisp.h>
54#include <yaz/diagbib1.h>
55
56#include <yaz/pquery.h>
57
58#ifdef ASN_COMPILED
59#include <yaz/ill.h>
60#endif
61
62#if HAVE_READLINE_READLINE_H
63#include <readline/readline.h>
64#endif
65#if HAVE_READLINE_HISTORY_H
66#include <readline/history.h>
67#endif
68
69#define C_PROMPT "Z> "
70
71static ODR out, in, print; /* encoding and decoding streams */
72static FILE *apdu_file = 0;
73static COMSTACK conn = 0; /* our z-association */
74static Z_IdAuthentication *auth = 0; /* our current auth definition */
75static char *databaseNames[128];
76static Z_External *record_last = 0;
77static int num_databaseNames = 0;
78static int setnumber = 0; /* current result set number */
79static int smallSetUpperBound = 0;
80static int largeSetLowerBound = 1;
81static int mediumSetPresentNumber = 0;
82static Z_ElementSetNames *elementSetNames = 0;
83static int setno = 1; /* current set offset */
84static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
85static enum oid_value recordsyntax = VAL_USMARC;
86static enum oid_value schema = VAL_NONE;
87static int sent_close = 0;
88static NMEM session_mem = NULL; /* memory handle for init-response */
89static Z_InitResponse *session = 0; /* session parameters */
90static char last_scan[512] = "0";
91static FILE *marcdump = 0;
92static char *refid = NULL;
93/*johnmcp*/
94Z_InitResponse *z_initresponse;
95typedef enum {
96 QueryType_Prefix,
97 QueryType_CCL,
98 QueryType_CCL2RPN
99} QueryType;
100
101static QueryType queryType = QueryType_Prefix;
102/*static QueryType queryType = QueryType_CCL;*/
103
104static void send_apdu(Z_APDU *a)
105{
106 char *buf;
107 int len;
108
109 if (!z_APDU(out, &a, 0, 0))
110 {
111 odr_perror(out, "Encoding APDU");
112 exit(1);
113 }
114 if (apdu_file)
115 {
116 z_APDU(print, &a, 0, 0);
117 odr_reset(print);
118 }
119 buf = odr_getbuf(out, &len, 0);
120 /* printf ("sending APDU of size %d\n", len); */
121 if (cs_put(conn, buf, len) < 0)
122 {
123 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
124 exit(1);
125 }
126 odr_reset(out); /* release the APDU structure */
127}
128
129static void print_refid (Z_ReferenceId *id)
130{
131 if (id)
132 {
133 printf ("ReferenceId: '%.*s'\n", id->len, id->buf);
134 }
135}
136
137static Z_ReferenceId *set_refid (ODR out)
138{
139 Z_ReferenceId *id;
140 if (!refid)
141 return 0;
142 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
143 id->size = id->len = strlen(refid);
144 id->buf = (unsigned char *) odr_malloc (out, id->len);
145 memcpy (id->buf, refid, id->len);
146 return id;
147}
148
149/* INIT SERVICE ------------------------------- */
150
151static void send_initRequest()
152{
153 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
154 Z_InitRequest *req = apdu->u.initRequest;
155
156 ODR_MASK_SET(req->options, Z_Options_search);
157 ODR_MASK_SET(req->options, Z_Options_present);
158 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
159 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
160 ODR_MASK_SET(req->options, Z_Options_scan);
161 ODR_MASK_SET(req->options, Z_Options_sort);
162 ODR_MASK_SET(req->options, Z_Options_extendedServices);
163 ODR_MASK_SET(req->options, Z_Options_delSet);
164
165 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
166 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
167 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
168
169 *req->maximumRecordSize = 1024*1024;
170 *req->preferredMessageSize = 1024*1024;
171
172 req->idAuthentication = auth;
173
174 send_apdu(apdu);
175}
176
177char *z_get_initResponse()
178{
179 char *buffer;
180 size_t needed_length;
181 char *text_id="ID: ";
182 char *text_name="<br>\nName: ";
183 char *text_ver="<br>\nVersion: ";
184 int counter;
185
186 buffer=NULL;
187 /* save session parameters for later use */
188 /* session_mem = odr_extract_mem(in);
189 session = res; */
190 if (!*session->result)
191 return NULL;
192
193 /* work out total string length needed. Note strlen(NULL) is a bad thing
194 to do. */
195 needed_length=strlen(text_id)+strlen(text_name)+strlen(text_ver)+
196 (session->implementationId?strlen(session->implementationId):0) +
197 (session->implementationName?strlen(session->implementationName):0) +
198 (session->implementationVersion?strlen(session->implementationVersion)
199 :0) +
200 (session->userInformationField?
201 strlen(session->userInformationField->u.octet_aligned->buf):0) +
202 1 /* for null char */ ;
203 if ((buffer=malloc((sizeof(char *)) * needed_length))==NULL) {
204 fprintf(stderr,"Malloc failed while initialising z39.50 server\n");
205 return (NULL);
206 }
207 /* can't pass NULL to sprintf as a (char *) */
208 sprintf(buffer,"%s%s%s%s%s%s",
209 session->implementationId?text_id:"",
210 session->implementationId?session->implementationId:"",
211 session->implementationName?text_name:"",
212 session->implementationName?session->implementationName:"",
213 session->implementationVersion?text_ver:"",
214 session->implementationVersion?session->implementationVersion:""
215 );
216
217 /* if version 3, also check the other-information parameter of the
218 response. (But check version is 3 first) */
219 if (session->otherInfo)
220 /**** From prt-proto.h *********** (comment added by johnmcp)
221 typedef struct Z_OtherInformationUnit
222 . { Z_InfoCategory *category; / * OPTIONAL * /
223 . int which;
224 #define Z_OtherInfo_characterInfo 0
225 #define Z_OtherInfo_binaryInfo 1
226 #define Z_OtherInfo_externallyDefinedInfo 2
227 #define Z_OtherInfo_oid 3
228 . union
229 . {
230 . char *characterInfo;
231 . Odr_oct *binaryInfo;
232 . Z_External *externallyDefinedInfo;
233 . Odr_oid *oid;
234 . } information;
235 . } Z_OtherInformationUnit;
236
237 typedef struct Z_OtherInformation
238 {
239 int num_elements;
240 Z_OtherInformationUnit **list;
241 } Z_OtherInformation;
242 ************/
243 for (counter=0;counter<session->otherInfo->num_elements;counter++)
244 if (session->otherInfo->list[counter]->which ==
245 Z_OtherInfo_characterInfo)
246 {
247 /* add this extra string to our buffer */
248 int where=strlen(buffer);
249 buffer=realloc(buffer,where+
250 strlen(session->otherInfo->list[counter]->
251 information.characterInfo));
252 strcpy(buffer+where,
253 session->otherInfo->list[counter]->
254 information.characterInfo);
255 }
256 return (buffer);
257}
258
259static int cmd_base(char *arg)
260{
261 int i;
262 char *cp;
263
264 if (!*arg)
265 {
266 printf("Usage: base <database> <database> ...\n");
267 return 0;
268 }
269 for (i = 0; i<num_databaseNames; i++)
270 xfree (databaseNames[i]);
271 num_databaseNames = 0;
272 while (1)
273 {
274 if (!(cp = strchr(arg, ' ')))
275 cp = arg + strlen(arg);
276 if (cp - arg < 1)
277 break;
278 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
279 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
280 databaseNames[num_databaseNames++][cp - arg] = '\0';
281 if (!*cp)
282 break;
283 arg = cp+1;
284 }
285 return 1;
286}
287
288
289int z_cmd_open(char *host_and_port, char *base)
290{
291 void *add;
292 CS_TYPE t;
293
294 if (conn)
295 {
296 printf("Already connected.\n");
297
298 cs_close (conn);
299 conn = NULL;
300 if (session_mem)
301 {
302 nmem_destroy (session_mem);
303 session_mem = NULL;
304 }
305 }
306
307 cmd_base (base);
308 t = tcpip_type;
309 protocol = PROTO_Z3950;
310
311 if (!(conn = cs_create(t, 1, protocol)))
312 {
313 perror("cs_create");
314 return 1;
315 }
316 if (!(add = cs_straddr(conn, host_and_port)))
317 {
318 perror(host_and_port);
319 return 1;
320 }
321
322 if (cs_connect(conn, add) < 0)
323 {
324 perror("connect");
325 cs_close(conn);
326 conn = 0;
327 return 1;
328 }
329 /* if here, we connected OK */
330 send_initRequest();
331 return 0;
332}
333
334int cmd_authentication(char *arg)
335{
336 static Z_IdAuthentication au;
337 static char open[256];
338
339 if (!*arg)
340 {
341 printf("Auth field set to null\n");
342 auth = 0;
343 return 1;
344 }
345 auth = &au;
346 au.which = Z_IdAuthentication_open;
347 au.u.open = open;
348 strcpy(open, arg);
349 return 1;
350}
351
352/* SEARCH SERVICE ------------------------------ */
353
354static void display_variant(Z_Variant *v, int level)
355{
356 int i;
357
358 for (i = 0; i < v->num_triples; i++)
359 {
360 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
361 *v->triples[i]->type);
362 if (v->triples[i]->which == Z_Triple_internationalString)
363 printf(",value=%s\n", v->triples[i]->value.internationalString);
364 else
365 printf("\n");
366 }
367}
368
369static void display_grs1(Z_GenericRecord *r, int level)
370{
371 int i;
372
373 if (!r)
374 return;
375 for (i = 0; i < r->num_elements; i++)
376 {
377 Z_TaggedElement *t;
378
379 printf("%*s", level * 4, "");
380 t = r->elements[i];
381 printf("(");
382 if (t->tagType)
383 printf("%d,", *t->tagType);
384 else
385 printf("?,");
386 if (t->tagValue->which == Z_StringOrNumeric_numeric)
387 printf("%d) ", *t->tagValue->u.numeric);
388 else
389 printf("%s) ", t->tagValue->u.string);
390 if (t->content->which == Z_ElementData_subtree)
391 {
392 printf("\n");
393 display_grs1(t->content->u.subtree, level+1);
394 }
395 else if (t->content->which == Z_ElementData_string)
396 printf("%s\n", t->content->u.string);
397 else if (t->content->which == Z_ElementData_numeric)
398 printf("%d\n", *t->content->u.numeric);
399 else if (t->content->which == Z_ElementData_oid)
400 {
401 int *ip = t->content->u.oid;
402 oident *oent;
403
404 if ((oent = oid_getentbyoid(t->content->u.oid)))
405 printf("OID: %s\n", oent->desc);
406 else
407 {
408 printf("{");
409 while (ip && *ip >= 0)
410 printf(" %d", *(ip++));
411 printf(" }\n");
412 }
413 }
414 else if (t->content->which == Z_ElementData_noDataRequested)
415 printf("[No data requested]\n");
416 else if (t->content->which == Z_ElementData_elementEmpty)
417 printf("[Element empty]\n");
418 else if (t->content->which == Z_ElementData_elementNotThere)
419 printf("[Element not there]\n");
420 else
421 printf("??????\n");
422 if (t->appliedVariant)
423 display_variant(t->appliedVariant, level+1);
424 if (t->metaData && t->metaData->supportedVariants)
425 {
426 int c;
427
428 printf("%*s---- variant list\n", (level+1)*4, "");
429 for (c = 0; c < t->metaData->num_supportedVariants; c++)
430 {
431 printf("%*svariant #%d\n", (level+1)*4, "", c);
432 display_variant(t->metaData->supportedVariants[c], level + 2);
433 }
434 }
435 }
436}
437
438static void print_record(const unsigned char *buf, size_t len)
439{
440 size_t i;
441 for (i = 0; i<len; i++)
442 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
443 fputc (buf[i], stdout);
444 else
445 printf ("\\X%02X", buf[i]);
446 /* add newline if not already added ... */
447 if (i <= 0 || buf[i-1] != '\n')
448 fputc ('\n', stdout);
449}
450
451static void display_record(Z_DatabaseRecord *p)
452{
453 Z_External *r = (Z_External*) p;
454 oident *ent = oid_getentbyoid(r->direct_reference);
455
456 record_last = r;
457 /*
458 * Tell the user what we got.
459 */
460 if (r->direct_reference)
461 {
462 printf("Record type: ");
463 if (ent)
464 printf("%s\n", ent->desc);
465 else if (!odr_oid(print, &r->direct_reference, 0, 0))
466 {
467 odr_perror(print, "print oid");
468 odr_reset(print);
469 }
470 }
471 /* Check if this is a known, ASN.1 type tucked away in an octet string */
472 if (ent && r->which == Z_External_octet)
473 {
474 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
475 void *rr;
476
477 if (type)
478 {
479 /*
480 * Call the given decoder to process the record.
481 */
482 odr_setbuf(in, (char*)p->u.octet_aligned->buf,
483 p->u.octet_aligned->len, 0);
484 if (!(*type->fun)(in, (char **)&rr, 0, 0))
485 {
486 odr_perror(in, "Decoding constructed record.");
487 fprintf(stderr, "[Near %d]\n", odr_offset(in));
488 fprintf(stderr, "Packet dump:\n---------\n");
489 odr_dumpBER(stderr, (char*)p->u.octet_aligned->buf,
490 p->u.octet_aligned->len);
491 fprintf(stderr, "---------\n");
492 exit(1);
493 }
494 /*
495 * Note: we throw away the original, BER-encoded record here.
496 * Do something else with it if you want to keep it.
497 */
498 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
499 r->which = type->what;
500 }
501 }
502 if (ent && ent->value == VAL_SOIF)
503 print_record((const unsigned char *) r->u.octet_aligned->buf, r->u.octet_aligned->len);
504 else if (r->which == Z_External_octet && p->u.octet_aligned->len)
505 {
506 /* johnmcp - this is called for USmarc for demo server, at least */
507 const char *octet_buf = (char*)p->u.octet_aligned->buf;
508 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
509 ent->value == VAL_HTML)
510 print_record((const unsigned char *) octet_buf,
511 p->u.octet_aligned->len);
512 else
513 {
514 /* johnmcp - here marc_display does the work */
515 if (marc_display (octet_buf, NULL) <= 0)
516 {
517 printf ("ISO2709 decoding failed, dumping record as is:\n");
518 print_record((const unsigned char*) octet_buf,
519 p->u.octet_aligned->len);
520 }
521 }
522 if (marcdump) /*here (false) */
523 fwrite (octet_buf, 1, p->u.octet_aligned->len, marcdump);
524 }
525 else if (ent && ent->value == VAL_SUTRS)
526 {
527 if (r->which != Z_External_sutrs)
528 {
529 printf("Expecting single SUTRS type for SUTRS.\n");
530 return;
531 }
532 print_record(r->u.sutrs->buf, r->u.sutrs->len);
533 }
534 else if (ent && ent->value == VAL_GRS1)
535 {
536 if (r->which != Z_External_grs1)
537 {
538 printf("Expecting single GRS type for GRS.\n");
539 return;
540 }
541 display_grs1(r->u.grs1, 0);
542 }
543 else
544 {
545 printf("Unknown record representation.\n");
546 if (!z_External(print, &r, 0, 0))
547 {
548 odr_perror(print, "Printing external");
549 odr_reset(print);
550 }
551 }
552}
553
554
555static void display_diagrecs(Z_DiagRec **pp, int num)
556{
557 int i;
558 oident *ent;
559 Z_DefaultDiagFormat *r;
560
561 printf("Diagnostic message(s) from database:\n");
562 for (i = 0; i<num; i++)
563 {
564 Z_DiagRec *p = pp[i];
565 if (p->which != Z_DiagRec_defaultFormat)
566 {
567 printf("Diagnostic record not in default format.\n");
568 return;
569 }
570 else
571 r = p->u.defaultFormat;
572 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
573 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
574 printf("Missing or unknown diagset\n");
575 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
576#ifdef ASN_COMPILED
577 switch (r->which)
578 {
579 case Z_DefaultDiagFormat_v2Addinfo:
580 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
581 break;
582 case Z_DefaultDiagFormat_v3Addinfo:
583 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
584 break;
585 }
586#else
587 if (r->addinfo && *r->addinfo)
588 printf(" -- '%s'\n", r->addinfo);
589 else
590 printf("\n");
591#endif
592 }
593}
594
595
596static void display_nameplusrecord(Z_NamePlusRecord *p)
597{
598 if (p->databaseName)
599 printf("[%s]", p->databaseName);
600 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
601 display_diagrecs(&p->u.surrogateDiagnostic, 1);
602 else if (p->which == Z_NamePlusRecord_databaseRecord)
603 display_record(p->u.databaseRecord);
604}
605
606static void display_records(Z_Records *p)
607{
608 int i;
609
610 if (p->which == Z_Records_NSD)
611 {
612#ifdef ASN_COMPILED
613 Z_DiagRec dr, *dr_p = &dr;
614 dr.which = Z_DiagRec_defaultFormat;
615 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
616 display_diagrecs (&dr_p, 1);
617#else
618 display_diagrecs (&p->u.nonSurrogateDiagnostic, 1);
619#endif
620 }
621 else if (p->which == Z_Records_multipleNSD)
622 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
623 p->u.multipleNonSurDiagnostics->num_diagRecs);
624 else
625 {
626 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
627 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
628 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
629 }
630}
631
632
633static int send_searchRequest(char *arg)
634{
635 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
636 Z_SearchRequest *req = apdu->u.searchRequest;
637 Z_Query query;
638 int oid[OID_SIZE];
639 char setstring[100];
640 Z_RPNQuery *RPNquery;
641 /* Odr_oct ccl_query; */
642
643 req->referenceId = set_refid (out);
644 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
645 {
646 static unsigned char big[2100];
647 static Odr_oct bigo;
648
649 /* send a very big referenceid to test transport stack etc. */
650 memset(big, 'A', 2100);
651 bigo.len = bigo.size = 2100;
652 bigo.buf = big;
653 req->referenceId = &bigo;
654 }
655
656 if (setnumber >= 0)
657 {
658 sprintf(setstring, "%d", ++setnumber);
659 req->resultSetName = setstring;
660 }
661 *req->smallSetUpperBound = smallSetUpperBound;
662 *req->largeSetLowerBound = largeSetLowerBound;
663 *req->mediumSetPresentNumber = mediumSetPresentNumber;
664 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
665 mediumSetPresentNumber > 0))
666 {
667 oident prefsyn;
668
669 prefsyn.proto = protocol;
670 prefsyn.oclass = CLASS_RECSYN;
671 prefsyn.value = recordsyntax;
672 req->preferredRecordSyntax =
673 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
674 req->smallSetElementSetNames =
675 req->mediumSetElementSetNames = elementSetNames;
676 }
677 req->num_databaseNames = num_databaseNames;
678 req->databaseNames = databaseNames;
679
680 req->query = &query;
681 /* johnmcp - this is where we choose our query format. either ccl or rpn */
682 /* switch (queryType)
683 {
684 case QueryType_Prefix: */
685 query.which = Z_Query_type_1;
686 RPNquery = p_query_rpn (out, protocol, arg);
687 if (!RPNquery)
688 {
689 printf("Prefix query error\n");
690 return (-1);
691 }
692 query.u.type_1 = RPNquery;
693 /* break;
694 case QueryType_CCL:
695 query.which = Z_Query_type_2;
696 query.u.type_2 = &ccl_query;
697 ccl_query.buf = (unsigned char*) arg;
698 ccl_query.len = strlen(arg);
699 break;
700 default:
701 printf ("Unsupported query type\n");
702 return 0;
703 }*/
704 send_apdu(apdu);
705 setno = 1;
706 /* printf("Sent searchRequest.\n"); */
707 return 0;
708}
709
710static int process_searchResponse(Z_SearchResponse *res)
711{
712 print_refid (res->referenceId);
713 if (!(*res->searchStatus)) {
714 /* this should return an error instead of 0 docs found... one day... */
715 return 0;
716 }
717 setno += *res->numberOfRecordsReturned;
718 if (res->records)
719 display_records(res->records);
720 return *res->resultCount;
721}
722
723static void print_level(int iLevel)
724{
725 int i;
726 for (i = 0; i < iLevel * 4; i++)
727 printf(" ");
728}
729
730static void print_int(int iLevel, const char *pTag, int *pInt)
731{
732 if (pInt != NULL)
733 {
734 print_level(iLevel);
735 printf("%s: %d\n", pTag, *pInt);
736 }
737}
738
739static void print_string(int iLevel, const char *pTag, const char *pString)
740{
741 if (pString != NULL)
742 {
743 print_level(iLevel);
744 printf("%s: %s\n", pTag, pString);
745 }
746}
747
748static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
749{
750 if (pOid != NULL)
751 {
752 int *pInt = pOid;
753
754 print_level(iLevel);
755 printf("%s:", pTag);
756 for (; *pInt != -1; pInt++)
757 printf(" %d", *pInt);
758 printf("\n");
759 }
760}
761
762static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
763{
764 if (referenceId != NULL)
765 {
766 int i;
767
768 print_level(iLevel);
769 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
770 for (i = 0; i < referenceId->len; i++)
771 printf("%c", referenceId->buf[i]);
772 printf("\n");
773 }
774}
775
776static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
777{
778 if (pStringNumeric != NULL)
779 {
780 switch (pStringNumeric->which)
781 {
782 case Z_StringOrNumeric_string:
783 print_string(iLevel, pTag, pStringNumeric->u.string);
784 break;
785
786 case Z_StringOrNumeric_numeric:
787 print_int(iLevel, pTag, pStringNumeric->u.numeric);
788 break;
789
790 default:
791 print_level(iLevel);
792 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
793 break;
794 }
795 }
796}
797
798static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
799{
800 if (pUniverseReportDuplicate != NULL)
801 {
802 print_level(iLevel);
803 printf("Universe Report Duplicate: \n");
804 iLevel++;
805 print_string_or_numeric(iLevel, "Hit No", pUniverseReportDuplicate->hitno);
806 }
807}
808
809static void print_universe_report_hits(int iLevel, Z_UniverseReportHits *pUniverseReportHits)
810{
811 if (pUniverseReportHits != NULL)
812 {
813 print_level(iLevel);
814 printf("Universe Report Hits: \n");
815 iLevel++;
816 print_string_or_numeric(iLevel, "Database", pUniverseReportHits->database);
817 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
818 }
819}
820
821static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
822{
823 if (pUniverseReport != NULL)
824 {
825 print_level(iLevel);
826 printf("Universe Report: \n");
827 iLevel++;
828 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
829 switch (pUniverseReport->which)
830 {
831 case Z_UniverseReport_databaseHits:
832 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
833 break;
834
835 case Z_UniverseReport_duplicate:
836 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
837 break;
838
839 default:
840 print_level(iLevel);
841 printf("Type: %d\n", pUniverseReport->which);
842 break;
843 }
844 }
845}
846
847static void print_external(int iLevel, Z_External *pExternal)
848{
849 if (pExternal != NULL)
850 {
851 print_level(iLevel);
852 printf("External: \n");
853 iLevel++;
854 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
855 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
856 print_string(iLevel, "Descriptor", pExternal->descriptor);
857 switch (pExternal->which)
858 {
859 case Z_External_universeReport:
860 print_universe_report(iLevel, pExternal->u.universeReport);
861 break;
862
863 default:
864 print_level(iLevel);
865 printf("Type: %d\n", pExternal->which);
866 break;
867 }
868 }
869}
870
871static int process_resourceControlRequest (Z_ResourceControlRequest *req)
872{
873 printf ("Received ResourceControlRequest.\n");
874 print_referenceId(1, req->referenceId);
875 print_int(1, "Suspended Flag", req->suspendedFlag);
876 print_int(1, "Partial Results Available", req->partialResultsAvailable);
877 print_int(1, "Response Required", req->responseRequired);
878 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
879 print_external(1, req->resourceReport);
880 return 0;
881}
882
883void process_ESResponse(Z_ExtendedServicesResponse *res)
884{
885 printf("process_ESResponse status=");
886 switch (*res->operationStatus)
887 {
888 case Z_ExtendedServicesResponse_done:
889 printf ("done\n");
890 break;
891 case Z_ExtendedServicesResponse_accepted:
892 printf ("accepted\n");
893 break;
894 case Z_ExtendedServicesResponse_failure:
895 printf ("failure\n");
896 display_diagrecs(res->diagnostics, res->num_diagnostics);
897 break;
898 }
899}
900
901#ifdef ASN_COMPILED
902
903const char *get_ill_element (void *clientData, const char *element)
904{
905 if (!strcmp (element, "ill,transaction-id,transaction-group-qualifier"))
906 return "1";
907 if (!strcmp (element, "ill,transaction-id,transaction-qualifier"))
908 return "1";
909 return 0;
910}
911
912#endif
913
914
915/* PRESENT SERVICE ----------------------------- */
916static int z_send_getbriefrecords(int starting, int set, int howmany) {
917 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
918 Z_PresentRequest *req = apdu->u.presentRequest;
919 Z_RecordComposition compo;
920 oident prefsyn;
921 int nos = 1;
922 int oid[OID_SIZE];
923 /* char *p;*/
924 char setstring[100];
925
926 req->referenceId = set_refid (out);
927 nos = howmany;
928
929 setno = starting;
930 setnumber=1;
931 sprintf(setstring, "%d", setnumber);
932 req->resultSetId = setstring;
933 req->resultSetStartPoint = &setno;
934 req->numberOfRecordsRequested = &nos;
935 prefsyn.proto = protocol;
936 prefsyn.oclass = CLASS_RECSYN;
937 prefsyn.value = recordsyntax;
938 req->preferredRecordSyntax =
939 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
940
941 if (schema != VAL_NONE)
942 {
943 oident prefschema;
944
945 prefschema.proto = protocol;
946 prefschema.oclass = CLASS_SCHEMA;
947 prefschema.value = schema;
948
949 req->recordComposition = &compo;
950 compo.which = Z_RecordComp_complex;
951 compo.u.complex = (Z_CompSpec *)
952 odr_malloc(out, sizeof(*compo.u.complex));
953 compo.u.complex->selectAlternativeSyntax = (bool_t *)
954 odr_malloc(out, sizeof(bool_t));
955 *compo.u.complex->selectAlternativeSyntax = 0;
956
957 compo.u.complex->generic = (Z_Specification *)
958 odr_malloc(out, sizeof(*compo.u.complex->generic));
959 compo.u.complex->generic->schema = (Odr_oid *)
960 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
961 if (!compo.u.complex->generic->schema)
962 {
963 /* OID wasn't a schema! Try record syntax instead. */
964 prefschema.oclass = CLASS_RECSYN;
965 compo.u.complex->generic->schema = (Odr_oid *)
966 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
967 }
968 if (!elementSetNames)
969 compo.u.complex->generic->elementSpec = 0;
970 else
971 {
972 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
973 odr_malloc(out, sizeof(Z_ElementSpec));
974 compo.u.complex->generic->elementSpec->which =
975 Z_ElementSpec_elementSetName;
976 compo.u.complex->generic->elementSpec->u.elementSetName =
977 elementSetNames->u.generic;
978 }
979 compo.u.complex->num_dbSpecific = 0;
980 compo.u.complex->dbSpecific = 0;
981 compo.u.complex->num_recordSyntax = 0;
982 compo.u.complex->recordSyntax = 0;
983 }
984 else if (elementSetNames)
985 {
986 req->recordComposition = &compo;
987 compo.which = Z_RecordComp_simple;
988 compo.u.simple = elementSetNames;
989 }
990 send_apdu(apdu);
991 return 0;
992}
993
994void process_close(Z_Close *req)
995{
996 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
997 Z_Close *res = apdu->u.close;
998
999 static char *reasons[] =
1000 {
1001 "finished",
1002 "shutdown",
1003 "system problem",
1004 "cost limit reached",
1005 "resources",
1006 "security violation",
1007 "protocolError",
1008 "lack of activity",
1009 "peer abort",
1010 "unspecified"
1011 };
1012
1013 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1014 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1015 if (sent_close)
1016 {
1017 cs_close (conn);
1018 conn = NULL;
1019 if (session_mem)
1020 {
1021 nmem_destroy (session_mem);
1022 session_mem = NULL;
1023 }
1024 sent_close = 0;
1025 }
1026 else
1027 {
1028 *res->closeReason = Z_Close_finished;
1029 send_apdu(apdu);
1030 printf("Sent response.\n");
1031 sent_close = 1;
1032 }
1033}
1034
1035
1036
1037int cmd_quit(char *arg)
1038{
1039 printf("See you later, alligator.\n");
1040 exit(0);
1041 return 0;
1042}
1043
1044int cmd_cancel(char *arg)
1045{
1046 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1047 Z_TriggerResourceControlRequest *req =
1048 apdu->u.triggerResourceControlRequest;
1049 bool_t rfalse = 0;
1050
1051 if (!conn)
1052 {
1053 printf("Session not initialized yet\n");
1054 return 0;
1055 }
1056 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1057 {
1058 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1059 return 0;
1060 }
1061 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1062 req->resultSetWanted = &rfalse;
1063
1064 send_apdu(apdu);
1065 printf("Sent cancel request\n");
1066 return 2;
1067}
1068
1069int send_scanrequest(char *string, int pp, int num)
1070{
1071 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1072 Z_ScanRequest *req = apdu->u.scanRequest;
1073
1074 if (!(req->termListAndStartPoint =
1075 p_query_scan(out, protocol, &req->attributeSet, string)))
1076 {
1077 printf("Prefix query error\n");
1078 return -1;
1079 }
1080 req->referenceId = set_refid (out);
1081 req->num_databaseNames = num_databaseNames;
1082 req->databaseNames = databaseNames;
1083 req->numberOfTermsRequested = &num;
1084 req->preferredPositionInResponse = &pp;
1085 send_apdu(apdu);
1086 return 2;
1087}
1088
1089int send_sortrequest(char *arg, int newset)
1090{
1091 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1092 Z_SortRequest *req = apdu->u.sortRequest;
1093 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1094 odr_malloc (out, sizeof(*sksl));
1095 char setstring[32];
1096 char sort_string[32], sort_flags[32];
1097 int off;
1098 int oid[OID_SIZE];
1099 oident bib1;
1100
1101 if (setnumber >= 0)
1102 sprintf (setstring, "%d", setnumber);
1103 else
1104 sprintf (setstring, "default");
1105
1106 req->referenceId = set_refid (out);
1107
1108#ifdef ASN_COMPILED
1109 req->num_inputResultSetNames = 1;
1110 req->inputResultSetNames = (Z_InternationalString **)
1111 odr_malloc (out, sizeof(*req->inputResultSetNames));
1112 req->inputResultSetNames[0] = odr_strdup (out, setstring);
1113#else
1114 req->inputResultSetNames =
1115 (Z_StringList *)odr_malloc (out, sizeof(*req->inputResultSetNames));
1116 req->inputResultSetNames->num_strings = 1;
1117 req->inputResultSetNames->strings =
1118 (char **)odr_malloc (out, sizeof(*req->inputResultSetNames->strings));
1119 req->inputResultSetNames->strings[0] =
1120 odr_strdup (out, setstring);
1121#endif
1122
1123 if (newset && setnumber >= 0)
1124 sprintf (setstring, "%d", ++setnumber);
1125
1126 req->sortedResultSetName = odr_strdup (out, setstring);
1127
1128 req->sortSequence = sksl;
1129 sksl->num_specs = 0;
1130 sksl->specs = (Z_SortKeySpec **)odr_malloc (out, sizeof(sksl->specs) * 20);
1131
1132 bib1.proto = protocol;
1133 bib1.oclass = CLASS_ATTSET;
1134 bib1.value = VAL_BIB1;
1135 while ((sscanf (arg, "%31s %31s%n", sort_string, sort_flags, &off)) == 2
1136 && off > 1)
1137 {
1138 int i;
1139 char *sort_string_sep;
1140 Z_SortKeySpec *sks = (Z_SortKeySpec *)odr_malloc (out, sizeof(*sks));
1141 Z_SortKey *sk = (Z_SortKey *)odr_malloc (out, sizeof(*sk));
1142
1143 arg += off;
1144 sksl->specs[sksl->num_specs++] = sks;
1145 sks->sortElement = (Z_SortElement *)odr_malloc (out, sizeof(*sks->sortElement));
1146 sks->sortElement->which = Z_SortElement_generic;
1147 sks->sortElement->u.generic = sk;
1148
1149 if ((sort_string_sep = strchr (sort_string, '=')))
1150 {
1151 Z_AttributeElement *el = (Z_AttributeElement *)odr_malloc (out, sizeof(*el));
1152 sk->which = Z_SortKey_sortAttributes;
1153 sk->u.sortAttributes =
1154 (Z_SortAttributes *)odr_malloc (out, sizeof(*sk->u.sortAttributes));
1155 sk->u.sortAttributes->id = oid_ent_to_oid(&bib1, oid);
1156 sk->u.sortAttributes->list =
1157 (Z_AttributeList *)odr_malloc (out, sizeof(*sk->u.sortAttributes->list));
1158 sk->u.sortAttributes->list->num_attributes = 1;
1159 sk->u.sortAttributes->list->attributes =
1160 (Z_AttributeElement **)odr_malloc (out,
1161 sizeof(*sk->u.sortAttributes->list->attributes));
1162 sk->u.sortAttributes->list->attributes[0] = el;
1163 el->attributeSet = 0;
1164 el->attributeType = (int *)odr_malloc (out, sizeof(*el->attributeType));
1165 *el->attributeType = atoi (sort_string);
1166 el->which = Z_AttributeValue_numeric;
1167 el->value.numeric = (int *)odr_malloc (out, sizeof(*el->value.numeric));
1168 *el->value.numeric = atoi (sort_string_sep + 1);
1169 }
1170 else
1171 {
1172 sk->which = Z_SortKey_sortField;
1173 sk->u.sortField = odr_strdup (out, sort_string);
1174 }
1175 sks->sortRelation = (int *)odr_malloc (out, sizeof(*sks->sortRelation));
1176 *sks->sortRelation = Z_SortRelation_ascending;
1177 sks->caseSensitivity = (int *)odr_malloc (out, sizeof(*sks->caseSensitivity));
1178 *sks->caseSensitivity = Z_SortCase_caseSensitive;
1179
1180#ifdef ASN_COMPILED
1181 sks->which = Z_SortKeySpec_null;
1182 sks->u.null = odr_nullval ();
1183#else
1184 sks->missingValueAction = NULL;
1185#endif
1186
1187 for (i = 0; sort_flags[i]; i++)
1188 {
1189 switch (sort_flags[i])
1190 {
1191 case 'a':
1192 case 'A':
1193 case '>':
1194 *sks->sortRelation = Z_SortRelation_descending;
1195 break;
1196 case 'd':
1197 case 'D':
1198 case '<':
1199 *sks->sortRelation = Z_SortRelation_ascending;
1200 break;
1201 case 'i':
1202 case 'I':
1203 *sks->caseSensitivity = Z_SortCase_caseInsensitive;
1204 break;
1205 case 'S':
1206 case 's':
1207 *sks->caseSensitivity = Z_SortCase_caseSensitive;
1208 break;
1209 }
1210 }
1211 }
1212 if (!sksl->num_specs)
1213 {
1214 printf ("Missing sort specifications\n");
1215 return -1;
1216 }
1217 send_apdu(apdu);
1218 return 2;
1219}
1220
1221void display_term(Z_TermInfo *t)
1222{
1223 if (t->term->which == Z_Term_general)
1224 {
1225 printf("%.*s (%d)\n", t->term->u.general->len, t->term->u.general->buf,
1226 t->globalOccurrences ? *t->globalOccurrences : -1);
1227 sprintf(last_scan, "%.*s", t->term->u.general->len,
1228 t->term->u.general->buf);
1229 }
1230 else
1231 printf("Term type not general.\n");
1232}
1233
1234void process_scanResponse(Z_ScanResponse *res)
1235{
1236 int i;
1237 Z_Entry **entries = NULL;
1238 int num_entries = 0;
1239
1240 printf("Received ScanResponse\n");
1241 print_refid (res->referenceId);
1242 printf("%d entries", *res->numberOfEntriesReturned);
1243 if (res->positionOfTerm)
1244 printf (", position=%d", *res->positionOfTerm);
1245 printf ("\n");
1246 if (*res->scanStatus != Z_Scan_success)
1247 printf("Scan returned code %d\n", *res->scanStatus);
1248 if (!res->entries)
1249 return;
1250 if ((entries = res->entries->entries))
1251 num_entries = res->entries->num_entries;
1252 for (i = 0; i < num_entries; i++)
1253 {
1254 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
1255 if (entries[i]->which == Z_Entry_termInfo)
1256 {
1257 printf("%c ", i + 1 == pos_term ? '*' : ' ');
1258 display_term(entries[i]->u.termInfo);
1259 }
1260 else
1261 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
1262 }
1263 if (res->entries->nonsurrogateDiagnostics)
1264 display_diagrecs (res->entries->nonsurrogateDiagnostics,
1265 res->entries->num_nonsurrogateDiagnostics);
1266}
1267
1268void process_sortResponse(Z_SortResponse *res)
1269{
1270 printf("Received SortResponse: status=");
1271 switch (*res->sortStatus)
1272 {
1273 case Z_SortStatus_success:
1274 printf ("success"); break;
1275 case Z_SortStatus_partial_1:
1276 printf ("partial"); break;
1277 case Z_SortStatus_failure:
1278 printf ("failure"); break;
1279 default:
1280 printf ("unknown (%d)", *res->sortStatus);
1281 }
1282 printf ("\n");
1283 print_refid (res->referenceId);
1284#ifdef ASN_COMPILED
1285 if (res->diagnostics)
1286 display_diagrecs(res->diagnostics,
1287 res->num_diagnostics);
1288#else
1289 if (res->diagnostics)
1290 display_diagrecs(res->diagnostics->diagRecs,
1291 res->diagnostics->num_diagRecs);
1292#endif
1293}
1294
1295void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
1296{
1297 printf("Got deleteResultSetResponse status=%d\n",
1298 *res->deleteOperationStatus);
1299 if (res->deleteListStatuses)
1300 {
1301 int i;
1302 for (i = 0; i < res->deleteListStatuses->num; i++)
1303 {
1304 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
1305 *res->deleteListStatuses->elements[i]->status);
1306 }
1307 }
1308}
1309
1310int cmd_sort_generic(char *arg, int newset)
1311{
1312 if (!conn)
1313 {
1314 printf("Session not initialized yet\n");
1315 return 0;
1316 }
1317 if (!ODR_MASK_GET(session->options, Z_Options_sort))
1318 {
1319 printf("Target doesn't support sort\n");
1320 return 0;
1321 }
1322 if (*arg)
1323 {
1324 if (send_sortrequest(arg, newset) < 0)
1325 return 0;
1326 return 2;
1327 }
1328 return 0;
1329}
1330
1331int cmd_sort(char *arg)
1332{
1333 return cmd_sort_generic (arg, 0);
1334}
1335
1336int cmd_sort_newset (char *arg)
1337{
1338 return cmd_sort_generic (arg, 1);
1339}
1340
1341int cmd_scan(char *arg)
1342{
1343 if (!conn)
1344 {
1345 printf("Session not initialized yet\n");
1346 return 0;
1347 }
1348 if (!ODR_MASK_GET(session->options, Z_Options_scan))
1349 {
1350 printf("Target doesn't support scan\n");
1351 return 0;
1352 }
1353 if (*arg)
1354 {
1355 if (send_scanrequest(arg, 1, 20) < 0)
1356 return 0;
1357 }
1358 else
1359 if (send_scanrequest(last_scan, 1, 20) < 0)
1360 return 0;
1361 return 2;
1362}
1363
1364int cmd_schema(char *arg)
1365{
1366 if (!arg || !*arg)
1367 {
1368 schema = VAL_NONE;
1369 return 1;
1370 }
1371 schema = oid_getvalbyname (arg);
1372 if (schema == VAL_NONE)
1373 {
1374 printf ("unknown schema\n");
1375 return 0;
1376 }
1377 return 1;
1378}
1379
1380int cmd_format(char *arg)
1381{
1382 if (!arg || !*arg)
1383 {
1384 printf("Usage: format <recordsyntax>\n");
1385 return 0;
1386 }
1387 recordsyntax = oid_getvalbyname (arg);
1388 if (recordsyntax == VAL_NONE)
1389 {
1390 printf ("unknown record syntax\n");
1391 return 0;
1392 }
1393 return 1;
1394}
1395
1396int cmd_elements(char *arg)
1397{
1398 static Z_ElementSetNames esn;
1399 static char what[100];
1400
1401 if (!arg || !*arg)
1402 {
1403 elementSetNames = 0;
1404 return 1;
1405 }
1406 strcpy(what, arg);
1407 esn.which = Z_ElementSetNames_generic;
1408 esn.u.generic = what;
1409 elementSetNames = &esn;
1410 return 1;
1411}
1412
1413int cmd_attributeset(char *arg)
1414{
1415 char what[100];
1416
1417 if (!arg || !*arg)
1418 {
1419 printf("Usage: attributeset <setname>\n");
1420 return 0;
1421 }
1422 sscanf(arg, "%s", what);
1423 if (p_query_attset (what))
1424 {
1425 printf("Unknown attribute set name\n");
1426 return 0;
1427 }
1428 return 1;
1429}
1430
1431int cmd_querytype (char *arg)
1432{
1433 if (!strcmp (arg, "ccl"))
1434 queryType = QueryType_CCL;
1435 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
1436 queryType = QueryType_Prefix;
1437 else
1438 {
1439 printf ("Querytype must be one of:\n");
1440 printf (" prefix - Prefix query\n");
1441 printf (" ccl - CCL query\n");
1442 return 0;
1443 }
1444 return 1;
1445}
1446
1447int cmd_refid (char *arg)
1448{
1449 xfree (refid);
1450 refid = NULL;
1451 if (*arg)
1452 {
1453 refid = (char *) xmalloc (strlen(arg)+1);
1454 strcpy (refid, arg);
1455 }
1456 return 1;
1457}
1458
1459int z_cmd_close(char *arg)
1460{
1461 Z_APDU *apdu;
1462 Z_Close *req;
1463 if (!conn)
1464 return 1;
1465
1466 apdu = zget_APDU(out, Z_APDU_close);
1467 req = apdu->u.close;
1468 *req->closeReason = Z_Close_finished;
1469 send_apdu(apdu);
1470 sent_close = 1;
1471 return 0;
1472}
1473
1474void z_initialize(void)
1475{
1476 nmem_init();
1477 if (!(out = odr_createmem(ODR_ENCODE)) ||
1478 !(in = odr_createmem(ODR_DECODE)) ||
1479 !(print = odr_createmem(ODR_PRINT)))
1480 {
1481 fprintf(stderr, "failed to allocate ODR streams\n");
1482 exit(1);
1483 }
1484 setvbuf(stdout, 0, _IONBF, 0);
1485 if (apdu_file)
1486 odr_setprint(print, apdu_file);
1487
1488 cmd_base("Default");
1489}
1490
1491static int z_getAPDU (Z_APDU **ret_apdu) {
1492 int res;
1493
1494 char *netbuffer= 0;
1495 int netbufferlen = 0;
1496 Z_APDU *apdu;
1497
1498 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0) {
1499 perror("cs_get");
1500 exit(1);
1501 }
1502 if (!res) {
1503 printf("Target closed connection.\n");
1504 exit(1);
1505 }
1506 odr_reset(in); /* release APDU from last round */
1507 record_last = 0;
1508 odr_setbuf(in, netbuffer, res, 0);
1509 /* johnmcp */
1510 if (!z_APDU(in, &apdu, 0, 0))
1511 {
1512 odr_perror(in, "Decoding incoming APDU");
1513 fprintf(stderr, "[Near %d]\n", odr_offset(in));
1514 fprintf(stderr, "Packet dump:\n---------\n");
1515 odr_dumpBER(stderr, netbuffer, res);
1516 fprintf(stderr, "---------\n");
1517 if (apdu_file)
1518 z_APDU(print, &apdu, 0, 0);
1519 exit(1);
1520 }
1521 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
1522 {
1523 odr_perror(print, "Failed to print incoming APDU");
1524 odr_reset(print);
1525 return -1; /* was continue */
1526 }
1527 (*ret_apdu)=apdu;
1528 return 0;
1529}
1530
1531
1532/* returns number found, arg is query string */
1533int z_cmd_dosearch(char *arg)
1534{
1535 Z_APDU *apdu;
1536 int matching;
1537 int ret_val;
1538 ret_val=send_searchRequest(arg);
1539 if (ret_val==-1) {
1540 /* prefix query error */
1541 return (-1);
1542 }
1543 z_getAPDU(&apdu);
1544 /* check return value??? */
1545 if (apdu->which != Z_APDU_searchResponse)
1546 {
1547 printf("sendsearchRequest() was not replied with a searchResponse!\n");
1548 return (-2);
1549 }
1550 /* let's keep going anyway... */
1551 matching=process_searchResponse(apdu->u.searchResponse);
1552 /* this assumes we want to take action on failure (-1) here rather than
1553 whereever we were called from */
1554 return (matching);
1555}
1556
1557/* src must be NULL-terminated */
1558static char *safeappendstr(char *dest, size_t *allocsize,
1559 size_t *offset, char *src) {
1560 /* allocsize is the amount of space currently allocated to dest,
1561 offset is how far into dest we want to append src */
1562 if (*offset + strlen(src) >= *allocsize) {
1563 *allocsize+=strlen(src)+64; /* add some extra space to save on reallocs */
1564 if ((dest=realloc(dest,*allocsize))==NULL) {
1565 fprintf(stderr, "malloc failed while decoding marc record.\n");
1566 return (NULL);
1567 }
1568 }
1569 strcpy(dest+(*offset), src);
1570 *offset+=strlen(src);
1571 return (dest);
1572}
1573
1574static char *getmarcfields(Z_DatabaseRecord *p, int titleonly) {
1575 /* this code is based on marc_display(), with a couple of lines taken from
1576 display_record() in the original client. */
1577 /* if titleonly is non-zero, we only get a (the?) title field, otherwise
1578 return the whole thing */
1579 const char *buf=(char *)p->u.octet_aligned->buf;
1580 char *title; /* our string to return */
1581 int title_maxlen=0; /* amount of space currently allocated */
1582 int title_curlen=0; /* amount of space actually used */
1583 int entry_p;
1584 int record_length;
1585 int indicator_length;
1586 int identifier_length;
1587 int base_address;
1588 int length_data_entry;
1589 int length_starting;
1590 int length_implementation;
1591 FILE *outf;
1592
1593 /* if (!outf) */
1594 outf = stdout;
1595
1596 /* initialise our title. Start with 64 chars */
1597 title_maxlen=64;
1598 if((title=malloc(title_maxlen))==NULL) {
1599 /* not quite sure where stderr will be going, but.... */
1600 fprintf(stderr,"Malloc failed while decoding marc record\n");
1601 return NULL;
1602 }
1603
1604 if (!titleonly) {
1605 strcpy(title,"<table border=1>\n");
1606 title_curlen=strlen(title);
1607 }
1608 else title_curlen=0;
1609
1610 record_length = atoi_n (buf, 5);
1611 if (record_length < 25)
1612 return (NULL); /* -1 */
1613 if (isdigit(buf[10]))
1614 indicator_length = atoi_n (buf+10, 1);
1615 else
1616 indicator_length = 2;
1617 if (isdigit(buf[11]))
1618 identifier_length = atoi_n (buf+11, 1);
1619 else
1620 identifier_length = 2;
1621 base_address = atoi_n (buf+12, 4);
1622
1623 length_data_entry = atoi_n (buf+20, 1);
1624 length_starting = atoi_n (buf+21, 1);
1625 length_implementation = atoi_n (buf+22, 1);
1626
1627 if (0) /* debug */
1628 {
1629 fprintf (outf, "Record length %5d\n", record_length);
1630 fprintf (outf, "Indicator length %5d\n", indicator_length);
1631 fprintf (outf, "Identifier length %5d\n", identifier_length);
1632 fprintf (outf, "Base address %5d\n", base_address);
1633 fprintf (outf, "Length data entry %5d\n", length_data_entry);
1634 fprintf (outf, "Length starting %5d\n", length_starting);
1635 fprintf (outf, "Length implementation %5d\n", length_implementation);
1636 }
1637 for (entry_p = 24; buf[entry_p] != ISO2709_FS; )
1638 {
1639 entry_p += 3+length_data_entry+length_starting;
1640 if (entry_p >= record_length)
1641 return (NULL); /* -1 */
1642 }
1643 base_address = entry_p+1;
1644 for (entry_p = 24; buf[entry_p] != ISO2709_FS; )
1645 {
1646 int data_length;
1647 int data_offset;
1648 int end_offset;
1649 int i /*, j*/ ;
1650 int startofstring;
1651 int whichtag;
1652 short int abbrtitle=0;
1653 char tag[4];
1654 memcpy (tag, buf+entry_p, 3);
1655 entry_p += 3;
1656 tag[3] = '\0';
1657 whichtag=atoi(tag);
1658 if (0) /* debug */
1659 fprintf (outf, "Tag: ");
1660 /* johnmcp
1661 Relevant tags (for "main entry") - assume only one of these is set,
1662 as we will only return the first one found.
1663 100=personal name
1664 110=corporate name
1665 111=meeting name
1666 130=uniform title
1667 subfields: $a=personal name, $c=title/other, $d=date
1668
1669 210=Abbreviated Title
1670 222=Key title
1671 240=uniform title
1672 243=collective uniform title
1673 245=title statement
1674 246=varying form of title
1675 247=former title or title variations
1676 subfields: $a=abbrev. title $b=qualifying info $2=source
1677 . $6=linkage $8=link field and sequence number.
1678 */
1679 /*fprintf (outf, "%s ", tag); */
1680 data_length = atoi_n (buf+entry_p, length_data_entry);
1681 entry_p += length_data_entry;
1682 data_offset = atoi_n (buf+entry_p, length_starting);
1683 entry_p += length_starting;
1684 i = data_offset + base_address;
1685 end_offset = i+data_length-1;
1686
1687 if (0) /* debug */
1688 fprintf (outf, " Ind: ");
1689
1690 /* memcmp (tag,"00",2) is true, then we DON'T have a control tag
1691 ie less than 10. */
1692 /*if (memcmp (tag, "00", 2) && indicator_length)
1693 {
1694 for (j = 0; j<indicator_length; j++)
1695 fprintf (outf, "%c", buf[i++]);
1696 }
1697 */
1698 if (whichtag>=10) i+=indicator_length;
1699 /* the control fields (<10) don't have leading chars. */
1700
1701
1702 if (0) /* debug */
1703 fprintf (outf, " Fields: ");
1704
1705 /* If we only want the title, then skip other fields */
1706 if (titleonly &&(whichtag<200||whichtag>249)) {
1707 /* skip this record */
1708 continue;
1709 i=end_offset;
1710 }
1711
1712 /* either titleonly is 0, or titleonly is 1 and whichtag is between
1713 200 and 249... */
1714 if (!titleonly) {
1715 /* This should probably be read in from a separate file.
1716 This is also hard-coded for USMARC/MARC21 fieldnames!!! */
1717
1718 /* print out what kind of tag this is */
1719 char *tagname;
1720 char *field_control1="<tr><td>Marc Control Number:</td><td>";
1721 char *field_control3="<tr><td>Marc Organisation Code:</td><td>";
1722 char *field_control5="<tr><td>Marc record Date Info.:</td><td>";
1723 char *field_control8="<tr><td>Control Field (Marc info):</td><td>";
1724 char *field_loc_nr="<tr><td>Lib. of Congress control #:</td><td>";
1725 char *field_issn="<tr><td>ISSN Number:</td><td>";
1726 char *field_catalog="<tr><td>Catalog agency:</td><td>";
1727 char *field_lang="<tr><td>3-letter language code(s):</td><td>";
1728 char *field_areacode="<tr><td>Geographic Area code:</td><td>";
1729 char *field_cn_loc="<tr><td>Lib. of Congress Call #:</td><td>";
1730 char *field_cn_dewdec="<tr><td>Dewey Decimal Call #:</td><td>";
1731 char *field_cn_other="<tr><td>Other Classification Info.:</td><td>";
1732 char *field_cn_gd="<tr><td>Govt. Document Call #:</td><td>";
1733 char *field_personalname="<tr><td>Personal Name:</td><td>";
1734 char *field_meetingname="<tr><td>Meeting Name:</td><td>";
1735 char *field_maintitle="<tr><td>Title:</td><td>";
1736 char *field_edition="<tr><td><Edition Information:</td><td>";
1737 char *field_publication="<tr><td>Publication Info.:</td><td>";
1738 char *field_physdesc="<tr><td>Physical Description:</td><td>";
1739 char *field_series_title="<tr><td>Series Title:</td><td>";
1740 char *field_series_statement="<tr><td>Series Statement:</td><td>";
1741 char *field_note_general="<tr><td>Note:</td><td>";
1742 char *field_note_bib="<tr><td>Bibliographic Note:</td><td>";
1743 char *field_note_summary="<tr><td>Summary Note:</td><td>";
1744 char *field_sub_note="<tr><td>Subject Notes:</td><td>";
1745 char *field_sub_topic="<tr><td>Subject - Topic:</td><td>";
1746 char *field_sub_geog="<tr><td>Subject - Location:</td><td>";
1747 char *field_added_persname="<tr><td>Author Note - Name:</td><td>";
1748 char *field_added_corpname="<tr><td>Author - Organisation:</td><td>";
1749 char *field_uniform_title="<tr><td>Extra Title Information:</td><td>";
1750 char *field_host_item="<tr><td>In:</td><td>";
1751 char *field_series_corpname="<tr><td>Series - Organisation:</td><td>";
1752 /*char *field_url="<tr><td>Electronic Access</td><td><a href=\"";*/
1753 char *field_url="<tr><td>Electronic Access</td><td>";
1754 /*char *field_other="<tr><td>(other field):</td><td>";*/
1755 char tag_num[100];
1756 switch (whichtag) {
1757 case (1): {tagname=field_control1;break;}
1758 case (3): {tagname=field_control3;break;}
1759 case (5): {tagname=field_control5;break;}
1760 case (8): {tagname=field_control8;break;}
1761 case (10): {tagname=field_loc_nr;break;}
1762 case (20): {tagname=field_issn;break;}
1763 case (40): {tagname=field_catalog;break;}
1764 case (41): {tagname=field_lang;break;}
1765 case (43): {tagname=field_areacode;break;}
1766 case (50): {tagname=field_cn_loc;break;}
1767 case (82): {tagname=field_cn_dewdec;break;}
1768 case (84): {tagname=field_cn_other;break;}
1769 case (86): {tagname=field_cn_gd;break;}
1770 case (100): {tagname=field_personalname;break;}
1771 case (111): {tagname=field_meetingname;break;}
1772 case (245): {tagname=field_maintitle;break;}
1773 case (250): {tagname=field_edition;break;}
1774 case (260): {tagname=field_publication;break;}
1775 case (300): {tagname=field_physdesc;break;}
1776 case (440): {tagname=field_series_title;break;}
1777 case (490): {tagname=field_series_statement;break;}
1778 case (500): {tagname=field_note_general;break;}
1779 case (504): {tagname=field_note_bib;break;}
1780 case (520): {tagname=field_note_summary;break;}
1781 case (630): {tagname=field_sub_note;break;}
1782 case (650): {tagname=field_sub_topic;break;}
1783 case (651): {tagname=field_sub_geog;break;}
1784 case (700): {tagname=field_added_persname;break;}
1785 case (710): {tagname=field_added_corpname;break;}
1786 case (730): {tagname=field_uniform_title;break;}
1787 case (773): {tagname=field_host_item;break;}
1788 case (810): {tagname=field_series_corpname;break;}
1789 case (856): {tagname=field_url;break;}
1790 default:
1791 if (whichtag>=90&&whichtag<=99)
1792 tagname="<tr><td>(obsolete field) Call #:</td><td>";
1793 else {
1794 /*tagname=field_other;*/
1795
1796 /*.*********** Following line "causes" (ie exposes) a seg fault
1797 in realloc(title,...). What is causing this????.
1798 ANSWER: The trailing '\0' needs to be explicit :-) */
1799 sprintf(tag_num,"<tr><td>(field %d)</td><td>\n\0",whichtag);
1800 tagname=tag_num;
1801 }
1802 }
1803
1804 /* add the field type */
1805 title=safeappendstr(title, &title_maxlen, &title_curlen, tagname);
1806 }
1807
1808 /* go through current field in current record */
1809 while (buf[i] != ISO2709_RS && buf[i] != ISO2709_FS && i < end_offset)
1810 {
1811 /* this loop goes through byte by byte, to find end-of-field or
1812 end-of-record separator tags */
1813
1814 /* if (memcmp (tag, "00", 2) && identifier_length)*/
1815 if ( ((titleonly==1&&whichtag==245)||(titleonly==0))
1816 && identifier_length)
1817 {
1818 if (buf[i]==ISO2709_IDFS) {
1819 /* this implies sub-fields for this field */
1820 /* skip sub-field tag, but wrap $a sub-field with <b> & </b>
1821 for HTML if titleonly==1 */
1822 if (buf[i+1]=='a' && titleonly) {
1823 abbrtitle=1;
1824 title=safeappendstr(title,&title_maxlen,&title_curlen,"<b>");
1825 }
1826 i+=identifier_length;
1827 }
1828 /* find end of this (sub-)field */
1829 startofstring=i;
1830 while (buf[i] != ISO2709_RS && buf[i] != ISO2709_IDFS &&
1831 buf[i] != ISO2709_FS && i < end_offset)
1832 i++;
1833 /*fprintf (outf, "%c", buf[i++]);*/
1834
1835 /* this only happens the first time around */
1836 if (i==startofstring) continue;
1837
1838 /* now put from $startofstring$ until $i$ into our
1839 string to return */
1840
1841 if (title_curlen+(i-startofstring)>=title_maxlen) {
1842 /* we need to make more room - add max(64,needed) bytes */
1843 if (title_curlen+(i-startofstring)-title_maxlen>63)
1844 title_maxlen+=(i-startofstring)+1;/*+1 for trailing \0 */
1845 else
1846 title_maxlen+=64;
1847 if ((title=realloc(title,title_maxlen))==NULL) {
1848 fprintf(stderr,"malloc failed decoding marc record\n");
1849 return (NULL);
1850 }
1851 }
1852
1853 strncpy(title+title_curlen,buf+startofstring,i-startofstring);
1854 title_curlen+=(i-startofstring);
1855 *(title+title_curlen)='\0';
1856 /* overwrite ISO2709_?S with \0 */
1857 /* *(title+title_curlen+i-startofstring)='\0';*/
1858 /*safeappendstr(title,&title_maxlen,
1859 &title_curlen,buf+startofstring);*/
1860
1861 /* if 'main' title, close HTML </B> tag */
1862 if (abbrtitle) {
1863 title=safeappendstr(title,&title_maxlen,&title_curlen,"</b>");
1864 abbrtitle=0;
1865 }
1866 /* end of this marc sub--field
1867 buf[i]==ISO2709_RS if end of record.
1868 buf[i]==ISO2709_FS if end of field,
1869 buf[i]==ISO2709_IDFS if end of sub-field. */
1870 if (titleonly==0) {
1871 if (buf[i]==ISO2709_IDFS) {
1872 /* there is a following sub-field, so only add whitespace */
1873 title=safeappendstr(title,&title_maxlen,&title_curlen," ");
1874 }
1875 else {
1876 /* end of record, so close HTML table row */
1877#if 0
1878 if (whichtag==856) /* special case: this is a url! */
1879 title=safeappendstr(title,&title_maxlen,&title_curlen,
1880 "\">Uniform Resource Locator</a>");
1881#endif
1882 title=safeappendstr(title, &title_maxlen, &title_curlen,
1883 "</td></tr>\n");
1884 }
1885 } /* end of if (titleonly==0) */
1886 } /* end of if ( ((titleonly==1&&....... */
1887 else { /* whichtag not matched (if titleonly) */
1888 /*fprintf (outf, "%c", buf[i++]);*/
1889 /* skip this char for now - should ideally skip whole field */
1890 i++;
1891 }
1892 } /* end of while loop - at end of field or record */
1893 /*fprintf (outf, "\n");*/
1894 /*if (i < end_offset)
1895 fprintf (outf, "-- separator but not at end of field\n");
1896 if (buf[i] != ISO2709_RS && buf[i] != ISO2709_FS)
1897 fprintf (outf, "-- no separator at end of field\n");
1898 */
1899 }
1900
1901 /* at end of whole record. */
1902 if (!titleonly)
1903 title=safeappendstr(title, &title_maxlen, &title_curlen, "</table>\n");
1904 return (title);
1905
1906}
1907static char *getrecordtitle(Z_DatabaseRecord *record) {
1908 return(getmarcfields(record,1));
1909}
1910
1911char *z_getfullRecord(int start) {
1912 Z_APDU *apdu;
1913 Z_DatabaseRecord *record;
1914 char *fullrecord;
1915
1916 fullrecord=NULL;
1917 z_send_getbriefrecords(start,1,1); /* for now, use getbriefrecords */
1918 z_getAPDU(&apdu);
1919
1920 if (apdu->which != Z_APDU_presentResponse) {
1921 /* out-of-order packets.... */
1922 fprintf(stderr,"Not a present response to present request\n");
1923 return NULL;
1924 }
1925
1926 /* just do some double checking */
1927 if (*apdu->u.presentResponse->numberOfRecordsReturned!=1 ||
1928 !apdu->u.presentResponse->records ||
1929 apdu->u.presentResponse->records->which!=Z_Records_DBOSD) {
1930 /* something bad has happened... johnmcp */
1931 fprintf (stderr,"Error occured in yaz while getting record (GSDL)\n");
1932 }
1933
1934 record=apdu->u.presentResponse->records->u.databaseOrSurDiagnostics->
1935 records[0]->u.databaseRecord;
1936
1937 return(getmarcfields(record,0));
1938}
1939
1940char **z_getrecordTitles(/*int resultset,*/ int starting, int howmany) {
1941 Z_APDU *apdu;
1942 char **titles;
1943 /* titles will be an array of strings. The first element will really
1944 be an int, saying how many strings follow. Ie 1st string in titles[1] */
1945 int count;
1946 int i;
1947
1948 titles=NULL;
1949
1950 /* WE SHOULD SET THE RECORD FORMAT SOMEWHERE..... USMARC (default)
1951 but may also want SUTRS support. */
1952
1953 /* sends a presentRequest - we need to know the set number - johnmcp */
1954 z_send_getbriefrecords(starting, 1, howmany);
1955 /* CHECK RETURN VALUE (currently only 0) */
1956
1957
1958 z_getAPDU(&apdu);
1959 if (apdu->which != Z_APDU_presentResponse) {
1960 /* we got out-of-sync.... */
1961 fprintf(stderr,"Not a present response to present request\n");
1962 return NULL;
1963 }
1964
1965 print_refid (apdu->u.presentResponse->referenceId);
1966 count=*apdu->u.presentResponse->numberOfRecordsReturned;
1967 setno += count;
1968 if (apdu->u.presentResponse->records) {
1969 /* extract the titles from each record, and return it as an array of
1970 strings */
1971 if (count==1 &&
1972 apdu->u.presentResponse->records->which!=Z_Records_DBOSD) {
1973 /* apdu->u.presentResponse->records->which gives a type:
1974 1=databaseOrSurDiagnostics | 2=nonSurrogateDiagnostic |
1975 3=multipleNonSurDiagnostics.
1976 Type 1 implies it is a database record. FROM z-core.h,
1977 NOT prt-proto.h!!!!! */
1978
1979 /* for type 2:
1980 apdu->u.presentResponse->records->u.nonSurrogateDiagnostic->which:
1981 1=v2Addinfo | 2=v3Addinfo, and u.v[23]Addinfo is a (char *).
1982
1983 */
1984 titles=malloc(sizeof(char *));
1985 titles[0]=(char *)0;
1986 /* could put error message and titles[1], and set titles[0] to -1. */
1987
1988
1989 }
1990 else /* more than 1 rec returned, so ?has? to be db records (dblcheck!!)*/
1991 {
1992 titles=malloc(sizeof(char *)*count + 1);
1993 /* check malloc succeeded... */
1994 titles[0]=(char *)count;
1995 for (i=1;i<=count;i++) {
1996 titles[i]=getrecordtitle(apdu->u.presentResponse->records->
1997 u.databaseOrSurDiagnostics->records[i-1]->
1998 u.databaseRecord);
1999 }
2000 }
2001 }
2002 else {
2003 titles=malloc(sizeof(char *));
2004 titles[0]=(char *)0;
2005 }
2006 /* printf ("nextResultSetPosition = %d\n",
2007 *apdu->u.presentResponse->nextResultSetPosition); */
2008 return (titles);
2009}
2010
2011
2012int z_getnextAPDU()
2013{
2014 Z_APDU *apdu;
2015 apdu=NULL;
2016
2017 z_getAPDU(&apdu);
2018
2019 switch(apdu->which)
2020 {
2021 case Z_APDU_initResponse:
2022 /* save session parameters for later use */
2023 session_mem = odr_extract_mem(in);
2024 session=apdu->u.initResponse;
2025 /*process_initResponse();*/
2026 break;
2027 case Z_APDU_searchResponse:
2028 process_searchResponse(apdu->u.searchResponse);
2029 break;
2030 case Z_APDU_scanResponse:
2031 process_scanResponse(apdu->u.scanResponse);
2032 break;
2033 case Z_APDU_presentResponse:
2034 print_refid (apdu->u.presentResponse->referenceId);
2035 setno +=
2036 *apdu->u.presentResponse->numberOfRecordsReturned;
2037 if (apdu->u.presentResponse->records)
2038 display_records(apdu->u.presentResponse->records);
2039 else
2040 printf("No records.\n");
2041 printf ("nextResultSetPosition = %d\n",
2042 *apdu->u.presentResponse->nextResultSetPosition);
2043 break;
2044 case Z_APDU_sortResponse:
2045 process_sortResponse(apdu->u.sortResponse);
2046 break;
2047 case Z_APDU_extendedServicesResponse:
2048 printf("Got extended services response\n");
2049 process_ESResponse(apdu->u.extendedServicesResponse);
2050 break;
2051 case Z_APDU_close:
2052 printf("Target has closed the association.\n");
2053 process_close(apdu->u.close);
2054 break;
2055 case Z_APDU_resourceControlRequest:
2056 process_resourceControlRequest
2057 (apdu->u.resourceControlRequest);
2058 break;
2059 case Z_APDU_deleteResultSetResponse:
2060 process_deleteResultSetResponse(apdu->u.
2061 deleteResultSetResponse);
2062 break;
2063 default:
2064 printf("Received unknown APDU type (%d).\n",
2065 apdu->which);
2066 exit(1);
2067 }
2068
2069 /*while (conn && cs_more(conn));*/
2070 return 0;
2071}
Note: See TracBrowser for help on using the repository browser.