2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.163 2002-08-26 12:15:35 adam Exp $
12 #include <yaz/yaz-util.h>
14 #include <yaz/comstack.h>
16 #include <yaz/proto.h>
17 #include <yaz/marcdisp.h>
18 #include <yaz/diagbib1.h>
19 #include <yaz/otherinfo.h>
20 #include <yaz/charneg.h>
22 #include <yaz/pquery.h>
23 #include <yaz/sortspec.h>
27 #include <yaz/yaz-ccl.h>
29 #if HAVE_READLINE_READLINE_H
30 #include <readline/readline.h>
33 #if HAVE_READLINE_HISTORY_H
34 #include <readline/history.h>
41 #include "tabcomplete.h"
43 #define C_PROMPT "Z> "
45 static ODR out, in, print; /* encoding and decoding streams */
46 static FILE *apdu_file = 0;
47 static COMSTACK conn = 0; /* our z-association */
48 static Z_IdAuthentication *auth = 0; /* our current auth definition */
49 char *databaseNames[128];
50 int num_databaseNames = 0;
51 static Z_External *record_last = 0;
52 static int setnumber = -1; /* current result set number */
53 static int smallSetUpperBound = 0;
54 static int largeSetLowerBound = 1;
55 static int mediumSetPresentNumber = 0;
56 static Z_ElementSetNames *elementSetNames = 0;
57 static int setno = 1; /* current set offset */
58 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
59 static enum oid_value recordsyntax = VAL_USMARC;
60 static enum oid_value schema = VAL_NONE;
61 static int sent_close = 0;
62 static NMEM session_mem = NULL; /* memory handle for init-response */
63 static Z_InitResponse *session = 0; /* session parameters */
64 static char last_scan_line[512] = "0";
65 static char last_scan_query[512] = "0";
66 static char ccl_fields[512] = "default.bib";
67 static char* esPackageName = 0;
68 static char* yazProxy = 0;
69 static int kilobytes = 1024;
70 static char* yazCharset = 0;
71 static char* yazLang = 0;
74 static char last_cmd[32] = "?";
75 static FILE *marcdump = 0;
76 static char *refid = NULL;
84 static QueryType queryType = QueryType_Prefix;
86 static CCL_bibset bibset; /* CCL bibset handle */
88 #if HAVE_READLINE_COMPLETION_OVER
91 /* readline doesn't have this var. Define it ourselves. */
92 int rl_attempted_completion_over = 0;
95 /* set this one to 1, to avoid decode of unknown MARCs */
96 #define AVOID_MARC_DECODE 1
98 /* nice helper macro as extensive tabbing gives spaces at the en of the args lines */
99 #define REMOVE_TAILING_BLANKS(a) {\
100 char* args_end=(a)+strlen(a)-1; \
101 while(isspace(*args_end)) {*args_end=0;--args_end;}; \
105 void process_cmd_line(char* line);
106 char ** readline_completer(char *text, int start, int end);
107 char *command_generator(const char *text, int state);
108 char** curret_global_list=NULL;
109 int cmd_register_tab(char* arg);
111 ODR getODROutputStream()
116 void send_apdu(Z_APDU *a)
123 z_APDU(print, &a, 0, 0);
126 if (!z_APDU(out, &a, 0, 0))
128 odr_perror(out, "Encoding APDU");
131 buf = odr_getbuf(out, &len, 0);
132 /* printf ("sending APDU of size %d\n", len); */
133 if (cs_put(conn, buf, len) < 0)
135 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
138 odr_reset(out); /* release the APDU structure */
141 static void print_stringn(const unsigned char *buf, size_t len)
144 for (i = 0; i<len; i++)
145 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
146 printf ("%c", buf[i]);
148 printf ("\\X%02X", buf[i]);
151 static void print_refid (Z_ReferenceId *id)
155 printf ("Reference Id: ");
156 print_stringn (id->buf, id->len);
161 static Z_ReferenceId *set_refid (ODR out)
166 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
167 id->size = id->len = strlen(refid);
168 id->buf = (unsigned char *) odr_malloc (out, id->len);
169 memcpy (id->buf, refid, id->len);
173 /* INIT SERVICE ------------------------------- */
175 static void send_initRequest(const char* type_and_host)
177 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
178 Z_InitRequest *req = apdu->u.initRequest;
180 ODR_MASK_SET(req->options, Z_Options_search);
181 ODR_MASK_SET(req->options, Z_Options_present);
182 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
183 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
184 ODR_MASK_SET(req->options, Z_Options_scan);
185 ODR_MASK_SET(req->options, Z_Options_sort);
186 ODR_MASK_SET(req->options, Z_Options_extendedServices);
187 ODR_MASK_SET(req->options, Z_Options_delSet);
189 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
190 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
191 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
193 *req->maximumRecordSize = 1024*kilobytes;
194 *req->preferredMessageSize = 1024*kilobytes;
196 req->idAuthentication = auth;
198 req->referenceId = set_refid (out);
201 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
204 if (yazCharset || yazLang) {
205 Z_OtherInformation **p;
206 Z_OtherInformationUnit *p0;
208 yaz_oi_APDU(apdu, &p);
210 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
211 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
213 p0->which = Z_OtherInfo_externallyDefinedInfo;
214 p0->information.externallyDefinedInfo =
215 yaz_set_proposal_charneg(out,
216 (const char**)&yazCharset, (yazCharset)?1:0,
217 (const char**)&yazLang, (yazLang)?1:0, 1);
222 printf("Sent initrequest.\n");
225 static int process_initResponse(Z_InitResponse *res)
227 /* save session parameters for later use */
228 session_mem = odr_extract_mem(in);
232 printf("Connection rejected by target.\n");
234 printf("Connection accepted by target.\n");
235 if (res->implementationId)
236 printf("ID : %s\n", res->implementationId);
237 if (res->implementationName)
238 printf("Name : %s\n", res->implementationName);
239 if (res->implementationVersion)
240 printf("Version: %s\n", res->implementationVersion);
241 if (res->userInformationField)
243 printf("UserInformationfield:\n");
244 if (!z_External(print, (Z_External**)&res-> userInformationField,
247 odr_perror(print, "Printing userinfo\n");
250 if (res->userInformationField->which == Z_External_octet)
252 printf("Guessing visiblestring:\n");
253 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
258 if (ODR_MASK_GET(res->options, Z_Options_search))
260 if (ODR_MASK_GET(res->options, Z_Options_present))
262 if (ODR_MASK_GET(res->options, Z_Options_delSet))
264 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
265 printf (" resourceReport");
266 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
267 printf (" resourceCtrl");
268 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
269 printf (" accessCtrl");
270 if (ODR_MASK_GET(res->options, Z_Options_scan))
272 if (ODR_MASK_GET(res->options, Z_Options_sort))
274 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
275 printf (" extendedServices");
276 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
277 printf (" level1Segmentation");
278 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
279 printf (" level2Segmentation");
280 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
281 printf (" concurrentOperations");
282 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
284 printf (" namedResultSets");
287 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
288 printf (" encapsulation");
289 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
290 printf (" resultCount");
291 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
292 printf (" negotiationModel");
293 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
294 printf (" duplicateDetection");
295 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
296 printf (" queryType104");
299 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
301 Z_CharSetandLanguageNegotiation *p =
302 yaz_get_charneg_record(res->otherInfo);
306 char *charset=NULL, *lang=NULL;
309 yaz_get_response_charneg(session_mem, p, &charset, &lang,
312 printf("Accepted character set : %s\n", charset);
313 printf("Accepted code language : %s\n", lang ? lang : "none");
314 printf("Accepted records in ...: %d\n", selected );
321 static int cmd_base(char *arg)
328 printf("Usage: base <database> <database> ...\n");
331 for (i = 0; i<num_databaseNames; i++)
332 xfree (databaseNames[i]);
333 num_databaseNames = 0;
337 if (!(cp = strchr(arg, ' ')))
338 cp = arg + strlen(arg);
341 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
342 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
343 databaseNames[num_databaseNames][cp - arg] = '\0';
345 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
357 int cmd_open(char *arg)
360 char type_and_host[101], base[101];
364 printf("Already connected.\n");
370 nmem_destroy (session_mem);
374 if (strncmp (arg, "unix:", 5) == 0)
377 conn = cs_create_host(arg, 1, &add);
382 if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
385 conn = cs_create_host(yazProxy, 1, &add);
387 conn = cs_create_host(type_and_host, 1, &add);
391 printf ("Couldn't create comstack\n");
394 printf("Connecting...");
396 if (cs_connect(conn, add) < 0)
398 printf ("error = %s\n", cs_strerror(conn));
399 if (conn->cerrno == CSYSERR)
407 send_initRequest(type_and_host);
413 int cmd_authentication(char *arg)
415 static Z_IdAuthentication au;
416 static char user[40], group[40], pass[40];
417 static Z_IdPass idPass;
422 printf("Auth field set to null\n");
426 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
429 printf("Auth field set to null\n");
435 au.which = Z_IdAuthentication_open;
441 au.which = Z_IdAuthentication_idPass;
442 au.u.idPass = &idPass;
443 idPass.groupId = NULL;
444 idPass.userId = user;
445 idPass.password = group;
450 au.which = Z_IdAuthentication_idPass;
451 au.u.idPass = &idPass;
452 idPass.groupId = group;
453 idPass.userId = user;
454 idPass.password = pass;
459 /* SEARCH SERVICE ------------------------------ */
460 static void display_record(Z_External *r);
462 static void display_variant(Z_Variant *v, int level)
466 for (i = 0; i < v->num_triples; i++)
468 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
469 *v->triples[i]->type);
470 if (v->triples[i]->which == Z_Triple_internationalString)
471 printf(",value=%s\n", v->triples[i]->value.internationalString);
477 static void display_grs1(Z_GenericRecord *r, int level)
485 for (i = 0; i < r->num_elements; i++)
489 printf("%*s", level * 4, "");
493 printf("%d,", *t->tagType);
496 if (t->tagValue->which == Z_StringOrNumeric_numeric)
497 printf("%d) ", *t->tagValue->u.numeric);
499 printf("%s) ", t->tagValue->u.string);
500 if (t->content->which == Z_ElementData_subtree)
502 if (!t->content->u.subtree)
503 printf (" (no subtree)\n");
507 display_grs1(t->content->u.subtree, level+1);
510 else if (t->content->which == Z_ElementData_string)
511 printf("%s\n", t->content->u.string);
512 else if (t->content->which == Z_ElementData_numeric)
513 printf("%d\n", *t->content->u.numeric);
514 else if (t->content->which == Z_ElementData_oid)
516 int *ip = t->content->u.oid;
519 if ((oent = oid_getentbyoid(t->content->u.oid)))
520 printf("OID: %s\n", oent->desc);
524 while (ip && *ip >= 0)
525 printf(" %d", *(ip++));
529 else if (t->content->which == Z_ElementData_noDataRequested)
530 printf("[No data requested]\n");
531 else if (t->content->which == Z_ElementData_elementEmpty)
532 printf("[Element empty]\n");
533 else if (t->content->which == Z_ElementData_elementNotThere)
534 printf("[Element not there]\n");
535 else if (t->content->which == Z_ElementData_date)
536 printf("Date: %s\n", t->content->u.date);
537 else if (t->content->which == Z_ElementData_ext)
539 printf ("External\n");
540 display_record (t->content->u.ext);
543 printf("? type = %d\n",t->content->which);
544 if (t->appliedVariant)
545 display_variant(t->appliedVariant, level+1);
546 if (t->metaData && t->metaData->supportedVariants)
550 printf("%*s---- variant list\n", (level+1)*4, "");
551 for (c = 0; c < t->metaData->num_supportedVariants; c++)
553 printf("%*svariant #%d\n", (level+1)*4, "", c);
554 display_variant(t->metaData->supportedVariants[c], level + 2);
561 static void print_record(const unsigned char *buf, size_t len)
564 print_stringn (buf, len);
565 /* add newline if not already added ... */
566 if (i <= 0 || buf[i-1] != '\n')
570 static void display_record(Z_External *r)
572 oident *ent = oid_getentbyoid(r->direct_reference);
576 * Tell the user what we got.
578 if (r->direct_reference)
580 printf("Record type: ");
582 printf("%s\n", ent->desc);
583 else if (!odr_oid(print, &r->direct_reference, 0, 0))
585 odr_perror(print, "print oid");
589 /* Check if this is a known, ASN.1 type tucked away in an octet string */
590 if (ent && r->which == Z_External_octet)
592 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
598 * Call the given decoder to process the record.
600 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
601 r->u.octet_aligned->len, 0);
602 if (!(*type->fun)(in, (char **)&rr, 0, 0))
604 odr_perror(in, "Decoding constructed record.");
605 fprintf(stderr, "[Near %d]\n", odr_offset(in));
606 fprintf(stderr, "Packet dump:\n---------\n");
607 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,r->u.octet_aligned->len);
608 fprintf(stderr, "---------\n");
610 /* note just ignores the error ant print the bytes form the octet_aligned laiter */
613 * Note: we throw away the original, BER-encoded record here.
614 * Do something else with it if you want to keep it.
616 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
617 r->which = type->what;
621 if (ent && ent->oclass != CLASS_RECSYN)
623 if (ent && ent->value == VAL_SOIF)
624 print_record((const unsigned char *) r->u.octet_aligned->buf,
625 r->u.octet_aligned->len);
626 else if (r->which == Z_External_octet && r->u.octet_aligned->len)
628 const char *octet_buf = (char*)r->u.octet_aligned->buf;
629 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
630 ent->value == VAL_HTML)
632 print_record((const unsigned char *) octet_buf,
633 r->u.octet_aligned->len);
635 else if (ent->value == VAL_POSTSCRIPT)
637 int size = r->u.octet_aligned->len;
640 print_record((const unsigned char *) octet_buf, size);
645 #if AVOID_MARC_DECODE
646 /* primitive check for a marc OID 5.1-29 except 16 */
647 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
648 ent->oidsuffix[1] != 16
654 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
655 r->u.octet_aligned->len) <= 0)
657 printf ("bad MARC. Dumping as it is:\n");
658 print_record((const unsigned char*) octet_buf,
659 r->u.octet_aligned->len);
664 print_record((const unsigned char*) octet_buf,
665 r->u.octet_aligned->len);
669 fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
671 else if (ent && ent->value == VAL_SUTRS)
673 if (r->which != Z_External_sutrs)
675 printf("Expecting single SUTRS type for SUTRS.\n");
678 print_record(r->u.sutrs->buf, r->u.sutrs->len);
680 else if (ent && ent->value == VAL_GRS1)
682 if (r->which != Z_External_grs1)
684 printf("Expecting single GRS type for GRS.\n");
687 display_grs1(r->u.grs1, 0);
691 printf("Unknown record representation.\n");
692 if (!z_External(print, &r, 0, 0))
694 odr_perror(print, "Printing external");
700 static void display_diagrecs(Z_DiagRec **pp, int num)
704 Z_DefaultDiagFormat *r;
706 printf("Diagnostic message(s) from database:\n");
707 for (i = 0; i<num; i++)
709 Z_DiagRec *p = pp[i];
710 if (p->which != Z_DiagRec_defaultFormat)
712 printf("Diagnostic record not in default format.\n");
716 r = p->u.defaultFormat;
717 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
718 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
719 printf("Missing or unknown diagset\n");
720 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
723 case Z_DefaultDiagFormat_v2Addinfo:
724 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
726 case Z_DefaultDiagFormat_v3Addinfo:
727 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
734 static void display_nameplusrecord(Z_NamePlusRecord *p)
737 printf("[%s]", p->databaseName);
738 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
739 display_diagrecs(&p->u.surrogateDiagnostic, 1);
740 else if (p->which == Z_NamePlusRecord_databaseRecord)
741 display_record(p->u.databaseRecord);
744 static void display_records(Z_Records *p)
748 if (p->which == Z_Records_NSD)
750 Z_DiagRec dr, *dr_p = &dr;
751 dr.which = Z_DiagRec_defaultFormat;
752 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
753 display_diagrecs (&dr_p, 1);
755 else if (p->which == Z_Records_multipleNSD)
756 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
757 p->u.multipleNonSurDiagnostics->num_diagRecs);
760 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
761 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
762 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
766 static int send_deleteResultSetRequest(char *arg)
771 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
772 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
774 req->referenceId = set_refid (out);
776 req->num_resultSetList =
777 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
778 names[0], names[1], names[2], names[3],
779 names[4], names[5], names[6], names[7]);
781 req->deleteFunction = (int *)
782 odr_malloc (out, sizeof(*req->deleteFunction));
783 if (req->num_resultSetList > 0)
785 *req->deleteFunction = Z_DeleteRequest_list;
786 req->resultSetList = (char **)
787 odr_malloc (out, sizeof(*req->resultSetList)*
788 req->num_resultSetList);
789 for (i = 0; i<req->num_resultSetList; i++)
790 req->resultSetList[i] = names[i];
794 *req->deleteFunction = Z_DeleteRequest_all;
795 req->resultSetList = 0;
799 printf("Sent deleteResultSetRequest.\n");
803 static int send_searchRequest(char *arg)
805 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
806 Z_SearchRequest *req = apdu->u.searchRequest;
809 struct ccl_rpn_node *rpn = NULL;
812 Z_RPNQuery *RPNquery;
815 if (queryType == QueryType_CCL2RPN)
817 rpn = ccl_find_str(bibset, arg, &error, &pos);
820 printf("CCL ERROR: %s\n", ccl_err_msg(error));
824 req->referenceId = set_refid (out);
825 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
827 static unsigned char big[2100];
830 /* send a very big referenceid to test transport stack etc. */
831 memset(big, 'A', 2100);
832 bigo.len = bigo.size = 2100;
834 req->referenceId = &bigo;
839 sprintf(setstring, "%d", ++setnumber);
840 req->resultSetName = setstring;
842 *req->smallSetUpperBound = smallSetUpperBound;
843 *req->largeSetLowerBound = largeSetLowerBound;
844 *req->mediumSetPresentNumber = mediumSetPresentNumber;
845 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
846 mediumSetPresentNumber > 0))
850 prefsyn.proto = protocol;
851 prefsyn.oclass = CLASS_RECSYN;
852 prefsyn.value = recordsyntax;
853 req->preferredRecordSyntax =
854 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
855 req->smallSetElementSetNames =
856 req->mediumSetElementSetNames = elementSetNames;
858 req->num_databaseNames = num_databaseNames;
859 req->databaseNames = databaseNames;
865 case QueryType_Prefix:
866 query.which = Z_Query_type_1;
867 RPNquery = p_query_rpn (out, protocol, arg);
870 printf("Prefix query error\n");
873 query.u.type_1 = RPNquery;
876 query.which = Z_Query_type_2;
877 query.u.type_2 = &ccl_query;
878 ccl_query.buf = (unsigned char*) arg;
879 ccl_query.len = strlen(arg);
881 case QueryType_CCL2RPN:
882 query.which = Z_Query_type_1;
883 RPNquery = ccl_rpn_query(out, rpn);
886 printf ("Couldn't convert from CCL to RPN\n");
889 query.u.type_1 = RPNquery;
890 ccl_rpn_delete (rpn);
893 printf ("Unsupported query type\n");
898 printf("Sent searchRequest.\n");
902 /* display Query Expression as part of searchResult-1 */
903 static void display_queryExpression (Z_QueryExpression *qe)
907 if (qe->which == Z_QueryExpression_term)
909 if (qe->u.term->queryTerm)
911 Z_Term *term = qe->u.term->queryTerm;
915 printf (" %.*s", term->u.general->len, term->u.general->buf);
917 case Z_Term_characterString:
918 printf (" %s", term->u.characterString);
921 printf (" %d", *term->u.numeric);
931 /* see if we can find USR:SearchResult-1 */
932 static void display_searchResult (Z_OtherInformation *o)
937 for (i = 0; i < o->num_elements; i++)
939 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
941 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
943 if (ext->which == Z_External_searchResult1)
946 Z_SearchInfoReport *sr = ext->u.searchResult1;
947 printf ("SearchResult-1:");
948 for (j = 0; j < sr->num; j++)
950 if (!sr->elements[j]->subqueryExpression)
952 display_queryExpression (
953 sr->elements[j]->subqueryExpression);
954 display_queryExpression (
955 sr->elements[j]->subqueryInterpretation);
956 display_queryExpression (
957 sr->elements[j]->subqueryRecommendation);
958 if (sr->elements[j]->subqueryCount)
959 printf ("(%d)", *sr->elements[j]->subqueryCount);
967 static int process_searchResponse(Z_SearchResponse *res)
969 printf ("Received SearchResponse.\n");
970 print_refid (res->referenceId);
971 if (*res->searchStatus)
972 printf("Search was a success.\n");
974 printf("Search was a bloomin' failure.\n");
975 printf("Number of hits: %d", *res->resultCount);
977 printf (", setno %d", setnumber);
979 display_searchResult (res->additionalSearchInfo);
980 printf("records returned: %d\n",
981 *res->numberOfRecordsReturned);
982 setno += *res->numberOfRecordsReturned;
984 display_records(res->records);
988 static void print_level(int iLevel)
991 for (i = 0; i < iLevel * 4; i++)
995 static void print_int(int iLevel, const char *pTag, int *pInt)
1000 printf("%s: %d\n", pTag, *pInt);
1004 static void print_string(int iLevel, const char *pTag, const char *pString)
1006 if (pString != NULL)
1008 print_level(iLevel);
1009 printf("%s: %s\n", pTag, pString);
1013 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1019 print_level(iLevel);
1020 printf("%s:", pTag);
1021 for (; *pInt != -1; pInt++)
1022 printf(" %d", *pInt);
1027 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1029 if (referenceId != NULL)
1033 print_level(iLevel);
1034 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1035 for (i = 0; i < referenceId->len; i++)
1036 printf("%c", referenceId->buf[i]);
1041 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1043 if (pStringNumeric != NULL)
1045 switch (pStringNumeric->which)
1047 case Z_StringOrNumeric_string:
1048 print_string(iLevel, pTag, pStringNumeric->u.string);
1051 case Z_StringOrNumeric_numeric:
1052 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1056 print_level(iLevel);
1057 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1063 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1065 if (pUniverseReportDuplicate != NULL)
1067 print_level(iLevel);
1068 printf("Universe Report Duplicate: \n");
1070 print_string_or_numeric(iLevel, "Hit No",
1071 pUniverseReportDuplicate->hitno);
1076 print_universe_report_hits(int iLevel,
1077 Z_UniverseReportHits *pUniverseReportHits)
1079 if (pUniverseReportHits != NULL)
1081 print_level(iLevel);
1082 printf("Universe Report Hits: \n");
1084 print_string_or_numeric(iLevel, "Database",
1085 pUniverseReportHits->database);
1086 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1090 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1092 if (pUniverseReport != NULL)
1094 print_level(iLevel);
1095 printf("Universe Report: \n");
1097 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1098 switch (pUniverseReport->which)
1100 case Z_UniverseReport_databaseHits:
1101 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
1104 case Z_UniverseReport_duplicate:
1105 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
1109 print_level(iLevel);
1110 printf("Type: %d\n", pUniverseReport->which);
1116 static void print_external(int iLevel, Z_External *pExternal)
1118 if (pExternal != NULL)
1120 print_level(iLevel);
1121 printf("External: \n");
1123 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1124 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1125 print_string(iLevel, "Descriptor", pExternal->descriptor);
1126 switch (pExternal->which)
1128 case Z_External_universeReport:
1129 print_universe_report(iLevel, pExternal->u.universeReport);
1133 print_level(iLevel);
1134 printf("Type: %d\n", pExternal->which);
1140 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1142 printf ("Received ResourceControlRequest.\n");
1143 print_referenceId(1, req->referenceId);
1144 print_int(1, "Suspended Flag", req->suspendedFlag);
1145 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1146 print_int(1, "Response Required", req->responseRequired);
1147 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1148 print_external(1, req->resourceReport);
1152 void process_ESResponse(Z_ExtendedServicesResponse *res)
1155 switch (*res->operationStatus)
1157 case Z_ExtendedServicesResponse_done:
1160 case Z_ExtendedServicesResponse_accepted:
1161 printf ("accepted\n");
1163 case Z_ExtendedServicesResponse_failure:
1164 printf ("failure\n");
1165 display_diagrecs(res->diagnostics, res->num_diagnostics);
1168 printf ("unknown\n");
1170 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1171 (res->num_diagnostics != 0) ) {
1172 display_diagrecs(res->diagnostics, res->num_diagnostics);
1174 print_refid (res->referenceId);
1175 if (res->taskPackage &&
1176 res->taskPackage->which == Z_External_extendedService)
1178 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1179 Odr_oct *id = taskPackage->targetReference;
1180 Z_External *ext = taskPackage->taskSpecificParameters;
1184 printf ("Target Reference: ");
1185 print_stringn (id->buf, id->len);
1188 if (ext->which == Z_External_update)
1190 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1191 if (utp && utp->targetPart)
1193 Z_IUTargetPart *targetPart = utp->targetPart;
1196 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1199 Z_IUTaskPackageRecordStructure *tpr =
1200 targetPart->taskPackageRecords[i];
1201 printf ("task package record %d\n", i+1);
1202 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1204 display_record (tpr->u.record);
1208 printf ("other type\n");
1216 const char *get_ill_element (void *clientData, const char *element)
1221 static Z_External *create_external_itemRequest()
1223 struct ill_get_ctl ctl;
1224 ILL_ItemRequest *req;
1226 int item_request_size = 0;
1227 char *item_request_buf = 0;
1231 ctl.f = get_ill_element;
1233 req = ill_get_ItemRequest(&ctl, "ill", 0);
1235 printf ("ill_get_ItemRequest failed\n");
1237 if (!ill_ItemRequest (out, &req, 0, 0))
1241 ill_ItemRequest(print, &req, 0, 0);
1244 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1245 if (item_request_buf)
1246 odr_setbuf (out, item_request_buf, item_request_size, 1);
1247 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1254 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1255 oid.proto = PROTO_GENERAL;
1256 oid.oclass = CLASS_GENERAL;
1257 oid.value = VAL_ISO_ILL_1;
1259 r = (Z_External *) odr_malloc (out, sizeof(*r));
1260 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1261 r->indirect_reference = 0;
1263 r->which = Z_External_single;
1265 r->u.single_ASN1_type = (Odr_oct *)
1266 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1267 r->u.single_ASN1_type->buf = (unsigned char *)
1268 odr_malloc (out, item_request_size);
1269 r->u.single_ASN1_type->len = item_request_size;
1270 r->u.single_ASN1_type->size = item_request_size;
1271 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1273 printf ("len = %d\n", item_request_size);
1278 static Z_External *create_external_ILL_APDU(int which)
1280 struct ill_get_ctl ctl;
1283 int ill_request_size = 0;
1284 char *ill_request_buf = 0;
1288 ctl.f = get_ill_element;
1290 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1292 if (!ill_APDU (out, &ill_apdu, 0, 0))
1296 printf ("-------------------\n");
1297 ill_APDU(print, &ill_apdu, 0, 0);
1299 printf ("-------------------\n");
1301 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1302 if (ill_request_buf)
1303 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1304 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1310 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1312 oid.proto = PROTO_GENERAL;
1313 oid.oclass = CLASS_GENERAL;
1314 oid.value = VAL_ISO_ILL_1;
1316 r = (Z_External *) odr_malloc (out, sizeof(*r));
1317 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1318 r->indirect_reference = 0;
1320 r->which = Z_External_single;
1322 r->u.single_ASN1_type = (Odr_oct *)
1323 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1324 r->u.single_ASN1_type->buf = (unsigned char *)
1325 odr_malloc (out, ill_request_size);
1326 r->u.single_ASN1_type->len = ill_request_size;
1327 r->u.single_ASN1_type->size = ill_request_size;
1328 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1329 printf ("len = %d\n", ill_request_size);
1335 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1337 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1338 oident ItemOrderRequest;
1340 ItemOrderRequest.proto = PROTO_Z3950;
1341 ItemOrderRequest.oclass = CLASS_EXTSERV;
1342 ItemOrderRequest.value = VAL_ITEMORDER;
1344 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1345 r->indirect_reference = 0;
1348 r->which = Z_External_itemOrder;
1350 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1351 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1352 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1354 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1355 odr_malloc(out,sizeof(Z_IORequest));
1356 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1358 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1359 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1360 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1361 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1362 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1363 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1365 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1366 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1367 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1369 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1370 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1371 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1372 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1374 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1375 (int *) odr_malloc(out, sizeof(int));
1376 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1378 if (!strcmp (type, "item") || !strcmp(type, "2"))
1380 printf ("using item-request\n");
1381 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1382 create_external_itemRequest();
1384 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1386 printf ("using ILL-request\n");
1387 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1388 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1390 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1392 const char *xml_buf =
1394 " <type>request</type>\n"
1395 " <libraryNo>000200</libraryNo>\n"
1396 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1398 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1399 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1402 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1407 static int send_itemorder(const char *type, int itemno)
1409 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1410 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1411 oident ItemOrderRequest;
1413 ItemOrderRequest.proto = PROTO_Z3950;
1414 ItemOrderRequest.oclass = CLASS_EXTSERV;
1415 ItemOrderRequest.value = VAL_ITEMORDER;
1416 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1417 req->packageName = esPackageName;
1419 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1425 static int cmd_update(char *arg)
1427 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1428 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1431 Z_IUOriginPartToKeep *toKeep;
1432 Z_IUSuppliedRecords *notToKeep;
1434 printf ("Update request\n");
1439 update_oid.proto = PROTO_Z3950;
1440 update_oid.oclass = CLASS_EXTSERV;
1441 update_oid.value = VAL_DBUPDATE;
1442 oid_ent_to_oid (&update_oid, oid);
1443 req->packageType = odr_oiddup(out,oid);
1444 req->packageName = esPackageName;
1446 req->referenceId = set_refid (out);
1448 r = req->taskSpecificParameters = (Z_External *)
1449 odr_malloc (out, sizeof(*r));
1450 r->direct_reference = odr_oiddup(out,oid);
1451 r->indirect_reference = 0;
1453 r->which = Z_External_update;
1454 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1455 r->u.update->which = Z_IUUpdate_esRequest;
1456 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1457 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1458 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1459 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1460 toKeep->databaseName = databaseNames[0];
1462 toKeep->elementSetName = 0;
1463 toKeep->actionQualifier = 0;
1464 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1465 *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1467 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1468 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1470 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1471 odr_malloc(out, sizeof(*notToKeep->elements));
1472 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1473 odr_malloc(out, sizeof(**notToKeep->elements));
1474 notToKeep->elements[0]->u.number = 0;
1475 notToKeep->elements[0]->supplementalId = 0;
1476 notToKeep->elements[0]->correlationInfo = 0;
1477 notToKeep->elements[0]->record = record_last;
1484 static int cmd_itemorder(char *arg)
1489 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1492 printf("Item order request\n");
1494 send_itemorder(type, itemno);
1498 static int cmd_find(char *arg)
1502 printf("Find what?\n");
1507 printf("Not connected yet\n");
1510 if (!send_searchRequest(arg))
1515 static int cmd_delete(char *arg)
1519 printf("Not connected yet\n");
1522 if (!send_deleteResultSetRequest(arg))
1527 static int cmd_ssub(char *arg)
1529 if (!(smallSetUpperBound = atoi(arg)))
1534 static int cmd_lslb(char *arg)
1536 if (!(largeSetLowerBound = atoi(arg)))
1541 static int cmd_mspn(char *arg)
1543 if (!(mediumSetPresentNumber = atoi(arg)))
1548 static int cmd_status(char *arg)
1550 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1551 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1552 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1556 static int cmd_setnames(char *arg)
1558 if (*arg == '1') /* enable ? */
1560 else if (*arg == '0') /* disable ? */
1562 else if (setnumber < 0) /* no args, toggle .. */
1568 printf("Set numbering enabled.\n");
1570 printf("Set numbering disabled.\n");
1574 /* PRESENT SERVICE ----------------------------- */
1576 static int send_presentRequest(char *arg)
1578 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1579 Z_PresentRequest *req = apdu->u.presentRequest;
1580 Z_RecordComposition compo;
1585 char setstring[100];
1587 req->referenceId = set_refid (out);
1588 if ((p = strchr(arg, '+')))
1595 if (p && (p=strchr(p+1, '+')))
1597 strcpy (setstring, p+1);
1598 req->resultSetId = setstring;
1600 else if (setnumber >= 0)
1602 sprintf(setstring, "%d", setnumber);
1603 req->resultSetId = setstring;
1605 req->resultSetStartPoint = &setno;
1606 req->numberOfRecordsRequested = &nos;
1607 prefsyn.proto = protocol;
1608 prefsyn.oclass = CLASS_RECSYN;
1609 prefsyn.value = recordsyntax;
1610 req->preferredRecordSyntax =
1611 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1613 if (schema != VAL_NONE)
1617 prefschema.proto = protocol;
1618 prefschema.oclass = CLASS_SCHEMA;
1619 prefschema.value = schema;
1621 req->recordComposition = &compo;
1622 compo.which = Z_RecordComp_complex;
1623 compo.u.complex = (Z_CompSpec *)
1624 odr_malloc(out, sizeof(*compo.u.complex));
1625 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1626 odr_malloc(out, sizeof(bool_t));
1627 *compo.u.complex->selectAlternativeSyntax = 0;
1629 compo.u.complex->generic = (Z_Specification *)
1630 odr_malloc(out, sizeof(*compo.u.complex->generic));
1631 compo.u.complex->generic->schema = (Odr_oid *)
1632 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1633 if (!compo.u.complex->generic->schema)
1635 /* OID wasn't a schema! Try record syntax instead. */
1636 prefschema.oclass = CLASS_RECSYN;
1637 compo.u.complex->generic->schema = (Odr_oid *)
1638 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1640 if (!elementSetNames)
1641 compo.u.complex->generic->elementSpec = 0;
1644 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1645 odr_malloc(out, sizeof(Z_ElementSpec));
1646 compo.u.complex->generic->elementSpec->which =
1647 Z_ElementSpec_elementSetName;
1648 compo.u.complex->generic->elementSpec->u.elementSetName =
1649 elementSetNames->u.generic;
1651 compo.u.complex->num_dbSpecific = 0;
1652 compo.u.complex->dbSpecific = 0;
1653 compo.u.complex->num_recordSyntax = 0;
1654 compo.u.complex->recordSyntax = 0;
1656 else if (elementSetNames)
1658 req->recordComposition = &compo;
1659 compo.which = Z_RecordComp_simple;
1660 compo.u.simple = elementSetNames;
1663 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1667 static void close_session (void)
1673 nmem_destroy (session_mem);
1679 void process_close(Z_Close *req)
1681 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1682 Z_Close *res = apdu->u.close;
1684 static char *reasons[] =
1689 "cost limit reached",
1691 "security violation",
1698 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1699 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1704 *res->closeReason = Z_Close_finished;
1706 printf("Sent response.\n");
1711 static int cmd_show(char *arg)
1715 printf("Not connected yet\n");
1718 if (!send_presentRequest(arg))
1723 int cmd_quit(char *arg)
1725 printf("See you later, alligator.\n");
1731 int cmd_cancel(char *arg)
1733 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1734 Z_TriggerResourceControlRequest *req =
1735 apdu->u.triggerResourceControlRequest;
1740 printf("Session not initialized yet\n");
1743 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1745 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1748 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1749 req->resultSetWanted = &rfalse;
1752 printf("Sent cancel request\n");
1756 int send_scanrequest(const char *query, int pp, int num, const char *term)
1758 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1759 Z_ScanRequest *req = apdu->u.scanRequest;
1763 if (queryType == QueryType_CCL2RPN)
1767 struct ccl_rpn_node *rpn;
1769 rpn = ccl_find_str (bibset, query, &error, &pos);
1772 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1776 bib1.proto = PROTO_Z3950;
1777 bib1.oclass = CLASS_ATTSET;
1778 bib1.value = VAL_BIB1;
1779 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1780 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1782 printf("Couldn't convert CCL to Scan term\n");
1785 ccl_rpn_delete (rpn);
1787 if (use_rpn && !(req->termListAndStartPoint =
1788 p_query_scan(out, protocol, &req->attributeSet, query)))
1790 printf("Prefix query error\n");
1795 if (req->termListAndStartPoint->term &&
1796 req->termListAndStartPoint->term->which == Z_Term_general &&
1797 req->termListAndStartPoint->term->u.general)
1799 req->termListAndStartPoint->term->u.general->buf =
1800 (unsigned char *) odr_strdup(out, term);
1801 req->termListAndStartPoint->term->u.general->len =
1802 req->termListAndStartPoint->term->u.general->size =
1806 req->referenceId = set_refid (out);
1807 req->num_databaseNames = num_databaseNames;
1808 req->databaseNames = databaseNames;
1809 req->numberOfTermsRequested = #
1810 req->preferredPositionInResponse = &pp;
1815 int send_sortrequest(char *arg, int newset)
1817 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1818 Z_SortRequest *req = apdu->u.sortRequest;
1819 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1820 odr_malloc (out, sizeof(*sksl));
1824 sprintf (setstring, "%d", setnumber);
1826 sprintf (setstring, "default");
1828 req->referenceId = set_refid (out);
1830 req->num_inputResultSetNames = 1;
1831 req->inputResultSetNames = (Z_InternationalString **)
1832 odr_malloc (out, sizeof(*req->inputResultSetNames));
1833 req->inputResultSetNames[0] = odr_strdup (out, setstring);
1835 if (newset && setnumber >= 0)
1836 sprintf (setstring, "%d", ++setnumber);
1838 req->sortedResultSetName = odr_strdup (out, setstring);
1840 req->sortSequence = yaz_sort_spec (out, arg);
1841 if (!req->sortSequence)
1843 printf ("Missing sort specifications\n");
1850 void display_term(Z_TermInfo *t)
1852 if (t->term->which == Z_Term_general)
1854 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1855 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1856 t->term->u.general->buf);
1859 printf("Term (not general)");
1860 if (t->globalOccurrences)
1861 printf (" (%d)\n", *t->globalOccurrences);
1866 void process_scanResponse(Z_ScanResponse *res)
1869 Z_Entry **entries = NULL;
1870 int num_entries = 0;
1872 printf("Received ScanResponse\n");
1873 print_refid (res->referenceId);
1874 printf("%d entries", *res->numberOfEntriesReturned);
1875 if (res->positionOfTerm)
1876 printf (", position=%d", *res->positionOfTerm);
1878 if (*res->scanStatus != Z_Scan_success)
1879 printf("Scan returned code %d\n", *res->scanStatus);
1882 if ((entries = res->entries->entries))
1883 num_entries = res->entries->num_entries;
1884 for (i = 0; i < num_entries; i++)
1886 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
1887 if (entries[i]->which == Z_Entry_termInfo)
1889 printf("%c ", i + 1 == pos_term ? '*' : ' ');
1890 display_term(entries[i]->u.termInfo);
1893 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
1895 if (res->entries->nonsurrogateDiagnostics)
1896 display_diagrecs (res->entries->nonsurrogateDiagnostics,
1897 res->entries->num_nonsurrogateDiagnostics);
1900 void process_sortResponse(Z_SortResponse *res)
1902 printf("Received SortResponse: status=");
1903 switch (*res->sortStatus)
1905 case Z_SortStatus_success:
1906 printf ("success"); break;
1907 case Z_SortStatus_partial_1:
1908 printf ("partial"); break;
1909 case Z_SortStatus_failure:
1910 printf ("failure"); break;
1912 printf ("unknown (%d)", *res->sortStatus);
1915 print_refid (res->referenceId);
1916 if (res->diagnostics)
1917 display_diagrecs(res->diagnostics,
1918 res->num_diagnostics);
1921 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
1923 printf("Got deleteResultSetResponse status=%d\n",
1924 *res->deleteOperationStatus);
1925 if (res->deleteListStatuses)
1928 for (i = 0; i < res->deleteListStatuses->num; i++)
1930 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
1931 *res->deleteListStatuses->elements[i]->status);
1936 int cmd_sort_generic(char *arg, int newset)
1940 printf("Session not initialized yet\n");
1943 if (!ODR_MASK_GET(session->options, Z_Options_sort))
1945 printf("Target doesn't support sort\n");
1950 if (send_sortrequest(arg, newset) < 0)
1957 int cmd_sort(char *arg)
1959 return cmd_sort_generic (arg, 0);
1962 int cmd_sort_newset (char *arg)
1964 return cmd_sort_generic (arg, 1);
1967 int cmd_scan(char *arg)
1971 printf("Session not initialized yet\n");
1974 if (!ODR_MASK_GET(session->options, Z_Options_scan))
1976 printf("Target doesn't support scan\n");
1981 strcpy (last_scan_query, arg);
1982 if (send_scanrequest(arg, 1, 20, 0) < 0)
1987 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
1993 int cmd_schema(char *arg)
2000 schema = oid_getvalbyname (arg);
2001 if (schema == VAL_NONE)
2003 printf ("unknown schema\n");
2009 int cmd_format(char *arg)
2013 printf("Usage: format <recordsyntax>\n");
2016 recordsyntax = oid_getvalbyname (arg);
2017 if (recordsyntax == VAL_NONE)
2019 printf ("unknown record syntax\n");
2025 int cmd_elements(char *arg)
2027 static Z_ElementSetNames esn;
2028 static char what[100];
2032 elementSetNames = 0;
2036 esn.which = Z_ElementSetNames_generic;
2037 esn.u.generic = what;
2038 elementSetNames = &esn;
2042 int cmd_attributeset(char *arg)
2048 printf("Usage: attributeset <setname>\n");
2051 sscanf(arg, "%s", what);
2052 if (p_query_attset (what))
2054 printf("Unknown attribute set name\n");
2060 int cmd_querytype (char *arg)
2062 if (!strcmp (arg, "ccl"))
2063 queryType = QueryType_CCL;
2064 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2065 queryType = QueryType_Prefix;
2066 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2067 queryType = QueryType_CCL2RPN;
2070 printf ("Querytype must be one of:\n");
2071 printf (" prefix - Prefix query\n");
2072 printf (" ccl - CCL query\n");
2073 printf (" ccl2rpn - CCL query converted to RPN\n");
2079 int cmd_refid (char *arg)
2085 refid = (char *) xmalloc (strlen(arg)+1);
2086 strcpy (refid, arg);
2091 int cmd_close(char *arg)
2098 apdu = zget_APDU(out, Z_APDU_close);
2099 req = apdu->u.close;
2100 *req->closeReason = Z_Close_finished;
2102 printf("Sent close request.\n");
2107 int cmd_packagename(char* arg)
2109 xfree (esPackageName);
2110 esPackageName = NULL;
2113 esPackageName = (char *) xmalloc (strlen(arg)+1);
2114 strcpy (esPackageName, arg);
2119 int cmd_proxy(char* arg)
2122 printf("Current proxy is `%s'\n", (yazCharset)?yazProxy:NULL);
2129 yazProxy = (char *) xmalloc (strlen(arg)+1);
2130 strcpy (yazProxy, arg);
2135 int cmd_charset(char* arg)
2137 char l1[30], l2[30];
2140 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2142 printf("Current character set is `%s'\n", (yazCharset) ?
2149 yazCharset = xstrdup(l1);
2152 odr_set_charset (out, l1, l2);
2153 odr_set_charset (in, l2, l1);
2158 int cmd_lang(char* arg)
2161 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2168 yazLang = (char *) xmalloc (strlen(arg)+1);
2169 strcpy (yazLang, arg);
2174 int cmd_source(char* arg)
2176 /* first should open the file and read one line at a time.. */
2178 char line[1024], *cp;
2181 char* args_end=(arg)+strlen(arg)-1;
2182 while(isspace(*args_end))
2187 REMOVE_TAILING_BLANKS(arg);
2190 fprintf(stderr,"Error in source command use a filename\n");
2194 includeFile = fopen (arg, "r");
2197 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2201 while(!feof(includeFile)) {
2202 memset(line,0,sizeof(line));
2203 fgets(line,sizeof(line),includeFile);
2205 if(strlen(line) < 2) continue;
2206 if(line[0] == '#') continue;
2208 if ((cp = strrchr (line, '\n')))
2211 process_cmd_line(line);
2214 if(fclose(includeFile)<0) {
2215 perror("unable to close include file");
2221 int cmd_subshell(char* args)
2226 system(getenv("SHELL"));
2232 int cmd_set_apdufile(char* arg)
2234 REMOVE_TAILING_BLANKS(arg);
2236 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2237 perror("unable to close apdu log file");
2245 if(!strcmp(arg,"-"))
2248 apdu_file=fopen(arg, "a");
2251 perror("unable to open apdu log file no apdu log loaded");
2253 odr_setprint(print, apdu_file);
2259 int cmd_set_cclfields(char* arg)
2263 REMOVE_TAILING_BLANKS(arg);
2265 bibset = ccl_qual_mk ();
2266 inf = fopen (arg, "r");
2269 ccl_qual_file (bibset, inf);
2276 int cmd_set_marcdump(char* arg)
2278 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2279 perror("unable to close apdu log file");
2287 if(!strcmp(arg,"-"))
2290 marcdump=fopen(arg, "a");
2293 perror("unable to open apdu marcdump file no marcdump done\n");
2299 int cmd_set_proxy(char* arg) {
2300 if(yazProxy) free(yazProxy);
2303 if(strlen(arg) > 1) {
2304 yazProxy=strdup(arg);
2310 this command takes 3 arge {name class oid}
2312 int cmd_register_oid(char* args) {
2317 {"appctx",CLASS_APPCTX},
2318 {"absyn",CLASS_ABSYN},
2319 {"attset",CLASS_ATTSET},
2320 {"transyn",CLASS_TRANSYN},
2321 {"diagset",CLASS_DIAGSET},
2322 {"recsyn",CLASS_RECSYN},
2323 {"resform",CLASS_RESFORM},
2324 {"accform",CLASS_ACCFORM},
2325 {"extserv",CLASS_EXTSERV},
2326 {"userinfo",CLASS_USERINFO},
2327 {"elemspec",CLASS_ELEMSPEC},
2328 {"varset",CLASS_VARSET},
2329 {"schema",CLASS_SCHEMA},
2330 {"tagset",CLASS_TAGSET},
2331 {"general",CLASS_GENERAL},
2334 char oname_str[101], oclass_str[101], oid_str[101];
2337 oid_class oidclass = CLASS_GENERAL;
2338 int val = 0, oid[OID_SIZE];
2339 struct oident * new_oident=NULL;
2341 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2342 oname_str,oclass_str, oid_str) < 1) {
2343 printf("Error in regristrate command \n");
2347 for (i = 0; oid_classes[i].className; i++) {
2348 if (!strcmp(oid_classes[i].className, oclass_str))
2350 oidclass=oid_classes[i].oclass;
2355 if(!(oid_classes[i].className)) {
2356 printf("Unknonwn oid class %s\n",oclass_str);
2364 while (isdigit (*name))
2366 val = val*10 + (*name - '0');
2379 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2380 if(strcmp(new_oident->desc,oname_str)) {
2381 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2387 int cmd_push_command(char* arg)
2389 #if HAVE_READLINE_HISTORY_H
2393 fprintf(stderr,"Not compiled with the readline/history module\n");
2398 void source_rcfile()
2400 /* Look for a $HOME/.yazclientrc and source it if it exists */
2401 struct stat statbuf;
2403 char* homedir=getenv("HOME");
2405 if(!homedir) return;
2407 sprintf(buffer,"%s/.yazclientrc",homedir);
2409 if(stat(buffer,&statbuf)==0) {
2413 if(stat(".yazclientrc",&statbuf)==0) {
2414 cmd_source(".yazclientrc");
2419 static void initialize(void)
2422 if (!(out = odr_createmem(ODR_ENCODE)) ||
2423 !(in = odr_createmem(ODR_DECODE)) ||
2424 !(print = odr_createmem(ODR_PRINT)))
2426 fprintf(stderr, "failed to allocate ODR streams\n");
2431 setvbuf(stdout, 0, _IONBF, 0);
2433 odr_setprint(print, apdu_file);
2435 bibset = ccl_qual_mk ();
2436 inf = fopen (ccl_fields, "r");
2439 ccl_qual_file (bibset, inf);
2442 cmd_base("Default");
2444 #if HAVE_READLINE_READLINE_H
2445 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2452 #if HAVE_GETTIMEOFDAY
2453 struct timeval tv_start, tv_end;
2456 void wait_and_handle_responce()
2461 int netbufferlen = 0;
2469 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2471 printf("Target closed connection\n");
2477 printf("Target closed connection.\n");
2481 odr_reset(in); /* release APDU from last round */
2483 odr_setbuf(in, netbuffer, res, 0);
2484 if (!z_APDU(in, &apdu, 0, 0))
2486 odr_perror(in, "Decoding incoming APDU");
2487 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2488 fprintf(stderr, "Packet dump:\n---------\n");
2489 odr_dumpBER(stderr, netbuffer, res);
2490 fprintf(stderr, "---------\n");
2492 z_APDU(print, &apdu, 0, 0);
2496 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2498 odr_perror(print, "Failed to print incoming APDU");
2504 case Z_APDU_initResponse:
2505 process_initResponse(apdu->u.initResponse);
2507 case Z_APDU_searchResponse:
2508 process_searchResponse(apdu->u.searchResponse);
2510 case Z_APDU_scanResponse:
2511 process_scanResponse(apdu->u.scanResponse);
2513 case Z_APDU_presentResponse:
2514 print_refid (apdu->u.presentResponse->referenceId);
2516 *apdu->u.presentResponse->numberOfRecordsReturned;
2517 if (apdu->u.presentResponse->records)
2518 display_records(apdu->u.presentResponse->records);
2520 printf("No records.\n");
2521 printf ("nextResultSetPosition = %d\n",
2522 *apdu->u.presentResponse->nextResultSetPosition);
2524 case Z_APDU_sortResponse:
2525 process_sortResponse(apdu->u.sortResponse);
2527 case Z_APDU_extendedServicesResponse:
2528 printf("Got extended services response\n");
2529 process_ESResponse(apdu->u.extendedServicesResponse);
2532 printf("Target has closed the association.\n");
2533 process_close(apdu->u.close);
2535 case Z_APDU_resourceControlRequest:
2536 process_resourceControlRequest
2537 (apdu->u.resourceControlRequest);
2539 case Z_APDU_deleteResultSetResponse:
2540 process_deleteResultSetResponse(apdu->u.
2541 deleteResultSetResponse);
2544 printf("Received unknown APDU type (%d).\n",
2549 while (conn && cs_more(conn));
2550 #if HAVE_GETTIMEOFDAY
2551 gettimeofday (&tv_end, 0);
2553 printf ("S/U S/U=%ld/%ld %ld/%ld",
2554 (long) tv_start.tv_sec,
2555 (long) tv_start.tv_usec,
2556 (long) tv_end.tv_sec,
2557 (long) tv_end.tv_usec);
2559 printf ("Elapsed: %.6f\n",
2560 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2561 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2568 int cmd_cclparse(char* arg) {
2570 struct ccl_rpn_node *rpn=NULL;
2573 rpn = ccl_find_str (bibset, arg, &error, &pos);
2576 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2577 printf ("%s\n", ccl_err_msg (error));
2583 ccl_pr_tree(rpn, stdout);
2587 ccl_rpn_delete(rpn);
2595 static int cmd_help (char *line);
2597 typedef char *(*completerFunctionType)(const char *text, int state);
2601 int (*fun)(char *arg);
2603 completerFunctionType rl_completerfunction;
2604 int complete_filenames;
2605 char **local_tabcompletes;
2607 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2608 {"quit", cmd_quit, "",NULL,0,NULL},
2609 {"find", cmd_find, "<query>",NULL,0,NULL},
2610 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2611 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2612 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2613 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2614 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2615 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2616 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2617 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2618 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2619 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2620 {"status", cmd_status, "",NULL,0,NULL},
2621 {"setnames", cmd_setnames, "",NULL,0,NULL},
2622 {"cancel", cmd_cancel, "",NULL,0,NULL},
2623 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2624 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
2625 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
2626 {"close", cmd_close, "",NULL,0,NULL},
2627 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
2628 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
2629 {"refid", cmd_refid, "<id>",NULL,0,NULL},
2630 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
2631 {"update", cmd_update, "<item>",NULL,0,NULL},
2632 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
2633 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
2634 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
2635 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
2636 {".", cmd_source, "<filename>",NULL,1,NULL},
2637 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
2638 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
2639 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
2640 {"set_cclfile", cmd_set_cclfields," <filename>",NULL,1,NULL},
2641 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
2642 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
2643 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
2644 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
2645 /* Server Admin Functions */
2646 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
2647 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
2648 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
2649 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
2650 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
2651 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
2652 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
2653 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
2654 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
2655 {"help", cmd_help, "", NULL,0,NULL},
2659 static int cmd_help (char *line)
2665 sscanf (line, "%20s", topic);
2668 printf("Commands:\n");
2669 for (i = 0; cmd[i].cmd; i++)
2670 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2671 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
2672 if (strcmp (topic, "find") == 0)
2675 printf (" \"term\" Simple Term\n");
2676 printf (" @attr [attset] type=value op Attribute\n");
2677 printf (" @and opl opr And\n");
2678 printf (" @or opl opr Or\n");
2679 printf (" @not opl opr And-Not\n");
2680 printf (" @set set Result set\n");
2682 printf ("Bib-1 attribute types\n");
2684 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
2685 printf ("2=Relation: ");
2686 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
2687 printf ("3=Position: ");
2688 printf ("1=First in Field 2=First in subfield 3=Any position\n");
2689 printf ("4=Structure: ");
2690 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
2691 printf ("5=Truncation: ");
2692 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
2693 printf ("6=Completeness:");
2694 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
2699 int cmd_register_tab(char* arg) {
2701 char command[101], tabargument[101];
2706 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
2710 /* locate the amdn in the list */
2711 for (i = 0; cmd[i].cmd; i++) {
2712 if (!strncmp(cmd[i].cmd, command, strlen(command))) {
2718 fprintf(stderr,"Unknown command %s\n",command);
2724 if(!cmd[i].local_tabcompletes) {
2725 cmd[i].local_tabcompletes = calloc(1,sizeof(char**));
2730 tabslist = cmd[i].local_tabcompletes;
2731 for(;tabslist && *tabslist;tabslist++) {
2735 cmd[i].local_tabcompletes=realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
2736 tabslist=cmd[i].local_tabcompletes;
2737 tabslist[num_of_tabs]=strdup(tabargument);
2738 tabslist[num_of_tabs+1]=NULL;
2743 void process_cmd_line(char* line)
2746 char word[32], arg[1024];
2748 #if HAVE_GETTIMEOFDAY
2749 gettimeofday (&tv_start, 0);
2752 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
2754 strcpy(word, last_cmd);
2759 strcpy(last_cmd, word);
2761 /* removed tailing spaces from the arg command */
2764 char* lastnonspace=NULL;
2773 *(++lastnonspace) = 0;
2777 for (i = 0; cmd[i].cmd; i++)
2778 if (!strncmp(cmd[i].cmd, word, strlen(word)))
2780 res = (*cmd[i].fun)(arg);
2784 if (!cmd[i].cmd) /* dump our help-screen */
2786 printf("Unknown command: %s.\n", word);
2791 if(apdu_file) fflush(apdu_file);
2794 wait_and_handle_responce();
2803 char *command_generator(const char *text, int state)
2809 for( ; cmd[idx].cmd; ++idx) {
2810 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
2811 ++idx; /* skip this entry on the next run */
2812 return strdup(cmd[idx-1].cmd);
2820 This function only known how to complete on the first word
2822 char ** readline_completer(char *text, int start, int end) {
2823 #if HAVE_READLINE_READLINE_H
2825 completerFunctionType completerToUse;
2828 #if HAVE_READLINE_RL_COMPLETION_MATCHES
2829 char** res=rl_completion_matches(text,
2832 char** res=completion_matches(text,
2833 (CPFunction*)command_generator);
2835 rl_attempted_completion_over = 1;
2838 char arg[1024],word[32];
2840 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
2841 rl_attempted_completion_over = 1;
2845 if(start != strlen(word) +1 ) {
2846 rl_attempted_completion_over = 1;
2849 for (i = 0; cmd[i].cmd; i++) {
2850 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
2855 if(!cmd[i].cmd) return NULL;
2858 curret_global_list = cmd[i].local_tabcompletes;
2860 completerToUse = cmd[i].rl_completerfunction;
2861 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
2862 completerToUse = default_completer;
2864 if(completerToUse) {
2865 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
2867 rl_completion_matches(text,
2871 completion_matches(text,
2872 (CPFunction*)completerToUse);
2874 if(!cmd[i].complete_filenames)
2875 rl_attempted_completion_over = 1;
2878 if(!cmd[i].complete_filenames)
2879 rl_attempted_completion_over = 1;
2889 static void client(void)
2895 #if HAVE_GETTIMEOFDAY
2896 gettimeofday (&tv_start, 0);
2901 char *line_in = NULL;
2902 #if HAVE_READLINE_READLINE_H
2905 line_in=readline(C_PROMPT);
2908 #if HAVE_READLINE_HISTORY_H
2910 add_history(line_in);
2912 strncpy(line, line_in, 1023);
2921 if (!fgets(line, 1023, stdin))
2923 if ((end_p = strchr (line, '\n')))
2926 process_cmd_line(line);
2930 int main(int argc, char **argv)
2933 char *open_command = 0;
2934 char *auth_command = 0;
2938 while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
2945 open_command = (char *) xmalloc (strlen(arg)+6);
2946 strcpy (open_command, "open ");
2947 strcat (open_command, arg);
2951 kilobytes = atoi(arg);
2954 if (!(marcdump = fopen (arg, "a")))
2961 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
2962 ccl_fields[sizeof(ccl_fields)-1] = '\0';
2965 if (!strcmp(arg, "-"))
2968 apdu_file=fopen(arg, "a");
2971 yazProxy=strdup(arg);
2976 auth_command = (char *) xmalloc (strlen(arg)+6);
2977 strcpy (auth_command, "auth ");
2978 strcat (auth_command, arg);
2982 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
2985 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
2986 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
2987 "[-k size] [<server-addr>]\n",
2995 #ifdef HAVE_GETTIMEOFDAY
2996 gettimeofday (&tv_start, 0);
2998 process_cmd_line (auth_command);
2999 #if HAVE_READLINE_HISTORY_H
3000 add_history(auth_command);
3002 xfree(auth_command);
3006 #ifdef HAVE_GETTIMEOFDAY
3007 gettimeofday (&tv_start, 0);
3009 process_cmd_line (open_command);
3010 #if HAVE_READLINE_HISTORY_H
3011 add_history(open_command);
3013 xfree(open_command);