2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.205 2003-07-23 12:57:22 mike Exp $
24 #define S_ISREG(x) (x & _S_IFREG)
25 #define S_ISDIR(x) (x & _S_IFDIR)
28 #include <yaz/yaz-util.h>
30 #include <yaz/comstack.h>
32 #include <yaz/proto.h>
33 #include <yaz/marcdisp.h>
34 #include <yaz/diagbib1.h>
35 #include <yaz/otherinfo.h>
36 #include <yaz/charneg.h>
38 #include <yaz/pquery.h>
39 #include <yaz/sortspec.h>
43 #include <yaz/yaz-ccl.h>
46 #if HAVE_READLINE_READLINE_H
47 #include <readline/readline.h>
50 #if HAVE_READLINE_HISTORY_H
51 #include <readline/history.h>
57 #include "tabcomplete.h"
59 #define C_PROMPT "Z> "
61 static char *codeset = 0; /* character set for output */
62 static int hex_dump = 0;
63 static ODR out, in, print; /* encoding and decoding streams */
65 static ODR srw_sr_odr_out = 0;
66 static Z_SRW_PDU *srw_sr = 0;
68 static FILE *apdu_file = 0;
69 static FILE *ber_file = 0;
70 static COMSTACK conn = 0; /* our z-association */
71 static Z_IdAuthentication *auth = 0; /* our current auth definition */
72 char *databaseNames[128];
73 int num_databaseNames = 0;
74 static Z_External *record_last = 0;
75 static int setnumber = -1; /* current result set number */
76 static int smallSetUpperBound = 0;
77 static int largeSetLowerBound = 1;
78 static int mediumSetPresentNumber = 0;
79 static Z_ElementSetNames *elementSetNames = 0;
80 static int setno = 1; /* current set offset */
81 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
82 static enum oid_value recordsyntax = VAL_USMARC;
83 static char *schema = 0;
84 static int sent_close = 0;
85 static NMEM session_mem = NULL; /* memory handle for init-response */
86 static Z_InitResponse *session = 0; /* session parameters */
87 static char last_scan_line[512] = "0";
88 static char last_scan_query[512] = "0";
89 static char ccl_fields[512] = "default.bib";
90 /* ### How can I set this path to use wherever YAZ is installed? */
91 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
92 static char *esPackageName = 0;
93 static char *yazProxy = 0;
94 static int kilobytes = 1024;
95 static char *negotiationCharset = 0;
96 static char *outputCharset = 0;
97 static char *marcCharset = 0;
98 static char* yazLang = 0;
100 static char last_cmd[32] = "?";
101 static FILE *marc_file = 0;
102 static char *refid = NULL;
103 static char *last_open_command = NULL;
104 static int auto_reconnect = 0;
114 static QueryType queryType = QueryType_Prefix;
116 static CCL_bibset bibset; /* CCL bibset handle */
117 static cql_transform_t cqltrans; /* CQL qualifier-set handle */
119 #if HAVE_READLINE_COMPLETION_OVER
122 /* readline doesn't have this var. Define it ourselves. */
123 int rl_attempted_completion_over = 0;
126 /* set this one to 1, to avoid decode of unknown MARCs */
127 #define AVOID_MARC_DECODE 1
129 #define maxOtherInfosSupported 10
133 } extraOtherInfos[maxOtherInfosSupported];
136 void process_cmd_line(char* line);
137 char ** readline_completer(char *text, int start, int end);
138 char *command_generator(const char *text, int state);
139 char** curret_global_list=NULL;
140 int cmd_register_tab(const char* arg);
142 static void close_session (void);
144 ODR getODROutputStream()
149 const char* query_type_as_string(QueryType q)
152 case QueryType_Prefix: return "prefix (RPN sent to server)";
153 case QueryType_CCL: return "CCL (CCL sent to server) ";
154 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
155 case QueryType_CQL: return "CQL (CQL sent to server)";
156 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
158 return "unknown Query type internal yaz-client error";
162 static void do_hex_dump(const char* buf, int len)
167 for( i=0; i<len ; i=i+16 )
170 for(x=0 ; i+x<len && x<16; ++x)
172 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
179 void add_otherInfos(Z_APDU *a)
181 Z_OtherInformation **oi;
185 for(i=0; i<maxOtherInfosSupported; ++i)
187 if(extraOtherInfos[i].oidval != -1)
188 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
189 1, extraOtherInfos[i].value);
193 int send_apdu(Z_APDU *a)
202 z_APDU(print, &a, 0, 0);
205 if (!z_APDU(out, &a, 0, 0))
207 odr_perror(out, "Encoding APDU");
211 buf = odr_getbuf(out, &len, 0);
213 odr_dumpBER(ber_file, buf, len);
214 /* printf ("sending APDU of size %d\n", len); */
215 if (cs_put(conn, buf, len) < 0)
217 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
221 do_hex_dump(buf,len);
222 odr_reset(out); /* release the APDU structure */
226 static void print_stringn(const unsigned char *buf, size_t len)
229 for (i = 0; i<len; i++)
230 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
231 printf ("%c", buf[i]);
233 printf ("\\X%02X", buf[i]);
236 static void print_refid (Z_ReferenceId *id)
240 printf ("Reference Id: ");
241 print_stringn (id->buf, id->len);
246 static Z_ReferenceId *set_refid (ODR out)
251 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
252 id->size = id->len = strlen(refid);
253 id->buf = (unsigned char *) odr_malloc (out, id->len);
254 memcpy (id->buf, refid, id->len);
258 /* INIT SERVICE ------------------------------- */
260 static void send_initRequest(const char* type_and_host)
262 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
263 Z_InitRequest *req = apdu->u.initRequest;
265 ODR_MASK_SET(req->options, Z_Options_search);
266 ODR_MASK_SET(req->options, Z_Options_present);
267 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
268 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
269 ODR_MASK_SET(req->options, Z_Options_scan);
270 ODR_MASK_SET(req->options, Z_Options_sort);
271 ODR_MASK_SET(req->options, Z_Options_extendedServices);
272 ODR_MASK_SET(req->options, Z_Options_delSet);
274 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
275 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
276 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
278 *req->maximumRecordSize = 1024*kilobytes;
279 *req->preferredMessageSize = 1024*kilobytes;
281 req->idAuthentication = auth;
283 req->referenceId = set_refid (out);
286 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
289 if (negotiationCharset || yazLang) {
290 Z_OtherInformation **p;
291 Z_OtherInformationUnit *p0;
293 yaz_oi_APDU(apdu, &p);
295 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
296 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
298 p0->which = Z_OtherInfo_externallyDefinedInfo;
299 p0->information.externallyDefinedInfo =
300 yaz_set_proposal_charneg(
302 (const char**)&negotiationCharset,
303 negotiationCharset ? 1 : 0,
304 (const char**)&yazLang, yazLang ? 1 : 0, 1);
309 printf("Sent initrequest.\n");
312 static int process_initResponse(Z_InitResponse *res)
315 /* save session parameters for later use */
316 session_mem = odr_extract_mem(in);
319 for (ver = 0; ver<5; ver++)
320 if (!ODR_MASK_GET(res->protocolVersion, ver))
324 printf("Connection rejected by v%d target.\n", ver);
326 printf("Connection accepted by v%d target.\n", ver);
327 if (res->implementationId)
328 printf("ID : %s\n", res->implementationId);
329 if (res->implementationName)
330 printf("Name : %s\n", res->implementationName);
331 if (res->implementationVersion)
332 printf("Version: %s\n", res->implementationVersion);
333 if (res->userInformationField)
335 Z_External *uif = res->userInformationField;
336 printf("UserInformationfield:\n");
337 if (!z_External(print, (Z_External**)&uif, 0, 0))
339 odr_perror(print, "Printing userinfo\n");
342 if (uif->which == Z_External_octet)
344 printf("Guessing visiblestring:\n");
345 printf("'%s'\n", uif->u. octet_aligned->buf);
346 } else if (uif->which == Z_External_single) {
347 /* Peek at any private Init-diagnostic APDUs */
348 Odr_any *sat = uif->u.single_ASN1_type;
349 printf("### NAUGHTY: External is '%s'\n", sat->buf);
354 if (ODR_MASK_GET(res->options, Z_Options_search))
356 if (ODR_MASK_GET(res->options, Z_Options_present))
358 if (ODR_MASK_GET(res->options, Z_Options_delSet))
360 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
361 printf (" resourceReport");
362 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
363 printf (" resourceCtrl");
364 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
365 printf (" accessCtrl");
366 if (ODR_MASK_GET(res->options, Z_Options_scan))
368 if (ODR_MASK_GET(res->options, Z_Options_sort))
370 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
371 printf (" extendedServices");
372 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
373 printf (" level1Segmentation");
374 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
375 printf (" level2Segmentation");
376 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
377 printf (" concurrentOperations");
378 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
380 printf (" namedResultSets");
383 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
384 printf (" encapsulation");
385 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
386 printf (" resultCount");
387 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
388 printf (" negotiationModel");
389 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
390 printf (" duplicateDetection");
391 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
392 printf (" queryType104");
395 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
397 Z_CharSetandLanguageNegotiation *p =
398 yaz_get_charneg_record(res->otherInfo);
402 char *charset=NULL, *lang=NULL;
405 yaz_get_response_charneg(session_mem, p, &charset, &lang,
408 printf("Accepted character set : %s\n", charset);
409 printf("Accepted code language : %s\n", lang ? lang : "none");
410 printf("Accepted records in ...: %d\n", selected );
417 static int set_base(const char *arg)
422 for (i = 0; i<num_databaseNames; i++)
423 xfree (databaseNames[i]);
424 num_databaseNames = 0;
428 if (!(cp = strchr(arg, ' ')))
429 cp = arg + strlen(arg);
432 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
433 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
434 databaseNames[num_databaseNames][cp - arg] = '\0';
436 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
445 if (num_databaseNames == 0)
447 num_databaseNames = 1;
448 databaseNames[0] = xstrdup("");
453 static int cmd_base(const char *arg)
457 printf("Usage: base <database> <database> ...\n");
460 return set_base(arg);
463 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
465 if(last_open_command != arg)
467 if(last_open_command) xfree(last_open_command);
468 last_open_command = xstrdup(new_open_command);
472 int session_connect(const char *arg)
475 char type_and_host[101];
476 const char *basep = 0;
483 nmem_destroy (session_mem);
487 cs_get_host_args(arg, &basep);
489 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
490 type_and_host[sizeof(type_and_host)-1] = '\0';
492 cmd_open_remember_last_open_command(arg,type_and_host);
495 conn = cs_create_host(yazProxy, 1, &add);
497 conn = cs_create_host(arg, 1, &add);
500 printf ("Couldn't create comstack\n");
505 if (conn->protocol == PROTO_HTTP)
507 printf ("SRW/HTTP not enabled in this YAZ\n");
513 protocol = conn->protocol;
514 if (conn->protocol == PROTO_HTTP)
518 printf("Connecting...");
520 if (cs_connect(conn, add) < 0)
522 printf ("error = %s\n", cs_strerror(conn));
523 if (conn->cerrno == CSYSERR)
526 yaz_strerror(msg, sizeof(msg));
527 printf ("%s\n", msg);
536 if (protocol == PROTO_Z3950)
538 send_initRequest(type_and_host);
544 int cmd_open(const char *arg)
546 static char cur_host[200];
549 strncpy (cur_host, arg, sizeof(cur_host)-1);
550 cur_host[sizeof(cur_host)-1] = 0;
552 return session_connect(cur_host);
559 if(!( auto_reconnect && last_open_command) ) return ;
561 open_command = (char *) xmalloc (strlen(last_open_command)+6);
562 strcpy (open_command, "open ");
564 strcat (open_command, last_open_command);
566 process_cmd_line(open_command);
571 int cmd_authentication(const char *arg)
573 static Z_IdAuthentication au;
574 static char user[40], group[40], pass[40];
575 static Z_IdPass idPass;
580 printf("Auth field set to null\n");
584 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
587 printf("Authentication set to null\n");
593 if (!strcmp(user, "-")) {
594 au.which = Z_IdAuthentication_anonymous;
595 printf("Authentication set to Anonymous\n");
597 au.which = Z_IdAuthentication_open;
599 printf("Authentication set to Open (%s)\n", user);
605 au.which = Z_IdAuthentication_idPass;
606 au.u.idPass = &idPass;
607 idPass.groupId = NULL;
608 idPass.userId = user;
609 idPass.password = group;
610 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
615 au.which = Z_IdAuthentication_idPass;
616 au.u.idPass = &idPass;
617 idPass.groupId = group;
618 idPass.userId = user;
619 idPass.password = pass;
620 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
626 /* SEARCH SERVICE ------------------------------ */
627 static void display_record(Z_External *r);
629 static void print_record(const unsigned char *buf, size_t len)
632 print_stringn (buf, len);
633 /* add newline if not already added ... */
634 if (i <= 0 || buf[i-1] != '\n')
638 static void display_record(Z_External *r)
640 oident *ent = oid_getentbyoid(r->direct_reference);
644 * Tell the user what we got.
646 if (r->direct_reference)
648 printf("Record type: ");
650 printf("%s\n", ent->desc);
651 else if (!odr_oid(print, &r->direct_reference, 0, 0))
653 odr_perror(print, "print oid");
657 /* Check if this is a known, ASN.1 type tucked away in an octet string */
658 if (ent && r->which == Z_External_octet)
660 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
666 * Call the given decoder to process the record.
668 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
669 r->u.octet_aligned->len, 0);
670 if (!(*type->fun)(in, (char **)&rr, 0, 0))
672 odr_perror(in, "Decoding constructed record.");
673 fprintf(stdout, "[Near %d]\n", odr_offset(in));
674 fprintf(stdout, "Packet dump:\n---------\n");
675 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
676 r->u.octet_aligned->len);
677 fprintf(stdout, "---------\n");
679 /* note just ignores the error ant print the bytes form the octet_aligned later */
682 * Note: we throw away the original, BER-encoded record here.
683 * Do something else with it if you want to keep it.
685 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
686 r->which = type->what;
690 if (ent && ent->oclass != CLASS_RECSYN)
692 if (ent && ent->value == VAL_SOIF)
693 print_record((const unsigned char *) r->u.octet_aligned->buf,
694 r->u.octet_aligned->len);
695 else if (r->which == Z_External_octet)
697 const char *octet_buf = (char*)r->u.octet_aligned->buf;
698 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
699 ent->value == VAL_HTML)
701 print_record((const unsigned char *) octet_buf,
702 r->u.octet_aligned->len);
704 else if (ent->value == VAL_POSTSCRIPT)
706 int size = r->u.octet_aligned->len;
709 print_record((const unsigned char *) octet_buf, size);
714 #if AVOID_MARC_DECODE
715 /* primitive check for a marc OID 5.1-29 except 16 */
716 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
717 ent->oidsuffix[1] != 16
726 yaz_marc_t mt = yaz_marc_create();
728 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
732 if (marcCharset && !strcmp(marcCharset, "auto"))
734 if (ent->value == VAL_USMARC)
736 if (octet_buf[9] == 'a')
744 else if (marcCharset)
746 if (outputCharset && from)
748 cd = yaz_iconv_open(outputCharset, from);
749 printf ("convert from %s to %s", from,
752 printf (" unsupported\n");
757 fwrite (result, 1, rlen, stdout);
761 size_t inbytesleft = rlen;
762 const char *inp = result;
766 size_t outbytesleft = sizeof(outbuf);
770 r = yaz_iconv (cd, (char**) &inp,
772 &outp, &outbytesleft);
773 if (r == (size_t) (-1))
775 int e = yaz_iconv_error(cd);
776 if (e != YAZ_ICONV_E2BIG)
779 fwrite (outbuf, outp - outbuf, 1, stdout);
785 printf ("bad MARC. Dumping as it is:\n");
786 print_record((const unsigned char*) octet_buf,
787 r->u.octet_aligned->len);
789 yaz_marc_destroy(mt);
795 print_record((const unsigned char*) octet_buf,
796 r->u.octet_aligned->len);
800 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
802 else if (ent && ent->value == VAL_SUTRS)
804 if (r->which != Z_External_sutrs)
806 printf("Expecting single SUTRS type for SUTRS.\n");
809 print_record(r->u.sutrs->buf, r->u.sutrs->len);
811 else if (ent && ent->value == VAL_GRS1)
814 if (r->which != Z_External_grs1)
816 printf("Expecting single GRS type for GRS.\n");
820 yaz_display_grs1(w, r->u.grs1, 0);
824 else if ( /* OPAC display not complete yet .. */
825 ent && ent->value == VAL_OPAC)
828 if (r->u.opac->bibliographicRecord)
829 display_record(r->u.opac->bibliographicRecord);
830 for (i = 0; i<r->u.opac->num_holdingsData; i++)
832 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
833 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
835 printf ("MARC holdings %d\n", i);
836 display_record(h->u.marcHoldingsRecord);
838 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
842 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
844 printf ("Data holdings %d\n", i);
845 if (data->typeOfRecord)
846 printf ("typeOfRecord: %s\n", data->typeOfRecord);
847 if (data->encodingLevel)
848 printf ("encodingLevel: %s\n", data->encodingLevel);
849 if (data->receiptAcqStatus)
850 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
851 if (data->generalRetention)
852 printf ("generalRetention: %s\n", data->generalRetention);
853 if (data->completeness)
854 printf ("completeness: %s\n", data->completeness);
855 if (data->dateOfReport)
856 printf ("dateOfReport: %s\n", data->dateOfReport);
858 printf ("nucCode: %s\n", data->nucCode);
859 if (data->localLocation)
860 printf ("localLocation: %s\n", data->localLocation);
861 if (data->shelvingLocation)
862 printf ("shelvingLocation: %s\n", data->shelvingLocation);
863 if (data->callNumber)
864 printf ("callNumber: %s\n", data->callNumber);
865 if (data->copyNumber)
866 printf ("copyNumber: %s\n", data->copyNumber);
867 if (data->publicNote)
868 printf ("publicNote: %s\n", data->publicNote);
869 if (data->reproductionNote)
870 printf ("reproductionNote: %s\n", data->reproductionNote);
871 if (data->termsUseRepro)
872 printf ("termsUseRepro: %s\n", data->termsUseRepro);
873 if (data->enumAndChron)
874 printf ("enumAndChron: %s\n", data->enumAndChron);
875 for (j = 0; j<data->num_volumes; j++)
877 printf ("volume %d\n", j);
878 if (data->volumes[j]->enumeration)
879 printf (" enumeration: %s\n",
880 data->volumes[j]->enumeration);
881 if (data->volumes[j]->chronology)
882 printf (" chronology: %s\n",
883 data->volumes[j]->chronology);
884 if (data->volumes[j]->enumAndChron)
885 printf (" enumAndChron: %s\n",
886 data->volumes[j]->enumAndChron);
888 for (j = 0; j<data->num_circulationData; j++)
890 printf ("circulation %d\n", j);
891 if (data->circulationData[j]->availableNow)
892 printf (" availableNow: %d\n",
893 *data->circulationData[j]->availableNow);
894 if (data->circulationData[j]->availablityDate)
895 printf (" availabiltyDate: %s\n",
896 data->circulationData[j]->availablityDate);
897 if (data->circulationData[j]->availableThru)
898 printf (" availableThru: %s\n",
899 data->circulationData[j]->availableThru);
900 if (data->circulationData[j]->restrictions)
901 printf (" restrictions: %s\n",
902 data->circulationData[j]->restrictions);
903 if (data->circulationData[j]->itemId)
904 printf (" itemId: %s\n",
905 data->circulationData[j]->itemId);
906 if (data->circulationData[j]->renewable)
907 printf (" renewable: %d\n",
908 *data->circulationData[j]->renewable);
909 if (data->circulationData[j]->onHold)
910 printf (" onHold: %d\n",
911 *data->circulationData[j]->onHold);
912 if (data->circulationData[j]->enumAndChron)
913 printf (" enumAndChron: %s\n",
914 data->circulationData[j]->enumAndChron);
915 if (data->circulationData[j]->midspine)
916 printf (" midspine: %s\n",
917 data->circulationData[j]->midspine);
918 if (data->circulationData[j]->temporaryLocation)
919 printf (" temporaryLocation: %s\n",
920 data->circulationData[j]->temporaryLocation);
927 printf("Unknown record representation.\n");
928 if (!z_External(print, &r, 0, 0))
930 odr_perror(print, "Printing external");
936 static void display_diagrecs(Z_DiagRec **pp, int num)
940 Z_DefaultDiagFormat *r;
942 printf("Diagnostic message(s) from database:\n");
943 for (i = 0; i<num; i++)
945 Z_DiagRec *p = pp[i];
946 if (p->which != Z_DiagRec_defaultFormat)
948 printf("Diagnostic record not in default format.\n");
952 r = p->u.defaultFormat;
953 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
954 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
955 printf("Missing or unknown diagset\n");
956 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
959 case Z_DefaultDiagFormat_v2Addinfo:
960 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
962 case Z_DefaultDiagFormat_v3Addinfo:
963 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
970 static void display_nameplusrecord(Z_NamePlusRecord *p)
973 printf("[%s]", p->databaseName);
974 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
975 display_diagrecs(&p->u.surrogateDiagnostic, 1);
976 else if (p->which == Z_NamePlusRecord_databaseRecord)
977 display_record(p->u.databaseRecord);
980 static void display_records(Z_Records *p)
984 if (p->which == Z_Records_NSD)
986 Z_DiagRec dr, *dr_p = &dr;
987 dr.which = Z_DiagRec_defaultFormat;
988 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
989 display_diagrecs (&dr_p, 1);
991 else if (p->which == Z_Records_multipleNSD)
992 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
993 p->u.multipleNonSurDiagnostics->num_diagRecs);
996 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
997 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
998 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1002 static int send_deleteResultSetRequest(const char *arg)
1007 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1008 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1010 req->referenceId = set_refid (out);
1012 req->num_resultSetList =
1013 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1014 names[0], names[1], names[2], names[3],
1015 names[4], names[5], names[6], names[7]);
1017 req->deleteFunction = (int *)
1018 odr_malloc (out, sizeof(*req->deleteFunction));
1019 if (req->num_resultSetList > 0)
1021 *req->deleteFunction = Z_DeleteRequest_list;
1022 req->resultSetList = (char **)
1023 odr_malloc (out, sizeof(*req->resultSetList)*
1024 req->num_resultSetList);
1025 for (i = 0; i<req->num_resultSetList; i++)
1026 req->resultSetList[i] = names[i];
1030 *req->deleteFunction = Z_DeleteRequest_all;
1031 req->resultSetList = 0;
1035 printf("Sent deleteResultSetRequest.\n");
1040 static int send_srw(Z_SRW_PDU *sr)
1042 const char *charset = negotiationCharset;
1043 const char *host_port = 0;
1046 Z_SOAP_Handler h[2] = {
1047 {"http://www.loc.gov/zing/srw/v1.0/", 0, (Z_SOAP_fun) yaz_srw_codec},
1050 ODR o = odr_createmem(ODR_ENCODE);
1052 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1055 path = odr_malloc(out, strlen(databaseNames[0])+2);
1057 strcpy(path+1, databaseNames[0]);
1059 gdu = z_get_HTTP_Request(out);
1060 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1064 const char *cp0 = strstr(host_port, "://");
1065 const char *cp1 = 0;
1071 cp1 = strchr(cp0, '/');
1073 cp1 = cp0+strlen(cp0);
1077 char *h = odr_malloc(out, cp1 - cp0 + 1);
1078 memcpy (h, cp0, cp1 - cp0);
1080 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1085 strcpy(ctype, "text/xml");
1086 if (charset && strlen(charset) < 20)
1088 strcat(ctype, "; charset=");
1089 strcat(ctype, charset);
1091 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1092 "Content-Type", ctype);
1093 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1094 "SOAPAction", "\"\"");
1095 p->which = Z_SOAP_generic;
1096 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1097 p->u.generic->no = 0;
1098 p->u.generic->ns = 0;
1099 p->u.generic->p = sr;
1100 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1102 ret = z_soap_codec_enc(o, &p,
1103 &gdu->u.HTTP_Request->content_buf,
1104 &gdu->u.HTTP_Request->content_len, h,
1107 if (z_GDU(out, &gdu, 0, 0))
1113 buf_out = odr_getbuf(out, &len_out, 0);
1115 /* we don't odr_reset(out), since we may need the buffer again */
1117 r = cs_put(conn, buf_out, len_out);
1129 static int send_SRW_searchRequest(const char *arg)
1135 assert(srw_sr_odr_out == 0);
1136 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1138 odr_reset(srw_sr_odr_out);
1142 /* save this for later .. when fetching individual records */
1143 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1144 sr->u.request->query_type = Z_SRW_query_type_cql;
1145 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1147 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1148 sr->u.request->query_type = Z_SRW_query_type_cql;
1149 sr->u.request->query.cql = odr_strdup(out, arg);
1151 sr->u.request->recordSchema = schema;
1152 return send_srw(sr);
1156 static int send_searchRequest(const char *arg)
1158 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1159 Z_SearchRequest *req = apdu->u.searchRequest;
1162 struct ccl_rpn_node *rpn = NULL;
1164 char setstring[100];
1165 Z_RPNQuery *RPNquery;
1167 YAZ_PQF_Parser pqf_parser;
1169 QueryType myQueryType = queryType;
1172 if (myQueryType == QueryType_CCL2RPN)
1174 rpn = ccl_find_str(bibset, arg, &error, &pos);
1177 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1180 } else if (myQueryType == QueryType_CQL2RPN) {
1181 /* ### All this code should be wrapped in a utility function */
1183 struct cql_node *node;
1184 const char *addinfo;
1185 if (cqltrans == 0) {
1186 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1189 parser = cql_parser_create();
1190 if ((error = cql_parser_string(parser, arg)) != 0) {
1191 printf("Can't parse CQL: must be a syntax error\n");
1194 node = cql_parser_result(parser);
1195 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1196 sizeof pqfbuf)) != 0) {
1197 error = cql_transform_error(cqltrans, &addinfo);
1198 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1199 cql_strerror(error), addinfo);
1203 myQueryType = QueryType_Prefix;
1206 req->referenceId = set_refid (out);
1207 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1209 static unsigned char big[2100];
1210 static Odr_oct bigo;
1212 /* send a very big referenceid to test transport stack etc. */
1213 memset(big, 'A', 2100);
1214 bigo.len = bigo.size = 2100;
1216 req->referenceId = &bigo;
1221 sprintf(setstring, "%d", ++setnumber);
1222 req->resultSetName = setstring;
1224 *req->smallSetUpperBound = smallSetUpperBound;
1225 *req->largeSetLowerBound = largeSetLowerBound;
1226 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1227 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1228 mediumSetPresentNumber > 0))
1232 prefsyn.proto = protocol;
1233 prefsyn.oclass = CLASS_RECSYN;
1234 prefsyn.value = recordsyntax;
1235 req->preferredRecordSyntax =
1236 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1237 req->smallSetElementSetNames =
1238 req->mediumSetElementSetNames = elementSetNames;
1240 req->num_databaseNames = num_databaseNames;
1241 req->databaseNames = databaseNames;
1243 req->query = &query;
1245 switch (myQueryType)
1247 case QueryType_Prefix:
1248 query.which = Z_Query_type_1;
1249 pqf_parser = yaz_pqf_create ();
1250 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1253 const char *pqf_msg;
1255 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1256 printf("%*s^\n", off+4, "");
1257 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1259 yaz_pqf_destroy (pqf_parser);
1262 yaz_pqf_destroy (pqf_parser);
1263 query.u.type_1 = RPNquery;
1266 query.which = Z_Query_type_2;
1267 query.u.type_2 = &ccl_query;
1268 ccl_query.buf = (unsigned char*) arg;
1269 ccl_query.len = strlen(arg);
1271 case QueryType_CCL2RPN:
1272 query.which = Z_Query_type_1;
1273 RPNquery = ccl_rpn_query(out, rpn);
1276 printf ("Couldn't convert from CCL to RPN\n");
1279 query.u.type_1 = RPNquery;
1280 ccl_rpn_delete (rpn);
1283 query.which = Z_Query_type_104;
1284 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1285 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1286 ext->indirect_reference = 0;
1287 ext->descriptor = 0;
1288 ext->which = Z_External_CQL;
1289 ext->u.cql = odr_strdup(out, arg);
1290 query.u.type_104 = ext;
1293 printf ("Unsupported query type\n");
1296 if (send_apdu(apdu))
1297 printf("Sent searchRequest.\n");
1302 /* display Query Expression as part of searchResult-1 */
1303 static void display_queryExpression (Z_QueryExpression *qe)
1307 if (qe->which == Z_QueryExpression_term)
1309 if (qe->u.term->queryTerm)
1311 Z_Term *term = qe->u.term->queryTerm;
1312 switch (term->which)
1314 case Z_Term_general:
1315 printf (" %.*s", term->u.general->len, term->u.general->buf);
1317 case Z_Term_characterString:
1318 printf (" %s", term->u.characterString);
1320 case Z_Term_numeric:
1321 printf (" %d", *term->u.numeric);
1331 /* see if we can find USR:SearchResult-1 */
1332 static void display_searchResult (Z_OtherInformation *o)
1337 for (i = 0; i < o->num_elements; i++)
1339 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1341 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1343 if (ext->which == Z_External_searchResult1)
1346 Z_SearchInfoReport *sr = ext->u.searchResult1;
1347 printf ("SearchResult-1:");
1348 for (j = 0; j < sr->num; j++)
1350 if (!sr->elements[j]->subqueryExpression)
1352 display_queryExpression (
1353 sr->elements[j]->subqueryExpression);
1354 display_queryExpression (
1355 sr->elements[j]->subqueryInterpretation);
1356 display_queryExpression (
1357 sr->elements[j]->subqueryRecommendation);
1358 if (sr->elements[j]->subqueryCount)
1359 printf ("(%d)", *sr->elements[j]->subqueryCount);
1367 static int process_searchResponse(Z_SearchResponse *res)
1369 printf ("Received SearchResponse.\n");
1370 print_refid (res->referenceId);
1371 if (*res->searchStatus)
1372 printf("Search was a success.\n");
1374 printf("Search was a bloomin' failure.\n");
1375 printf("Number of hits: %d", *res->resultCount);
1377 printf (", setno %d", setnumber);
1379 display_searchResult (res->additionalSearchInfo);
1380 printf("records returned: %d\n",
1381 *res->numberOfRecordsReturned);
1382 setno += *res->numberOfRecordsReturned;
1384 display_records(res->records);
1388 static void print_level(int iLevel)
1391 for (i = 0; i < iLevel * 4; i++)
1395 static void print_int(int iLevel, const char *pTag, int *pInt)
1399 print_level(iLevel);
1400 printf("%s: %d\n", pTag, *pInt);
1404 static void print_string(int iLevel, const char *pTag, const char *pString)
1406 if (pString != NULL)
1408 print_level(iLevel);
1409 printf("%s: %s\n", pTag, pString);
1413 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1419 print_level(iLevel);
1420 printf("%s:", pTag);
1421 for (; *pInt != -1; pInt++)
1422 printf(" %d", *pInt);
1427 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1429 if (referenceId != NULL)
1433 print_level(iLevel);
1434 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1435 for (i = 0; i < referenceId->len; i++)
1436 printf("%c", referenceId->buf[i]);
1441 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1443 if (pStringNumeric != NULL)
1445 switch (pStringNumeric->which)
1447 case Z_StringOrNumeric_string:
1448 print_string(iLevel, pTag, pStringNumeric->u.string);
1451 case Z_StringOrNumeric_numeric:
1452 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1456 print_level(iLevel);
1457 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1463 static void print_universe_report_duplicate(
1465 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1467 if (pUniverseReportDuplicate != NULL)
1469 print_level(iLevel);
1470 printf("Universe Report Duplicate: \n");
1472 print_string_or_numeric(iLevel, "Hit No",
1473 pUniverseReportDuplicate->hitno);
1477 static void print_universe_report_hits(
1479 Z_UniverseReportHits *pUniverseReportHits)
1481 if (pUniverseReportHits != NULL)
1483 print_level(iLevel);
1484 printf("Universe Report Hits: \n");
1486 print_string_or_numeric(iLevel, "Database",
1487 pUniverseReportHits->database);
1488 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1492 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1494 if (pUniverseReport != NULL)
1496 print_level(iLevel);
1497 printf("Universe Report: \n");
1499 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1500 switch (pUniverseReport->which)
1502 case Z_UniverseReport_databaseHits:
1503 print_universe_report_hits(iLevel,
1504 pUniverseReport->u.databaseHits);
1507 case Z_UniverseReport_duplicate:
1508 print_universe_report_duplicate(iLevel,
1509 pUniverseReport->u.duplicate);
1513 print_level(iLevel);
1514 printf("Type: %d\n", pUniverseReport->which);
1520 static void print_external(int iLevel, Z_External *pExternal)
1522 if (pExternal != NULL)
1524 print_level(iLevel);
1525 printf("External: \n");
1527 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1528 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1529 print_string(iLevel, "Descriptor", pExternal->descriptor);
1530 switch (pExternal->which)
1532 case Z_External_universeReport:
1533 print_universe_report(iLevel, pExternal->u.universeReport);
1537 print_level(iLevel);
1538 printf("Type: %d\n", pExternal->which);
1544 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1546 printf ("Received ResourceControlRequest.\n");
1547 print_referenceId(1, req->referenceId);
1548 print_int(1, "Suspended Flag", req->suspendedFlag);
1549 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1550 print_int(1, "Response Required", req->responseRequired);
1551 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1552 print_external(1, req->resourceReport);
1556 void process_ESResponse(Z_ExtendedServicesResponse *res)
1559 switch (*res->operationStatus)
1561 case Z_ExtendedServicesResponse_done:
1564 case Z_ExtendedServicesResponse_accepted:
1565 printf ("accepted\n");
1567 case Z_ExtendedServicesResponse_failure:
1568 printf ("failure\n");
1569 display_diagrecs(res->diagnostics, res->num_diagnostics);
1572 printf ("unknown\n");
1574 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1575 (res->num_diagnostics != 0) ) {
1576 display_diagrecs(res->diagnostics, res->num_diagnostics);
1578 print_refid (res->referenceId);
1579 if (res->taskPackage &&
1580 res->taskPackage->which == Z_External_extendedService)
1582 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1583 Odr_oct *id = taskPackage->targetReference;
1584 Z_External *ext = taskPackage->taskSpecificParameters;
1588 printf ("Target Reference: ");
1589 print_stringn (id->buf, id->len);
1592 if (ext->which == Z_External_update)
1594 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1595 if (utp && utp->targetPart)
1597 Z_IUTargetPart *targetPart = utp->targetPart;
1600 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1603 Z_IUTaskPackageRecordStructure *tpr =
1604 targetPart->taskPackageRecords[i];
1605 printf ("task package record %d\n", i+1);
1606 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1608 display_record (tpr->u.record);
1612 printf ("other type\n");
1620 const char *get_ill_element (void *clientData, const char *element)
1625 static Z_External *create_external_itemRequest()
1627 struct ill_get_ctl ctl;
1628 ILL_ItemRequest *req;
1630 int item_request_size = 0;
1631 char *item_request_buf = 0;
1635 ctl.f = get_ill_element;
1637 req = ill_get_ItemRequest(&ctl, "ill", 0);
1639 printf ("ill_get_ItemRequest failed\n");
1641 if (!ill_ItemRequest (out, &req, 0, 0))
1645 ill_ItemRequest(print, &req, 0, 0);
1648 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1649 if (item_request_buf)
1650 odr_setbuf (out, item_request_buf, item_request_size, 1);
1651 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1658 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1659 oid.proto = PROTO_GENERAL;
1660 oid.oclass = CLASS_GENERAL;
1661 oid.value = VAL_ISO_ILL_1;
1663 r = (Z_External *) odr_malloc (out, sizeof(*r));
1664 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1665 r->indirect_reference = 0;
1667 r->which = Z_External_single;
1669 r->u.single_ASN1_type = (Odr_oct *)
1670 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1671 r->u.single_ASN1_type->buf = (unsigned char *)
1672 odr_malloc (out, item_request_size);
1673 r->u.single_ASN1_type->len = item_request_size;
1674 r->u.single_ASN1_type->size = item_request_size;
1675 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1678 do_hex_dump(item_request_buf,item_request_size);
1683 static Z_External *create_external_ILL_APDU(int which)
1685 struct ill_get_ctl ctl;
1688 int ill_request_size = 0;
1689 char *ill_request_buf = 0;
1693 ctl.f = get_ill_element;
1695 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1697 if (!ill_APDU (out, &ill_apdu, 0, 0))
1701 printf ("-------------------\n");
1702 ill_APDU(print, &ill_apdu, 0, 0);
1704 printf ("-------------------\n");
1706 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1707 if (ill_request_buf)
1708 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1709 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1715 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1717 oid.proto = PROTO_GENERAL;
1718 oid.oclass = CLASS_GENERAL;
1719 oid.value = VAL_ISO_ILL_1;
1721 r = (Z_External *) odr_malloc (out, sizeof(*r));
1722 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1723 r->indirect_reference = 0;
1725 r->which = Z_External_single;
1727 r->u.single_ASN1_type = (Odr_oct *)
1728 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1729 r->u.single_ASN1_type->buf = (unsigned char *)
1730 odr_malloc (out, ill_request_size);
1731 r->u.single_ASN1_type->len = ill_request_size;
1732 r->u.single_ASN1_type->size = ill_request_size;
1733 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1734 /* printf ("len = %d\n", ill_request_size); */
1735 /* do_hex_dump(ill_request_buf,ill_request_size); */
1736 /* printf("--- end of extenal\n"); */
1743 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1745 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1746 oident ItemOrderRequest;
1748 ItemOrderRequest.proto = PROTO_Z3950;
1749 ItemOrderRequest.oclass = CLASS_EXTSERV;
1750 ItemOrderRequest.value = VAL_ITEMORDER;
1752 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1753 r->indirect_reference = 0;
1756 r->which = Z_External_itemOrder;
1758 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1759 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1760 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1762 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1763 odr_malloc(out,sizeof(Z_IORequest));
1764 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1766 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1767 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1768 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1769 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1770 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1771 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1773 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1774 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1775 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1777 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1778 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1779 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1780 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1782 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1783 (int *) odr_malloc(out, sizeof(int));
1784 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1786 if (!strcmp (type, "item") || !strcmp(type, "2"))
1788 printf ("using item-request\n");
1789 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1790 create_external_itemRequest();
1792 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1794 printf ("using ILL-request\n");
1795 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1796 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1798 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1800 const char *xml_buf =
1802 " <type>request</type>\n"
1803 " <libraryNo>000200</libraryNo>\n"
1804 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1806 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1807 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1810 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1815 static int send_itemorder(const char *type, int itemno)
1817 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1818 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1819 oident ItemOrderRequest;
1821 ItemOrderRequest.proto = PROTO_Z3950;
1822 ItemOrderRequest.oclass = CLASS_EXTSERV;
1823 ItemOrderRequest.value = VAL_ITEMORDER;
1824 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1825 req->packageName = esPackageName;
1827 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1833 static int only_z3950()
1835 if (protocol == PROTO_HTTP)
1837 printf ("Not supported by SRW\n");
1843 static int cmd_update(const char *arg)
1845 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1846 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1849 Z_IUOriginPartToKeep *toKeep;
1850 Z_IUSuppliedRecords *notToKeep;
1852 char action[20], recid[20], fname[80];
1854 Z_External *record_this = 0;
1861 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1863 if (!strcmp (action, "insert"))
1864 action_no = Z_IUOriginPartToKeep_recordInsert;
1865 else if (!strcmp (action, "replace"))
1866 action_no = Z_IUOriginPartToKeep_recordReplace;
1867 else if (!strcmp (action, "delete"))
1868 action_no = Z_IUOriginPartToKeep_recordDelete;
1869 else if (!strcmp (action, "update"))
1870 action_no = Z_IUOriginPartToKeep_specialUpdate;
1873 printf ("Bad action: %s\n", action);
1874 printf ("Possible values: insert, replace, delete, update\n");
1882 stat (fname, &status);
1883 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1885 size_t len = status.st_size;
1886 char *buf = (char *) xmalloc (len);
1888 fread (buf, 1, len, inf);
1892 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1898 printf ("File %s doesn't exist\n", fname);
1906 printf ("No last record (update ignored)\n");
1909 record_this = record_last;
1912 update_oid.proto = PROTO_Z3950;
1913 update_oid.oclass = CLASS_EXTSERV;
1914 update_oid.value = VAL_DBUPDATE;
1915 oid_ent_to_oid (&update_oid, oid);
1916 req->packageType = odr_oiddup(out,oid);
1917 req->packageName = esPackageName;
1919 req->referenceId = set_refid (out);
1921 r = req->taskSpecificParameters = (Z_External *)
1922 odr_malloc (out, sizeof(*r));
1923 r->direct_reference = odr_oiddup(out,oid);
1924 r->indirect_reference = 0;
1926 r->which = Z_External_update;
1927 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1928 r->u.update->which = Z_IUUpdate_esRequest;
1929 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1930 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1931 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1932 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1933 toKeep->databaseName = databaseNames[0];
1935 toKeep->elementSetName = 0;
1936 toKeep->actionQualifier = 0;
1937 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1938 *toKeep->action = action_no;
1940 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1941 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1943 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1944 odr_malloc(out, sizeof(*notToKeep->elements));
1945 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1946 odr_malloc(out, sizeof(**notToKeep->elements));
1947 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1950 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1951 odr_malloc (out, sizeof(Odr_oct));
1952 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1953 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1954 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1957 notToKeep->elements[0]->u.opaque = 0;
1958 notToKeep->elements[0]->supplementalId = 0;
1959 notToKeep->elements[0]->correlationInfo = 0;
1960 notToKeep->elements[0]->record = record_this;
1967 static int cmd_itemorder(const char *arg)
1974 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1977 printf("Item order request\n");
1979 send_itemorder(type, itemno);
1983 static int cmd_find(const char *arg)
1987 printf("Find what?\n");
1990 if (protocol == PROTO_HTTP)
1995 if (!send_SRW_searchRequest(arg))
2008 printf("Not connected yet\n");
2012 if (!send_searchRequest(arg))
2018 static int cmd_delete(const char *arg)
2022 printf("Not connected yet\n");
2027 if (!send_deleteResultSetRequest(arg))
2032 static int cmd_ssub(const char *arg)
2034 if (!(smallSetUpperBound = atoi(arg)))
2039 static int cmd_lslb(const char *arg)
2043 if (!(largeSetLowerBound = atoi(arg)))
2048 static int cmd_mspn(const char *arg)
2052 if (!(mediumSetPresentNumber = atoi(arg)))
2057 static int cmd_status(const char *arg)
2059 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2060 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2061 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2065 static int cmd_setnames(const char *arg)
2067 if (*arg == '1') /* enable ? */
2069 else if (*arg == '0') /* disable ? */
2071 else if (setnumber < 0) /* no args, toggle .. */
2077 printf("Set numbering enabled.\n");
2079 printf("Set numbering disabled.\n");
2083 /* PRESENT SERVICE ----------------------------- */
2085 static void parse_show_args(const char *arg_c, char *setstring,
2086 int *start, int *number)
2091 strncpy(arg, arg_c, sizeof(arg)-1);
2092 arg[sizeof(arg)-1] = '\0';
2094 if ((p = strchr(arg, '+')))
2096 *number = atoi(p + 1);
2101 if (p && (p=strchr(p+1, '+')))
2102 strcpy (setstring, p+1);
2103 else if (setnumber >= 0)
2104 sprintf(setstring, "%d", setnumber);
2109 static int send_presentRequest(const char *arg)
2111 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2112 Z_PresentRequest *req = apdu->u.presentRequest;
2113 Z_RecordComposition compo;
2117 char setstring[100];
2119 req->referenceId = set_refid (out);
2121 parse_show_args(arg, setstring, &setno, &nos);
2123 req->resultSetId = setstring;
2125 req->resultSetStartPoint = &setno;
2126 req->numberOfRecordsRequested = &nos;
2127 prefsyn.proto = protocol;
2128 prefsyn.oclass = CLASS_RECSYN;
2129 prefsyn.value = recordsyntax;
2130 req->preferredRecordSyntax =
2131 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2137 prefschema.proto = protocol;
2138 prefschema.oclass = CLASS_SCHEMA;
2139 prefschema.value = oid_getvalbyname(schema);
2141 req->recordComposition = &compo;
2142 compo.which = Z_RecordComp_complex;
2143 compo.u.complex = (Z_CompSpec *)
2144 odr_malloc(out, sizeof(*compo.u.complex));
2145 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2146 odr_malloc(out, sizeof(bool_t));
2147 *compo.u.complex->selectAlternativeSyntax = 0;
2149 compo.u.complex->generic = (Z_Specification *)
2150 odr_malloc(out, sizeof(*compo.u.complex->generic));
2151 compo.u.complex->generic->which = Z_Schema_oid;
2152 compo.u.complex->generic->schema.oid = (Odr_oid *)
2153 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2154 if (!compo.u.complex->generic->schema.oid)
2156 /* OID wasn't a schema! Try record syntax instead. */
2157 prefschema.oclass = CLASS_RECSYN;
2158 compo.u.complex->generic->schema.oid = (Odr_oid *)
2159 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2161 if (!elementSetNames)
2162 compo.u.complex->generic->elementSpec = 0;
2165 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2166 odr_malloc(out, sizeof(Z_ElementSpec));
2167 compo.u.complex->generic->elementSpec->which =
2168 Z_ElementSpec_elementSetName;
2169 compo.u.complex->generic->elementSpec->u.elementSetName =
2170 elementSetNames->u.generic;
2172 compo.u.complex->num_dbSpecific = 0;
2173 compo.u.complex->dbSpecific = 0;
2174 compo.u.complex->num_recordSyntax = 0;
2175 compo.u.complex->recordSyntax = 0;
2177 else if (elementSetNames)
2179 req->recordComposition = &compo;
2180 compo.which = Z_RecordComp_simple;
2181 compo.u.simple = elementSetNames;
2184 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2189 static int send_SRW_presentRequest(const char *arg)
2191 char setstring[100];
2193 Z_SRW_PDU *sr = srw_sr;
2197 parse_show_args(arg, setstring, &setno, &nos);
2198 sr->u.request->startRecord = odr_intdup(out, setno);
2199 sr->u.request->maximumRecords = odr_intdup(out, nos);
2201 sr->u.request->recordSchema = schema;
2202 return send_srw(sr);
2206 static void close_session (void)
2213 nmem_destroy (session_mem);
2222 void process_close(Z_Close *req)
2224 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2225 Z_Close *res = apdu->u.close;
2227 static char *reasons[] =
2232 "cost limit reached",
2234 "security violation",
2241 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2242 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2247 *res->closeReason = Z_Close_finished;
2249 printf("Sent response.\n");
2254 static int cmd_show(const char *arg)
2256 if (protocol == PROTO_HTTP)
2261 if (!send_SRW_presentRequest(arg))
2271 printf("Not connected yet\n");
2274 if (!send_presentRequest(arg))
2280 int cmd_quit(const char *arg)
2282 printf("See you later, alligator.\n");
2288 int cmd_cancel(const char *arg)
2290 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2291 Z_TriggerResourceControlRequest *req =
2292 apdu->u.triggerResourceControlRequest;
2297 printf("Session not initialized yet\n");
2302 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2304 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2307 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2308 req->resultSetWanted = &rfalse;
2311 printf("Sent cancel request\n");
2315 int send_scanrequest(const char *query, int pp, int num, const char *term)
2317 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2318 Z_ScanRequest *req = apdu->u.scanRequest;
2323 if (queryType == QueryType_CCL2RPN)
2327 struct ccl_rpn_node *rpn;
2329 rpn = ccl_find_str (bibset, query, &error, &pos);
2332 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2335 bib1.proto = PROTO_Z3950;
2336 bib1.oclass = CLASS_ATTSET;
2337 bib1.value = VAL_BIB1;
2338 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2339 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2341 printf("Couldn't convert CCL to Scan term\n");
2344 ccl_rpn_delete (rpn);
2348 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2350 if (!(req->termListAndStartPoint =
2351 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2353 const char *pqf_msg;
2355 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2356 printf("%*s^\n", off+7, "");
2357 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2358 yaz_pqf_destroy (pqf_parser);
2361 yaz_pqf_destroy (pqf_parser);
2365 if (req->termListAndStartPoint->term &&
2366 req->termListAndStartPoint->term->which == Z_Term_general &&
2367 req->termListAndStartPoint->term->u.general)
2369 req->termListAndStartPoint->term->u.general->buf =
2370 (unsigned char *) odr_strdup(out, term);
2371 req->termListAndStartPoint->term->u.general->len =
2372 req->termListAndStartPoint->term->u.general->size =
2376 req->referenceId = set_refid (out);
2377 req->num_databaseNames = num_databaseNames;
2378 req->databaseNames = databaseNames;
2379 req->numberOfTermsRequested = #
2380 req->preferredPositionInResponse = &pp;
2385 int send_sortrequest(const char *arg, int newset)
2387 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2388 Z_SortRequest *req = apdu->u.sortRequest;
2389 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2390 odr_malloc (out, sizeof(*sksl));
2396 sprintf (setstring, "%d", setnumber);
2398 sprintf (setstring, "default");
2400 req->referenceId = set_refid (out);
2402 req->num_inputResultSetNames = 1;
2403 req->inputResultSetNames = (Z_InternationalString **)
2404 odr_malloc (out, sizeof(*req->inputResultSetNames));
2405 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2407 if (newset && setnumber >= 0)
2408 sprintf (setstring, "%d", ++setnumber);
2410 req->sortedResultSetName = odr_strdup (out, setstring);
2412 req->sortSequence = yaz_sort_spec (out, arg);
2413 if (!req->sortSequence)
2415 printf ("Missing sort specifications\n");
2422 void display_term(Z_TermInfo *t)
2424 if (t->term->which == Z_Term_general)
2426 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2427 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2428 t->term->u.general->buf);
2431 printf("Term (not general)");
2432 if (t->globalOccurrences)
2433 printf (" (%d)\n", *t->globalOccurrences);
2438 void process_scanResponse(Z_ScanResponse *res)
2441 Z_Entry **entries = NULL;
2442 int num_entries = 0;
2444 printf("Received ScanResponse\n");
2445 print_refid (res->referenceId);
2446 printf("%d entries", *res->numberOfEntriesReturned);
2447 if (res->positionOfTerm)
2448 printf (", position=%d", *res->positionOfTerm);
2450 if (*res->scanStatus != Z_Scan_success)
2451 printf("Scan returned code %d\n", *res->scanStatus);
2454 if ((entries = res->entries->entries))
2455 num_entries = res->entries->num_entries;
2456 for (i = 0; i < num_entries; i++)
2458 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2459 if (entries[i]->which == Z_Entry_termInfo)
2461 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2462 display_term(entries[i]->u.termInfo);
2465 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2467 if (res->entries->nonsurrogateDiagnostics)
2468 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2469 res->entries->num_nonsurrogateDiagnostics);
2472 void process_sortResponse(Z_SortResponse *res)
2474 printf("Received SortResponse: status=");
2475 switch (*res->sortStatus)
2477 case Z_SortStatus_success:
2478 printf ("success"); break;
2479 case Z_SortStatus_partial_1:
2480 printf ("partial"); break;
2481 case Z_SortStatus_failure:
2482 printf ("failure"); break;
2484 printf ("unknown (%d)", *res->sortStatus);
2487 print_refid (res->referenceId);
2488 if (res->diagnostics)
2489 display_diagrecs(res->diagnostics,
2490 res->num_diagnostics);
2493 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2495 printf("Got deleteResultSetResponse status=%d\n",
2496 *res->deleteOperationStatus);
2497 if (res->deleteListStatuses)
2500 for (i = 0; i < res->deleteListStatuses->num; i++)
2502 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2503 *res->deleteListStatuses->elements[i]->status);
2508 int cmd_sort_generic(const char *arg, int newset)
2512 printf("Session not initialized yet\n");
2517 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2519 printf("Target doesn't support sort\n");
2524 if (send_sortrequest(arg, newset) < 0)
2531 int cmd_sort(const char *arg)
2533 return cmd_sort_generic (arg, 0);
2536 int cmd_sort_newset (const char *arg)
2538 return cmd_sort_generic (arg, 1);
2541 int cmd_scan(const char *arg)
2550 printf("Session not initialized yet\n");
2554 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2556 printf("Target doesn't support scan\n");
2561 strcpy (last_scan_query, arg);
2562 if (send_scanrequest(arg, 1, 20, 0) < 0)
2567 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2573 int cmd_schema(const char *arg)
2578 schema = xstrdup(arg);
2582 int cmd_format(const char *arg)
2587 printf("Usage: format <recordsyntax>\n");
2590 nsyntax = oid_getvalbyname (arg);
2591 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2593 printf ("unknown record syntax\n");
2596 recordsyntax = nsyntax;
2600 int cmd_elements(const char *arg)
2602 static Z_ElementSetNames esn;
2603 static char what[100];
2607 elementSetNames = 0;
2611 esn.which = Z_ElementSetNames_generic;
2612 esn.u.generic = what;
2613 elementSetNames = &esn;
2617 int cmd_attributeset(const char *arg)
2623 printf("Usage: attributeset <setname>\n");
2626 sscanf(arg, "%s", what);
2627 if (p_query_attset (what))
2629 printf("Unknown attribute set name\n");
2635 int cmd_querytype (const char *arg)
2637 if (!strcmp (arg, "ccl"))
2638 queryType = QueryType_CCL;
2639 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2640 queryType = QueryType_Prefix;
2641 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2642 queryType = QueryType_CCL2RPN;
2643 else if (!strcmp(arg, "cql"))
2644 queryType = QueryType_CQL;
2645 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2646 queryType = QueryType_CQL2RPN;
2649 printf ("Querytype must be one of:\n");
2650 printf (" prefix - Prefix query\n");
2651 printf (" ccl - CCL query\n");
2652 printf (" ccl2rpn - CCL query converted to RPN\n");
2653 printf (" cql - CQL\n");
2654 printf (" cql2rpn - CQL query converted to RPN\n");
2660 int cmd_refid (const char *arg)
2666 refid = (char *) xmalloc (strlen(arg)+1);
2667 strcpy (refid, arg);
2672 int cmd_close(const char *arg)
2681 apdu = zget_APDU(out, Z_APDU_close);
2682 req = apdu->u.close;
2683 *req->closeReason = Z_Close_finished;
2685 printf("Sent close request.\n");
2690 int cmd_packagename(const char* arg)
2692 xfree (esPackageName);
2693 esPackageName = NULL;
2695 esPackageName = xstrdup(arg);
2699 int cmd_proxy(const char* arg)
2704 yazProxy = xstrdup (arg);
2708 int cmd_marccharset(const char *arg)
2713 if (sscanf(arg, "%29s", l1) < 1)
2715 xfree (marcCharset);
2717 if (strcmp(l1, "-"))
2718 marcCharset = xstrdup(l1);
2722 int cmd_charset(const char* arg)
2724 char l1[30], l2[30];
2727 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2729 printf("Current negotiation character set is `%s'\n",
2730 negotiationCharset ? negotiationCharset: "none");
2731 printf("Current output character set is `%s'\n",
2732 outputCharset ? outputCharset: "none");
2735 xfree (negotiationCharset);
2736 negotiationCharset = NULL;
2737 if (*l1 && strcmp(l1, "-"))
2739 negotiationCharset = xstrdup(l1);
2740 printf ("Character set negotiation : %s\n", negotiationCharset);
2743 printf ("Character set negotiation disabled\n");
2746 xfree (outputCharset);
2748 if (!strcmp(l2, "auto") && codeset)
2752 printf ("output charset: %s\n", codeset);
2753 outputCharset = xstrdup(codeset);
2758 printf ("No codeset found on this system\n");
2760 else if (strcmp(l2, "-"))
2761 outputCharset = xstrdup(l2);
2763 printf ("Output charset conversion disabled\n");
2765 if (outputCharset && negotiationCharset)
2767 odr_set_charset (out, negotiationCharset, outputCharset);
2768 odr_set_charset (in, outputCharset, negotiationCharset);
2772 odr_set_charset (out, 0, 0);
2773 odr_set_charset (in, 0, 0);
2778 int cmd_lang(const char* arg)
2781 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2788 yazLang = (char *) xmalloc (strlen(arg)+1);
2789 strcpy (yazLang, arg);
2794 int cmd_source(const char* arg)
2796 /* first should open the file and read one line at a time.. */
2798 char line[1024], *cp;
2801 fprintf(stderr,"Error in source command use a filename\n");
2805 includeFile = fopen (arg, "r");
2808 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2812 while(!feof(includeFile)) {
2813 memset(line,0,sizeof(line));
2814 fgets(line,sizeof(line),includeFile);
2816 if(strlen(line) < 2) continue;
2817 if(line[0] == '#') continue;
2819 if ((cp = strrchr (line, '\n')))
2822 process_cmd_line(line);
2825 if(fclose(includeFile)<0) {
2826 perror("unable to close include file");
2832 int cmd_subshell(const char* args)
2837 system(getenv("SHELL"));
2843 int cmd_set_berfile(const char *arg)
2845 if (ber_file && ber_file != stdout && ber_file != stderr)
2847 if (!strcmp(arg, ""))
2849 else if (!strcmp(arg, "-"))
2852 ber_file = fopen(arg, "a");
2856 int cmd_set_apdufile(const char *arg)
2858 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2860 if (!strcmp(arg, ""))
2862 else if (!strcmp(arg, "-"))
2866 apdu_file = fopen(arg, "a");
2868 perror("unable to open apdu log file");
2871 odr_setprint(print, apdu_file);
2875 int cmd_set_cclfile(const char* arg)
2879 bibset = ccl_qual_mk ();
2880 inf = fopen (arg, "r");
2882 perror("unable to open CCL file");
2885 ccl_qual_file (bibset, inf);
2888 strcpy(ccl_fields,arg);
2892 int cmd_set_cqlfile(const char* arg)
2894 cql_transform_t newcqltrans;
2896 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
2897 perror("unable to open CQL file");
2901 cql_transform_close(cqltrans);
2903 cqltrans = newcqltrans;
2904 strcpy(cql_fields, arg);
2908 int cmd_set_auto_reconnect(const char* arg)
2910 if(strlen(arg)==0) {
2911 auto_reconnect = ! auto_reconnect;
2912 } else if(strcmp(arg,"on")==0) {
2914 } else if(strcmp(arg,"off")==0) {
2917 printf("Error use on or off\n");
2922 printf("Set auto reconnect enabled.\n");
2924 printf("Set auto reconnect disabled.\n");
2929 int cmd_set_marcdump(const char* arg)
2931 if(marc_file && marc_file != stderr) { /* don't close stdout*/
2935 if (!strcmp(arg, ""))
2937 else if (!strcmp(arg, "-"))
2941 marc_file = fopen(arg, "a");
2943 perror("unable to open marc log file");
2949 this command takes 3 arge {name class oid}
2951 int cmd_register_oid(const char* args) {
2956 {"appctx",CLASS_APPCTX},
2957 {"absyn",CLASS_ABSYN},
2958 {"attset",CLASS_ATTSET},
2959 {"transyn",CLASS_TRANSYN},
2960 {"diagset",CLASS_DIAGSET},
2961 {"recsyn",CLASS_RECSYN},
2962 {"resform",CLASS_RESFORM},
2963 {"accform",CLASS_ACCFORM},
2964 {"extserv",CLASS_EXTSERV},
2965 {"userinfo",CLASS_USERINFO},
2966 {"elemspec",CLASS_ELEMSPEC},
2967 {"varset",CLASS_VARSET},
2968 {"schema",CLASS_SCHEMA},
2969 {"tagset",CLASS_TAGSET},
2970 {"general",CLASS_GENERAL},
2971 {0,(enum oid_class) 0}
2973 char oname_str[101], oclass_str[101], oid_str[101];
2976 oid_class oidclass = CLASS_GENERAL;
2977 int val = 0, oid[OID_SIZE];
2978 struct oident * new_oident=NULL;
2980 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2981 oname_str,oclass_str, oid_str) < 1) {
2982 printf("Error in regristrate command \n");
2986 for (i = 0; oid_classes[i].className; i++) {
2987 if (!strcmp(oid_classes[i].className, oclass_str))
2989 oidclass=oid_classes[i].oclass;
2994 if(!(oid_classes[i].className)) {
2995 printf("Unknonwn oid class %s\n",oclass_str);
3003 while (isdigit (*name))
3005 val = val*10 + (*name - '0');
3018 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3019 if(strcmp(new_oident->desc,oname_str)) {
3020 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3026 int cmd_push_command(const char* arg)
3028 #if HAVE_READLINE_HISTORY_H
3032 fprintf(stderr,"Not compiled with the readline/history module\n");
3037 void source_rcfile()
3039 /* Look for a $HOME/.yazclientrc and source it if it exists */
3040 struct stat statbuf;
3042 char* homedir=getenv("HOME");
3044 if(!homedir) return;
3046 sprintf(buffer,"%s/.yazclientrc",homedir);
3048 if(stat(buffer,&statbuf)==0) {
3052 if(stat(".yazclientrc",&statbuf)==0) {
3053 cmd_source(".yazclientrc");
3058 static void initialize(void)
3063 if (!(out = odr_createmem(ODR_ENCODE)) ||
3064 !(in = odr_createmem(ODR_DECODE)) ||
3065 !(print = odr_createmem(ODR_PRINT)))
3067 fprintf(stderr, "failed to allocate ODR streams\n");
3072 setvbuf(stdout, 0, _IONBF, 0);
3074 odr_setprint(print, apdu_file);
3076 bibset = ccl_qual_mk ();
3077 inf = fopen (ccl_fields, "r");
3080 ccl_qual_file (bibset, inf);
3084 cqltrans = cql_transform_open_fname(cql_fields);
3085 /* If this fails, no problem: we detect cqltrans == 0 later */
3087 #if HAVE_READLINE_READLINE_H
3088 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3092 for(i=0; i<maxOtherInfosSupported; ++i) {
3093 extraOtherInfos[i].oidval = -1;
3100 #if HAVE_GETTIMEOFDAY
3101 struct timeval tv_start, tv_end;
3105 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3109 printf ("Received SRW SearchRetrieve Response\n");
3111 for (i = 0; i<res->num_diagnostics; i++)
3113 printf ("SRW diagnostic %d %s\n",
3114 *res->diagnostics[i].code,
3115 yaz_diag_srw_str(*res->diagnostics[i].code));
3117 if (res->diagnostics[i].details)
3118 printf ("Details: %s\n", res->diagnostics[i].details);
3120 if (res->numberOfRecords)
3121 printf ("Number of hits: %d\n", *res->numberOfRecords);
3122 for (i = 0; i<res->num_records; i++)
3124 Z_SRW_record *rec = res->records + i;
3126 if (rec->recordPosition)
3128 printf ("pos=%d", *rec->recordPosition);
3129 setno = *rec->recordPosition + 1;
3131 if (rec->recordSchema)
3132 printf (" schema=%s", rec->recordSchema);
3134 if (rec->recordData_buf && rec->recordData_len)
3136 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3142 static void http_response(Z_HTTP_Response *hres)
3145 const char *content_type = z_HTTP_header_lookup(hres->headers,
3147 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3149 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3151 Z_SOAP *soap_package = 0;
3152 ODR o = odr_createmem(ODR_DECODE);
3153 Z_SOAP_Handler soap_handlers[2] = {
3154 {"http://www.loc.gov/zing/srw/v1.0/", 0,
3155 (Z_SOAP_fun) yaz_srw_codec},
3158 ret = z_soap_codec(o, &soap_package,
3159 &hres->content_buf, &hres->content_len,
3161 if (!ret && soap_package->which == Z_SOAP_generic &&
3162 soap_package->u.generic->no == 0)
3164 Z_SRW_PDU *sr = soap_package->u.generic->p;
3165 if (sr->which == Z_SRW_searchRetrieve_response)
3166 handle_srw_response(sr->u.response);
3170 else if (!ret && (soap_package->which == Z_SOAP_fault
3171 || soap_package->which == Z_SOAP_error))
3173 printf ("HTTP Error Status=%d\n", hres->code);
3174 printf ("SOAP Fault code %s\n",
3175 soap_package->u.fault->fault_code);
3176 printf ("SOAP Fault string %s\n",
3177 soap_package->u.fault->fault_string);
3185 if (hres->code != 200)
3187 printf ("HTTP Error Status=%d\n", hres->code);
3191 printf ("Decoding of SRW package failed\n");
3195 if (!strcmp(hres->version, "1.0"))
3197 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3198 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3203 /* HTTP 1.1: only if no close we stay alive .. */
3204 if (connection_head && !strcmp(connection_head, "close"))
3210 void wait_and_handle_response()
3212 int reconnect_ok = 1;
3215 int netbufferlen = 0;
3220 res = cs_get(conn, &netbuffer, &netbufferlen);
3221 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3232 buf_out = odr_getbuf(out, &len_out, 0);
3234 cs_put(conn, buf_out, len_out);
3242 printf("Target closed connection\n");
3247 odr_reset(in); /* release APDU from last round */
3249 do_hex_dump(netbuffer, res);
3250 odr_setbuf(in, netbuffer, res, 0);
3252 if (!z_GDU(in, &gdu, 0, 0))
3254 FILE *f = ber_file ? ber_file : stdout;
3255 odr_perror(in, "Decoding incoming APDU");
3256 fprintf(f, "[Near %d]\n", odr_offset(in));
3257 fprintf(f, "Packet dump:\n---------\n");
3258 odr_dumpBER(f, netbuffer, res);
3259 fprintf(f, "---------\n");
3261 z_GDU(print, &gdu, 0, 0);
3262 if (conn && cs_more(conn))
3267 odr_dumpBER(ber_file, netbuffer, res);
3268 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3270 odr_perror(print, "Failed to print incoming APDU");
3274 if (gdu->which == Z_GDU_Z3950)
3276 Z_APDU *apdu = gdu->u.z3950;
3279 case Z_APDU_initResponse:
3280 process_initResponse(apdu->u.initResponse);
3282 case Z_APDU_searchResponse:
3283 process_searchResponse(apdu->u.searchResponse);
3285 case Z_APDU_scanResponse:
3286 process_scanResponse(apdu->u.scanResponse);
3288 case Z_APDU_presentResponse:
3289 print_refid (apdu->u.presentResponse->referenceId);
3291 *apdu->u.presentResponse->numberOfRecordsReturned;
3292 if (apdu->u.presentResponse->records)
3293 display_records(apdu->u.presentResponse->records);
3295 printf("No records.\n");
3296 printf ("nextResultSetPosition = %d\n",
3297 *apdu->u.presentResponse->nextResultSetPosition);
3299 case Z_APDU_sortResponse:
3300 process_sortResponse(apdu->u.sortResponse);
3302 case Z_APDU_extendedServicesResponse:
3303 printf("Got extended services response\n");
3304 process_ESResponse(apdu->u.extendedServicesResponse);
3307 printf("Target has closed the association.\n");
3308 process_close(apdu->u.close);
3310 case Z_APDU_resourceControlRequest:
3311 process_resourceControlRequest
3312 (apdu->u.resourceControlRequest);
3314 case Z_APDU_deleteResultSetResponse:
3315 process_deleteResultSetResponse(apdu->u.
3316 deleteResultSetResponse);
3319 printf("Received unknown APDU type (%d).\n",
3325 else if (gdu->which == Z_GDU_HTTP_Response)
3327 http_response(gdu->u.HTTP_Response);
3330 if (conn && !cs_more(conn))
3335 #if HAVE_GETTIMEOFDAY
3336 gettimeofday (&tv_end, 0);
3338 printf ("S/U S/U=%ld/%ld %ld/%ld",
3339 (long) tv_start.tv_sec,
3340 (long) tv_start.tv_usec,
3341 (long) tv_end.tv_sec,
3342 (long) tv_end.tv_usec);
3344 printf ("Elapsed: %.6f\n",
3345 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3346 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3353 int cmd_cclparse(const char* arg)
3356 struct ccl_rpn_node *rpn=NULL;
3359 rpn = ccl_find_str (bibset, arg, &error, &pos);
3362 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3363 printf ("%s\n", ccl_err_msg (error));
3369 ccl_pr_tree(rpn, stdout);
3373 ccl_rpn_delete(rpn);
3381 int cmd_set_otherinfo(const char* args)
3383 char oid[101], otherinfoString[101];
3388 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3390 /* reset this otherinfo */
3391 if(otherinfoNo>=maxOtherInfosSupported) {
3392 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3394 extraOtherInfos[otherinfoNo].oidval = -1;
3395 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3399 printf("Error in set_otherinfo command \n");
3403 if(otherinfoNo>=maxOtherInfosSupported) {
3404 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3408 oidval = oid_getvalbyname (oid);
3410 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3413 extraOtherInfos[otherinfoNo].oidval = oidval;
3414 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3415 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3420 int cmd_list_otherinfo(const char* args)
3424 if(strlen(args)>0) {
3426 if( i >= maxOtherInfosSupported ) {
3427 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3431 if(extraOtherInfos[i].oidval != -1)
3432 printf(" otherinfo %d %s %s\n",
3434 yaz_z3950_oid_value_to_str(
3435 (enum oid_value) extraOtherInfos[i].oidval,
3437 extraOtherInfos[i].value);
3440 for(i=0; i<maxOtherInfosSupported; ++i) {
3441 if(extraOtherInfos[i].oidval != -1)
3442 printf(" otherinfo %d %s %s\n",
3444 yaz_z3950_oid_value_to_str(
3445 (enum oid_value) extraOtherInfos[i].oidval,
3447 extraOtherInfos[i].value);
3455 int cmd_list_all(const char* args) {
3458 /* connection options */
3460 printf("Connected to : %s\n",last_open_command);
3462 if(last_open_command)
3463 printf("Not connected to : %s\n",last_open_command);
3465 printf("Not connected : \n");
3468 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3470 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3473 printf("Authentication : none\n");
3475 switch(auth->which) {
3476 case Z_IdAuthentication_idPass:
3477 printf("Authentication : IdPass\n");
3478 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3479 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3480 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3482 case Z_IdAuthentication_open:
3483 printf("Authentication : psOpen\n");
3484 printf(" Open string : %s\n",auth->u.open);
3487 printf("Authentication : Unknown\n");
3490 if (negotiationCharset)
3491 printf("Neg. Character set : `%s'\n", negotiationCharset);
3495 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3499 printf("CCL file : %s\n",ccl_fields);
3500 printf("CQL file : %s\n",cql_fields);
3501 printf("Query type : %s\n",query_type_as_string(queryType));
3503 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3505 /* piggy back options */
3506 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3508 /* print present related options */
3509 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3510 printf("Schema : %s\n",schema);
3511 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3513 /* loging options */
3514 printf("APDU log : %s\n",apdu_file?"on":"off");
3515 printf("Record log : %s\n",marc_file?"on":"off");
3518 printf("Other Info: \n");
3519 cmd_list_otherinfo("");
3524 int cmd_clear_otherinfo(const char* args)
3526 if(strlen(args)>0) {
3528 otherinfoNo = atoi(args);
3529 if( otherinfoNo >= maxOtherInfosSupported ) {
3530 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3534 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3535 /* only clear if set. */
3536 extraOtherInfos[otherinfoNo].oidval=-1;
3537 free(extraOtherInfos[otherinfoNo].value);
3542 for(i=0; i<maxOtherInfosSupported; ++i) {
3543 if (extraOtherInfos[i].oidval!=-1 ) {
3544 extraOtherInfos[i].oidval=-1;
3545 free(extraOtherInfos[i].value);
3552 static int cmd_help (const char *line);
3554 typedef char *(*completerFunctionType)(const char *text, int state);
3558 int (*fun)(const char *arg);
3560 completerFunctionType rl_completerfunction;
3561 int complete_filenames;
3562 char **local_tabcompletes;
3564 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3565 {"quit", cmd_quit, "",NULL,0,NULL},
3566 {"find", cmd_find, "<query>",NULL,0,NULL},
3567 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3568 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3569 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3570 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3571 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3572 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3573 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3574 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3575 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3576 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3577 {"status", cmd_status, "",NULL,0,NULL},
3578 {"setnames", cmd_setnames, "",NULL,0,NULL},
3579 {"cancel", cmd_cancel, "",NULL,0,NULL},
3580 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3581 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3582 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3583 {"close", cmd_close, "",NULL,0,NULL},
3584 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3585 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3586 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3587 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3588 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3589 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3590 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3591 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3592 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3593 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3594 {".", cmd_source, "<filename>",NULL,1,NULL},
3595 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3596 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3597 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3598 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3599 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3600 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3601 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3602 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3603 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3604 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3605 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3606 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3607 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3608 {"list_all",cmd_list_all,"",NULL,0,NULL},
3609 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3610 /* Server Admin Functions */
3611 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3612 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3613 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3614 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3615 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3616 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3617 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3618 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3619 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3620 {"help", cmd_help, "", NULL,0,NULL},
3624 static int cmd_help (const char *line)
3630 sscanf (line, "%20s", topic);
3633 printf("Commands:\n");
3634 for (i = 0; cmd_array[i].cmd; i++)
3635 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3636 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3637 if (strcmp (topic, "find") == 0)
3640 printf (" \"term\" Simple Term\n");
3641 printf (" @attr [attset] type=value op Attribute\n");
3642 printf (" @and opl opr And\n");
3643 printf (" @or opl opr Or\n");
3644 printf (" @not opl opr And-Not\n");
3645 printf (" @set set Result set\n");
3647 printf ("Bib-1 attribute types\n");
3649 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3650 printf ("2=Relation: ");
3651 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3652 printf ("3=Position: ");
3653 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3654 printf ("4=Structure: ");
3655 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3656 printf ("5=Truncation: ");
3657 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3658 printf ("6=Completeness:");
3659 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3664 int cmd_register_tab(const char* arg) {
3666 char command[101], tabargument[101];
3671 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3675 /* locate the amdn in the list */
3676 for (i = 0; cmd_array[i].cmd; i++) {
3677 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3682 if(!cmd_array[i].cmd) {
3683 fprintf(stderr,"Unknown command %s\n",command);
3688 if(!cmd_array[i].local_tabcompletes)
3689 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3693 tabslist = cmd_array[i].local_tabcompletes;
3694 for(;tabslist && *tabslist;tabslist++) {
3698 cmd_array[i].local_tabcompletes = (char **)
3699 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3700 tabslist=cmd_array[i].local_tabcompletes;
3701 tabslist[num_of_tabs]=strdup(tabargument);
3702 tabslist[num_of_tabs+1]=NULL;
3707 void process_cmd_line(char* line)
3710 char word[32], arg[1024];
3712 #if HAVE_GETTIMEOFDAY
3713 gettimeofday (&tv_start, 0);
3716 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3718 strcpy(word, last_cmd);
3723 strcpy(last_cmd, word);
3725 /* removed tailing spaces from the arg command */
3728 char* lastnonspace=NULL;
3736 *(++lastnonspace) = 0;
3739 for (i = 0; cmd_array[i].cmd; i++)
3740 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3742 res = (*cmd_array[i].fun)(arg);
3746 if (!cmd_array[i].cmd) /* dump our help-screen */
3748 printf("Unknown command: %s.\n", word);
3749 printf("use help for list of commands\n");
3750 /* cmd_help (""); */
3754 if(apdu_file) fflush(apdu_file);
3757 wait_and_handle_response();
3766 char *command_generator(const char *text, int state)
3772 for( ; cmd_array[idx].cmd; ++idx) {
3773 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3774 ++idx; /* skip this entry on the next run */
3775 return strdup(cmd_array[idx-1].cmd);
3783 This function only known how to complete on the first word
3785 char ** readline_completer(char *text, int start, int end) {
3786 #if HAVE_READLINE_READLINE_H
3788 completerFunctionType completerToUse;
3791 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3792 char** res=rl_completion_matches(text,
3795 char** res=completion_matches(text,
3796 (CPFunction*)command_generator);
3798 rl_attempted_completion_over = 1;
3801 char arg[1024],word[32];
3803 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3804 rl_attempted_completion_over = 1;
3808 for (i = 0; cmd_array[i].cmd; i++) {
3809 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3814 if(!cmd_array[i].cmd) return NULL;
3816 curret_global_list = cmd_array[i].local_tabcompletes;
3818 completerToUse = cmd_array[i].rl_completerfunction;
3819 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3820 completerToUse = default_completer;
3822 if(completerToUse) {
3823 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3825 rl_completion_matches(text,
3829 completion_matches(text,
3830 (CPFunction*)completerToUse);
3832 if(!cmd_array[i].complete_filenames)
3833 rl_attempted_completion_over = 1;
3836 if(!cmd_array[i].complete_filenames)
3837 rl_attempted_completion_over = 1;
3847 static void client(void)
3853 #if HAVE_GETTIMEOFDAY
3854 gettimeofday (&tv_start, 0);
3859 char *line_in = NULL;
3860 #if HAVE_READLINE_READLINE_H
3863 line_in=readline(C_PROMPT);
3866 #if HAVE_READLINE_HISTORY_H
3868 add_history(line_in);
3870 strncpy(line, line_in, 1023);
3879 if (!fgets(line, 1023, stdin))
3881 if ((end_p = strchr (line, '\n')))
3884 process_cmd_line(line);
3888 static void show_version(void)
3892 yaz_version(vstr, 0);
3893 printf ("YAZ version: %s\n", YAZ_VERSION);
3894 if (strcmp(vstr, YAZ_VERSION))
3895 printf ("YAZ DLL/SO: %s\n", vstr);
3899 int main(int argc, char **argv)
3902 char *open_command = 0;
3903 char *auth_command = 0;
3908 if (!setlocale(LC_CTYPE, ""))
3909 fprintf (stderr, "setlocale failed\n");
3913 codeset = nl_langinfo(CODESET);
3917 outputCharset = xstrdup(codeset);
3919 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vx", argv, argc, &arg)) != -2)
3926 open_command = (char *) xmalloc (strlen(arg)+6);
3927 strcpy (open_command, "open ");
3928 strcat (open_command, arg);
3932 kilobytes = atoi(arg);
3935 if (!(marc_file = fopen (arg, "a")))
3942 outputCharset = xstrdup(arg);
3945 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3946 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3949 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
3950 cql_fields[sizeof(cql_fields)-1] = '\0';
3953 if (!strcmp(arg, "-"))
3956 ber_file=fopen(arg, "a");
3959 if (!strcmp(arg, "-"))
3962 apdu_file=fopen(arg, "a");
3968 yazProxy=strdup(arg);
3973 auth_command = (char *) xmalloc (strlen(arg)+6);
3974 strcpy (auth_command, "auth ");
3975 strcat (auth_command, arg);
3979 yaz_log_init(yaz_log_mask_str(arg), "", 0);
3985 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3986 "[-b berdump] [-c cclfields] \n"
3987 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
3988 "[-k size] [-V] [<server-addr>]\n",
3996 #ifdef HAVE_GETTIMEOFDAY
3997 gettimeofday (&tv_start, 0);
3999 process_cmd_line (auth_command);
4000 #if HAVE_READLINE_HISTORY_H
4001 add_history(auth_command);
4003 xfree(auth_command);
4007 #ifdef HAVE_GETTIMEOFDAY
4008 gettimeofday (&tv_start, 0);
4010 process_cmd_line (open_command);
4011 #if HAVE_READLINE_HISTORY_H
4012 add_history(open_command);
4014 xfree(open_command);
4025 * vim600: sw=4 ts=8 fdm=marker
4026 * vim<600: sw=4 ts=8