2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.204 2003-07-18 22:41:25 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 au.which = Z_IdAuthentication_open;
595 printf("Authentication set to Open (%s)\n", user);
600 au.which = Z_IdAuthentication_idPass;
601 au.u.idPass = &idPass;
602 idPass.groupId = NULL;
603 idPass.userId = user;
604 idPass.password = group;
605 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
610 au.which = Z_IdAuthentication_idPass;
611 au.u.idPass = &idPass;
612 idPass.groupId = group;
613 idPass.userId = user;
614 idPass.password = pass;
615 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
621 /* SEARCH SERVICE ------------------------------ */
622 static void display_record(Z_External *r);
624 static void print_record(const unsigned char *buf, size_t len)
627 print_stringn (buf, len);
628 /* add newline if not already added ... */
629 if (i <= 0 || buf[i-1] != '\n')
633 static void display_record(Z_External *r)
635 oident *ent = oid_getentbyoid(r->direct_reference);
639 * Tell the user what we got.
641 if (r->direct_reference)
643 printf("Record type: ");
645 printf("%s\n", ent->desc);
646 else if (!odr_oid(print, &r->direct_reference, 0, 0))
648 odr_perror(print, "print oid");
652 /* Check if this is a known, ASN.1 type tucked away in an octet string */
653 if (ent && r->which == Z_External_octet)
655 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
661 * Call the given decoder to process the record.
663 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
664 r->u.octet_aligned->len, 0);
665 if (!(*type->fun)(in, (char **)&rr, 0, 0))
667 odr_perror(in, "Decoding constructed record.");
668 fprintf(stdout, "[Near %d]\n", odr_offset(in));
669 fprintf(stdout, "Packet dump:\n---------\n");
670 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
671 r->u.octet_aligned->len);
672 fprintf(stdout, "---------\n");
674 /* note just ignores the error ant print the bytes form the octet_aligned later */
677 * Note: we throw away the original, BER-encoded record here.
678 * Do something else with it if you want to keep it.
680 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
681 r->which = type->what;
685 if (ent && ent->oclass != CLASS_RECSYN)
687 if (ent && ent->value == VAL_SOIF)
688 print_record((const unsigned char *) r->u.octet_aligned->buf,
689 r->u.octet_aligned->len);
690 else if (r->which == Z_External_octet)
692 const char *octet_buf = (char*)r->u.octet_aligned->buf;
693 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
694 ent->value == VAL_HTML)
696 print_record((const unsigned char *) octet_buf,
697 r->u.octet_aligned->len);
699 else if (ent->value == VAL_POSTSCRIPT)
701 int size = r->u.octet_aligned->len;
704 print_record((const unsigned char *) octet_buf, size);
709 #if AVOID_MARC_DECODE
710 /* primitive check for a marc OID 5.1-29 except 16 */
711 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
712 ent->oidsuffix[1] != 16
721 yaz_marc_t mt = yaz_marc_create();
723 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
727 if (marcCharset && !strcmp(marcCharset, "auto"))
729 if (ent->value == VAL_USMARC)
731 if (octet_buf[9] == 'a')
739 else if (marcCharset)
741 if (outputCharset && from)
743 cd = yaz_iconv_open(outputCharset, from);
744 printf ("convert from %s to %s", from,
747 printf (" unsupported\n");
752 fwrite (result, 1, rlen, stdout);
756 size_t inbytesleft = rlen;
757 const char *inp = result;
761 size_t outbytesleft = sizeof(outbuf);
765 r = yaz_iconv (cd, (char**) &inp,
767 &outp, &outbytesleft);
768 if (r == (size_t) (-1))
770 int e = yaz_iconv_error(cd);
771 if (e != YAZ_ICONV_E2BIG)
774 fwrite (outbuf, outp - outbuf, 1, stdout);
780 printf ("bad MARC. Dumping as it is:\n");
781 print_record((const unsigned char*) octet_buf,
782 r->u.octet_aligned->len);
784 yaz_marc_destroy(mt);
790 print_record((const unsigned char*) octet_buf,
791 r->u.octet_aligned->len);
795 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
797 else if (ent && ent->value == VAL_SUTRS)
799 if (r->which != Z_External_sutrs)
801 printf("Expecting single SUTRS type for SUTRS.\n");
804 print_record(r->u.sutrs->buf, r->u.sutrs->len);
806 else if (ent && ent->value == VAL_GRS1)
809 if (r->which != Z_External_grs1)
811 printf("Expecting single GRS type for GRS.\n");
815 yaz_display_grs1(w, r->u.grs1, 0);
819 else if ( /* OPAC display not complete yet .. */
820 ent && ent->value == VAL_OPAC)
823 if (r->u.opac->bibliographicRecord)
824 display_record(r->u.opac->bibliographicRecord);
825 for (i = 0; i<r->u.opac->num_holdingsData; i++)
827 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
828 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
830 printf ("MARC holdings %d\n", i);
831 display_record(h->u.marcHoldingsRecord);
833 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
837 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
839 printf ("Data holdings %d\n", i);
840 if (data->typeOfRecord)
841 printf ("typeOfRecord: %s\n", data->typeOfRecord);
842 if (data->encodingLevel)
843 printf ("encodingLevel: %s\n", data->encodingLevel);
844 if (data->receiptAcqStatus)
845 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
846 if (data->generalRetention)
847 printf ("generalRetention: %s\n", data->generalRetention);
848 if (data->completeness)
849 printf ("completeness: %s\n", data->completeness);
850 if (data->dateOfReport)
851 printf ("dateOfReport: %s\n", data->dateOfReport);
853 printf ("nucCode: %s\n", data->nucCode);
854 if (data->localLocation)
855 printf ("localLocation: %s\n", data->localLocation);
856 if (data->shelvingLocation)
857 printf ("shelvingLocation: %s\n", data->shelvingLocation);
858 if (data->callNumber)
859 printf ("callNumber: %s\n", data->callNumber);
860 if (data->copyNumber)
861 printf ("copyNumber: %s\n", data->copyNumber);
862 if (data->publicNote)
863 printf ("publicNote: %s\n", data->publicNote);
864 if (data->reproductionNote)
865 printf ("reproductionNote: %s\n", data->reproductionNote);
866 if (data->termsUseRepro)
867 printf ("termsUseRepro: %s\n", data->termsUseRepro);
868 if (data->enumAndChron)
869 printf ("enumAndChron: %s\n", data->enumAndChron);
870 for (j = 0; j<data->num_volumes; j++)
872 printf ("volume %d\n", j);
873 if (data->volumes[j]->enumeration)
874 printf (" enumeration: %s\n",
875 data->volumes[j]->enumeration);
876 if (data->volumes[j]->chronology)
877 printf (" chronology: %s\n",
878 data->volumes[j]->chronology);
879 if (data->volumes[j]->enumAndChron)
880 printf (" enumAndChron: %s\n",
881 data->volumes[j]->enumAndChron);
883 for (j = 0; j<data->num_circulationData; j++)
885 printf ("circulation %d\n", j);
886 if (data->circulationData[j]->availableNow)
887 printf (" availableNow: %d\n",
888 *data->circulationData[j]->availableNow);
889 if (data->circulationData[j]->availablityDate)
890 printf (" availabiltyDate: %s\n",
891 data->circulationData[j]->availablityDate);
892 if (data->circulationData[j]->availableThru)
893 printf (" availableThru: %s\n",
894 data->circulationData[j]->availableThru);
895 if (data->circulationData[j]->restrictions)
896 printf (" restrictions: %s\n",
897 data->circulationData[j]->restrictions);
898 if (data->circulationData[j]->itemId)
899 printf (" itemId: %s\n",
900 data->circulationData[j]->itemId);
901 if (data->circulationData[j]->renewable)
902 printf (" renewable: %d\n",
903 *data->circulationData[j]->renewable);
904 if (data->circulationData[j]->onHold)
905 printf (" onHold: %d\n",
906 *data->circulationData[j]->onHold);
907 if (data->circulationData[j]->enumAndChron)
908 printf (" enumAndChron: %s\n",
909 data->circulationData[j]->enumAndChron);
910 if (data->circulationData[j]->midspine)
911 printf (" midspine: %s\n",
912 data->circulationData[j]->midspine);
913 if (data->circulationData[j]->temporaryLocation)
914 printf (" temporaryLocation: %s\n",
915 data->circulationData[j]->temporaryLocation);
922 printf("Unknown record representation.\n");
923 if (!z_External(print, &r, 0, 0))
925 odr_perror(print, "Printing external");
931 static void display_diagrecs(Z_DiagRec **pp, int num)
935 Z_DefaultDiagFormat *r;
937 printf("Diagnostic message(s) from database:\n");
938 for (i = 0; i<num; i++)
940 Z_DiagRec *p = pp[i];
941 if (p->which != Z_DiagRec_defaultFormat)
943 printf("Diagnostic record not in default format.\n");
947 r = p->u.defaultFormat;
948 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
949 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
950 printf("Missing or unknown diagset\n");
951 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
954 case Z_DefaultDiagFormat_v2Addinfo:
955 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
957 case Z_DefaultDiagFormat_v3Addinfo:
958 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
965 static void display_nameplusrecord(Z_NamePlusRecord *p)
968 printf("[%s]", p->databaseName);
969 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
970 display_diagrecs(&p->u.surrogateDiagnostic, 1);
971 else if (p->which == Z_NamePlusRecord_databaseRecord)
972 display_record(p->u.databaseRecord);
975 static void display_records(Z_Records *p)
979 if (p->which == Z_Records_NSD)
981 Z_DiagRec dr, *dr_p = &dr;
982 dr.which = Z_DiagRec_defaultFormat;
983 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
984 display_diagrecs (&dr_p, 1);
986 else if (p->which == Z_Records_multipleNSD)
987 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
988 p->u.multipleNonSurDiagnostics->num_diagRecs);
991 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
992 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
993 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
997 static int send_deleteResultSetRequest(const char *arg)
1002 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1003 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1005 req->referenceId = set_refid (out);
1007 req->num_resultSetList =
1008 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1009 names[0], names[1], names[2], names[3],
1010 names[4], names[5], names[6], names[7]);
1012 req->deleteFunction = (int *)
1013 odr_malloc (out, sizeof(*req->deleteFunction));
1014 if (req->num_resultSetList > 0)
1016 *req->deleteFunction = Z_DeleteRequest_list;
1017 req->resultSetList = (char **)
1018 odr_malloc (out, sizeof(*req->resultSetList)*
1019 req->num_resultSetList);
1020 for (i = 0; i<req->num_resultSetList; i++)
1021 req->resultSetList[i] = names[i];
1025 *req->deleteFunction = Z_DeleteRequest_all;
1026 req->resultSetList = 0;
1030 printf("Sent deleteResultSetRequest.\n");
1035 static int send_srw(Z_SRW_PDU *sr)
1037 const char *charset = negotiationCharset;
1038 const char *host_port = 0;
1041 Z_SOAP_Handler h[2] = {
1042 {"http://www.loc.gov/zing/srw/v1.0/", 0, (Z_SOAP_fun) yaz_srw_codec},
1045 ODR o = odr_createmem(ODR_ENCODE);
1047 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1050 path = odr_malloc(out, strlen(databaseNames[0])+2);
1052 strcpy(path+1, databaseNames[0]);
1054 gdu = z_get_HTTP_Request(out);
1055 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1059 const char *cp0 = strstr(host_port, "://");
1060 const char *cp1 = 0;
1066 cp1 = strchr(cp0, '/');
1068 cp1 = cp0+strlen(cp0);
1072 char *h = odr_malloc(out, cp1 - cp0 + 1);
1073 memcpy (h, cp0, cp1 - cp0);
1075 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1080 strcpy(ctype, "text/xml");
1081 if (charset && strlen(charset) < 20)
1083 strcat(ctype, "; charset=");
1084 strcat(ctype, charset);
1086 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1087 "Content-Type", ctype);
1088 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1089 "SOAPAction", "\"\"");
1090 p->which = Z_SOAP_generic;
1091 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1092 p->u.generic->no = 0;
1093 p->u.generic->ns = 0;
1094 p->u.generic->p = sr;
1095 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1097 ret = z_soap_codec_enc(o, &p,
1098 &gdu->u.HTTP_Request->content_buf,
1099 &gdu->u.HTTP_Request->content_len, h,
1102 if (z_GDU(out, &gdu, 0, 0))
1108 buf_out = odr_getbuf(out, &len_out, 0);
1110 /* we don't odr_reset(out), since we may need the buffer again */
1112 r = cs_put(conn, buf_out, len_out);
1124 static int send_SRW_searchRequest(const char *arg)
1130 assert(srw_sr_odr_out == 0);
1131 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1133 odr_reset(srw_sr_odr_out);
1137 /* save this for later .. when fetching individual records */
1138 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1139 sr->u.request->query_type = Z_SRW_query_type_cql;
1140 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1142 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1143 sr->u.request->query_type = Z_SRW_query_type_cql;
1144 sr->u.request->query.cql = odr_strdup(out, arg);
1146 sr->u.request->recordSchema = schema;
1147 return send_srw(sr);
1151 static int send_searchRequest(const char *arg)
1153 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1154 Z_SearchRequest *req = apdu->u.searchRequest;
1157 struct ccl_rpn_node *rpn = NULL;
1159 char setstring[100];
1160 Z_RPNQuery *RPNquery;
1162 YAZ_PQF_Parser pqf_parser;
1164 QueryType myQueryType = queryType;
1167 if (myQueryType == QueryType_CCL2RPN)
1169 rpn = ccl_find_str(bibset, arg, &error, &pos);
1172 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1175 } else if (myQueryType == QueryType_CQL2RPN) {
1176 /* ### All this code should be wrapped in a utility function */
1178 struct cql_node *node;
1179 const char *addinfo;
1180 if (cqltrans == 0) {
1181 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1184 parser = cql_parser_create();
1185 if ((error = cql_parser_string(parser, arg)) != 0) {
1186 printf("Can't parse CQL: must be a syntax error\n");
1189 node = cql_parser_result(parser);
1190 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1191 sizeof pqfbuf)) != 0) {
1192 error = cql_transform_error(cqltrans, &addinfo);
1193 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1194 cql_strerror(error), addinfo);
1198 myQueryType = QueryType_Prefix;
1201 req->referenceId = set_refid (out);
1202 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1204 static unsigned char big[2100];
1205 static Odr_oct bigo;
1207 /* send a very big referenceid to test transport stack etc. */
1208 memset(big, 'A', 2100);
1209 bigo.len = bigo.size = 2100;
1211 req->referenceId = &bigo;
1216 sprintf(setstring, "%d", ++setnumber);
1217 req->resultSetName = setstring;
1219 *req->smallSetUpperBound = smallSetUpperBound;
1220 *req->largeSetLowerBound = largeSetLowerBound;
1221 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1222 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1223 mediumSetPresentNumber > 0))
1227 prefsyn.proto = protocol;
1228 prefsyn.oclass = CLASS_RECSYN;
1229 prefsyn.value = recordsyntax;
1230 req->preferredRecordSyntax =
1231 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1232 req->smallSetElementSetNames =
1233 req->mediumSetElementSetNames = elementSetNames;
1235 req->num_databaseNames = num_databaseNames;
1236 req->databaseNames = databaseNames;
1238 req->query = &query;
1240 switch (myQueryType)
1242 case QueryType_Prefix:
1243 query.which = Z_Query_type_1;
1244 pqf_parser = yaz_pqf_create ();
1245 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1248 const char *pqf_msg;
1250 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1251 printf("%*s^\n", off+4, "");
1252 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1254 yaz_pqf_destroy (pqf_parser);
1257 yaz_pqf_destroy (pqf_parser);
1258 query.u.type_1 = RPNquery;
1261 query.which = Z_Query_type_2;
1262 query.u.type_2 = &ccl_query;
1263 ccl_query.buf = (unsigned char*) arg;
1264 ccl_query.len = strlen(arg);
1266 case QueryType_CCL2RPN:
1267 query.which = Z_Query_type_1;
1268 RPNquery = ccl_rpn_query(out, rpn);
1271 printf ("Couldn't convert from CCL to RPN\n");
1274 query.u.type_1 = RPNquery;
1275 ccl_rpn_delete (rpn);
1278 query.which = Z_Query_type_104;
1279 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1280 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1281 ext->indirect_reference = 0;
1282 ext->descriptor = 0;
1283 ext->which = Z_External_CQL;
1284 ext->u.cql = odr_strdup(out, arg);
1285 query.u.type_104 = ext;
1288 printf ("Unsupported query type\n");
1291 if (send_apdu(apdu))
1292 printf("Sent searchRequest.\n");
1297 /* display Query Expression as part of searchResult-1 */
1298 static void display_queryExpression (Z_QueryExpression *qe)
1302 if (qe->which == Z_QueryExpression_term)
1304 if (qe->u.term->queryTerm)
1306 Z_Term *term = qe->u.term->queryTerm;
1307 switch (term->which)
1309 case Z_Term_general:
1310 printf (" %.*s", term->u.general->len, term->u.general->buf);
1312 case Z_Term_characterString:
1313 printf (" %s", term->u.characterString);
1315 case Z_Term_numeric:
1316 printf (" %d", *term->u.numeric);
1326 /* see if we can find USR:SearchResult-1 */
1327 static void display_searchResult (Z_OtherInformation *o)
1332 for (i = 0; i < o->num_elements; i++)
1334 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1336 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1338 if (ext->which == Z_External_searchResult1)
1341 Z_SearchInfoReport *sr = ext->u.searchResult1;
1342 printf ("SearchResult-1:");
1343 for (j = 0; j < sr->num; j++)
1345 if (!sr->elements[j]->subqueryExpression)
1347 display_queryExpression (
1348 sr->elements[j]->subqueryExpression);
1349 display_queryExpression (
1350 sr->elements[j]->subqueryInterpretation);
1351 display_queryExpression (
1352 sr->elements[j]->subqueryRecommendation);
1353 if (sr->elements[j]->subqueryCount)
1354 printf ("(%d)", *sr->elements[j]->subqueryCount);
1362 static int process_searchResponse(Z_SearchResponse *res)
1364 printf ("Received SearchResponse.\n");
1365 print_refid (res->referenceId);
1366 if (*res->searchStatus)
1367 printf("Search was a success.\n");
1369 printf("Search was a bloomin' failure.\n");
1370 printf("Number of hits: %d", *res->resultCount);
1372 printf (", setno %d", setnumber);
1374 display_searchResult (res->additionalSearchInfo);
1375 printf("records returned: %d\n",
1376 *res->numberOfRecordsReturned);
1377 setno += *res->numberOfRecordsReturned;
1379 display_records(res->records);
1383 static void print_level(int iLevel)
1386 for (i = 0; i < iLevel * 4; i++)
1390 static void print_int(int iLevel, const char *pTag, int *pInt)
1394 print_level(iLevel);
1395 printf("%s: %d\n", pTag, *pInt);
1399 static void print_string(int iLevel, const char *pTag, const char *pString)
1401 if (pString != NULL)
1403 print_level(iLevel);
1404 printf("%s: %s\n", pTag, pString);
1408 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1414 print_level(iLevel);
1415 printf("%s:", pTag);
1416 for (; *pInt != -1; pInt++)
1417 printf(" %d", *pInt);
1422 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1424 if (referenceId != NULL)
1428 print_level(iLevel);
1429 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1430 for (i = 0; i < referenceId->len; i++)
1431 printf("%c", referenceId->buf[i]);
1436 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1438 if (pStringNumeric != NULL)
1440 switch (pStringNumeric->which)
1442 case Z_StringOrNumeric_string:
1443 print_string(iLevel, pTag, pStringNumeric->u.string);
1446 case Z_StringOrNumeric_numeric:
1447 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1451 print_level(iLevel);
1452 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1458 static void print_universe_report_duplicate(
1460 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1462 if (pUniverseReportDuplicate != NULL)
1464 print_level(iLevel);
1465 printf("Universe Report Duplicate: \n");
1467 print_string_or_numeric(iLevel, "Hit No",
1468 pUniverseReportDuplicate->hitno);
1472 static void print_universe_report_hits(
1474 Z_UniverseReportHits *pUniverseReportHits)
1476 if (pUniverseReportHits != NULL)
1478 print_level(iLevel);
1479 printf("Universe Report Hits: \n");
1481 print_string_or_numeric(iLevel, "Database",
1482 pUniverseReportHits->database);
1483 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1487 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1489 if (pUniverseReport != NULL)
1491 print_level(iLevel);
1492 printf("Universe Report: \n");
1494 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1495 switch (pUniverseReport->which)
1497 case Z_UniverseReport_databaseHits:
1498 print_universe_report_hits(iLevel,
1499 pUniverseReport->u.databaseHits);
1502 case Z_UniverseReport_duplicate:
1503 print_universe_report_duplicate(iLevel,
1504 pUniverseReport->u.duplicate);
1508 print_level(iLevel);
1509 printf("Type: %d\n", pUniverseReport->which);
1515 static void print_external(int iLevel, Z_External *pExternal)
1517 if (pExternal != NULL)
1519 print_level(iLevel);
1520 printf("External: \n");
1522 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1523 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1524 print_string(iLevel, "Descriptor", pExternal->descriptor);
1525 switch (pExternal->which)
1527 case Z_External_universeReport:
1528 print_universe_report(iLevel, pExternal->u.universeReport);
1532 print_level(iLevel);
1533 printf("Type: %d\n", pExternal->which);
1539 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1541 printf ("Received ResourceControlRequest.\n");
1542 print_referenceId(1, req->referenceId);
1543 print_int(1, "Suspended Flag", req->suspendedFlag);
1544 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1545 print_int(1, "Response Required", req->responseRequired);
1546 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1547 print_external(1, req->resourceReport);
1551 void process_ESResponse(Z_ExtendedServicesResponse *res)
1554 switch (*res->operationStatus)
1556 case Z_ExtendedServicesResponse_done:
1559 case Z_ExtendedServicesResponse_accepted:
1560 printf ("accepted\n");
1562 case Z_ExtendedServicesResponse_failure:
1563 printf ("failure\n");
1564 display_diagrecs(res->diagnostics, res->num_diagnostics);
1567 printf ("unknown\n");
1569 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1570 (res->num_diagnostics != 0) ) {
1571 display_diagrecs(res->diagnostics, res->num_diagnostics);
1573 print_refid (res->referenceId);
1574 if (res->taskPackage &&
1575 res->taskPackage->which == Z_External_extendedService)
1577 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1578 Odr_oct *id = taskPackage->targetReference;
1579 Z_External *ext = taskPackage->taskSpecificParameters;
1583 printf ("Target Reference: ");
1584 print_stringn (id->buf, id->len);
1587 if (ext->which == Z_External_update)
1589 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1590 if (utp && utp->targetPart)
1592 Z_IUTargetPart *targetPart = utp->targetPart;
1595 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1598 Z_IUTaskPackageRecordStructure *tpr =
1599 targetPart->taskPackageRecords[i];
1600 printf ("task package record %d\n", i+1);
1601 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1603 display_record (tpr->u.record);
1607 printf ("other type\n");
1615 const char *get_ill_element (void *clientData, const char *element)
1620 static Z_External *create_external_itemRequest()
1622 struct ill_get_ctl ctl;
1623 ILL_ItemRequest *req;
1625 int item_request_size = 0;
1626 char *item_request_buf = 0;
1630 ctl.f = get_ill_element;
1632 req = ill_get_ItemRequest(&ctl, "ill", 0);
1634 printf ("ill_get_ItemRequest failed\n");
1636 if (!ill_ItemRequest (out, &req, 0, 0))
1640 ill_ItemRequest(print, &req, 0, 0);
1643 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1644 if (item_request_buf)
1645 odr_setbuf (out, item_request_buf, item_request_size, 1);
1646 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1653 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1654 oid.proto = PROTO_GENERAL;
1655 oid.oclass = CLASS_GENERAL;
1656 oid.value = VAL_ISO_ILL_1;
1658 r = (Z_External *) odr_malloc (out, sizeof(*r));
1659 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1660 r->indirect_reference = 0;
1662 r->which = Z_External_single;
1664 r->u.single_ASN1_type = (Odr_oct *)
1665 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1666 r->u.single_ASN1_type->buf = (unsigned char *)
1667 odr_malloc (out, item_request_size);
1668 r->u.single_ASN1_type->len = item_request_size;
1669 r->u.single_ASN1_type->size = item_request_size;
1670 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1673 do_hex_dump(item_request_buf,item_request_size);
1678 static Z_External *create_external_ILL_APDU(int which)
1680 struct ill_get_ctl ctl;
1683 int ill_request_size = 0;
1684 char *ill_request_buf = 0;
1688 ctl.f = get_ill_element;
1690 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1692 if (!ill_APDU (out, &ill_apdu, 0, 0))
1696 printf ("-------------------\n");
1697 ill_APDU(print, &ill_apdu, 0, 0);
1699 printf ("-------------------\n");
1701 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1702 if (ill_request_buf)
1703 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1704 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1710 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1712 oid.proto = PROTO_GENERAL;
1713 oid.oclass = CLASS_GENERAL;
1714 oid.value = VAL_ISO_ILL_1;
1716 r = (Z_External *) odr_malloc (out, sizeof(*r));
1717 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1718 r->indirect_reference = 0;
1720 r->which = Z_External_single;
1722 r->u.single_ASN1_type = (Odr_oct *)
1723 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1724 r->u.single_ASN1_type->buf = (unsigned char *)
1725 odr_malloc (out, ill_request_size);
1726 r->u.single_ASN1_type->len = ill_request_size;
1727 r->u.single_ASN1_type->size = ill_request_size;
1728 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1729 /* printf ("len = %d\n", ill_request_size); */
1730 /* do_hex_dump(ill_request_buf,ill_request_size); */
1731 /* printf("--- end of extenal\n"); */
1738 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1740 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1741 oident ItemOrderRequest;
1743 ItemOrderRequest.proto = PROTO_Z3950;
1744 ItemOrderRequest.oclass = CLASS_EXTSERV;
1745 ItemOrderRequest.value = VAL_ITEMORDER;
1747 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1748 r->indirect_reference = 0;
1751 r->which = Z_External_itemOrder;
1753 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1754 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1755 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1757 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1758 odr_malloc(out,sizeof(Z_IORequest));
1759 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1761 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1762 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1763 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1764 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1765 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1766 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1768 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1769 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1770 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1772 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1773 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1774 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1775 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1777 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1778 (int *) odr_malloc(out, sizeof(int));
1779 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1781 if (!strcmp (type, "item") || !strcmp(type, "2"))
1783 printf ("using item-request\n");
1784 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1785 create_external_itemRequest();
1787 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1789 printf ("using ILL-request\n");
1790 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1791 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1793 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1795 const char *xml_buf =
1797 " <type>request</type>\n"
1798 " <libraryNo>000200</libraryNo>\n"
1799 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1801 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1802 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1805 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1810 static int send_itemorder(const char *type, int itemno)
1812 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1813 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1814 oident ItemOrderRequest;
1816 ItemOrderRequest.proto = PROTO_Z3950;
1817 ItemOrderRequest.oclass = CLASS_EXTSERV;
1818 ItemOrderRequest.value = VAL_ITEMORDER;
1819 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1820 req->packageName = esPackageName;
1822 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1828 static int only_z3950()
1830 if (protocol == PROTO_HTTP)
1832 printf ("Not supported by SRW\n");
1838 static int cmd_update(const char *arg)
1840 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1841 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1844 Z_IUOriginPartToKeep *toKeep;
1845 Z_IUSuppliedRecords *notToKeep;
1847 char action[20], recid[20], fname[80];
1849 Z_External *record_this = 0;
1856 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1858 if (!strcmp (action, "insert"))
1859 action_no = Z_IUOriginPartToKeep_recordInsert;
1860 else if (!strcmp (action, "replace"))
1861 action_no = Z_IUOriginPartToKeep_recordReplace;
1862 else if (!strcmp (action, "delete"))
1863 action_no = Z_IUOriginPartToKeep_recordDelete;
1864 else if (!strcmp (action, "update"))
1865 action_no = Z_IUOriginPartToKeep_specialUpdate;
1868 printf ("Bad action: %s\n", action);
1869 printf ("Possible values: insert, replace, delete, update\n");
1877 stat (fname, &status);
1878 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1880 size_t len = status.st_size;
1881 char *buf = (char *) xmalloc (len);
1883 fread (buf, 1, len, inf);
1887 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1893 printf ("File %s doesn't exist\n", fname);
1901 printf ("No last record (update ignored)\n");
1904 record_this = record_last;
1907 update_oid.proto = PROTO_Z3950;
1908 update_oid.oclass = CLASS_EXTSERV;
1909 update_oid.value = VAL_DBUPDATE;
1910 oid_ent_to_oid (&update_oid, oid);
1911 req->packageType = odr_oiddup(out,oid);
1912 req->packageName = esPackageName;
1914 req->referenceId = set_refid (out);
1916 r = req->taskSpecificParameters = (Z_External *)
1917 odr_malloc (out, sizeof(*r));
1918 r->direct_reference = odr_oiddup(out,oid);
1919 r->indirect_reference = 0;
1921 r->which = Z_External_update;
1922 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1923 r->u.update->which = Z_IUUpdate_esRequest;
1924 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1925 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1926 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1927 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1928 toKeep->databaseName = databaseNames[0];
1930 toKeep->elementSetName = 0;
1931 toKeep->actionQualifier = 0;
1932 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1933 *toKeep->action = action_no;
1935 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1936 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1938 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1939 odr_malloc(out, sizeof(*notToKeep->elements));
1940 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1941 odr_malloc(out, sizeof(**notToKeep->elements));
1942 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1945 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1946 odr_malloc (out, sizeof(Odr_oct));
1947 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1948 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1949 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1952 notToKeep->elements[0]->u.opaque = 0;
1953 notToKeep->elements[0]->supplementalId = 0;
1954 notToKeep->elements[0]->correlationInfo = 0;
1955 notToKeep->elements[0]->record = record_this;
1962 static int cmd_itemorder(const char *arg)
1969 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1972 printf("Item order request\n");
1974 send_itemorder(type, itemno);
1978 static int cmd_find(const char *arg)
1982 printf("Find what?\n");
1985 if (protocol == PROTO_HTTP)
1990 if (!send_SRW_searchRequest(arg))
2003 printf("Not connected yet\n");
2007 if (!send_searchRequest(arg))
2013 static int cmd_delete(const char *arg)
2017 printf("Not connected yet\n");
2022 if (!send_deleteResultSetRequest(arg))
2027 static int cmd_ssub(const char *arg)
2029 if (!(smallSetUpperBound = atoi(arg)))
2034 static int cmd_lslb(const char *arg)
2038 if (!(largeSetLowerBound = atoi(arg)))
2043 static int cmd_mspn(const char *arg)
2047 if (!(mediumSetPresentNumber = atoi(arg)))
2052 static int cmd_status(const char *arg)
2054 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2055 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2056 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2060 static int cmd_setnames(const char *arg)
2062 if (*arg == '1') /* enable ? */
2064 else if (*arg == '0') /* disable ? */
2066 else if (setnumber < 0) /* no args, toggle .. */
2072 printf("Set numbering enabled.\n");
2074 printf("Set numbering disabled.\n");
2078 /* PRESENT SERVICE ----------------------------- */
2080 static void parse_show_args(const char *arg_c, char *setstring,
2081 int *start, int *number)
2086 strncpy(arg, arg_c, sizeof(arg)-1);
2087 arg[sizeof(arg)-1] = '\0';
2089 if ((p = strchr(arg, '+')))
2091 *number = atoi(p + 1);
2096 if (p && (p=strchr(p+1, '+')))
2097 strcpy (setstring, p+1);
2098 else if (setnumber >= 0)
2099 sprintf(setstring, "%d", setnumber);
2104 static int send_presentRequest(const char *arg)
2106 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2107 Z_PresentRequest *req = apdu->u.presentRequest;
2108 Z_RecordComposition compo;
2112 char setstring[100];
2114 req->referenceId = set_refid (out);
2116 parse_show_args(arg, setstring, &setno, &nos);
2118 req->resultSetId = setstring;
2120 req->resultSetStartPoint = &setno;
2121 req->numberOfRecordsRequested = &nos;
2122 prefsyn.proto = protocol;
2123 prefsyn.oclass = CLASS_RECSYN;
2124 prefsyn.value = recordsyntax;
2125 req->preferredRecordSyntax =
2126 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2132 prefschema.proto = protocol;
2133 prefschema.oclass = CLASS_SCHEMA;
2134 prefschema.value = oid_getvalbyname(schema);
2136 req->recordComposition = &compo;
2137 compo.which = Z_RecordComp_complex;
2138 compo.u.complex = (Z_CompSpec *)
2139 odr_malloc(out, sizeof(*compo.u.complex));
2140 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2141 odr_malloc(out, sizeof(bool_t));
2142 *compo.u.complex->selectAlternativeSyntax = 0;
2144 compo.u.complex->generic = (Z_Specification *)
2145 odr_malloc(out, sizeof(*compo.u.complex->generic));
2146 compo.u.complex->generic->which = Z_Schema_oid;
2147 compo.u.complex->generic->schema.oid = (Odr_oid *)
2148 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2149 if (!compo.u.complex->generic->schema.oid)
2151 /* OID wasn't a schema! Try record syntax instead. */
2152 prefschema.oclass = CLASS_RECSYN;
2153 compo.u.complex->generic->schema.oid = (Odr_oid *)
2154 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2156 if (!elementSetNames)
2157 compo.u.complex->generic->elementSpec = 0;
2160 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2161 odr_malloc(out, sizeof(Z_ElementSpec));
2162 compo.u.complex->generic->elementSpec->which =
2163 Z_ElementSpec_elementSetName;
2164 compo.u.complex->generic->elementSpec->u.elementSetName =
2165 elementSetNames->u.generic;
2167 compo.u.complex->num_dbSpecific = 0;
2168 compo.u.complex->dbSpecific = 0;
2169 compo.u.complex->num_recordSyntax = 0;
2170 compo.u.complex->recordSyntax = 0;
2172 else if (elementSetNames)
2174 req->recordComposition = &compo;
2175 compo.which = Z_RecordComp_simple;
2176 compo.u.simple = elementSetNames;
2179 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2184 static int send_SRW_presentRequest(const char *arg)
2186 char setstring[100];
2188 Z_SRW_PDU *sr = srw_sr;
2192 parse_show_args(arg, setstring, &setno, &nos);
2193 sr->u.request->startRecord = odr_intdup(out, setno);
2194 sr->u.request->maximumRecords = odr_intdup(out, nos);
2196 sr->u.request->recordSchema = schema;
2197 return send_srw(sr);
2201 static void close_session (void)
2208 nmem_destroy (session_mem);
2217 void process_close(Z_Close *req)
2219 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2220 Z_Close *res = apdu->u.close;
2222 static char *reasons[] =
2227 "cost limit reached",
2229 "security violation",
2236 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2237 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2242 *res->closeReason = Z_Close_finished;
2244 printf("Sent response.\n");
2249 static int cmd_show(const char *arg)
2251 if (protocol == PROTO_HTTP)
2256 if (!send_SRW_presentRequest(arg))
2266 printf("Not connected yet\n");
2269 if (!send_presentRequest(arg))
2275 int cmd_quit(const char *arg)
2277 printf("See you later, alligator.\n");
2283 int cmd_cancel(const char *arg)
2285 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2286 Z_TriggerResourceControlRequest *req =
2287 apdu->u.triggerResourceControlRequest;
2292 printf("Session not initialized yet\n");
2297 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2299 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2302 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2303 req->resultSetWanted = &rfalse;
2306 printf("Sent cancel request\n");
2310 int send_scanrequest(const char *query, int pp, int num, const char *term)
2312 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2313 Z_ScanRequest *req = apdu->u.scanRequest;
2318 if (queryType == QueryType_CCL2RPN)
2322 struct ccl_rpn_node *rpn;
2324 rpn = ccl_find_str (bibset, query, &error, &pos);
2327 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2330 bib1.proto = PROTO_Z3950;
2331 bib1.oclass = CLASS_ATTSET;
2332 bib1.value = VAL_BIB1;
2333 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2334 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2336 printf("Couldn't convert CCL to Scan term\n");
2339 ccl_rpn_delete (rpn);
2343 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2345 if (!(req->termListAndStartPoint =
2346 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2348 const char *pqf_msg;
2350 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2351 printf("%*s^\n", off+7, "");
2352 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2353 yaz_pqf_destroy (pqf_parser);
2356 yaz_pqf_destroy (pqf_parser);
2360 if (req->termListAndStartPoint->term &&
2361 req->termListAndStartPoint->term->which == Z_Term_general &&
2362 req->termListAndStartPoint->term->u.general)
2364 req->termListAndStartPoint->term->u.general->buf =
2365 (unsigned char *) odr_strdup(out, term);
2366 req->termListAndStartPoint->term->u.general->len =
2367 req->termListAndStartPoint->term->u.general->size =
2371 req->referenceId = set_refid (out);
2372 req->num_databaseNames = num_databaseNames;
2373 req->databaseNames = databaseNames;
2374 req->numberOfTermsRequested = #
2375 req->preferredPositionInResponse = &pp;
2380 int send_sortrequest(const char *arg, int newset)
2382 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2383 Z_SortRequest *req = apdu->u.sortRequest;
2384 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2385 odr_malloc (out, sizeof(*sksl));
2391 sprintf (setstring, "%d", setnumber);
2393 sprintf (setstring, "default");
2395 req->referenceId = set_refid (out);
2397 req->num_inputResultSetNames = 1;
2398 req->inputResultSetNames = (Z_InternationalString **)
2399 odr_malloc (out, sizeof(*req->inputResultSetNames));
2400 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2402 if (newset && setnumber >= 0)
2403 sprintf (setstring, "%d", ++setnumber);
2405 req->sortedResultSetName = odr_strdup (out, setstring);
2407 req->sortSequence = yaz_sort_spec (out, arg);
2408 if (!req->sortSequence)
2410 printf ("Missing sort specifications\n");
2417 void display_term(Z_TermInfo *t)
2419 if (t->term->which == Z_Term_general)
2421 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2422 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2423 t->term->u.general->buf);
2426 printf("Term (not general)");
2427 if (t->globalOccurrences)
2428 printf (" (%d)\n", *t->globalOccurrences);
2433 void process_scanResponse(Z_ScanResponse *res)
2436 Z_Entry **entries = NULL;
2437 int num_entries = 0;
2439 printf("Received ScanResponse\n");
2440 print_refid (res->referenceId);
2441 printf("%d entries", *res->numberOfEntriesReturned);
2442 if (res->positionOfTerm)
2443 printf (", position=%d", *res->positionOfTerm);
2445 if (*res->scanStatus != Z_Scan_success)
2446 printf("Scan returned code %d\n", *res->scanStatus);
2449 if ((entries = res->entries->entries))
2450 num_entries = res->entries->num_entries;
2451 for (i = 0; i < num_entries; i++)
2453 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2454 if (entries[i]->which == Z_Entry_termInfo)
2456 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2457 display_term(entries[i]->u.termInfo);
2460 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2462 if (res->entries->nonsurrogateDiagnostics)
2463 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2464 res->entries->num_nonsurrogateDiagnostics);
2467 void process_sortResponse(Z_SortResponse *res)
2469 printf("Received SortResponse: status=");
2470 switch (*res->sortStatus)
2472 case Z_SortStatus_success:
2473 printf ("success"); break;
2474 case Z_SortStatus_partial_1:
2475 printf ("partial"); break;
2476 case Z_SortStatus_failure:
2477 printf ("failure"); break;
2479 printf ("unknown (%d)", *res->sortStatus);
2482 print_refid (res->referenceId);
2483 if (res->diagnostics)
2484 display_diagrecs(res->diagnostics,
2485 res->num_diagnostics);
2488 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2490 printf("Got deleteResultSetResponse status=%d\n",
2491 *res->deleteOperationStatus);
2492 if (res->deleteListStatuses)
2495 for (i = 0; i < res->deleteListStatuses->num; i++)
2497 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2498 *res->deleteListStatuses->elements[i]->status);
2503 int cmd_sort_generic(const char *arg, int newset)
2507 printf("Session not initialized yet\n");
2512 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2514 printf("Target doesn't support sort\n");
2519 if (send_sortrequest(arg, newset) < 0)
2526 int cmd_sort(const char *arg)
2528 return cmd_sort_generic (arg, 0);
2531 int cmd_sort_newset (const char *arg)
2533 return cmd_sort_generic (arg, 1);
2536 int cmd_scan(const char *arg)
2545 printf("Session not initialized yet\n");
2549 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2551 printf("Target doesn't support scan\n");
2556 strcpy (last_scan_query, arg);
2557 if (send_scanrequest(arg, 1, 20, 0) < 0)
2562 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2568 int cmd_schema(const char *arg)
2573 schema = xstrdup(arg);
2577 int cmd_format(const char *arg)
2582 printf("Usage: format <recordsyntax>\n");
2585 nsyntax = oid_getvalbyname (arg);
2586 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2588 printf ("unknown record syntax\n");
2591 recordsyntax = nsyntax;
2595 int cmd_elements(const char *arg)
2597 static Z_ElementSetNames esn;
2598 static char what[100];
2602 elementSetNames = 0;
2606 esn.which = Z_ElementSetNames_generic;
2607 esn.u.generic = what;
2608 elementSetNames = &esn;
2612 int cmd_attributeset(const char *arg)
2618 printf("Usage: attributeset <setname>\n");
2621 sscanf(arg, "%s", what);
2622 if (p_query_attset (what))
2624 printf("Unknown attribute set name\n");
2630 int cmd_querytype (const char *arg)
2632 if (!strcmp (arg, "ccl"))
2633 queryType = QueryType_CCL;
2634 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2635 queryType = QueryType_Prefix;
2636 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2637 queryType = QueryType_CCL2RPN;
2638 else if (!strcmp(arg, "cql"))
2639 queryType = QueryType_CQL;
2640 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2641 queryType = QueryType_CQL2RPN;
2644 printf ("Querytype must be one of:\n");
2645 printf (" prefix - Prefix query\n");
2646 printf (" ccl - CCL query\n");
2647 printf (" ccl2rpn - CCL query converted to RPN\n");
2648 printf (" cql - CQL\n");
2649 printf (" cql2rpn - CQL query converted to RPN\n");
2655 int cmd_refid (const char *arg)
2661 refid = (char *) xmalloc (strlen(arg)+1);
2662 strcpy (refid, arg);
2667 int cmd_close(const char *arg)
2676 apdu = zget_APDU(out, Z_APDU_close);
2677 req = apdu->u.close;
2678 *req->closeReason = Z_Close_finished;
2680 printf("Sent close request.\n");
2685 int cmd_packagename(const char* arg)
2687 xfree (esPackageName);
2688 esPackageName = NULL;
2690 esPackageName = xstrdup(arg);
2694 int cmd_proxy(const char* arg)
2699 yazProxy = xstrdup (arg);
2703 int cmd_marccharset(const char *arg)
2708 if (sscanf(arg, "%29s", l1) < 1)
2710 xfree (marcCharset);
2712 if (strcmp(l1, "-"))
2713 marcCharset = xstrdup(l1);
2717 int cmd_charset(const char* arg)
2719 char l1[30], l2[30];
2722 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2724 printf("Current negotiation character set is `%s'\n",
2725 negotiationCharset ? negotiationCharset: "none");
2726 printf("Current output character set is `%s'\n",
2727 outputCharset ? outputCharset: "none");
2730 xfree (negotiationCharset);
2731 negotiationCharset = NULL;
2732 if (*l1 && strcmp(l1, "-"))
2734 negotiationCharset = xstrdup(l1);
2735 printf ("Character set negotiation : %s\n", negotiationCharset);
2738 printf ("Character set negotiation disabled\n");
2741 xfree (outputCharset);
2743 if (!strcmp(l2, "auto") && codeset)
2747 printf ("output charset: %s\n", codeset);
2748 outputCharset = xstrdup(codeset);
2753 printf ("No codeset found on this system\n");
2755 else if (strcmp(l2, "-"))
2756 outputCharset = xstrdup(l2);
2758 printf ("Output charset conversion disabled\n");
2760 if (outputCharset && negotiationCharset)
2762 odr_set_charset (out, negotiationCharset, outputCharset);
2763 odr_set_charset (in, outputCharset, negotiationCharset);
2767 odr_set_charset (out, 0, 0);
2768 odr_set_charset (in, 0, 0);
2773 int cmd_lang(const char* arg)
2776 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2783 yazLang = (char *) xmalloc (strlen(arg)+1);
2784 strcpy (yazLang, arg);
2789 int cmd_source(const char* arg)
2791 /* first should open the file and read one line at a time.. */
2793 char line[1024], *cp;
2796 fprintf(stderr,"Error in source command use a filename\n");
2800 includeFile = fopen (arg, "r");
2803 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2807 while(!feof(includeFile)) {
2808 memset(line,0,sizeof(line));
2809 fgets(line,sizeof(line),includeFile);
2811 if(strlen(line) < 2) continue;
2812 if(line[0] == '#') continue;
2814 if ((cp = strrchr (line, '\n')))
2817 process_cmd_line(line);
2820 if(fclose(includeFile)<0) {
2821 perror("unable to close include file");
2827 int cmd_subshell(const char* args)
2832 system(getenv("SHELL"));
2838 int cmd_set_berfile(const char *arg)
2840 if (ber_file && ber_file != stdout && ber_file != stderr)
2842 if (!strcmp(arg, ""))
2844 else if (!strcmp(arg, "-"))
2847 ber_file = fopen(arg, "a");
2851 int cmd_set_apdufile(const char *arg)
2853 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2855 if (!strcmp(arg, ""))
2857 else if (!strcmp(arg, "-"))
2861 apdu_file = fopen(arg, "a");
2863 perror("unable to open apdu log file");
2866 odr_setprint(print, apdu_file);
2870 int cmd_set_cclfile(const char* arg)
2874 bibset = ccl_qual_mk ();
2875 inf = fopen (arg, "r");
2877 perror("unable to open CCL file");
2880 ccl_qual_file (bibset, inf);
2883 strcpy(ccl_fields,arg);
2887 int cmd_set_cqlfile(const char* arg)
2889 cql_transform_t newcqltrans;
2891 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
2892 perror("unable to open CQL file");
2896 cql_transform_close(cqltrans);
2898 cqltrans = newcqltrans;
2899 strcpy(cql_fields, arg);
2903 int cmd_set_auto_reconnect(const char* arg)
2905 if(strlen(arg)==0) {
2906 auto_reconnect = ! auto_reconnect;
2907 } else if(strcmp(arg,"on")==0) {
2909 } else if(strcmp(arg,"off")==0) {
2912 printf("Error use on or off\n");
2917 printf("Set auto reconnect enabled.\n");
2919 printf("Set auto reconnect disabled.\n");
2924 int cmd_set_marcdump(const char* arg)
2926 if(marc_file && marc_file != stderr) { /* don't close stdout*/
2930 if (!strcmp(arg, ""))
2932 else if (!strcmp(arg, "-"))
2936 marc_file = fopen(arg, "a");
2938 perror("unable to open marc log file");
2944 this command takes 3 arge {name class oid}
2946 int cmd_register_oid(const char* args) {
2951 {"appctx",CLASS_APPCTX},
2952 {"absyn",CLASS_ABSYN},
2953 {"attset",CLASS_ATTSET},
2954 {"transyn",CLASS_TRANSYN},
2955 {"diagset",CLASS_DIAGSET},
2956 {"recsyn",CLASS_RECSYN},
2957 {"resform",CLASS_RESFORM},
2958 {"accform",CLASS_ACCFORM},
2959 {"extserv",CLASS_EXTSERV},
2960 {"userinfo",CLASS_USERINFO},
2961 {"elemspec",CLASS_ELEMSPEC},
2962 {"varset",CLASS_VARSET},
2963 {"schema",CLASS_SCHEMA},
2964 {"tagset",CLASS_TAGSET},
2965 {"general",CLASS_GENERAL},
2966 {0,(enum oid_class) 0}
2968 char oname_str[101], oclass_str[101], oid_str[101];
2971 oid_class oidclass = CLASS_GENERAL;
2972 int val = 0, oid[OID_SIZE];
2973 struct oident * new_oident=NULL;
2975 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2976 oname_str,oclass_str, oid_str) < 1) {
2977 printf("Error in regristrate command \n");
2981 for (i = 0; oid_classes[i].className; i++) {
2982 if (!strcmp(oid_classes[i].className, oclass_str))
2984 oidclass=oid_classes[i].oclass;
2989 if(!(oid_classes[i].className)) {
2990 printf("Unknonwn oid class %s\n",oclass_str);
2998 while (isdigit (*name))
3000 val = val*10 + (*name - '0');
3013 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3014 if(strcmp(new_oident->desc,oname_str)) {
3015 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3021 int cmd_push_command(const char* arg)
3023 #if HAVE_READLINE_HISTORY_H
3027 fprintf(stderr,"Not compiled with the readline/history module\n");
3032 void source_rcfile()
3034 /* Look for a $HOME/.yazclientrc and source it if it exists */
3035 struct stat statbuf;
3037 char* homedir=getenv("HOME");
3039 if(!homedir) return;
3041 sprintf(buffer,"%s/.yazclientrc",homedir);
3043 if(stat(buffer,&statbuf)==0) {
3047 if(stat(".yazclientrc",&statbuf)==0) {
3048 cmd_source(".yazclientrc");
3053 static void initialize(void)
3058 if (!(out = odr_createmem(ODR_ENCODE)) ||
3059 !(in = odr_createmem(ODR_DECODE)) ||
3060 !(print = odr_createmem(ODR_PRINT)))
3062 fprintf(stderr, "failed to allocate ODR streams\n");
3067 setvbuf(stdout, 0, _IONBF, 0);
3069 odr_setprint(print, apdu_file);
3071 bibset = ccl_qual_mk ();
3072 inf = fopen (ccl_fields, "r");
3075 ccl_qual_file (bibset, inf);
3079 cqltrans = cql_transform_open_fname(cql_fields);
3080 /* If this fails, no problem: we detect cqltrans == 0 later */
3082 #if HAVE_READLINE_READLINE_H
3083 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3087 for(i=0; i<maxOtherInfosSupported; ++i) {
3088 extraOtherInfos[i].oidval = -1;
3095 #if HAVE_GETTIMEOFDAY
3096 struct timeval tv_start, tv_end;
3100 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3104 printf ("Received SRW SearchRetrieve Response\n");
3106 for (i = 0; i<res->num_diagnostics; i++)
3108 printf ("SRW diagnostic %d %s\n",
3109 *res->diagnostics[i].code,
3110 yaz_diag_srw_str(*res->diagnostics[i].code));
3112 if (res->diagnostics[i].details)
3113 printf ("Details: %s\n", res->diagnostics[i].details);
3115 if (res->numberOfRecords)
3116 printf ("Number of hits: %d\n", *res->numberOfRecords);
3117 for (i = 0; i<res->num_records; i++)
3119 Z_SRW_record *rec = res->records + i;
3121 if (rec->recordPosition)
3123 printf ("pos=%d", *rec->recordPosition);
3124 setno = *rec->recordPosition + 1;
3126 if (rec->recordSchema)
3127 printf (" schema=%s", rec->recordSchema);
3129 if (rec->recordData_buf && rec->recordData_len)
3131 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3137 static void http_response(Z_HTTP_Response *hres)
3140 const char *content_type = z_HTTP_header_lookup(hres->headers,
3142 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3144 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3146 Z_SOAP *soap_package = 0;
3147 ODR o = odr_createmem(ODR_DECODE);
3148 Z_SOAP_Handler soap_handlers[2] = {
3149 {"http://www.loc.gov/zing/srw/v1.0/", 0,
3150 (Z_SOAP_fun) yaz_srw_codec},
3153 ret = z_soap_codec(o, &soap_package,
3154 &hres->content_buf, &hres->content_len,
3156 if (!ret && soap_package->which == Z_SOAP_generic &&
3157 soap_package->u.generic->no == 0)
3159 Z_SRW_PDU *sr = soap_package->u.generic->p;
3160 if (sr->which == Z_SRW_searchRetrieve_response)
3161 handle_srw_response(sr->u.response);
3165 else if (!ret && (soap_package->which == Z_SOAP_fault
3166 || soap_package->which == Z_SOAP_error))
3168 printf ("HTTP Error Status=%d\n", hres->code);
3169 printf ("SOAP Fault code %s\n",
3170 soap_package->u.fault->fault_code);
3171 printf ("SOAP Fault string %s\n",
3172 soap_package->u.fault->fault_string);
3180 if (hres->code != 200)
3182 printf ("HTTP Error Status=%d\n", hres->code);
3186 printf ("Decoding of SRW package failed\n");
3190 if (!strcmp(hres->version, "1.0"))
3192 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3193 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3198 /* HTTP 1.1: only if no close we stay alive .. */
3199 if (connection_head && !strcmp(connection_head, "close"))
3205 void wait_and_handle_response()
3207 int reconnect_ok = 1;
3210 int netbufferlen = 0;
3215 res = cs_get(conn, &netbuffer, &netbufferlen);
3216 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3227 buf_out = odr_getbuf(out, &len_out, 0);
3229 cs_put(conn, buf_out, len_out);
3237 printf("Target closed connection\n");
3242 odr_reset(in); /* release APDU from last round */
3244 do_hex_dump(netbuffer, res);
3245 odr_setbuf(in, netbuffer, res, 0);
3247 if (!z_GDU(in, &gdu, 0, 0))
3249 FILE *f = ber_file ? ber_file : stdout;
3250 odr_perror(in, "Decoding incoming APDU");
3251 fprintf(f, "[Near %d]\n", odr_offset(in));
3252 fprintf(f, "Packet dump:\n---------\n");
3253 odr_dumpBER(f, netbuffer, res);
3254 fprintf(f, "---------\n");
3256 z_GDU(print, &gdu, 0, 0);
3257 if (conn && cs_more(conn))
3262 odr_dumpBER(ber_file, netbuffer, res);
3263 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3265 odr_perror(print, "Failed to print incoming APDU");
3269 if (gdu->which == Z_GDU_Z3950)
3271 Z_APDU *apdu = gdu->u.z3950;
3274 case Z_APDU_initResponse:
3275 process_initResponse(apdu->u.initResponse);
3277 case Z_APDU_searchResponse:
3278 process_searchResponse(apdu->u.searchResponse);
3280 case Z_APDU_scanResponse:
3281 process_scanResponse(apdu->u.scanResponse);
3283 case Z_APDU_presentResponse:
3284 print_refid (apdu->u.presentResponse->referenceId);
3286 *apdu->u.presentResponse->numberOfRecordsReturned;
3287 if (apdu->u.presentResponse->records)
3288 display_records(apdu->u.presentResponse->records);
3290 printf("No records.\n");
3291 printf ("nextResultSetPosition = %d\n",
3292 *apdu->u.presentResponse->nextResultSetPosition);
3294 case Z_APDU_sortResponse:
3295 process_sortResponse(apdu->u.sortResponse);
3297 case Z_APDU_extendedServicesResponse:
3298 printf("Got extended services response\n");
3299 process_ESResponse(apdu->u.extendedServicesResponse);
3302 printf("Target has closed the association.\n");
3303 process_close(apdu->u.close);
3305 case Z_APDU_resourceControlRequest:
3306 process_resourceControlRequest
3307 (apdu->u.resourceControlRequest);
3309 case Z_APDU_deleteResultSetResponse:
3310 process_deleteResultSetResponse(apdu->u.
3311 deleteResultSetResponse);
3314 printf("Received unknown APDU type (%d).\n",
3320 else if (gdu->which == Z_GDU_HTTP_Response)
3322 http_response(gdu->u.HTTP_Response);
3325 if (conn && !cs_more(conn))
3330 #if HAVE_GETTIMEOFDAY
3331 gettimeofday (&tv_end, 0);
3333 printf ("S/U S/U=%ld/%ld %ld/%ld",
3334 (long) tv_start.tv_sec,
3335 (long) tv_start.tv_usec,
3336 (long) tv_end.tv_sec,
3337 (long) tv_end.tv_usec);
3339 printf ("Elapsed: %.6f\n",
3340 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3341 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3348 int cmd_cclparse(const char* arg)
3351 struct ccl_rpn_node *rpn=NULL;
3354 rpn = ccl_find_str (bibset, arg, &error, &pos);
3357 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3358 printf ("%s\n", ccl_err_msg (error));
3364 ccl_pr_tree(rpn, stdout);
3368 ccl_rpn_delete(rpn);
3376 int cmd_set_otherinfo(const char* args)
3378 char oid[101], otherinfoString[101];
3383 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3385 /* reset this otherinfo */
3386 if(otherinfoNo>=maxOtherInfosSupported) {
3387 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3389 extraOtherInfos[otherinfoNo].oidval = -1;
3390 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3394 printf("Error in set_otherinfo command \n");
3398 if(otherinfoNo>=maxOtherInfosSupported) {
3399 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3403 oidval = oid_getvalbyname (oid);
3405 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3408 extraOtherInfos[otherinfoNo].oidval = oidval;
3409 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3410 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3415 int cmd_list_otherinfo(const char* args)
3419 if(strlen(args)>0) {
3421 if( i >= maxOtherInfosSupported ) {
3422 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3426 if(extraOtherInfos[i].oidval != -1)
3427 printf(" otherinfo %d %s %s\n",
3429 yaz_z3950_oid_value_to_str(
3430 (enum oid_value) extraOtherInfos[i].oidval,
3432 extraOtherInfos[i].value);
3435 for(i=0; i<maxOtherInfosSupported; ++i) {
3436 if(extraOtherInfos[i].oidval != -1)
3437 printf(" otherinfo %d %s %s\n",
3439 yaz_z3950_oid_value_to_str(
3440 (enum oid_value) extraOtherInfos[i].oidval,
3442 extraOtherInfos[i].value);
3450 int cmd_list_all(const char* args) {
3453 /* connection options */
3455 printf("Connected to : %s\n",last_open_command);
3457 if(last_open_command)
3458 printf("Not connected to : %s\n",last_open_command);
3460 printf("Not connected : \n");
3463 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3465 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3468 printf("Authentication : none\n");
3470 switch(auth->which) {
3471 case Z_IdAuthentication_idPass:
3472 printf("Authentication : IdPass\n");
3473 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3474 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3475 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3477 case Z_IdAuthentication_open:
3478 printf("Authentication : psOpen\n");
3479 printf(" Open string : %s\n",auth->u.open);
3482 printf("Authentication : Unknown\n");
3485 if (negotiationCharset)
3486 printf("Neg. Character set : `%s'\n", negotiationCharset);
3490 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3494 printf("CCL file : %s\n",ccl_fields);
3495 printf("CQL file : %s\n",cql_fields);
3496 printf("Query type : %s\n",query_type_as_string(queryType));
3498 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3500 /* piggy back options */
3501 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3503 /* print present related options */
3504 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3505 printf("Schema : %s\n",schema);
3506 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3508 /* loging options */
3509 printf("APDU log : %s\n",apdu_file?"on":"off");
3510 printf("Record log : %s\n",marc_file?"on":"off");
3513 printf("Other Info: \n");
3514 cmd_list_otherinfo("");
3519 int cmd_clear_otherinfo(const char* args)
3521 if(strlen(args)>0) {
3523 otherinfoNo = atoi(args);
3524 if( otherinfoNo >= maxOtherInfosSupported ) {
3525 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3529 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3530 /* only clear if set. */
3531 extraOtherInfos[otherinfoNo].oidval=-1;
3532 free(extraOtherInfos[otherinfoNo].value);
3537 for(i=0; i<maxOtherInfosSupported; ++i) {
3538 if (extraOtherInfos[i].oidval!=-1 ) {
3539 extraOtherInfos[i].oidval=-1;
3540 free(extraOtherInfos[i].value);
3547 static int cmd_help (const char *line);
3549 typedef char *(*completerFunctionType)(const char *text, int state);
3553 int (*fun)(const char *arg);
3555 completerFunctionType rl_completerfunction;
3556 int complete_filenames;
3557 char **local_tabcompletes;
3559 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3560 {"quit", cmd_quit, "",NULL,0,NULL},
3561 {"find", cmd_find, "<query>",NULL,0,NULL},
3562 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3563 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3564 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3565 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3566 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3567 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3568 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3569 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3570 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3571 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3572 {"status", cmd_status, "",NULL,0,NULL},
3573 {"setnames", cmd_setnames, "",NULL,0,NULL},
3574 {"cancel", cmd_cancel, "",NULL,0,NULL},
3575 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3576 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3577 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3578 {"close", cmd_close, "",NULL,0,NULL},
3579 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3580 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3581 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3582 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3583 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3584 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3585 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3586 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3587 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3588 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3589 {".", cmd_source, "<filename>",NULL,1,NULL},
3590 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3591 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3592 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3593 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3594 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3595 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3596 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3597 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3598 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3599 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3600 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3601 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3602 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3603 {"list_all",cmd_list_all,"",NULL,0,NULL},
3604 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3605 /* Server Admin Functions */
3606 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3607 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3608 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3609 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3610 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3611 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3612 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3613 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3614 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3615 {"help", cmd_help, "", NULL,0,NULL},
3619 static int cmd_help (const char *line)
3625 sscanf (line, "%20s", topic);
3628 printf("Commands:\n");
3629 for (i = 0; cmd_array[i].cmd; i++)
3630 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3631 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3632 if (strcmp (topic, "find") == 0)
3635 printf (" \"term\" Simple Term\n");
3636 printf (" @attr [attset] type=value op Attribute\n");
3637 printf (" @and opl opr And\n");
3638 printf (" @or opl opr Or\n");
3639 printf (" @not opl opr And-Not\n");
3640 printf (" @set set Result set\n");
3642 printf ("Bib-1 attribute types\n");
3644 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3645 printf ("2=Relation: ");
3646 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3647 printf ("3=Position: ");
3648 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3649 printf ("4=Structure: ");
3650 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3651 printf ("5=Truncation: ");
3652 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3653 printf ("6=Completeness:");
3654 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3659 int cmd_register_tab(const char* arg) {
3661 char command[101], tabargument[101];
3666 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3670 /* locate the amdn in the list */
3671 for (i = 0; cmd_array[i].cmd; i++) {
3672 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3677 if(!cmd_array[i].cmd) {
3678 fprintf(stderr,"Unknown command %s\n",command);
3683 if(!cmd_array[i].local_tabcompletes)
3684 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3688 tabslist = cmd_array[i].local_tabcompletes;
3689 for(;tabslist && *tabslist;tabslist++) {
3693 cmd_array[i].local_tabcompletes = (char **)
3694 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3695 tabslist=cmd_array[i].local_tabcompletes;
3696 tabslist[num_of_tabs]=strdup(tabargument);
3697 tabslist[num_of_tabs+1]=NULL;
3702 void process_cmd_line(char* line)
3705 char word[32], arg[1024];
3707 #if HAVE_GETTIMEOFDAY
3708 gettimeofday (&tv_start, 0);
3711 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3713 strcpy(word, last_cmd);
3718 strcpy(last_cmd, word);
3720 /* removed tailing spaces from the arg command */
3723 char* lastnonspace=NULL;
3731 *(++lastnonspace) = 0;
3734 for (i = 0; cmd_array[i].cmd; i++)
3735 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3737 res = (*cmd_array[i].fun)(arg);
3741 if (!cmd_array[i].cmd) /* dump our help-screen */
3743 printf("Unknown command: %s.\n", word);
3744 printf("use help for list of commands\n");
3745 /* cmd_help (""); */
3749 if(apdu_file) fflush(apdu_file);
3752 wait_and_handle_response();
3761 char *command_generator(const char *text, int state)
3767 for( ; cmd_array[idx].cmd; ++idx) {
3768 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3769 ++idx; /* skip this entry on the next run */
3770 return strdup(cmd_array[idx-1].cmd);
3778 This function only known how to complete on the first word
3780 char ** readline_completer(char *text, int start, int end) {
3781 #if HAVE_READLINE_READLINE_H
3783 completerFunctionType completerToUse;
3786 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3787 char** res=rl_completion_matches(text,
3790 char** res=completion_matches(text,
3791 (CPFunction*)command_generator);
3793 rl_attempted_completion_over = 1;
3796 char arg[1024],word[32];
3798 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3799 rl_attempted_completion_over = 1;
3803 for (i = 0; cmd_array[i].cmd; i++) {
3804 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3809 if(!cmd_array[i].cmd) return NULL;
3811 curret_global_list = cmd_array[i].local_tabcompletes;
3813 completerToUse = cmd_array[i].rl_completerfunction;
3814 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3815 completerToUse = default_completer;
3817 if(completerToUse) {
3818 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3820 rl_completion_matches(text,
3824 completion_matches(text,
3825 (CPFunction*)completerToUse);
3827 if(!cmd_array[i].complete_filenames)
3828 rl_attempted_completion_over = 1;
3831 if(!cmd_array[i].complete_filenames)
3832 rl_attempted_completion_over = 1;
3842 static void client(void)
3848 #if HAVE_GETTIMEOFDAY
3849 gettimeofday (&tv_start, 0);
3854 char *line_in = NULL;
3855 #if HAVE_READLINE_READLINE_H
3858 line_in=readline(C_PROMPT);
3861 #if HAVE_READLINE_HISTORY_H
3863 add_history(line_in);
3865 strncpy(line, line_in, 1023);
3874 if (!fgets(line, 1023, stdin))
3876 if ((end_p = strchr (line, '\n')))
3879 process_cmd_line(line);
3883 static void show_version(void)
3887 yaz_version(vstr, 0);
3888 printf ("YAZ version: %s\n", YAZ_VERSION);
3889 if (strcmp(vstr, YAZ_VERSION))
3890 printf ("YAZ DLL/SO: %s\n", vstr);
3894 int main(int argc, char **argv)
3897 char *open_command = 0;
3898 char *auth_command = 0;
3903 if (!setlocale(LC_CTYPE, ""))
3904 fprintf (stderr, "setlocale failed\n");
3908 codeset = nl_langinfo(CODESET);
3912 outputCharset = xstrdup(codeset);
3914 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vx", argv, argc, &arg)) != -2)
3921 open_command = (char *) xmalloc (strlen(arg)+6);
3922 strcpy (open_command, "open ");
3923 strcat (open_command, arg);
3927 kilobytes = atoi(arg);
3930 if (!(marc_file = fopen (arg, "a")))
3937 outputCharset = xstrdup(arg);
3940 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3941 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3944 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
3945 cql_fields[sizeof(cql_fields)-1] = '\0';
3948 if (!strcmp(arg, "-"))
3951 ber_file=fopen(arg, "a");
3954 if (!strcmp(arg, "-"))
3957 apdu_file=fopen(arg, "a");
3963 yazProxy=strdup(arg);
3968 auth_command = (char *) xmalloc (strlen(arg)+6);
3969 strcpy (auth_command, "auth ");
3970 strcat (auth_command, arg);
3974 yaz_log_init(yaz_log_mask_str(arg), "", 0);
3980 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3981 "[-b berdump] [-c cclfields] \n"
3982 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
3983 "[-k size] [-V] [<server-addr>]\n",
3991 #ifdef HAVE_GETTIMEOFDAY
3992 gettimeofday (&tv_start, 0);
3994 process_cmd_line (auth_command);
3995 #if HAVE_READLINE_HISTORY_H
3996 add_history(auth_command);
3998 xfree(auth_command);
4002 #ifdef HAVE_GETTIMEOFDAY
4003 gettimeofday (&tv_start, 0);
4005 process_cmd_line (open_command);
4006 #if HAVE_READLINE_HISTORY_H
4007 add_history(open_command);
4009 xfree(open_command);
4020 * vim600: sw=4 ts=8 fdm=marker
4021 * vim<600: sw=4 ts=8