2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.207 2003-09-02 12:12:12 adam 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 if (outputCharset && negotiationCharset) {
409 odr_set_charset (out, charset, outputCharset);
410 odr_set_charset (in, outputCharset, charset);
413 odr_set_charset (out, 0, 0);
414 odr_set_charset (in, 0, 0);
417 printf("Accepted character set : %s\n", charset);
418 printf("Accepted code language : %s\n", lang ? lang : "none");
419 printf("Accepted records in ...: %d\n", selected );
426 static int set_base(const char *arg)
431 for (i = 0; i<num_databaseNames; i++)
432 xfree (databaseNames[i]);
433 num_databaseNames = 0;
437 if (!(cp = strchr(arg, ' ')))
438 cp = arg + strlen(arg);
441 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
442 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
443 databaseNames[num_databaseNames][cp - arg] = '\0';
445 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
454 if (num_databaseNames == 0)
456 num_databaseNames = 1;
457 databaseNames[0] = xstrdup("");
462 static int cmd_base(const char *arg)
466 printf("Usage: base <database> <database> ...\n");
469 return set_base(arg);
472 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
474 if(last_open_command != arg)
476 if(last_open_command) xfree(last_open_command);
477 last_open_command = xstrdup(new_open_command);
481 int session_connect(const char *arg)
484 char type_and_host[101];
485 const char *basep = 0;
492 nmem_destroy (session_mem);
496 cs_get_host_args(arg, &basep);
498 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
499 type_and_host[sizeof(type_and_host)-1] = '\0';
501 cmd_open_remember_last_open_command(arg,type_and_host);
504 conn = cs_create_host(yazProxy, 1, &add);
506 conn = cs_create_host(arg, 1, &add);
509 printf ("Couldn't create comstack\n");
514 if (conn->protocol == PROTO_HTTP)
516 printf ("SRW/HTTP not enabled in this YAZ\n");
522 protocol = conn->protocol;
523 if (conn->protocol == PROTO_HTTP)
527 printf("Connecting...");
529 if (cs_connect(conn, add) < 0)
531 printf ("error = %s\n", cs_strerror(conn));
532 if (conn->cerrno == CSYSERR)
535 yaz_strerror(msg, sizeof(msg));
536 printf ("%s\n", msg);
545 if (protocol == PROTO_Z3950)
547 send_initRequest(type_and_host);
553 int cmd_open(const char *arg)
555 static char cur_host[200];
558 strncpy (cur_host, arg, sizeof(cur_host)-1);
559 cur_host[sizeof(cur_host)-1] = 0;
561 return session_connect(cur_host);
568 if(!( auto_reconnect && last_open_command) ) return ;
570 open_command = (char *) xmalloc (strlen(last_open_command)+6);
571 strcpy (open_command, "open ");
573 strcat (open_command, last_open_command);
575 process_cmd_line(open_command);
580 int cmd_authentication(const char *arg)
582 static Z_IdAuthentication au;
583 static char user[40], group[40], pass[40];
584 static Z_IdPass idPass;
589 printf("Auth field set to null\n");
593 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
596 printf("Authentication set to null\n");
602 if (!strcmp(user, "-")) {
603 au.which = Z_IdAuthentication_anonymous;
604 printf("Authentication set to Anonymous\n");
606 au.which = Z_IdAuthentication_open;
608 printf("Authentication set to Open (%s)\n", user);
614 au.which = Z_IdAuthentication_idPass;
615 au.u.idPass = &idPass;
616 idPass.groupId = NULL;
617 idPass.userId = user;
618 idPass.password = group;
619 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
624 au.which = Z_IdAuthentication_idPass;
625 au.u.idPass = &idPass;
626 idPass.groupId = group;
627 idPass.userId = user;
628 idPass.password = pass;
629 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
635 /* SEARCH SERVICE ------------------------------ */
636 static void display_record(Z_External *r);
638 static void print_record(const unsigned char *buf, size_t len)
641 print_stringn (buf, len);
642 /* add newline if not already added ... */
643 if (i <= 0 || buf[i-1] != '\n')
647 static void display_record(Z_External *r)
649 oident *ent = oid_getentbyoid(r->direct_reference);
653 * Tell the user what we got.
655 if (r->direct_reference)
657 printf("Record type: ");
659 printf("%s\n", ent->desc);
660 else if (!odr_oid(print, &r->direct_reference, 0, 0))
662 odr_perror(print, "print oid");
666 /* Check if this is a known, ASN.1 type tucked away in an octet string */
667 if (ent && r->which == Z_External_octet)
669 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
675 * Call the given decoder to process the record.
677 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
678 r->u.octet_aligned->len, 0);
679 if (!(*type->fun)(in, (char **)&rr, 0, 0))
681 odr_perror(in, "Decoding constructed record.");
682 fprintf(stdout, "[Near %d]\n", odr_offset(in));
683 fprintf(stdout, "Packet dump:\n---------\n");
684 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
685 r->u.octet_aligned->len);
686 fprintf(stdout, "---------\n");
688 /* note just ignores the error ant print the bytes form the octet_aligned later */
691 * Note: we throw away the original, BER-encoded record here.
692 * Do something else with it if you want to keep it.
694 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
695 r->which = type->what;
699 if (ent && ent->oclass != CLASS_RECSYN)
701 if (ent && ent->value == VAL_SOIF)
702 print_record((const unsigned char *) r->u.octet_aligned->buf,
703 r->u.octet_aligned->len);
704 else if (r->which == Z_External_octet)
706 const char *octet_buf = (char*)r->u.octet_aligned->buf;
707 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
708 ent->value == VAL_HTML)
710 print_record((const unsigned char *) octet_buf,
711 r->u.octet_aligned->len);
713 else if (ent->value == VAL_POSTSCRIPT)
715 int size = r->u.octet_aligned->len;
718 print_record((const unsigned char *) octet_buf, size);
723 #if AVOID_MARC_DECODE
724 /* primitive check for a marc OID 5.1-29 except 16 */
725 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
726 ent->oidsuffix[1] != 16
735 yaz_marc_t mt = yaz_marc_create();
737 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
741 if (marcCharset && !strcmp(marcCharset, "auto"))
743 if (ent->value == VAL_USMARC)
745 if (octet_buf[9] == 'a')
753 else if (marcCharset)
755 if (outputCharset && from)
757 cd = yaz_iconv_open(outputCharset, from);
758 printf ("convert from %s to %s", from,
761 printf (" unsupported\n");
766 fwrite (result, 1, rlen, stdout);
770 size_t inbytesleft = rlen;
771 const char *inp = result;
775 size_t outbytesleft = sizeof(outbuf);
779 r = yaz_iconv (cd, (char**) &inp,
781 &outp, &outbytesleft);
782 if (r == (size_t) (-1))
784 int e = yaz_iconv_error(cd);
785 if (e != YAZ_ICONV_E2BIG)
788 fwrite (outbuf, outp - outbuf, 1, stdout);
794 printf ("bad MARC. Dumping as it is:\n");
795 print_record((const unsigned char*) octet_buf,
796 r->u.octet_aligned->len);
798 yaz_marc_destroy(mt);
804 print_record((const unsigned char*) octet_buf,
805 r->u.octet_aligned->len);
809 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
811 else if (ent && ent->value == VAL_SUTRS)
813 if (r->which != Z_External_sutrs)
815 printf("Expecting single SUTRS type for SUTRS.\n");
818 print_record(r->u.sutrs->buf, r->u.sutrs->len);
820 else if (ent && ent->value == VAL_GRS1)
823 if (r->which != Z_External_grs1)
825 printf("Expecting single GRS type for GRS.\n");
829 yaz_display_grs1(w, r->u.grs1, 0);
833 else if ( /* OPAC display not complete yet .. */
834 ent && ent->value == VAL_OPAC)
837 if (r->u.opac->bibliographicRecord)
838 display_record(r->u.opac->bibliographicRecord);
839 for (i = 0; i<r->u.opac->num_holdingsData; i++)
841 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
842 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
844 printf ("MARC holdings %d\n", i);
845 display_record(h->u.marcHoldingsRecord);
847 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
851 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
853 printf ("Data holdings %d\n", i);
854 if (data->typeOfRecord)
855 printf ("typeOfRecord: %s\n", data->typeOfRecord);
856 if (data->encodingLevel)
857 printf ("encodingLevel: %s\n", data->encodingLevel);
858 if (data->receiptAcqStatus)
859 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
860 if (data->generalRetention)
861 printf ("generalRetention: %s\n", data->generalRetention);
862 if (data->completeness)
863 printf ("completeness: %s\n", data->completeness);
864 if (data->dateOfReport)
865 printf ("dateOfReport: %s\n", data->dateOfReport);
867 printf ("nucCode: %s\n", data->nucCode);
868 if (data->localLocation)
869 printf ("localLocation: %s\n", data->localLocation);
870 if (data->shelvingLocation)
871 printf ("shelvingLocation: %s\n", data->shelvingLocation);
872 if (data->callNumber)
873 printf ("callNumber: %s\n", data->callNumber);
874 if (data->copyNumber)
875 printf ("copyNumber: %s\n", data->copyNumber);
876 if (data->publicNote)
877 printf ("publicNote: %s\n", data->publicNote);
878 if (data->reproductionNote)
879 printf ("reproductionNote: %s\n", data->reproductionNote);
880 if (data->termsUseRepro)
881 printf ("termsUseRepro: %s\n", data->termsUseRepro);
882 if (data->enumAndChron)
883 printf ("enumAndChron: %s\n", data->enumAndChron);
884 for (j = 0; j<data->num_volumes; j++)
886 printf ("volume %d\n", j);
887 if (data->volumes[j]->enumeration)
888 printf (" enumeration: %s\n",
889 data->volumes[j]->enumeration);
890 if (data->volumes[j]->chronology)
891 printf (" chronology: %s\n",
892 data->volumes[j]->chronology);
893 if (data->volumes[j]->enumAndChron)
894 printf (" enumAndChron: %s\n",
895 data->volumes[j]->enumAndChron);
897 for (j = 0; j<data->num_circulationData; j++)
899 printf ("circulation %d\n", j);
900 if (data->circulationData[j]->availableNow)
901 printf (" availableNow: %d\n",
902 *data->circulationData[j]->availableNow);
903 if (data->circulationData[j]->availablityDate)
904 printf (" availabiltyDate: %s\n",
905 data->circulationData[j]->availablityDate);
906 if (data->circulationData[j]->availableThru)
907 printf (" availableThru: %s\n",
908 data->circulationData[j]->availableThru);
909 if (data->circulationData[j]->restrictions)
910 printf (" restrictions: %s\n",
911 data->circulationData[j]->restrictions);
912 if (data->circulationData[j]->itemId)
913 printf (" itemId: %s\n",
914 data->circulationData[j]->itemId);
915 if (data->circulationData[j]->renewable)
916 printf (" renewable: %d\n",
917 *data->circulationData[j]->renewable);
918 if (data->circulationData[j]->onHold)
919 printf (" onHold: %d\n",
920 *data->circulationData[j]->onHold);
921 if (data->circulationData[j]->enumAndChron)
922 printf (" enumAndChron: %s\n",
923 data->circulationData[j]->enumAndChron);
924 if (data->circulationData[j]->midspine)
925 printf (" midspine: %s\n",
926 data->circulationData[j]->midspine);
927 if (data->circulationData[j]->temporaryLocation)
928 printf (" temporaryLocation: %s\n",
929 data->circulationData[j]->temporaryLocation);
936 printf("Unknown record representation.\n");
937 if (!z_External(print, &r, 0, 0))
939 odr_perror(print, "Printing external");
945 static void display_diagrecs(Z_DiagRec **pp, int num)
949 Z_DefaultDiagFormat *r;
951 printf("Diagnostic message(s) from database:\n");
952 for (i = 0; i<num; i++)
954 Z_DiagRec *p = pp[i];
955 if (p->which != Z_DiagRec_defaultFormat)
957 printf("Diagnostic record not in default format.\n");
961 r = p->u.defaultFormat;
962 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
963 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
964 printf("Missing or unknown diagset\n");
965 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
968 case Z_DefaultDiagFormat_v2Addinfo:
969 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
971 case Z_DefaultDiagFormat_v3Addinfo:
972 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
979 static void display_nameplusrecord(Z_NamePlusRecord *p)
982 printf("[%s]", p->databaseName);
983 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
984 display_diagrecs(&p->u.surrogateDiagnostic, 1);
985 else if (p->which == Z_NamePlusRecord_databaseRecord)
986 display_record(p->u.databaseRecord);
989 static void display_records(Z_Records *p)
993 if (p->which == Z_Records_NSD)
995 Z_DiagRec dr, *dr_p = &dr;
996 dr.which = Z_DiagRec_defaultFormat;
997 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
998 display_diagrecs (&dr_p, 1);
1000 else if (p->which == Z_Records_multipleNSD)
1001 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1002 p->u.multipleNonSurDiagnostics->num_diagRecs);
1005 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1006 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1007 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1011 static int send_deleteResultSetRequest(const char *arg)
1016 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1017 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1019 req->referenceId = set_refid (out);
1021 req->num_resultSetList =
1022 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1023 names[0], names[1], names[2], names[3],
1024 names[4], names[5], names[6], names[7]);
1026 req->deleteFunction = (int *)
1027 odr_malloc (out, sizeof(*req->deleteFunction));
1028 if (req->num_resultSetList > 0)
1030 *req->deleteFunction = Z_DeleteRequest_list;
1031 req->resultSetList = (char **)
1032 odr_malloc (out, sizeof(*req->resultSetList)*
1033 req->num_resultSetList);
1034 for (i = 0; i<req->num_resultSetList; i++)
1035 req->resultSetList[i] = names[i];
1039 *req->deleteFunction = Z_DeleteRequest_all;
1040 req->resultSetList = 0;
1044 printf("Sent deleteResultSetRequest.\n");
1049 static int send_srw(Z_SRW_PDU *sr)
1051 const char *charset = negotiationCharset;
1052 const char *host_port = 0;
1055 Z_SOAP_Handler h[2] = {
1056 {"http://www.loc.gov/zing/srw/v1.0/", 0, (Z_SOAP_fun) yaz_srw_codec},
1059 ODR o = odr_createmem(ODR_ENCODE);
1061 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1064 path = odr_malloc(out, strlen(databaseNames[0])+2);
1066 strcpy(path+1, databaseNames[0]);
1068 gdu = z_get_HTTP_Request(out);
1069 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1073 const char *cp0 = strstr(host_port, "://");
1074 const char *cp1 = 0;
1080 cp1 = strchr(cp0, '/');
1082 cp1 = cp0+strlen(cp0);
1086 char *h = odr_malloc(out, cp1 - cp0 + 1);
1087 memcpy (h, cp0, cp1 - cp0);
1089 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1094 strcpy(ctype, "text/xml");
1095 if (charset && strlen(charset) < 20)
1097 strcat(ctype, "; charset=");
1098 strcat(ctype, charset);
1100 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1101 "Content-Type", ctype);
1102 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1103 "SOAPAction", "\"\"");
1104 p->which = Z_SOAP_generic;
1105 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1106 p->u.generic->no = 0;
1107 p->u.generic->ns = 0;
1108 p->u.generic->p = sr;
1109 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1111 ret = z_soap_codec_enc(o, &p,
1112 &gdu->u.HTTP_Request->content_buf,
1113 &gdu->u.HTTP_Request->content_len, h,
1116 if (z_GDU(out, &gdu, 0, 0))
1122 buf_out = odr_getbuf(out, &len_out, 0);
1124 /* we don't odr_reset(out), since we may need the buffer again */
1126 r = cs_put(conn, buf_out, len_out);
1138 static int send_SRW_searchRequest(const char *arg)
1144 assert(srw_sr_odr_out == 0);
1145 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1147 odr_reset(srw_sr_odr_out);
1151 /* save this for later .. when fetching individual records */
1152 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1153 sr->u.request->query_type = Z_SRW_query_type_cql;
1154 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1156 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1157 sr->u.request->query_type = Z_SRW_query_type_cql;
1158 sr->u.request->query.cql = odr_strdup(out, arg);
1160 sr->u.request->recordSchema = schema;
1161 return send_srw(sr);
1165 static int send_searchRequest(const char *arg)
1167 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1168 Z_SearchRequest *req = apdu->u.searchRequest;
1171 struct ccl_rpn_node *rpn = NULL;
1173 char setstring[100];
1174 Z_RPNQuery *RPNquery;
1176 YAZ_PQF_Parser pqf_parser;
1178 QueryType myQueryType = queryType;
1181 if (myQueryType == QueryType_CCL2RPN)
1183 rpn = ccl_find_str(bibset, arg, &error, &pos);
1186 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1189 } else if (myQueryType == QueryType_CQL2RPN) {
1190 /* ### All this code should be wrapped in a utility function */
1192 struct cql_node *node;
1193 const char *addinfo;
1194 if (cqltrans == 0) {
1195 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1198 parser = cql_parser_create();
1199 if ((error = cql_parser_string(parser, arg)) != 0) {
1200 printf("Can't parse CQL: must be a syntax error\n");
1203 node = cql_parser_result(parser);
1204 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1205 sizeof pqfbuf)) != 0) {
1206 error = cql_transform_error(cqltrans, &addinfo);
1207 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1208 cql_strerror(error), addinfo);
1212 myQueryType = QueryType_Prefix;
1215 req->referenceId = set_refid (out);
1216 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1218 static unsigned char big[2100];
1219 static Odr_oct bigo;
1221 /* send a very big referenceid to test transport stack etc. */
1222 memset(big, 'A', 2100);
1223 bigo.len = bigo.size = 2100;
1225 req->referenceId = &bigo;
1230 sprintf(setstring, "%d", ++setnumber);
1231 req->resultSetName = setstring;
1233 *req->smallSetUpperBound = smallSetUpperBound;
1234 *req->largeSetLowerBound = largeSetLowerBound;
1235 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1236 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1237 mediumSetPresentNumber > 0))
1241 prefsyn.proto = protocol;
1242 prefsyn.oclass = CLASS_RECSYN;
1243 prefsyn.value = recordsyntax;
1244 req->preferredRecordSyntax =
1245 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1246 req->smallSetElementSetNames =
1247 req->mediumSetElementSetNames = elementSetNames;
1249 req->num_databaseNames = num_databaseNames;
1250 req->databaseNames = databaseNames;
1252 req->query = &query;
1254 switch (myQueryType)
1256 case QueryType_Prefix:
1257 query.which = Z_Query_type_1;
1258 pqf_parser = yaz_pqf_create ();
1259 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1262 const char *pqf_msg;
1264 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1265 printf("%*s^\n", off+4, "");
1266 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1268 yaz_pqf_destroy (pqf_parser);
1271 yaz_pqf_destroy (pqf_parser);
1272 query.u.type_1 = RPNquery;
1275 query.which = Z_Query_type_2;
1276 query.u.type_2 = &ccl_query;
1277 ccl_query.buf = (unsigned char*) arg;
1278 ccl_query.len = strlen(arg);
1280 case QueryType_CCL2RPN:
1281 query.which = Z_Query_type_1;
1282 RPNquery = ccl_rpn_query(out, rpn);
1285 printf ("Couldn't convert from CCL to RPN\n");
1288 query.u.type_1 = RPNquery;
1289 ccl_rpn_delete (rpn);
1292 query.which = Z_Query_type_104;
1293 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1294 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1295 ext->indirect_reference = 0;
1296 ext->descriptor = 0;
1297 ext->which = Z_External_CQL;
1298 ext->u.cql = odr_strdup(out, arg);
1299 query.u.type_104 = ext;
1302 printf ("Unsupported query type\n");
1305 if (send_apdu(apdu))
1306 printf("Sent searchRequest.\n");
1311 /* display Query Expression as part of searchResult-1 */
1312 static void display_queryExpression (Z_QueryExpression *qe)
1316 if (qe->which == Z_QueryExpression_term)
1318 if (qe->u.term->queryTerm)
1320 Z_Term *term = qe->u.term->queryTerm;
1321 switch (term->which)
1323 case Z_Term_general:
1324 printf (" %.*s", term->u.general->len, term->u.general->buf);
1326 case Z_Term_characterString:
1327 printf (" %s", term->u.characterString);
1329 case Z_Term_numeric:
1330 printf (" %d", *term->u.numeric);
1340 /* see if we can find USR:SearchResult-1 */
1341 static void display_searchResult (Z_OtherInformation *o)
1346 for (i = 0; i < o->num_elements; i++)
1348 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1350 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1352 if (ext->which == Z_External_searchResult1)
1355 Z_SearchInfoReport *sr = ext->u.searchResult1;
1356 printf ("SearchResult-1:");
1357 for (j = 0; j < sr->num; j++)
1359 if (!sr->elements[j]->subqueryExpression)
1361 display_queryExpression (
1362 sr->elements[j]->subqueryExpression);
1363 display_queryExpression (
1364 sr->elements[j]->subqueryInterpretation);
1365 display_queryExpression (
1366 sr->elements[j]->subqueryRecommendation);
1367 if (sr->elements[j]->subqueryCount)
1368 printf ("(%d)", *sr->elements[j]->subqueryCount);
1376 static int process_searchResponse(Z_SearchResponse *res)
1378 printf ("Received SearchResponse.\n");
1379 print_refid (res->referenceId);
1380 if (*res->searchStatus)
1381 printf("Search was a success.\n");
1383 printf("Search was a bloomin' failure.\n");
1384 printf("Number of hits: %d", *res->resultCount);
1386 printf (", setno %d", setnumber);
1388 display_searchResult (res->additionalSearchInfo);
1389 printf("records returned: %d\n",
1390 *res->numberOfRecordsReturned);
1391 setno += *res->numberOfRecordsReturned;
1393 display_records(res->records);
1397 static void print_level(int iLevel)
1400 for (i = 0; i < iLevel * 4; i++)
1404 static void print_int(int iLevel, const char *pTag, int *pInt)
1408 print_level(iLevel);
1409 printf("%s: %d\n", pTag, *pInt);
1413 static void print_string(int iLevel, const char *pTag, const char *pString)
1415 if (pString != NULL)
1417 print_level(iLevel);
1418 printf("%s: %s\n", pTag, pString);
1422 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1428 print_level(iLevel);
1429 printf("%s:", pTag);
1430 for (; *pInt != -1; pInt++)
1431 printf(" %d", *pInt);
1436 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1438 if (referenceId != NULL)
1442 print_level(iLevel);
1443 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1444 for (i = 0; i < referenceId->len; i++)
1445 printf("%c", referenceId->buf[i]);
1450 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1452 if (pStringNumeric != NULL)
1454 switch (pStringNumeric->which)
1456 case Z_StringOrNumeric_string:
1457 print_string(iLevel, pTag, pStringNumeric->u.string);
1460 case Z_StringOrNumeric_numeric:
1461 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1465 print_level(iLevel);
1466 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1472 static void print_universe_report_duplicate(
1474 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1476 if (pUniverseReportDuplicate != NULL)
1478 print_level(iLevel);
1479 printf("Universe Report Duplicate: \n");
1481 print_string_or_numeric(iLevel, "Hit No",
1482 pUniverseReportDuplicate->hitno);
1486 static void print_universe_report_hits(
1488 Z_UniverseReportHits *pUniverseReportHits)
1490 if (pUniverseReportHits != NULL)
1492 print_level(iLevel);
1493 printf("Universe Report Hits: \n");
1495 print_string_or_numeric(iLevel, "Database",
1496 pUniverseReportHits->database);
1497 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1501 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1503 if (pUniverseReport != NULL)
1505 print_level(iLevel);
1506 printf("Universe Report: \n");
1508 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1509 switch (pUniverseReport->which)
1511 case Z_UniverseReport_databaseHits:
1512 print_universe_report_hits(iLevel,
1513 pUniverseReport->u.databaseHits);
1516 case Z_UniverseReport_duplicate:
1517 print_universe_report_duplicate(iLevel,
1518 pUniverseReport->u.duplicate);
1522 print_level(iLevel);
1523 printf("Type: %d\n", pUniverseReport->which);
1529 static void print_external(int iLevel, Z_External *pExternal)
1531 if (pExternal != NULL)
1533 print_level(iLevel);
1534 printf("External: \n");
1536 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1537 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1538 print_string(iLevel, "Descriptor", pExternal->descriptor);
1539 switch (pExternal->which)
1541 case Z_External_universeReport:
1542 print_universe_report(iLevel, pExternal->u.universeReport);
1546 print_level(iLevel);
1547 printf("Type: %d\n", pExternal->which);
1553 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1555 printf ("Received ResourceControlRequest.\n");
1556 print_referenceId(1, req->referenceId);
1557 print_int(1, "Suspended Flag", req->suspendedFlag);
1558 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1559 print_int(1, "Response Required", req->responseRequired);
1560 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1561 print_external(1, req->resourceReport);
1565 void process_ESResponse(Z_ExtendedServicesResponse *res)
1568 switch (*res->operationStatus)
1570 case Z_ExtendedServicesResponse_done:
1573 case Z_ExtendedServicesResponse_accepted:
1574 printf ("accepted\n");
1576 case Z_ExtendedServicesResponse_failure:
1577 printf ("failure\n");
1578 display_diagrecs(res->diagnostics, res->num_diagnostics);
1581 printf ("unknown\n");
1583 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1584 (res->num_diagnostics != 0) ) {
1585 display_diagrecs(res->diagnostics, res->num_diagnostics);
1587 print_refid (res->referenceId);
1588 if (res->taskPackage &&
1589 res->taskPackage->which == Z_External_extendedService)
1591 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1592 Odr_oct *id = taskPackage->targetReference;
1593 Z_External *ext = taskPackage->taskSpecificParameters;
1597 printf ("Target Reference: ");
1598 print_stringn (id->buf, id->len);
1601 if (ext->which == Z_External_update)
1603 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1604 if (utp && utp->targetPart)
1606 Z_IUTargetPart *targetPart = utp->targetPart;
1609 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1612 Z_IUTaskPackageRecordStructure *tpr =
1613 targetPart->taskPackageRecords[i];
1614 printf ("task package record %d\n", i+1);
1615 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1617 display_record (tpr->u.record);
1621 printf ("other type\n");
1629 const char *get_ill_element (void *clientData, const char *element)
1634 static Z_External *create_external_itemRequest()
1636 struct ill_get_ctl ctl;
1637 ILL_ItemRequest *req;
1639 int item_request_size = 0;
1640 char *item_request_buf = 0;
1644 ctl.f = get_ill_element;
1646 req = ill_get_ItemRequest(&ctl, "ill", 0);
1648 printf ("ill_get_ItemRequest failed\n");
1650 if (!ill_ItemRequest (out, &req, 0, 0))
1654 ill_ItemRequest(print, &req, 0, 0);
1657 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1658 if (item_request_buf)
1659 odr_setbuf (out, item_request_buf, item_request_size, 1);
1660 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1667 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1668 oid.proto = PROTO_GENERAL;
1669 oid.oclass = CLASS_GENERAL;
1670 oid.value = VAL_ISO_ILL_1;
1672 r = (Z_External *) odr_malloc (out, sizeof(*r));
1673 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1674 r->indirect_reference = 0;
1676 r->which = Z_External_single;
1678 r->u.single_ASN1_type = (Odr_oct *)
1679 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1680 r->u.single_ASN1_type->buf = (unsigned char *)
1681 odr_malloc (out, item_request_size);
1682 r->u.single_ASN1_type->len = item_request_size;
1683 r->u.single_ASN1_type->size = item_request_size;
1684 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1687 do_hex_dump(item_request_buf,item_request_size);
1692 static Z_External *create_external_ILL_APDU(int which)
1694 struct ill_get_ctl ctl;
1697 int ill_request_size = 0;
1698 char *ill_request_buf = 0;
1702 ctl.f = get_ill_element;
1704 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1706 if (!ill_APDU (out, &ill_apdu, 0, 0))
1710 printf ("-------------------\n");
1711 ill_APDU(print, &ill_apdu, 0, 0);
1713 printf ("-------------------\n");
1715 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1716 if (ill_request_buf)
1717 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1718 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1724 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1726 oid.proto = PROTO_GENERAL;
1727 oid.oclass = CLASS_GENERAL;
1728 oid.value = VAL_ISO_ILL_1;
1730 r = (Z_External *) odr_malloc (out, sizeof(*r));
1731 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1732 r->indirect_reference = 0;
1734 r->which = Z_External_single;
1736 r->u.single_ASN1_type = (Odr_oct *)
1737 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1738 r->u.single_ASN1_type->buf = (unsigned char *)
1739 odr_malloc (out, ill_request_size);
1740 r->u.single_ASN1_type->len = ill_request_size;
1741 r->u.single_ASN1_type->size = ill_request_size;
1742 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1743 /* printf ("len = %d\n", ill_request_size); */
1744 /* do_hex_dump(ill_request_buf,ill_request_size); */
1745 /* printf("--- end of extenal\n"); */
1752 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1754 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1755 oident ItemOrderRequest;
1757 ItemOrderRequest.proto = PROTO_Z3950;
1758 ItemOrderRequest.oclass = CLASS_EXTSERV;
1759 ItemOrderRequest.value = VAL_ITEMORDER;
1761 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1762 r->indirect_reference = 0;
1765 r->which = Z_External_itemOrder;
1767 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1768 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1769 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1771 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1772 odr_malloc(out,sizeof(Z_IORequest));
1773 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1775 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1776 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1777 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1778 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1779 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1780 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1782 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1783 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1784 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1786 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1787 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1788 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1789 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1791 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1792 (int *) odr_malloc(out, sizeof(int));
1793 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1795 if (!strcmp (type, "item") || !strcmp(type, "2"))
1797 printf ("using item-request\n");
1798 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1799 create_external_itemRequest();
1801 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1803 printf ("using ILL-request\n");
1804 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1805 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1807 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1809 const char *xml_buf =
1811 " <type>request</type>\n"
1812 " <libraryNo>000200</libraryNo>\n"
1813 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1815 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1816 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1819 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1824 static int send_itemorder(const char *type, int itemno)
1826 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1827 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1828 oident ItemOrderRequest;
1830 ItemOrderRequest.proto = PROTO_Z3950;
1831 ItemOrderRequest.oclass = CLASS_EXTSERV;
1832 ItemOrderRequest.value = VAL_ITEMORDER;
1833 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1834 req->packageName = esPackageName;
1836 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1842 static int only_z3950()
1844 if (protocol == PROTO_HTTP)
1846 printf ("Not supported by SRW\n");
1852 static int cmd_update_common(const char *arg, int version);
1854 static int cmd_update(const char *arg)
1856 cmd_update_common(arg, 1);
1859 static int cmd_update0(const char *arg)
1861 cmd_update_common(arg, 0);
1864 static int cmd_update_common(const char *arg, int version)
1866 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1867 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1871 char action[20], recid[20], fname[80];
1873 Z_External *record_this = 0;
1880 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1882 if (!strcmp (action, "insert"))
1883 action_no = Z_IUOriginPartToKeep_recordInsert;
1884 else if (!strcmp (action, "replace"))
1885 action_no = Z_IUOriginPartToKeep_recordReplace;
1886 else if (!strcmp (action, "delete"))
1887 action_no = Z_IUOriginPartToKeep_recordDelete;
1888 else if (!strcmp (action, "update"))
1889 action_no = Z_IUOriginPartToKeep_specialUpdate;
1892 printf ("Bad action: %s\n", action);
1893 printf ("Possible values: insert, replace, delete, update\n");
1901 stat (fname, &status);
1902 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1904 size_t len = status.st_size;
1905 char *buf = (char *) xmalloc (len);
1907 fread (buf, 1, len, inf);
1911 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1917 printf ("File %s doesn't exist\n", fname);
1925 printf ("No last record (update ignored)\n");
1928 record_this = record_last;
1931 update_oid.proto = PROTO_Z3950;
1932 update_oid.oclass = CLASS_EXTSERV;
1934 update_oid.value = VAL_DBUPDATE0;
1936 update_oid.value = VAL_DBUPDATE;
1937 oid_ent_to_oid (&update_oid, oid);
1938 req->packageType = odr_oiddup(out,oid);
1939 req->packageName = esPackageName;
1941 req->referenceId = set_refid (out);
1943 r = req->taskSpecificParameters = (Z_External *)
1944 odr_malloc (out, sizeof(*r));
1945 r->direct_reference = odr_oiddup(out,oid);
1946 r->indirect_reference = 0;
1950 Z_IU0OriginPartToKeep *toKeep;
1951 Z_IU0SuppliedRecords *notToKeep;
1953 r->which = Z_External_update0;
1954 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
1955 r->u.update0->which = Z_IUUpdate_esRequest;
1956 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
1957 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
1958 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
1959 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
1961 toKeep->databaseName = databaseNames[0];
1963 toKeep->elementSetName = 0;
1965 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1966 *toKeep->action = action_no;
1968 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
1969 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
1971 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
1972 odr_malloc(out, sizeof(*notToKeep->elements));
1973 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
1974 odr_malloc(out, sizeof(**notToKeep->elements));
1975 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1978 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1979 odr_malloc (out, sizeof(Odr_oct));
1980 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1981 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1982 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1985 notToKeep->elements[0]->u.opaque = 0;
1986 notToKeep->elements[0]->supplementalId = 0;
1987 notToKeep->elements[0]->correlationInfo = 0;
1988 notToKeep->elements[0]->record = record_this;
1992 Z_IUOriginPartToKeep *toKeep;
1993 Z_IUSuppliedRecords *notToKeep;
1995 r->which = Z_External_update;
1996 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1997 r->u.update->which = Z_IUUpdate_esRequest;
1998 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1999 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2000 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2001 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2003 toKeep->databaseName = databaseNames[0];
2005 toKeep->elementSetName = 0;
2006 toKeep->actionQualifier = 0;
2007 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2008 *toKeep->action = action_no;
2010 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2011 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2013 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2014 odr_malloc(out, sizeof(*notToKeep->elements));
2015 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2016 odr_malloc(out, sizeof(**notToKeep->elements));
2017 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2020 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2021 odr_malloc (out, sizeof(Odr_oct));
2022 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2023 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2024 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2027 notToKeep->elements[0]->u.opaque = 0;
2028 notToKeep->elements[0]->supplementalId = 0;
2029 notToKeep->elements[0]->correlationInfo = 0;
2030 notToKeep->elements[0]->record = record_this;
2038 static int cmd_itemorder(const char *arg)
2045 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2048 printf("Item order request\n");
2050 send_itemorder(type, itemno);
2054 static int cmd_find(const char *arg)
2058 printf("Find what?\n");
2061 if (protocol == PROTO_HTTP)
2066 if (!send_SRW_searchRequest(arg))
2079 printf("Not connected yet\n");
2083 if (!send_searchRequest(arg))
2089 static int cmd_delete(const char *arg)
2093 printf("Not connected yet\n");
2098 if (!send_deleteResultSetRequest(arg))
2103 static int cmd_ssub(const char *arg)
2105 if (!(smallSetUpperBound = atoi(arg)))
2110 static int cmd_lslb(const char *arg)
2114 if (!(largeSetLowerBound = atoi(arg)))
2119 static int cmd_mspn(const char *arg)
2123 if (!(mediumSetPresentNumber = atoi(arg)))
2128 static int cmd_status(const char *arg)
2130 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2131 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2132 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2136 static int cmd_setnames(const char *arg)
2138 if (*arg == '1') /* enable ? */
2140 else if (*arg == '0') /* disable ? */
2142 else if (setnumber < 0) /* no args, toggle .. */
2148 printf("Set numbering enabled.\n");
2150 printf("Set numbering disabled.\n");
2154 /* PRESENT SERVICE ----------------------------- */
2156 static void parse_show_args(const char *arg_c, char *setstring,
2157 int *start, int *number)
2162 strncpy(arg, arg_c, sizeof(arg)-1);
2163 arg[sizeof(arg)-1] = '\0';
2165 if ((p = strchr(arg, '+')))
2167 *number = atoi(p + 1);
2172 if (p && (p=strchr(p+1, '+')))
2173 strcpy (setstring, p+1);
2174 else if (setnumber >= 0)
2175 sprintf(setstring, "%d", setnumber);
2180 static int send_presentRequest(const char *arg)
2182 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2183 Z_PresentRequest *req = apdu->u.presentRequest;
2184 Z_RecordComposition compo;
2188 char setstring[100];
2190 req->referenceId = set_refid (out);
2192 parse_show_args(arg, setstring, &setno, &nos);
2194 req->resultSetId = setstring;
2196 req->resultSetStartPoint = &setno;
2197 req->numberOfRecordsRequested = &nos;
2198 prefsyn.proto = protocol;
2199 prefsyn.oclass = CLASS_RECSYN;
2200 prefsyn.value = recordsyntax;
2201 req->preferredRecordSyntax =
2202 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2208 prefschema.proto = protocol;
2209 prefschema.oclass = CLASS_SCHEMA;
2210 prefschema.value = oid_getvalbyname(schema);
2212 req->recordComposition = &compo;
2213 compo.which = Z_RecordComp_complex;
2214 compo.u.complex = (Z_CompSpec *)
2215 odr_malloc(out, sizeof(*compo.u.complex));
2216 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2217 odr_malloc(out, sizeof(bool_t));
2218 *compo.u.complex->selectAlternativeSyntax = 0;
2220 compo.u.complex->generic = (Z_Specification *)
2221 odr_malloc(out, sizeof(*compo.u.complex->generic));
2222 compo.u.complex->generic->which = Z_Schema_oid;
2223 compo.u.complex->generic->schema.oid = (Odr_oid *)
2224 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2225 if (!compo.u.complex->generic->schema.oid)
2227 /* OID wasn't a schema! Try record syntax instead. */
2228 prefschema.oclass = CLASS_RECSYN;
2229 compo.u.complex->generic->schema.oid = (Odr_oid *)
2230 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2232 if (!elementSetNames)
2233 compo.u.complex->generic->elementSpec = 0;
2236 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2237 odr_malloc(out, sizeof(Z_ElementSpec));
2238 compo.u.complex->generic->elementSpec->which =
2239 Z_ElementSpec_elementSetName;
2240 compo.u.complex->generic->elementSpec->u.elementSetName =
2241 elementSetNames->u.generic;
2243 compo.u.complex->num_dbSpecific = 0;
2244 compo.u.complex->dbSpecific = 0;
2245 compo.u.complex->num_recordSyntax = 0;
2246 compo.u.complex->recordSyntax = 0;
2248 else if (elementSetNames)
2250 req->recordComposition = &compo;
2251 compo.which = Z_RecordComp_simple;
2252 compo.u.simple = elementSetNames;
2255 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2260 static int send_SRW_presentRequest(const char *arg)
2262 char setstring[100];
2264 Z_SRW_PDU *sr = srw_sr;
2268 parse_show_args(arg, setstring, &setno, &nos);
2269 sr->u.request->startRecord = odr_intdup(out, setno);
2270 sr->u.request->maximumRecords = odr_intdup(out, nos);
2272 sr->u.request->recordSchema = schema;
2273 return send_srw(sr);
2277 static void close_session (void)
2284 nmem_destroy (session_mem);
2293 void process_close(Z_Close *req)
2295 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2296 Z_Close *res = apdu->u.close;
2298 static char *reasons[] =
2303 "cost limit reached",
2305 "security violation",
2312 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2313 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2318 *res->closeReason = Z_Close_finished;
2320 printf("Sent response.\n");
2325 static int cmd_show(const char *arg)
2327 if (protocol == PROTO_HTTP)
2332 if (!send_SRW_presentRequest(arg))
2342 printf("Not connected yet\n");
2345 if (!send_presentRequest(arg))
2351 int cmd_quit(const char *arg)
2353 printf("See you later, alligator.\n");
2359 int cmd_cancel(const char *arg)
2361 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2362 Z_TriggerResourceControlRequest *req =
2363 apdu->u.triggerResourceControlRequest;
2368 printf("Session not initialized yet\n");
2373 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2375 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2378 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2379 req->resultSetWanted = &rfalse;
2382 printf("Sent cancel request\n");
2386 int send_scanrequest(const char *query, int pp, int num, const char *term)
2388 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2389 Z_ScanRequest *req = apdu->u.scanRequest;
2394 if (queryType == QueryType_CCL2RPN)
2398 struct ccl_rpn_node *rpn;
2400 rpn = ccl_find_str (bibset, query, &error, &pos);
2403 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2406 bib1.proto = PROTO_Z3950;
2407 bib1.oclass = CLASS_ATTSET;
2408 bib1.value = VAL_BIB1;
2409 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2410 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2412 printf("Couldn't convert CCL to Scan term\n");
2415 ccl_rpn_delete (rpn);
2419 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2421 if (!(req->termListAndStartPoint =
2422 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2424 const char *pqf_msg;
2426 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2427 printf("%*s^\n", off+7, "");
2428 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2429 yaz_pqf_destroy (pqf_parser);
2432 yaz_pqf_destroy (pqf_parser);
2436 if (req->termListAndStartPoint->term &&
2437 req->termListAndStartPoint->term->which == Z_Term_general &&
2438 req->termListAndStartPoint->term->u.general)
2440 req->termListAndStartPoint->term->u.general->buf =
2441 (unsigned char *) odr_strdup(out, term);
2442 req->termListAndStartPoint->term->u.general->len =
2443 req->termListAndStartPoint->term->u.general->size =
2447 req->referenceId = set_refid (out);
2448 req->num_databaseNames = num_databaseNames;
2449 req->databaseNames = databaseNames;
2450 req->numberOfTermsRequested = #
2451 req->preferredPositionInResponse = &pp;
2456 int send_sortrequest(const char *arg, int newset)
2458 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2459 Z_SortRequest *req = apdu->u.sortRequest;
2460 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2461 odr_malloc (out, sizeof(*sksl));
2467 sprintf (setstring, "%d", setnumber);
2469 sprintf (setstring, "default");
2471 req->referenceId = set_refid (out);
2473 req->num_inputResultSetNames = 1;
2474 req->inputResultSetNames = (Z_InternationalString **)
2475 odr_malloc (out, sizeof(*req->inputResultSetNames));
2476 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2478 if (newset && setnumber >= 0)
2479 sprintf (setstring, "%d", ++setnumber);
2481 req->sortedResultSetName = odr_strdup (out, setstring);
2483 req->sortSequence = yaz_sort_spec (out, arg);
2484 if (!req->sortSequence)
2486 printf ("Missing sort specifications\n");
2493 void display_term(Z_TermInfo *t)
2495 if (t->term->which == Z_Term_general)
2497 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2498 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2499 t->term->u.general->buf);
2502 printf("Term (not general)");
2503 if (t->globalOccurrences)
2504 printf (" (%d)\n", *t->globalOccurrences);
2509 void process_scanResponse(Z_ScanResponse *res)
2512 Z_Entry **entries = NULL;
2513 int num_entries = 0;
2515 printf("Received ScanResponse\n");
2516 print_refid (res->referenceId);
2517 printf("%d entries", *res->numberOfEntriesReturned);
2518 if (res->positionOfTerm)
2519 printf (", position=%d", *res->positionOfTerm);
2521 if (*res->scanStatus != Z_Scan_success)
2522 printf("Scan returned code %d\n", *res->scanStatus);
2525 if ((entries = res->entries->entries))
2526 num_entries = res->entries->num_entries;
2527 for (i = 0; i < num_entries; i++)
2529 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2530 if (entries[i]->which == Z_Entry_termInfo)
2532 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2533 display_term(entries[i]->u.termInfo);
2536 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2538 if (res->entries->nonsurrogateDiagnostics)
2539 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2540 res->entries->num_nonsurrogateDiagnostics);
2543 void process_sortResponse(Z_SortResponse *res)
2545 printf("Received SortResponse: status=");
2546 switch (*res->sortStatus)
2548 case Z_SortStatus_success:
2549 printf ("success"); break;
2550 case Z_SortStatus_partial_1:
2551 printf ("partial"); break;
2552 case Z_SortStatus_failure:
2553 printf ("failure"); break;
2555 printf ("unknown (%d)", *res->sortStatus);
2558 print_refid (res->referenceId);
2559 if (res->diagnostics)
2560 display_diagrecs(res->diagnostics,
2561 res->num_diagnostics);
2564 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2566 printf("Got deleteResultSetResponse status=%d\n",
2567 *res->deleteOperationStatus);
2568 if (res->deleteListStatuses)
2571 for (i = 0; i < res->deleteListStatuses->num; i++)
2573 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2574 *res->deleteListStatuses->elements[i]->status);
2579 int cmd_sort_generic(const char *arg, int newset)
2583 printf("Session not initialized yet\n");
2588 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2590 printf("Target doesn't support sort\n");
2595 if (send_sortrequest(arg, newset) < 0)
2602 int cmd_sort(const char *arg)
2604 return cmd_sort_generic (arg, 0);
2607 int cmd_sort_newset (const char *arg)
2609 return cmd_sort_generic (arg, 1);
2612 int cmd_scan(const char *arg)
2621 printf("Session not initialized yet\n");
2625 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2627 printf("Target doesn't support scan\n");
2632 strcpy (last_scan_query, arg);
2633 if (send_scanrequest(arg, 1, 20, 0) < 0)
2638 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2644 int cmd_schema(const char *arg)
2649 schema = xstrdup(arg);
2653 int cmd_format(const char *arg)
2658 printf("Usage: format <recordsyntax>\n");
2661 nsyntax = oid_getvalbyname (arg);
2662 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2664 printf ("unknown record syntax\n");
2667 recordsyntax = nsyntax;
2671 int cmd_elements(const char *arg)
2673 static Z_ElementSetNames esn;
2674 static char what[100];
2678 elementSetNames = 0;
2682 esn.which = Z_ElementSetNames_generic;
2683 esn.u.generic = what;
2684 elementSetNames = &esn;
2688 int cmd_attributeset(const char *arg)
2694 printf("Usage: attributeset <setname>\n");
2697 sscanf(arg, "%s", what);
2698 if (p_query_attset (what))
2700 printf("Unknown attribute set name\n");
2706 int cmd_querytype (const char *arg)
2708 if (!strcmp (arg, "ccl"))
2709 queryType = QueryType_CCL;
2710 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2711 queryType = QueryType_Prefix;
2712 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2713 queryType = QueryType_CCL2RPN;
2714 else if (!strcmp(arg, "cql"))
2715 queryType = QueryType_CQL;
2716 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2717 queryType = QueryType_CQL2RPN;
2720 printf ("Querytype must be one of:\n");
2721 printf (" prefix - Prefix query\n");
2722 printf (" ccl - CCL query\n");
2723 printf (" ccl2rpn - CCL query converted to RPN\n");
2724 printf (" cql - CQL\n");
2725 printf (" cql2rpn - CQL query converted to RPN\n");
2731 int cmd_refid (const char *arg)
2737 refid = (char *) xmalloc (strlen(arg)+1);
2738 strcpy (refid, arg);
2743 int cmd_close(const char *arg)
2752 apdu = zget_APDU(out, Z_APDU_close);
2753 req = apdu->u.close;
2754 *req->closeReason = Z_Close_finished;
2756 printf("Sent close request.\n");
2761 int cmd_packagename(const char* arg)
2763 xfree (esPackageName);
2764 esPackageName = NULL;
2766 esPackageName = xstrdup(arg);
2770 int cmd_proxy(const char* arg)
2775 yazProxy = xstrdup (arg);
2779 int cmd_marccharset(const char *arg)
2784 if (sscanf(arg, "%29s", l1) < 1)
2786 xfree (marcCharset);
2788 if (strcmp(l1, "-"))
2789 marcCharset = xstrdup(l1);
2793 int cmd_charset(const char* arg)
2795 char l1[30], l2[30];
2798 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2800 printf("Current negotiation character set is `%s'\n",
2801 negotiationCharset ? negotiationCharset: "none");
2802 printf("Current output character set is `%s'\n",
2803 outputCharset ? outputCharset: "none");
2806 xfree (negotiationCharset);
2807 negotiationCharset = NULL;
2808 if (*l1 && strcmp(l1, "-"))
2810 negotiationCharset = xstrdup(l1);
2811 printf ("Character set negotiation : %s\n", negotiationCharset);
2814 printf ("Character set negotiation disabled\n");
2817 xfree (outputCharset);
2819 if (!strcmp(l2, "auto") && codeset)
2823 printf ("output charset: %s\n", codeset);
2824 outputCharset = xstrdup(codeset);
2829 printf ("No codeset found on this system\n");
2831 else if (strcmp(l2, "-"))
2832 outputCharset = xstrdup(l2);
2834 printf ("Output charset conversion disabled\n");
2840 int cmd_lang(const char* arg)
2843 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2850 yazLang = (char *) xmalloc (strlen(arg)+1);
2851 strcpy (yazLang, arg);
2856 int cmd_source(const char* arg)
2858 /* first should open the file and read one line at a time.. */
2860 char line[1024], *cp;
2863 fprintf(stderr,"Error in source command use a filename\n");
2867 includeFile = fopen (arg, "r");
2870 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2874 while(!feof(includeFile)) {
2875 memset(line,0,sizeof(line));
2876 fgets(line,sizeof(line),includeFile);
2878 if(strlen(line) < 2) continue;
2879 if(line[0] == '#') continue;
2881 if ((cp = strrchr (line, '\n')))
2884 process_cmd_line(line);
2887 if(fclose(includeFile)<0) {
2888 perror("unable to close include file");
2894 int cmd_subshell(const char* args)
2899 system(getenv("SHELL"));
2905 int cmd_set_berfile(const char *arg)
2907 if (ber_file && ber_file != stdout && ber_file != stderr)
2909 if (!strcmp(arg, ""))
2911 else if (!strcmp(arg, "-"))
2914 ber_file = fopen(arg, "a");
2918 int cmd_set_apdufile(const char *arg)
2920 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2922 if (!strcmp(arg, ""))
2924 else if (!strcmp(arg, "-"))
2928 apdu_file = fopen(arg, "a");
2930 perror("unable to open apdu log file");
2933 odr_setprint(print, apdu_file);
2937 int cmd_set_cclfile(const char* arg)
2941 bibset = ccl_qual_mk ();
2942 inf = fopen (arg, "r");
2944 perror("unable to open CCL file");
2947 ccl_qual_file (bibset, inf);
2950 strcpy(ccl_fields,arg);
2954 int cmd_set_cqlfile(const char* arg)
2956 cql_transform_t newcqltrans;
2958 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
2959 perror("unable to open CQL file");
2963 cql_transform_close(cqltrans);
2965 cqltrans = newcqltrans;
2966 strcpy(cql_fields, arg);
2970 int cmd_set_auto_reconnect(const char* arg)
2972 if(strlen(arg)==0) {
2973 auto_reconnect = ! auto_reconnect;
2974 } else if(strcmp(arg,"on")==0) {
2976 } else if(strcmp(arg,"off")==0) {
2979 printf("Error use on or off\n");
2984 printf("Set auto reconnect enabled.\n");
2986 printf("Set auto reconnect disabled.\n");
2991 int cmd_set_marcdump(const char* arg)
2993 if(marc_file && marc_file != stderr) { /* don't close stdout*/
2997 if (!strcmp(arg, ""))
2999 else if (!strcmp(arg, "-"))
3003 marc_file = fopen(arg, "a");
3005 perror("unable to open marc log file");
3011 this command takes 3 arge {name class oid}
3013 int cmd_register_oid(const char* args) {
3018 {"appctx",CLASS_APPCTX},
3019 {"absyn",CLASS_ABSYN},
3020 {"attset",CLASS_ATTSET},
3021 {"transyn",CLASS_TRANSYN},
3022 {"diagset",CLASS_DIAGSET},
3023 {"recsyn",CLASS_RECSYN},
3024 {"resform",CLASS_RESFORM},
3025 {"accform",CLASS_ACCFORM},
3026 {"extserv",CLASS_EXTSERV},
3027 {"userinfo",CLASS_USERINFO},
3028 {"elemspec",CLASS_ELEMSPEC},
3029 {"varset",CLASS_VARSET},
3030 {"schema",CLASS_SCHEMA},
3031 {"tagset",CLASS_TAGSET},
3032 {"general",CLASS_GENERAL},
3033 {0,(enum oid_class) 0}
3035 char oname_str[101], oclass_str[101], oid_str[101];
3038 oid_class oidclass = CLASS_GENERAL;
3039 int val = 0, oid[OID_SIZE];
3040 struct oident * new_oident=NULL;
3042 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3043 oname_str,oclass_str, oid_str) < 1) {
3044 printf("Error in regristrate command \n");
3048 for (i = 0; oid_classes[i].className; i++) {
3049 if (!strcmp(oid_classes[i].className, oclass_str))
3051 oidclass=oid_classes[i].oclass;
3056 if(!(oid_classes[i].className)) {
3057 printf("Unknonwn oid class %s\n",oclass_str);
3065 while (isdigit (*name))
3067 val = val*10 + (*name - '0');
3080 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3081 if(strcmp(new_oident->desc,oname_str)) {
3082 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3088 int cmd_push_command(const char* arg)
3090 #if HAVE_READLINE_HISTORY_H
3094 fprintf(stderr,"Not compiled with the readline/history module\n");
3099 void source_rcfile()
3101 /* Look for a $HOME/.yazclientrc and source it if it exists */
3102 struct stat statbuf;
3104 char* homedir=getenv("HOME");
3106 if(!homedir) return;
3108 sprintf(buffer,"%s/.yazclientrc",homedir);
3110 if(stat(buffer,&statbuf)==0) {
3114 if(stat(".yazclientrc",&statbuf)==0) {
3115 cmd_source(".yazclientrc");
3120 static void initialize(void)
3125 if (!(out = odr_createmem(ODR_ENCODE)) ||
3126 !(in = odr_createmem(ODR_DECODE)) ||
3127 !(print = odr_createmem(ODR_PRINT)))
3129 fprintf(stderr, "failed to allocate ODR streams\n");
3134 setvbuf(stdout, 0, _IONBF, 0);
3136 odr_setprint(print, apdu_file);
3138 bibset = ccl_qual_mk ();
3139 inf = fopen (ccl_fields, "r");
3142 ccl_qual_file (bibset, inf);
3146 cqltrans = cql_transform_open_fname(cql_fields);
3147 /* If this fails, no problem: we detect cqltrans == 0 later */
3149 #if HAVE_READLINE_READLINE_H
3150 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3154 for(i=0; i<maxOtherInfosSupported; ++i) {
3155 extraOtherInfos[i].oidval = -1;
3162 #if HAVE_GETTIMEOFDAY
3163 struct timeval tv_start, tv_end;
3167 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3171 printf ("Received SRW SearchRetrieve Response\n");
3173 for (i = 0; i<res->num_diagnostics; i++)
3175 printf ("SRW diagnostic %d %s\n",
3176 *res->diagnostics[i].code,
3177 yaz_diag_srw_str(*res->diagnostics[i].code));
3179 if (res->diagnostics[i].details)
3180 printf ("Details: %s\n", res->diagnostics[i].details);
3182 if (res->numberOfRecords)
3183 printf ("Number of hits: %d\n", *res->numberOfRecords);
3184 for (i = 0; i<res->num_records; i++)
3186 Z_SRW_record *rec = res->records + i;
3188 if (rec->recordPosition)
3190 printf ("pos=%d", *rec->recordPosition);
3191 setno = *rec->recordPosition + 1;
3193 if (rec->recordSchema)
3194 printf (" schema=%s", rec->recordSchema);
3196 if (rec->recordData_buf && rec->recordData_len)
3198 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3204 static void http_response(Z_HTTP_Response *hres)
3207 const char *content_type = z_HTTP_header_lookup(hres->headers,
3209 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3211 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3213 Z_SOAP *soap_package = 0;
3214 ODR o = odr_createmem(ODR_DECODE);
3215 Z_SOAP_Handler soap_handlers[2] = {
3216 {"http://www.loc.gov/zing/srw/v1.0/", 0,
3217 (Z_SOAP_fun) yaz_srw_codec},
3220 ret = z_soap_codec(o, &soap_package,
3221 &hres->content_buf, &hres->content_len,
3223 if (!ret && soap_package->which == Z_SOAP_generic &&
3224 soap_package->u.generic->no == 0)
3226 Z_SRW_PDU *sr = soap_package->u.generic->p;
3227 if (sr->which == Z_SRW_searchRetrieve_response)
3228 handle_srw_response(sr->u.response);
3232 else if (!ret && (soap_package->which == Z_SOAP_fault
3233 || soap_package->which == Z_SOAP_error))
3235 printf ("HTTP Error Status=%d\n", hres->code);
3236 printf ("SOAP Fault code %s\n",
3237 soap_package->u.fault->fault_code);
3238 printf ("SOAP Fault string %s\n",
3239 soap_package->u.fault->fault_string);
3247 if (hres->code != 200)
3249 printf ("HTTP Error Status=%d\n", hres->code);
3253 printf ("Decoding of SRW package failed\n");
3257 if (!strcmp(hres->version, "1.0"))
3259 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3260 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3265 /* HTTP 1.1: only if no close we stay alive .. */
3266 if (connection_head && !strcmp(connection_head, "close"))
3272 void wait_and_handle_response()
3274 int reconnect_ok = 1;
3277 int netbufferlen = 0;
3282 res = cs_get(conn, &netbuffer, &netbufferlen);
3283 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3294 buf_out = odr_getbuf(out, &len_out, 0);
3296 cs_put(conn, buf_out, len_out);
3304 printf("Target closed connection\n");
3309 odr_reset(in); /* release APDU from last round */
3311 do_hex_dump(netbuffer, res);
3312 odr_setbuf(in, netbuffer, res, 0);
3314 if (!z_GDU(in, &gdu, 0, 0))
3316 FILE *f = ber_file ? ber_file : stdout;
3317 odr_perror(in, "Decoding incoming APDU");
3318 fprintf(f, "[Near %d]\n", odr_offset(in));
3319 fprintf(f, "Packet dump:\n---------\n");
3320 odr_dumpBER(f, netbuffer, res);
3321 fprintf(f, "---------\n");
3323 z_GDU(print, &gdu, 0, 0);
3324 if (conn && cs_more(conn))
3329 odr_dumpBER(ber_file, netbuffer, res);
3330 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3332 odr_perror(print, "Failed to print incoming APDU");
3336 if (gdu->which == Z_GDU_Z3950)
3338 Z_APDU *apdu = gdu->u.z3950;
3341 case Z_APDU_initResponse:
3342 process_initResponse(apdu->u.initResponse);
3344 case Z_APDU_searchResponse:
3345 process_searchResponse(apdu->u.searchResponse);
3347 case Z_APDU_scanResponse:
3348 process_scanResponse(apdu->u.scanResponse);
3350 case Z_APDU_presentResponse:
3351 print_refid (apdu->u.presentResponse->referenceId);
3353 *apdu->u.presentResponse->numberOfRecordsReturned;
3354 if (apdu->u.presentResponse->records)
3355 display_records(apdu->u.presentResponse->records);
3357 printf("No records.\n");
3358 printf ("nextResultSetPosition = %d\n",
3359 *apdu->u.presentResponse->nextResultSetPosition);
3361 case Z_APDU_sortResponse:
3362 process_sortResponse(apdu->u.sortResponse);
3364 case Z_APDU_extendedServicesResponse:
3365 printf("Got extended services response\n");
3366 process_ESResponse(apdu->u.extendedServicesResponse);
3369 printf("Target has closed the association.\n");
3370 process_close(apdu->u.close);
3372 case Z_APDU_resourceControlRequest:
3373 process_resourceControlRequest
3374 (apdu->u.resourceControlRequest);
3376 case Z_APDU_deleteResultSetResponse:
3377 process_deleteResultSetResponse(apdu->u.
3378 deleteResultSetResponse);
3381 printf("Received unknown APDU type (%d).\n",
3387 else if (gdu->which == Z_GDU_HTTP_Response)
3389 http_response(gdu->u.HTTP_Response);
3392 if (conn && !cs_more(conn))
3397 #if HAVE_GETTIMEOFDAY
3398 gettimeofday (&tv_end, 0);
3400 printf ("S/U S/U=%ld/%ld %ld/%ld",
3401 (long) tv_start.tv_sec,
3402 (long) tv_start.tv_usec,
3403 (long) tv_end.tv_sec,
3404 (long) tv_end.tv_usec);
3406 printf ("Elapsed: %.6f\n",
3407 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3408 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3415 int cmd_cclparse(const char* arg)
3418 struct ccl_rpn_node *rpn=NULL;
3421 rpn = ccl_find_str (bibset, arg, &error, &pos);
3424 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3425 printf ("%s\n", ccl_err_msg (error));
3431 ccl_pr_tree(rpn, stdout);
3435 ccl_rpn_delete(rpn);
3443 int cmd_set_otherinfo(const char* args)
3445 char oid[101], otherinfoString[101];
3450 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3452 /* reset this otherinfo */
3453 if(otherinfoNo>=maxOtherInfosSupported) {
3454 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3456 extraOtherInfos[otherinfoNo].oidval = -1;
3457 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3461 printf("Error in set_otherinfo command \n");
3465 if(otherinfoNo>=maxOtherInfosSupported) {
3466 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3470 oidval = oid_getvalbyname (oid);
3472 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3475 extraOtherInfos[otherinfoNo].oidval = oidval;
3476 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3477 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3482 int cmd_list_otherinfo(const char* args)
3486 if(strlen(args)>0) {
3488 if( i >= maxOtherInfosSupported ) {
3489 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3493 if(extraOtherInfos[i].oidval != -1)
3494 printf(" otherinfo %d %s %s\n",
3496 yaz_z3950_oid_value_to_str(
3497 (enum oid_value) extraOtherInfos[i].oidval,
3499 extraOtherInfos[i].value);
3502 for(i=0; i<maxOtherInfosSupported; ++i) {
3503 if(extraOtherInfos[i].oidval != -1)
3504 printf(" otherinfo %d %s %s\n",
3506 yaz_z3950_oid_value_to_str(
3507 (enum oid_value) extraOtherInfos[i].oidval,
3509 extraOtherInfos[i].value);
3517 int cmd_list_all(const char* args) {
3520 /* connection options */
3522 printf("Connected to : %s\n",last_open_command);
3524 if(last_open_command)
3525 printf("Not connected to : %s\n",last_open_command);
3527 printf("Not connected : \n");
3530 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3532 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3535 printf("Authentication : none\n");
3537 switch(auth->which) {
3538 case Z_IdAuthentication_idPass:
3539 printf("Authentication : IdPass\n");
3540 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3541 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3542 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3544 case Z_IdAuthentication_open:
3545 printf("Authentication : psOpen\n");
3546 printf(" Open string : %s\n",auth->u.open);
3549 printf("Authentication : Unknown\n");
3552 if (negotiationCharset)
3553 printf("Neg. Character set : `%s'\n", negotiationCharset);
3557 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3561 printf("CCL file : %s\n",ccl_fields);
3562 printf("CQL file : %s\n",cql_fields);
3563 printf("Query type : %s\n",query_type_as_string(queryType));
3565 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3567 /* piggy back options */
3568 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3570 /* print present related options */
3571 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3572 printf("Schema : %s\n",schema);
3573 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3575 /* loging options */
3576 printf("APDU log : %s\n",apdu_file?"on":"off");
3577 printf("Record log : %s\n",marc_file?"on":"off");
3580 printf("Other Info: \n");
3581 cmd_list_otherinfo("");
3586 int cmd_clear_otherinfo(const char* args)
3588 if(strlen(args)>0) {
3590 otherinfoNo = atoi(args);
3591 if( otherinfoNo >= maxOtherInfosSupported ) {
3592 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3596 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3597 /* only clear if set. */
3598 extraOtherInfos[otherinfoNo].oidval=-1;
3599 free(extraOtherInfos[otherinfoNo].value);
3604 for(i=0; i<maxOtherInfosSupported; ++i) {
3605 if (extraOtherInfos[i].oidval!=-1 ) {
3606 extraOtherInfos[i].oidval=-1;
3607 free(extraOtherInfos[i].value);
3614 static int cmd_help (const char *line);
3616 typedef char *(*completerFunctionType)(const char *text, int state);
3620 int (*fun)(const char *arg);
3622 completerFunctionType rl_completerfunction;
3623 int complete_filenames;
3624 char **local_tabcompletes;
3626 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3627 {"quit", cmd_quit, "",NULL,0,NULL},
3628 {"find", cmd_find, "<query>",NULL,0,NULL},
3629 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3630 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3631 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3632 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3633 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3634 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3635 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3636 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3637 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3638 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3639 {"status", cmd_status, "",NULL,0,NULL},
3640 {"setnames", cmd_setnames, "",NULL,0,NULL},
3641 {"cancel", cmd_cancel, "",NULL,0,NULL},
3642 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3643 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3644 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3645 {"close", cmd_close, "",NULL,0,NULL},
3646 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3647 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3648 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3649 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3650 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3651 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3652 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3653 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3654 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3655 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3656 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3657 {".", cmd_source, "<filename>",NULL,1,NULL},
3658 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3659 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3660 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3661 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3662 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3663 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3664 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3665 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3666 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3667 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3668 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3669 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3670 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3671 {"list_all",cmd_list_all,"",NULL,0,NULL},
3672 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3673 /* Server Admin Functions */
3674 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3675 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3676 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3677 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3678 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3679 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3680 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3681 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3682 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3683 {"help", cmd_help, "", NULL,0,NULL},
3687 static int cmd_help (const char *line)
3693 sscanf (line, "%20s", topic);
3696 printf("Commands:\n");
3697 for (i = 0; cmd_array[i].cmd; i++)
3698 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3699 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3700 if (strcmp (topic, "find") == 0)
3703 printf (" \"term\" Simple Term\n");
3704 printf (" @attr [attset] type=value op Attribute\n");
3705 printf (" @and opl opr And\n");
3706 printf (" @or opl opr Or\n");
3707 printf (" @not opl opr And-Not\n");
3708 printf (" @set set Result set\n");
3710 printf ("Bib-1 attribute types\n");
3712 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3713 printf ("2=Relation: ");
3714 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3715 printf ("3=Position: ");
3716 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3717 printf ("4=Structure: ");
3718 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3719 printf ("5=Truncation: ");
3720 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3721 printf ("6=Completeness:");
3722 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3727 int cmd_register_tab(const char* arg) {
3729 char command[101], tabargument[101];
3734 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3738 /* locate the amdn in the list */
3739 for (i = 0; cmd_array[i].cmd; i++) {
3740 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3745 if(!cmd_array[i].cmd) {
3746 fprintf(stderr,"Unknown command %s\n",command);
3751 if(!cmd_array[i].local_tabcompletes)
3752 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3756 tabslist = cmd_array[i].local_tabcompletes;
3757 for(;tabslist && *tabslist;tabslist++) {
3761 cmd_array[i].local_tabcompletes = (char **)
3762 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3763 tabslist=cmd_array[i].local_tabcompletes;
3764 tabslist[num_of_tabs]=strdup(tabargument);
3765 tabslist[num_of_tabs+1]=NULL;
3770 void process_cmd_line(char* line)
3773 char word[32], arg[1024];
3775 #if HAVE_GETTIMEOFDAY
3776 gettimeofday (&tv_start, 0);
3779 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3781 strcpy(word, last_cmd);
3786 strcpy(last_cmd, word);
3788 /* removed tailing spaces from the arg command */
3791 char* lastnonspace=NULL;
3799 *(++lastnonspace) = 0;
3802 for (i = 0; cmd_array[i].cmd; i++)
3803 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3805 res = (*cmd_array[i].fun)(arg);
3809 if (!cmd_array[i].cmd) /* dump our help-screen */
3811 printf("Unknown command: %s.\n", word);
3812 printf("use help for list of commands\n");
3813 /* cmd_help (""); */
3817 if(apdu_file) fflush(apdu_file);
3820 wait_and_handle_response();
3829 char *command_generator(const char *text, int state)
3835 for( ; cmd_array[idx].cmd; ++idx) {
3836 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3837 ++idx; /* skip this entry on the next run */
3838 return strdup(cmd_array[idx-1].cmd);
3846 This function only known how to complete on the first word
3848 char ** readline_completer(char *text, int start, int end) {
3849 #if HAVE_READLINE_READLINE_H
3851 completerFunctionType completerToUse;
3854 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3855 char** res=rl_completion_matches(text,
3858 char** res=completion_matches(text,
3859 (CPFunction*)command_generator);
3861 rl_attempted_completion_over = 1;
3864 char arg[1024],word[32];
3866 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3867 rl_attempted_completion_over = 1;
3871 for (i = 0; cmd_array[i].cmd; i++) {
3872 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3877 if(!cmd_array[i].cmd) return NULL;
3879 curret_global_list = cmd_array[i].local_tabcompletes;
3881 completerToUse = cmd_array[i].rl_completerfunction;
3882 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3883 completerToUse = default_completer;
3885 if(completerToUse) {
3886 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3888 rl_completion_matches(text,
3892 completion_matches(text,
3893 (CPFunction*)completerToUse);
3895 if(!cmd_array[i].complete_filenames)
3896 rl_attempted_completion_over = 1;
3899 if(!cmd_array[i].complete_filenames)
3900 rl_attempted_completion_over = 1;
3910 static void client(void)
3916 #if HAVE_GETTIMEOFDAY
3917 gettimeofday (&tv_start, 0);
3922 char *line_in = NULL;
3923 #if HAVE_READLINE_READLINE_H
3926 line_in=readline(C_PROMPT);
3929 #if HAVE_READLINE_HISTORY_H
3931 add_history(line_in);
3933 strncpy(line, line_in, 1023);
3942 if (!fgets(line, 1023, stdin))
3944 if ((end_p = strchr (line, '\n')))
3947 process_cmd_line(line);
3951 static void show_version(void)
3955 yaz_version(vstr, 0);
3956 printf ("YAZ version: %s\n", YAZ_VERSION);
3957 if (strcmp(vstr, YAZ_VERSION))
3958 printf ("YAZ DLL/SO: %s\n", vstr);
3962 int main(int argc, char **argv)
3965 char *open_command = 0;
3966 char *auth_command = 0;
3971 if (!setlocale(LC_CTYPE, ""))
3972 fprintf (stderr, "setlocale failed\n");
3976 codeset = nl_langinfo(CODESET);
3980 outputCharset = xstrdup(codeset);
3982 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vx", argv, argc, &arg)) != -2)
3989 open_command = (char *) xmalloc (strlen(arg)+6);
3990 strcpy (open_command, "open ");
3991 strcat (open_command, arg);
3995 kilobytes = atoi(arg);
3998 if (!(marc_file = fopen (arg, "a")))
4005 outputCharset = xstrdup(arg);
4008 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4009 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4012 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4013 cql_fields[sizeof(cql_fields)-1] = '\0';
4016 if (!strcmp(arg, "-"))
4019 ber_file=fopen(arg, "a");
4022 if (!strcmp(arg, "-"))
4025 apdu_file=fopen(arg, "a");
4031 yazProxy=strdup(arg);
4036 auth_command = (char *) xmalloc (strlen(arg)+6);
4037 strcpy (auth_command, "auth ");
4038 strcat (auth_command, arg);
4042 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4048 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4049 "[-b berdump] [-c cclfields] \n"
4050 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4051 "[-k size] [-V] [<server-addr>]\n",
4059 #ifdef HAVE_GETTIMEOFDAY
4060 gettimeofday (&tv_start, 0);
4062 process_cmd_line (auth_command);
4063 #if HAVE_READLINE_HISTORY_H
4064 add_history(auth_command);
4066 xfree(auth_command);
4070 #ifdef HAVE_GETTIMEOFDAY
4071 gettimeofday (&tv_start, 0);
4073 process_cmd_line (open_command);
4074 #if HAVE_READLINE_HISTORY_H
4075 add_history(open_command);
4077 xfree(open_command);
4088 * vim600: sw=4 ts=8 fdm=marker
4089 * vim<600: sw=4 ts=8