2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.192 2003-05-12 22:35:06 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>
45 #if HAVE_READLINE_READLINE_H
46 #include <readline/readline.h>
49 #if HAVE_READLINE_HISTORY_H
50 #include <readline/history.h>
56 #include "tabcomplete.h"
58 #define C_PROMPT "Z> "
60 static char *codeset = 0; /* character set for output */
62 static ODR out, in, print; /* encoding and decoding streams */
63 static ODR srw_sr_odr_out = 0;
64 static Z_SRW_PDU *srw_sr = 0;
65 static FILE *apdu_file = 0;
66 static FILE *ber_file = 0;
67 static COMSTACK conn = 0; /* our z-association */
68 static Z_IdAuthentication *auth = 0; /* our current auth definition */
69 char *databaseNames[128];
70 int num_databaseNames = 0;
71 static Z_External *record_last = 0;
72 static int setnumber = -1; /* current result set number */
73 static int smallSetUpperBound = 0;
74 static int largeSetLowerBound = 1;
75 static int mediumSetPresentNumber = 0;
76 static Z_ElementSetNames *elementSetNames = 0;
77 static int setno = 1; /* current set offset */
78 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
79 static enum oid_value recordsyntax = VAL_USMARC;
80 //static enum oid_value schema = VAL_NONE;
81 static char *schema = 0;
82 static int sent_close = 0;
83 static NMEM session_mem = NULL; /* memory handle for init-response */
84 static Z_InitResponse *session = 0; /* session parameters */
85 static char last_scan_line[512] = "0";
86 static char last_scan_query[512] = "0";
87 static char ccl_fields[512] = "default.bib";
88 static char* esPackageName = 0;
89 static char* yazProxy = 0;
90 static int kilobytes = 1024;
91 static char* yazCharset = 0;
92 static char* yazLang = 0;
94 static char last_cmd[32] = "?";
95 static FILE *marc_file = 0;
96 static char *refid = NULL;
97 static char *last_open_command = NULL;
98 static int auto_reconnect = 0;
107 static QueryType queryType = QueryType_Prefix;
109 static CCL_bibset bibset; /* CCL bibset handle */
111 #if HAVE_READLINE_COMPLETION_OVER
114 /* readline doesn't have this var. Define it ourselves. */
115 int rl_attempted_completion_over = 0;
118 /* set this one to 1, to avoid decode of unknown MARCs */
119 #define AVOID_MARC_DECODE 1
121 #define maxOtherInfosSupported 10
125 } extraOtherInfos[maxOtherInfosSupported];
128 void process_cmd_line(char* line);
129 char ** readline_completer(char *text, int start, int end);
130 char *command_generator(const char *text, int state);
131 char** curret_global_list=NULL;
132 int cmd_register_tab(const char* arg);
134 static void close_session (void);
136 ODR getODROutputStream()
141 const char* query_type_as_string(QueryType q)
144 case QueryType_Prefix: return "prefix (RPN sent to server)";
145 case QueryType_CCL: return "CCL (CCL sent to server) ";
146 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
147 case QueryType_CQL: return "CQL (CQL sent to server)";
149 return "unknown Query type internal yaz-client error";
154 void do_hex_dump(char* buf,int len)
158 for( i=0; i<len ; i=i+16 )
161 for(x=0 ; i+x<len && x<16; ++x)
163 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
170 void add_otherInfos(Z_APDU *a)
172 Z_OtherInformation **oi;
176 for(i=0; i<maxOtherInfosSupported; ++i)
178 if(extraOtherInfos[i].oidval != -1)
179 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
180 1, extraOtherInfos[i].value);
184 void send_apdu(Z_APDU *a)
193 z_APDU(print, &a, 0, 0);
196 if (!z_APDU(out, &a, 0, 0))
198 odr_perror(out, "Encoding APDU");
202 buf = odr_getbuf(out, &len, 0);
204 odr_dumpBER(ber_file, buf, len);
205 /* printf ("sending APDU of size %d\n", len); */
206 if (cs_put(conn, buf, len) < 0)
208 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
212 do_hex_dump(buf,len);
213 odr_reset(out); /* release the APDU structure */
216 static void print_stringn(const unsigned char *buf, size_t len)
219 for (i = 0; i<len; i++)
220 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
221 printf ("%c", buf[i]);
223 printf ("\\X%02X", buf[i]);
226 static void print_refid (Z_ReferenceId *id)
230 printf ("Reference Id: ");
231 print_stringn (id->buf, id->len);
236 static Z_ReferenceId *set_refid (ODR out)
241 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
242 id->size = id->len = strlen(refid);
243 id->buf = (unsigned char *) odr_malloc (out, id->len);
244 memcpy (id->buf, refid, id->len);
248 /* INIT SERVICE ------------------------------- */
250 static void send_initRequest(const char* type_and_host)
252 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
253 Z_InitRequest *req = apdu->u.initRequest;
255 ODR_MASK_SET(req->options, Z_Options_search);
256 ODR_MASK_SET(req->options, Z_Options_present);
257 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
258 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
259 ODR_MASK_SET(req->options, Z_Options_scan);
260 ODR_MASK_SET(req->options, Z_Options_sort);
261 ODR_MASK_SET(req->options, Z_Options_extendedServices);
262 ODR_MASK_SET(req->options, Z_Options_delSet);
264 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
265 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
266 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
268 *req->maximumRecordSize = 1024*kilobytes;
269 *req->preferredMessageSize = 1024*kilobytes;
271 req->idAuthentication = auth;
273 req->referenceId = set_refid (out);
276 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
279 if (yazCharset || yazLang) {
280 Z_OtherInformation **p;
281 Z_OtherInformationUnit *p0;
283 yaz_oi_APDU(apdu, &p);
285 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
286 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
288 p0->which = Z_OtherInfo_externallyDefinedInfo;
289 p0->information.externallyDefinedInfo =
290 yaz_set_proposal_charneg(out,
291 (const char**)&yazCharset, (yazCharset)?1:0,
292 (const char**)&yazLang, (yazLang)?1:0, 1);
297 printf("Sent initrequest.\n");
300 static int process_initResponse(Z_InitResponse *res)
303 /* save session parameters for later use */
304 session_mem = odr_extract_mem(in);
307 for (ver = 0; ver<5; ver++)
308 if (!ODR_MASK_GET(res->protocolVersion, ver))
312 printf("Connection rejected by v%d target.\n", ver);
314 printf("Connection accepted by v%d target.\n", ver);
315 if (res->implementationId)
316 printf("ID : %s\n", res->implementationId);
317 if (res->implementationName)
318 printf("Name : %s\n", res->implementationName);
319 if (res->implementationVersion)
320 printf("Version: %s\n", res->implementationVersion);
321 if (res->userInformationField)
323 printf("UserInformationfield:\n");
324 if (!z_External(print, (Z_External**)&res-> userInformationField,
327 odr_perror(print, "Printing userinfo\n");
330 if (res->userInformationField->which == Z_External_octet)
332 printf("Guessing visiblestring:\n");
333 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
338 if (ODR_MASK_GET(res->options, Z_Options_search))
340 if (ODR_MASK_GET(res->options, Z_Options_present))
342 if (ODR_MASK_GET(res->options, Z_Options_delSet))
344 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
345 printf (" resourceReport");
346 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
347 printf (" resourceCtrl");
348 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
349 printf (" accessCtrl");
350 if (ODR_MASK_GET(res->options, Z_Options_scan))
352 if (ODR_MASK_GET(res->options, Z_Options_sort))
354 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
355 printf (" extendedServices");
356 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
357 printf (" level1Segmentation");
358 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
359 printf (" level2Segmentation");
360 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
361 printf (" concurrentOperations");
362 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
364 printf (" namedResultSets");
367 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
368 printf (" encapsulation");
369 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
370 printf (" resultCount");
371 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
372 printf (" negotiationModel");
373 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
374 printf (" duplicateDetection");
375 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
376 printf (" queryType104");
379 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
381 Z_CharSetandLanguageNegotiation *p =
382 yaz_get_charneg_record(res->otherInfo);
386 char *charset=NULL, *lang=NULL;
389 yaz_get_response_charneg(session_mem, p, &charset, &lang,
392 printf("Accepted character set : %s\n", charset);
393 printf("Accepted code language : %s\n", lang ? lang : "none");
394 printf("Accepted records in ...: %d\n", selected );
401 static int set_base(const char *arg)
406 for (i = 0; i<num_databaseNames; i++)
407 xfree (databaseNames[i]);
408 num_databaseNames = 0;
412 if (!(cp = strchr(arg, ' ')))
413 cp = arg + strlen(arg);
416 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
417 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
418 databaseNames[num_databaseNames][cp - arg] = '\0';
420 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
429 if (num_databaseNames == 0)
431 num_databaseNames = 1;
432 databaseNames[0] = xstrdup("");
437 static int cmd_base(const char *arg)
441 printf("Usage: base <database> <database> ...\n");
444 return set_base(arg);
447 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
449 if(last_open_command != arg)
451 if(last_open_command) xfree(last_open_command);
452 last_open_command = xstrdup(new_open_command);
456 int session_connect(const char *arg)
459 char type_and_host[101];
460 const char *basep = 0;
467 nmem_destroy (session_mem);
471 cs_get_host_args(arg, &basep);
473 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
474 type_and_host[sizeof(type_and_host)-1] = '\0';
476 cmd_open_remember_last_open_command(arg,type_and_host);
479 conn = cs_create_host(yazProxy, 1, &add);
481 conn = cs_create_host(arg, 1, &add);
484 printf ("Couldn't create comstack\n");
489 if (conn->protocol == PROTO_HTTP)
491 printf ("SRW/HTTP not enabled in this YAZ\n");
497 protocol = conn->protocol;
498 if (conn->protocol == PROTO_HTTP)
502 printf("Connecting...");
504 if (cs_connect(conn, add) < 0)
506 printf ("error = %s\n", cs_strerror(conn));
507 if (conn->cerrno == CSYSERR)
510 yaz_strerror(msg, sizeof(msg));
511 printf ("%s\n", msg);
520 if (protocol == PROTO_Z3950)
522 send_initRequest(type_and_host);
528 int cmd_open(const char *arg)
530 static char cur_host[200];
533 strncpy (cur_host, arg, sizeof(cur_host)-1);
534 cur_host[sizeof(cur_host)-1] = 0;
536 return session_connect(cur_host);
543 if(!( auto_reconnect && last_open_command) ) return ;
545 open_command = (char *) xmalloc (strlen(last_open_command)+6);
546 strcpy (open_command, "open ");
548 strcat (open_command, last_open_command);
550 process_cmd_line(open_command);
555 int cmd_authentication(const char *arg)
557 static Z_IdAuthentication au;
558 static char user[40], group[40], pass[40];
559 static Z_IdPass idPass;
564 printf("Auth field set to null\n");
568 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
571 printf("Auth field set to null\n");
577 au.which = Z_IdAuthentication_open;
583 au.which = Z_IdAuthentication_idPass;
584 au.u.idPass = &idPass;
585 idPass.groupId = NULL;
586 idPass.userId = user;
587 idPass.password = group;
592 au.which = Z_IdAuthentication_idPass;
593 au.u.idPass = &idPass;
594 idPass.groupId = group;
595 idPass.userId = user;
596 idPass.password = pass;
601 /* SEARCH SERVICE ------------------------------ */
602 static void display_record(Z_External *r);
604 static void print_record(const unsigned char *buf, size_t len)
607 print_stringn (buf, len);
608 /* add newline if not already added ... */
609 if (i <= 0 || buf[i-1] != '\n')
613 static void display_record(Z_External *r)
615 oident *ent = oid_getentbyoid(r->direct_reference);
619 * Tell the user what we got.
621 if (r->direct_reference)
623 printf("Record type: ");
625 printf("%s\n", ent->desc);
626 else if (!odr_oid(print, &r->direct_reference, 0, 0))
628 odr_perror(print, "print oid");
632 /* Check if this is a known, ASN.1 type tucked away in an octet string */
633 if (ent && r->which == Z_External_octet)
635 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
641 * Call the given decoder to process the record.
643 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
644 r->u.octet_aligned->len, 0);
645 if (!(*type->fun)(in, (char **)&rr, 0, 0))
647 odr_perror(in, "Decoding constructed record.");
648 fprintf(stdout, "[Near %d]\n", odr_offset(in));
649 fprintf(stdout, "Packet dump:\n---------\n");
650 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
651 r->u.octet_aligned->len);
652 fprintf(stdout, "---------\n");
654 /* note just ignores the error ant print the bytes form the octet_aligned later */
657 * Note: we throw away the original, BER-encoded record here.
658 * Do something else with it if you want to keep it.
660 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
661 r->which = type->what;
665 if (ent && ent->oclass != CLASS_RECSYN)
667 if (ent && ent->value == VAL_SOIF)
668 print_record((const unsigned char *) r->u.octet_aligned->buf,
669 r->u.octet_aligned->len);
670 else if (r->which == Z_External_octet)
672 const char *octet_buf = (char*)r->u.octet_aligned->buf;
673 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
674 ent->value == VAL_HTML)
676 print_record((const unsigned char *) octet_buf,
677 r->u.octet_aligned->len);
679 else if (ent->value == VAL_POSTSCRIPT)
681 int size = r->u.octet_aligned->len;
684 print_record((const unsigned char *) octet_buf, size);
689 #if AVOID_MARC_DECODE
690 /* primitive check for a marc OID 5.1-29 except 16 */
691 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
692 ent->oidsuffix[1] != 16
701 yaz_marc_t mt = yaz_marc_create();
703 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
707 if (ent->value == VAL_USMARC)
709 if (octet_buf[9] == 'a')
719 printf ("convert from %s to %s\n", from, codeset);
720 cd = yaz_iconv_open(codeset, from);
723 fwrite (result, 1, rlen, stdout);
727 size_t inbytesleft = rlen;
728 const char *inp = result;
732 size_t outbytesleft = sizeof(outbuf);
734 size_t r = yaz_iconv (cd, (char**) &inp,
736 &outp, &outbytesleft);
737 if (r == (size_t) (-1))
739 int e = yaz_iconv_error(cd);
740 if (e != YAZ_ICONV_E2BIG)
743 fwrite (outbuf, outp - outbuf, 1, stdout);
749 printf ("bad MARC. Dumping as it is:\n");
750 print_record((const unsigned char*) octet_buf,
751 r->u.octet_aligned->len);
753 yaz_marc_destroy(mt);
759 print_record((const unsigned char*) octet_buf,
760 r->u.octet_aligned->len);
764 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
766 else if (ent && ent->value == VAL_SUTRS)
768 if (r->which != Z_External_sutrs)
770 printf("Expecting single SUTRS type for SUTRS.\n");
773 print_record(r->u.sutrs->buf, r->u.sutrs->len);
775 else if (ent && ent->value == VAL_GRS1)
778 if (r->which != Z_External_grs1)
780 printf("Expecting single GRS type for GRS.\n");
784 yaz_display_grs1(w, r->u.grs1, 0);
790 printf("Unknown record representation.\n");
791 if (!z_External(print, &r, 0, 0))
793 odr_perror(print, "Printing external");
799 static void display_diagrecs(Z_DiagRec **pp, int num)
803 Z_DefaultDiagFormat *r;
805 printf("Diagnostic message(s) from database:\n");
806 for (i = 0; i<num; i++)
808 Z_DiagRec *p = pp[i];
809 if (p->which != Z_DiagRec_defaultFormat)
811 printf("Diagnostic record not in default format.\n");
815 r = p->u.defaultFormat;
816 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
817 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
818 printf("Missing or unknown diagset\n");
819 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
822 case Z_DefaultDiagFormat_v2Addinfo:
823 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
825 case Z_DefaultDiagFormat_v3Addinfo:
826 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
833 static void display_nameplusrecord(Z_NamePlusRecord *p)
836 printf("[%s]", p->databaseName);
837 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
838 display_diagrecs(&p->u.surrogateDiagnostic, 1);
839 else if (p->which == Z_NamePlusRecord_databaseRecord)
840 display_record(p->u.databaseRecord);
843 static void display_records(Z_Records *p)
847 if (p->which == Z_Records_NSD)
849 Z_DiagRec dr, *dr_p = &dr;
850 dr.which = Z_DiagRec_defaultFormat;
851 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
852 display_diagrecs (&dr_p, 1);
854 else if (p->which == Z_Records_multipleNSD)
855 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
856 p->u.multipleNonSurDiagnostics->num_diagRecs);
859 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
860 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
861 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
865 static int send_deleteResultSetRequest(const char *arg)
870 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
871 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
873 req->referenceId = set_refid (out);
875 req->num_resultSetList =
876 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
877 names[0], names[1], names[2], names[3],
878 names[4], names[5], names[6], names[7]);
880 req->deleteFunction = (int *)
881 odr_malloc (out, sizeof(*req->deleteFunction));
882 if (req->num_resultSetList > 0)
884 *req->deleteFunction = Z_DeleteRequest_list;
885 req->resultSetList = (char **)
886 odr_malloc (out, sizeof(*req->resultSetList)*
887 req->num_resultSetList);
888 for (i = 0; i<req->num_resultSetList; i++)
889 req->resultSetList[i] = names[i];
893 *req->deleteFunction = Z_DeleteRequest_all;
894 req->resultSetList = 0;
898 printf("Sent deleteResultSetRequest.\n");
903 static int send_srw(Z_SRW_PDU *sr)
905 const char *charset = 0;
906 const char *host_port = 0;
909 Z_SOAP_Handler h[2] = {
910 {"http://www.loc.gov/zing/srw/v1.0/", 0, (Z_SOAP_fun) yaz_srw_codec},
913 ODR o = odr_createmem(ODR_ENCODE);
915 Z_SOAP *p = odr_malloc(o, sizeof(*p));
918 path = odr_malloc(out, strlen(databaseNames[0])+2);
920 strcpy(path+1, databaseNames[0]);
922 gdu = z_get_HTTP_Request(out);
923 gdu->u.HTTP_Request->path = odr_strdup(out, path);
927 const char *cp0 = strstr(host_port, "://");
934 cp1 = strchr(cp0, '/');
936 cp1 = cp0+strlen(cp0);
940 char *h = odr_malloc(out, cp1 - cp0 + 1);
941 memcpy (h, cp0, cp1 - cp0);
943 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
948 strcpy(ctype, "text/xml");
949 if (charset && strlen(charset) < 20)
951 strcat(ctype, "; charset=");
952 strcat(ctype, charset);
954 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
955 "Content-Type", ctype);
956 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
957 "SOAPAction", "\"\"");
958 p->which = Z_SOAP_generic;
959 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
960 p->u.generic->no = 0;
961 p->u.generic->ns = 0;
962 p->u.generic->p = sr;
963 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
965 ret = z_soap_codec_enc(o, &p,
966 &gdu->u.HTTP_Request->content_buf,
967 &gdu->u.HTTP_Request->content_len, h,
970 if (z_GDU(out, &gdu, 0, 0))
976 buf_out = odr_getbuf(out, &len_out, 0);
978 /* we don't odr_reset(out), since we may need the buffer again */
980 r = cs_put(conn, buf_out, len_out);
992 static int send_SRW_searchRequest(const char *arg)
998 assert(srw_sr_odr_out == 0);
999 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1001 odr_reset(srw_sr_odr_out);
1005 /* save this for later .. when fetching individual records */
1006 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1007 sr->u.request->query_type = Z_SRW_query_type_cql;
1008 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1010 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1011 sr->u.request->query_type = Z_SRW_query_type_cql;
1012 sr->u.request->query.cql = odr_strdup(out, arg);
1014 sr->u.request->recordSchema = schema;
1015 return send_srw(sr);
1019 static int send_searchRequest(const char *arg)
1021 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1022 Z_SearchRequest *req = apdu->u.searchRequest;
1025 struct ccl_rpn_node *rpn = NULL;
1027 char setstring[100];
1028 Z_RPNQuery *RPNquery;
1030 YAZ_PQF_Parser pqf_parser;
1033 if (queryType == QueryType_CCL2RPN)
1035 rpn = ccl_find_str(bibset, arg, &error, &pos);
1038 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1042 req->referenceId = set_refid (out);
1043 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1045 static unsigned char big[2100];
1046 static Odr_oct bigo;
1048 /* send a very big referenceid to test transport stack etc. */
1049 memset(big, 'A', 2100);
1050 bigo.len = bigo.size = 2100;
1052 req->referenceId = &bigo;
1057 sprintf(setstring, "%d", ++setnumber);
1058 req->resultSetName = setstring;
1060 *req->smallSetUpperBound = smallSetUpperBound;
1061 *req->largeSetLowerBound = largeSetLowerBound;
1062 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1063 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1064 mediumSetPresentNumber > 0))
1068 prefsyn.proto = protocol;
1069 prefsyn.oclass = CLASS_RECSYN;
1070 prefsyn.value = recordsyntax;
1071 req->preferredRecordSyntax =
1072 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1073 req->smallSetElementSetNames =
1074 req->mediumSetElementSetNames = elementSetNames;
1076 req->num_databaseNames = num_databaseNames;
1077 req->databaseNames = databaseNames;
1079 req->query = &query;
1083 case QueryType_Prefix:
1084 query.which = Z_Query_type_1;
1085 pqf_parser = yaz_pqf_create ();
1086 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1089 const char *pqf_msg;
1091 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1092 printf("%*s^\n", off+4, "");
1093 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1095 yaz_pqf_destroy (pqf_parser);
1098 yaz_pqf_destroy (pqf_parser);
1099 query.u.type_1 = RPNquery;
1102 query.which = Z_Query_type_2;
1103 query.u.type_2 = &ccl_query;
1104 ccl_query.buf = (unsigned char*) arg;
1105 ccl_query.len = strlen(arg);
1107 case QueryType_CCL2RPN:
1108 query.which = Z_Query_type_1;
1109 RPNquery = ccl_rpn_query(out, rpn);
1112 printf ("Couldn't convert from CCL to RPN\n");
1115 query.u.type_1 = RPNquery;
1116 ccl_rpn_delete (rpn);
1119 query.which = Z_Query_type_104;
1120 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1121 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1122 ext->indirect_reference = 0;
1123 ext->descriptor = 0;
1124 ext->which = Z_External_CQL;
1125 ext->u.cql = odr_strdup(out, arg);
1126 query.u.type_104 = ext;
1129 printf ("Unsupported query type\n");
1134 printf("Sent searchRequest.\n");
1138 /* display Query Expression as part of searchResult-1 */
1139 static void display_queryExpression (Z_QueryExpression *qe)
1143 if (qe->which == Z_QueryExpression_term)
1145 if (qe->u.term->queryTerm)
1147 Z_Term *term = qe->u.term->queryTerm;
1148 switch (term->which)
1150 case Z_Term_general:
1151 printf (" %.*s", term->u.general->len, term->u.general->buf);
1153 case Z_Term_characterString:
1154 printf (" %s", term->u.characterString);
1156 case Z_Term_numeric:
1157 printf (" %d", *term->u.numeric);
1167 /* see if we can find USR:SearchResult-1 */
1168 static void display_searchResult (Z_OtherInformation *o)
1173 for (i = 0; i < o->num_elements; i++)
1175 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1177 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1179 if (ext->which == Z_External_searchResult1)
1182 Z_SearchInfoReport *sr = ext->u.searchResult1;
1183 printf ("SearchResult-1:");
1184 for (j = 0; j < sr->num; j++)
1186 if (!sr->elements[j]->subqueryExpression)
1188 display_queryExpression (
1189 sr->elements[j]->subqueryExpression);
1190 display_queryExpression (
1191 sr->elements[j]->subqueryInterpretation);
1192 display_queryExpression (
1193 sr->elements[j]->subqueryRecommendation);
1194 if (sr->elements[j]->subqueryCount)
1195 printf ("(%d)", *sr->elements[j]->subqueryCount);
1203 static int process_searchResponse(Z_SearchResponse *res)
1205 printf ("Received SearchResponse.\n");
1206 print_refid (res->referenceId);
1207 if (*res->searchStatus)
1208 printf("Search was a success.\n");
1210 printf("Search was a bloomin' failure.\n");
1211 printf("Number of hits: %d", *res->resultCount);
1213 printf (", setno %d", setnumber);
1215 display_searchResult (res->additionalSearchInfo);
1216 printf("records returned: %d\n",
1217 *res->numberOfRecordsReturned);
1218 setno += *res->numberOfRecordsReturned;
1220 display_records(res->records);
1224 static void print_level(int iLevel)
1227 for (i = 0; i < iLevel * 4; i++)
1231 static void print_int(int iLevel, const char *pTag, int *pInt)
1235 print_level(iLevel);
1236 printf("%s: %d\n", pTag, *pInt);
1240 static void print_string(int iLevel, const char *pTag, const char *pString)
1242 if (pString != NULL)
1244 print_level(iLevel);
1245 printf("%s: %s\n", pTag, pString);
1249 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1255 print_level(iLevel);
1256 printf("%s:", pTag);
1257 for (; *pInt != -1; pInt++)
1258 printf(" %d", *pInt);
1263 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1265 if (referenceId != NULL)
1269 print_level(iLevel);
1270 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1271 for (i = 0; i < referenceId->len; i++)
1272 printf("%c", referenceId->buf[i]);
1277 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1279 if (pStringNumeric != NULL)
1281 switch (pStringNumeric->which)
1283 case Z_StringOrNumeric_string:
1284 print_string(iLevel, pTag, pStringNumeric->u.string);
1287 case Z_StringOrNumeric_numeric:
1288 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1292 print_level(iLevel);
1293 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1299 static void print_universe_report_duplicate(
1301 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1303 if (pUniverseReportDuplicate != NULL)
1305 print_level(iLevel);
1306 printf("Universe Report Duplicate: \n");
1308 print_string_or_numeric(iLevel, "Hit No",
1309 pUniverseReportDuplicate->hitno);
1313 static void print_universe_report_hits(
1315 Z_UniverseReportHits *pUniverseReportHits)
1317 if (pUniverseReportHits != NULL)
1319 print_level(iLevel);
1320 printf("Universe Report Hits: \n");
1322 print_string_or_numeric(iLevel, "Database",
1323 pUniverseReportHits->database);
1324 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1328 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1330 if (pUniverseReport != NULL)
1332 print_level(iLevel);
1333 printf("Universe Report: \n");
1335 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1336 switch (pUniverseReport->which)
1338 case Z_UniverseReport_databaseHits:
1339 print_universe_report_hits(iLevel,
1340 pUniverseReport->u.databaseHits);
1343 case Z_UniverseReport_duplicate:
1344 print_universe_report_duplicate(iLevel,
1345 pUniverseReport->u.duplicate);
1349 print_level(iLevel);
1350 printf("Type: %d\n", pUniverseReport->which);
1356 static void print_external(int iLevel, Z_External *pExternal)
1358 if (pExternal != NULL)
1360 print_level(iLevel);
1361 printf("External: \n");
1363 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1364 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1365 print_string(iLevel, "Descriptor", pExternal->descriptor);
1366 switch (pExternal->which)
1368 case Z_External_universeReport:
1369 print_universe_report(iLevel, pExternal->u.universeReport);
1373 print_level(iLevel);
1374 printf("Type: %d\n", pExternal->which);
1380 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1382 printf ("Received ResourceControlRequest.\n");
1383 print_referenceId(1, req->referenceId);
1384 print_int(1, "Suspended Flag", req->suspendedFlag);
1385 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1386 print_int(1, "Response Required", req->responseRequired);
1387 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1388 print_external(1, req->resourceReport);
1392 void process_ESResponse(Z_ExtendedServicesResponse *res)
1395 switch (*res->operationStatus)
1397 case Z_ExtendedServicesResponse_done:
1400 case Z_ExtendedServicesResponse_accepted:
1401 printf ("accepted\n");
1403 case Z_ExtendedServicesResponse_failure:
1404 printf ("failure\n");
1405 display_diagrecs(res->diagnostics, res->num_diagnostics);
1408 printf ("unknown\n");
1410 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1411 (res->num_diagnostics != 0) ) {
1412 display_diagrecs(res->diagnostics, res->num_diagnostics);
1414 print_refid (res->referenceId);
1415 if (res->taskPackage &&
1416 res->taskPackage->which == Z_External_extendedService)
1418 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1419 Odr_oct *id = taskPackage->targetReference;
1420 Z_External *ext = taskPackage->taskSpecificParameters;
1424 printf ("Target Reference: ");
1425 print_stringn (id->buf, id->len);
1428 if (ext->which == Z_External_update)
1430 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1431 if (utp && utp->targetPart)
1433 Z_IUTargetPart *targetPart = utp->targetPart;
1436 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1439 Z_IUTaskPackageRecordStructure *tpr =
1440 targetPart->taskPackageRecords[i];
1441 printf ("task package record %d\n", i+1);
1442 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1444 display_record (tpr->u.record);
1448 printf ("other type\n");
1456 const char *get_ill_element (void *clientData, const char *element)
1461 static Z_External *create_external_itemRequest()
1463 struct ill_get_ctl ctl;
1464 ILL_ItemRequest *req;
1466 int item_request_size = 0;
1467 char *item_request_buf = 0;
1471 ctl.f = get_ill_element;
1473 req = ill_get_ItemRequest(&ctl, "ill", 0);
1475 printf ("ill_get_ItemRequest failed\n");
1477 if (!ill_ItemRequest (out, &req, 0, 0))
1481 ill_ItemRequest(print, &req, 0, 0);
1484 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1485 if (item_request_buf)
1486 odr_setbuf (out, item_request_buf, item_request_size, 1);
1487 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1494 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1495 oid.proto = PROTO_GENERAL;
1496 oid.oclass = CLASS_GENERAL;
1497 oid.value = VAL_ISO_ILL_1;
1499 r = (Z_External *) odr_malloc (out, sizeof(*r));
1500 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1501 r->indirect_reference = 0;
1503 r->which = Z_External_single;
1505 r->u.single_ASN1_type = (Odr_oct *)
1506 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1507 r->u.single_ASN1_type->buf = (unsigned char *)
1508 odr_malloc (out, item_request_size);
1509 r->u.single_ASN1_type->len = item_request_size;
1510 r->u.single_ASN1_type->size = item_request_size;
1511 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1514 do_hex_dump(item_request_buf,item_request_size);
1519 static Z_External *create_external_ILL_APDU(int which)
1521 struct ill_get_ctl ctl;
1524 int ill_request_size = 0;
1525 char *ill_request_buf = 0;
1529 ctl.f = get_ill_element;
1531 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1533 if (!ill_APDU (out, &ill_apdu, 0, 0))
1537 printf ("-------------------\n");
1538 ill_APDU(print, &ill_apdu, 0, 0);
1540 printf ("-------------------\n");
1542 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1543 if (ill_request_buf)
1544 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1545 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1551 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1553 oid.proto = PROTO_GENERAL;
1554 oid.oclass = CLASS_GENERAL;
1555 oid.value = VAL_ISO_ILL_1;
1557 r = (Z_External *) odr_malloc (out, sizeof(*r));
1558 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1559 r->indirect_reference = 0;
1561 r->which = Z_External_single;
1563 r->u.single_ASN1_type = (Odr_oct *)
1564 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1565 r->u.single_ASN1_type->buf = (unsigned char *)
1566 odr_malloc (out, ill_request_size);
1567 r->u.single_ASN1_type->len = ill_request_size;
1568 r->u.single_ASN1_type->size = ill_request_size;
1569 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1570 /* printf ("len = %d\n", ill_request_size); */
1571 /* do_hex_dump(ill_request_buf,ill_request_size); */
1572 /* printf("--- end of extenal\n"); */
1579 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1581 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1582 oident ItemOrderRequest;
1584 ItemOrderRequest.proto = PROTO_Z3950;
1585 ItemOrderRequest.oclass = CLASS_EXTSERV;
1586 ItemOrderRequest.value = VAL_ITEMORDER;
1588 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1589 r->indirect_reference = 0;
1592 r->which = Z_External_itemOrder;
1594 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1595 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1596 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1598 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1599 odr_malloc(out,sizeof(Z_IORequest));
1600 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1602 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1603 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1604 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1605 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1606 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1607 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1609 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1610 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1611 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1613 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1614 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1615 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1616 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1618 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1619 (int *) odr_malloc(out, sizeof(int));
1620 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1622 if (!strcmp (type, "item") || !strcmp(type, "2"))
1624 printf ("using item-request\n");
1625 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1626 create_external_itemRequest();
1628 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1630 printf ("using ILL-request\n");
1631 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1632 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1634 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1636 const char *xml_buf =
1638 " <type>request</type>\n"
1639 " <libraryNo>000200</libraryNo>\n"
1640 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1642 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1643 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1646 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1651 static int send_itemorder(const char *type, int itemno)
1653 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1654 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1655 oident ItemOrderRequest;
1657 ItemOrderRequest.proto = PROTO_Z3950;
1658 ItemOrderRequest.oclass = CLASS_EXTSERV;
1659 ItemOrderRequest.value = VAL_ITEMORDER;
1660 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1661 req->packageName = esPackageName;
1663 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1669 static int only_z3950()
1671 if (protocol == PROTO_HTTP)
1673 printf ("Not supported by SRW\n");
1679 static int cmd_update(const char *arg)
1681 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1682 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1685 Z_IUOriginPartToKeep *toKeep;
1686 Z_IUSuppliedRecords *notToKeep;
1688 char action[20], recid[20], fname[80];
1690 Z_External *record_this = 0;
1697 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1699 if (!strcmp (action, "insert"))
1700 action_no = Z_IUOriginPartToKeep_recordInsert;
1701 else if (!strcmp (action, "replace"))
1702 action_no = Z_IUOriginPartToKeep_recordReplace;
1703 else if (!strcmp (action, "delete"))
1704 action_no = Z_IUOriginPartToKeep_recordDelete;
1705 else if (!strcmp (action, "update"))
1706 action_no = Z_IUOriginPartToKeep_specialUpdate;
1709 printf ("Bad action: %s\n", action);
1710 printf ("Possible values: insert, replace, delete, update\n");
1718 stat (fname, &status);
1719 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1721 size_t len = status.st_size;
1722 char *buf = (char *) xmalloc (len);
1724 fread (buf, 1, len, inf);
1728 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1734 printf ("File %s doesn't exist\n", fname);
1742 printf ("No last record (update ignored)\n");
1745 record_this = record_last;
1748 update_oid.proto = PROTO_Z3950;
1749 update_oid.oclass = CLASS_EXTSERV;
1750 update_oid.value = VAL_DBUPDATE;
1751 oid_ent_to_oid (&update_oid, oid);
1752 req->packageType = odr_oiddup(out,oid);
1753 req->packageName = esPackageName;
1755 req->referenceId = set_refid (out);
1757 r = req->taskSpecificParameters = (Z_External *)
1758 odr_malloc (out, sizeof(*r));
1759 r->direct_reference = odr_oiddup(out,oid);
1760 r->indirect_reference = 0;
1762 r->which = Z_External_update;
1763 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1764 r->u.update->which = Z_IUUpdate_esRequest;
1765 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1766 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1767 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1768 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1769 toKeep->databaseName = databaseNames[0];
1771 toKeep->elementSetName = 0;
1772 toKeep->actionQualifier = 0;
1773 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1774 *toKeep->action = action_no;
1776 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1777 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1779 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1780 odr_malloc(out, sizeof(*notToKeep->elements));
1781 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1782 odr_malloc(out, sizeof(**notToKeep->elements));
1783 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1786 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1787 odr_malloc (out, sizeof(Odr_oct));
1788 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1789 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1790 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1793 notToKeep->elements[0]->u.opaque = 0;
1794 notToKeep->elements[0]->supplementalId = 0;
1795 notToKeep->elements[0]->correlationInfo = 0;
1796 notToKeep->elements[0]->record = record_this;
1803 static int cmd_itemorder(const char *arg)
1810 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1813 printf("Item order request\n");
1815 send_itemorder(type, itemno);
1819 static int cmd_find(const char *arg)
1823 printf("Find what?\n");
1826 if (protocol == PROTO_HTTP)
1831 if (!send_SRW_searchRequest(arg))
1844 printf("Not connected yet\n");
1848 if (!send_searchRequest(arg))
1854 static int cmd_delete(const char *arg)
1858 printf("Not connected yet\n");
1863 if (!send_deleteResultSetRequest(arg))
1868 static int cmd_ssub(const char *arg)
1870 if (!(smallSetUpperBound = atoi(arg)))
1875 static int cmd_lslb(const char *arg)
1879 if (!(largeSetLowerBound = atoi(arg)))
1884 static int cmd_mspn(const char *arg)
1888 if (!(mediumSetPresentNumber = atoi(arg)))
1893 static int cmd_status(const char *arg)
1895 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1896 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1897 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1901 static int cmd_setnames(const char *arg)
1903 if (*arg == '1') /* enable ? */
1905 else if (*arg == '0') /* disable ? */
1907 else if (setnumber < 0) /* no args, toggle .. */
1913 printf("Set numbering enabled.\n");
1915 printf("Set numbering disabled.\n");
1919 /* PRESENT SERVICE ----------------------------- */
1921 static void parse_show_args(const char *arg_c, char *setstring,
1922 int *start, int *number)
1927 strncpy(arg, arg_c, sizeof(arg)-1);
1928 arg[sizeof(arg)-1] = '\0';
1930 if ((p = strchr(arg, '+')))
1932 *number = atoi(p + 1);
1937 if (p && (p=strchr(p+1, '+')))
1938 strcpy (setstring, p+1);
1939 else if (setnumber >= 0)
1940 sprintf(setstring, "%d", setnumber);
1945 static int send_presentRequest(const char *arg)
1947 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1948 Z_PresentRequest *req = apdu->u.presentRequest;
1949 Z_RecordComposition compo;
1953 char setstring[100];
1955 req->referenceId = set_refid (out);
1957 parse_show_args(arg, setstring, &setno, &nos);
1959 req->resultSetId = setstring;
1961 req->resultSetStartPoint = &setno;
1962 req->numberOfRecordsRequested = &nos;
1963 prefsyn.proto = protocol;
1964 prefsyn.oclass = CLASS_RECSYN;
1965 prefsyn.value = recordsyntax;
1966 req->preferredRecordSyntax =
1967 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1973 prefschema.proto = protocol;
1974 prefschema.oclass = CLASS_SCHEMA;
1975 prefschema.value = oid_getvalbyname(schema);
1977 req->recordComposition = &compo;
1978 compo.which = Z_RecordComp_complex;
1979 compo.u.complex = (Z_CompSpec *)
1980 odr_malloc(out, sizeof(*compo.u.complex));
1981 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1982 odr_malloc(out, sizeof(bool_t));
1983 *compo.u.complex->selectAlternativeSyntax = 0;
1985 compo.u.complex->generic = (Z_Specification *)
1986 odr_malloc(out, sizeof(*compo.u.complex->generic));
1987 compo.u.complex->generic->which = Z_Schema_oid;
1988 compo.u.complex->generic->schema.oid = (Odr_oid *)
1989 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1990 if (!compo.u.complex->generic->schema.oid)
1992 /* OID wasn't a schema! Try record syntax instead. */
1993 prefschema.oclass = CLASS_RECSYN;
1994 compo.u.complex->generic->schema.oid = (Odr_oid *)
1995 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1997 if (!elementSetNames)
1998 compo.u.complex->generic->elementSpec = 0;
2001 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2002 odr_malloc(out, sizeof(Z_ElementSpec));
2003 compo.u.complex->generic->elementSpec->which =
2004 Z_ElementSpec_elementSetName;
2005 compo.u.complex->generic->elementSpec->u.elementSetName =
2006 elementSetNames->u.generic;
2008 compo.u.complex->num_dbSpecific = 0;
2009 compo.u.complex->dbSpecific = 0;
2010 compo.u.complex->num_recordSyntax = 0;
2011 compo.u.complex->recordSyntax = 0;
2013 else if (elementSetNames)
2015 req->recordComposition = &compo;
2016 compo.which = Z_RecordComp_simple;
2017 compo.u.simple = elementSetNames;
2020 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2025 static int send_SRW_presentRequest(const char *arg)
2027 char setstring[100];
2029 Z_SRW_PDU *sr = srw_sr;
2033 parse_show_args(arg, setstring, &setno, &nos);
2034 sr->u.request->startRecord = odr_intdup(out, setno);
2035 sr->u.request->maximumRecords = odr_intdup(out, nos);
2037 sr->u.request->recordSchema = schema;
2038 return send_srw(sr);
2042 static void close_session (void)
2049 nmem_destroy (session_mem);
2058 void process_close(Z_Close *req)
2060 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2061 Z_Close *res = apdu->u.close;
2063 static char *reasons[] =
2068 "cost limit reached",
2070 "security violation",
2077 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2078 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2083 *res->closeReason = Z_Close_finished;
2085 printf("Sent response.\n");
2090 static int cmd_show(const char *arg)
2092 if (protocol == PROTO_HTTP)
2097 if (!send_SRW_presentRequest(arg))
2107 printf("Not connected yet\n");
2110 if (!send_presentRequest(arg))
2116 int cmd_quit(const char *arg)
2118 printf("See you later, alligator.\n");
2124 int cmd_cancel(const char *arg)
2126 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2127 Z_TriggerResourceControlRequest *req =
2128 apdu->u.triggerResourceControlRequest;
2133 printf("Session not initialized yet\n");
2138 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2140 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2143 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2144 req->resultSetWanted = &rfalse;
2147 printf("Sent cancel request\n");
2151 int send_scanrequest(const char *query, int pp, int num, const char *term)
2153 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2154 Z_ScanRequest *req = apdu->u.scanRequest;
2159 if (queryType == QueryType_CCL2RPN)
2163 struct ccl_rpn_node *rpn;
2165 rpn = ccl_find_str (bibset, query, &error, &pos);
2168 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2171 bib1.proto = PROTO_Z3950;
2172 bib1.oclass = CLASS_ATTSET;
2173 bib1.value = VAL_BIB1;
2174 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2175 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2177 printf("Couldn't convert CCL to Scan term\n");
2180 ccl_rpn_delete (rpn);
2184 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2186 if (!(req->termListAndStartPoint =
2187 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2189 const char *pqf_msg;
2191 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2192 printf("%*s^\n", off+7, "");
2193 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2194 yaz_pqf_destroy (pqf_parser);
2197 yaz_pqf_destroy (pqf_parser);
2201 if (req->termListAndStartPoint->term &&
2202 req->termListAndStartPoint->term->which == Z_Term_general &&
2203 req->termListAndStartPoint->term->u.general)
2205 req->termListAndStartPoint->term->u.general->buf =
2206 (unsigned char *) odr_strdup(out, term);
2207 req->termListAndStartPoint->term->u.general->len =
2208 req->termListAndStartPoint->term->u.general->size =
2212 req->referenceId = set_refid (out);
2213 req->num_databaseNames = num_databaseNames;
2214 req->databaseNames = databaseNames;
2215 req->numberOfTermsRequested = #
2216 req->preferredPositionInResponse = &pp;
2221 int send_sortrequest(const char *arg, int newset)
2223 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2224 Z_SortRequest *req = apdu->u.sortRequest;
2225 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2226 odr_malloc (out, sizeof(*sksl));
2232 sprintf (setstring, "%d", setnumber);
2234 sprintf (setstring, "default");
2236 req->referenceId = set_refid (out);
2238 req->num_inputResultSetNames = 1;
2239 req->inputResultSetNames = (Z_InternationalString **)
2240 odr_malloc (out, sizeof(*req->inputResultSetNames));
2241 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2243 if (newset && setnumber >= 0)
2244 sprintf (setstring, "%d", ++setnumber);
2246 req->sortedResultSetName = odr_strdup (out, setstring);
2248 req->sortSequence = yaz_sort_spec (out, arg);
2249 if (!req->sortSequence)
2251 printf ("Missing sort specifications\n");
2258 void display_term(Z_TermInfo *t)
2260 if (t->term->which == Z_Term_general)
2262 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2263 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2264 t->term->u.general->buf);
2267 printf("Term (not general)");
2268 if (t->globalOccurrences)
2269 printf (" (%d)\n", *t->globalOccurrences);
2274 void process_scanResponse(Z_ScanResponse *res)
2277 Z_Entry **entries = NULL;
2278 int num_entries = 0;
2280 printf("Received ScanResponse\n");
2281 print_refid (res->referenceId);
2282 printf("%d entries", *res->numberOfEntriesReturned);
2283 if (res->positionOfTerm)
2284 printf (", position=%d", *res->positionOfTerm);
2286 if (*res->scanStatus != Z_Scan_success)
2287 printf("Scan returned code %d\n", *res->scanStatus);
2290 if ((entries = res->entries->entries))
2291 num_entries = res->entries->num_entries;
2292 for (i = 0; i < num_entries; i++)
2294 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2295 if (entries[i]->which == Z_Entry_termInfo)
2297 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2298 display_term(entries[i]->u.termInfo);
2301 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2303 if (res->entries->nonsurrogateDiagnostics)
2304 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2305 res->entries->num_nonsurrogateDiagnostics);
2308 void process_sortResponse(Z_SortResponse *res)
2310 printf("Received SortResponse: status=");
2311 switch (*res->sortStatus)
2313 case Z_SortStatus_success:
2314 printf ("success"); break;
2315 case Z_SortStatus_partial_1:
2316 printf ("partial"); break;
2317 case Z_SortStatus_failure:
2318 printf ("failure"); break;
2320 printf ("unknown (%d)", *res->sortStatus);
2323 print_refid (res->referenceId);
2324 if (res->diagnostics)
2325 display_diagrecs(res->diagnostics,
2326 res->num_diagnostics);
2329 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2331 printf("Got deleteResultSetResponse status=%d\n",
2332 *res->deleteOperationStatus);
2333 if (res->deleteListStatuses)
2336 for (i = 0; i < res->deleteListStatuses->num; i++)
2338 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2339 *res->deleteListStatuses->elements[i]->status);
2344 int cmd_sort_generic(const char *arg, int newset)
2348 printf("Session not initialized yet\n");
2353 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2355 printf("Target doesn't support sort\n");
2360 if (send_sortrequest(arg, newset) < 0)
2367 int cmd_sort(const char *arg)
2369 return cmd_sort_generic (arg, 0);
2372 int cmd_sort_newset (const char *arg)
2374 return cmd_sort_generic (arg, 1);
2377 int cmd_scan(const char *arg)
2386 printf("Session not initialized yet\n");
2390 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2392 printf("Target doesn't support scan\n");
2397 strcpy (last_scan_query, arg);
2398 if (send_scanrequest(arg, 1, 20, 0) < 0)
2403 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2409 int cmd_schema(const char *arg)
2414 schema = xstrdup(arg);
2418 int cmd_format(const char *arg)
2423 printf("Usage: format <recordsyntax>\n");
2426 nsyntax = oid_getvalbyname (arg);
2427 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2429 printf ("unknown record syntax\n");
2432 recordsyntax = nsyntax;
2436 int cmd_elements(const char *arg)
2438 static Z_ElementSetNames esn;
2439 static char what[100];
2443 elementSetNames = 0;
2447 esn.which = Z_ElementSetNames_generic;
2448 esn.u.generic = what;
2449 elementSetNames = &esn;
2453 int cmd_attributeset(const char *arg)
2459 printf("Usage: attributeset <setname>\n");
2462 sscanf(arg, "%s", what);
2463 if (p_query_attset (what))
2465 printf("Unknown attribute set name\n");
2471 int cmd_querytype (const char *arg)
2473 if (!strcmp (arg, "ccl"))
2474 queryType = QueryType_CCL;
2475 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2476 queryType = QueryType_Prefix;
2477 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2478 queryType = QueryType_CCL2RPN;
2479 else if (!strcmp(arg, "cql"))
2480 queryType = QueryType_CQL;
2483 printf ("Querytype must be one of:\n");
2484 printf (" prefix - Prefix query\n");
2485 printf (" ccl - CCL query\n");
2486 printf (" ccl2rpn - CCL query converted to RPN\n");
2487 printf (" cql - CQL\n");
2493 int cmd_refid (const char *arg)
2499 refid = (char *) xmalloc (strlen(arg)+1);
2500 strcpy (refid, arg);
2505 int cmd_close(const char *arg)
2514 apdu = zget_APDU(out, Z_APDU_close);
2515 req = apdu->u.close;
2516 *req->closeReason = Z_Close_finished;
2518 printf("Sent close request.\n");
2523 int cmd_packagename(const char* arg)
2525 xfree (esPackageName);
2526 esPackageName = NULL;
2529 esPackageName = (char *) xmalloc (strlen(arg)+1);
2530 strcpy (esPackageName, arg);
2535 int cmd_proxy(const char* arg)
2546 yazProxy = (char *) xmalloc (strlen(arg)+1);
2547 strcpy (yazProxy, arg);
2552 int cmd_charset(const char* arg)
2554 char l1[30], l2[30];
2557 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2559 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2565 yazCharset = xstrdup(l1);
2568 odr_set_charset (out, l1, l2);
2569 odr_set_charset (in, l2, l1);
2574 int cmd_lang(const char* arg)
2577 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2584 yazLang = (char *) xmalloc (strlen(arg)+1);
2585 strcpy (yazLang, arg);
2590 int cmd_source(const char* arg)
2592 /* first should open the file and read one line at a time.. */
2594 char line[1024], *cp;
2597 fprintf(stderr,"Error in source command use a filename\n");
2601 includeFile = fopen (arg, "r");
2604 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2608 while(!feof(includeFile)) {
2609 memset(line,0,sizeof(line));
2610 fgets(line,sizeof(line),includeFile);
2612 if(strlen(line) < 2) continue;
2613 if(line[0] == '#') continue;
2615 if ((cp = strrchr (line, '\n')))
2618 process_cmd_line(line);
2621 if(fclose(includeFile)<0) {
2622 perror("unable to close include file");
2628 int cmd_subshell(const char* args)
2633 system(getenv("SHELL"));
2639 int cmd_set_berfile(const char *arg)
2641 if (ber_file && ber_file != stdout && ber_file != stderr)
2643 if (!strcmp(arg, ""))
2645 else if (!strcmp(arg, "-"))
2648 ber_file = fopen(arg, "a");
2652 int cmd_set_apdufile(const char *arg)
2654 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2656 if (!strcmp(arg, ""))
2658 else if (!strcmp(arg, "-"))
2662 apdu_file = fopen(arg, "a");
2664 perror("unable to open apdu log file");
2667 odr_setprint(print, apdu_file);
2671 int cmd_set_cclfile(const char* arg)
2675 bibset = ccl_qual_mk ();
2676 inf = fopen (arg, "r");
2678 perror("unable to open CCL file");
2681 ccl_qual_file (bibset, inf);
2684 strcpy(ccl_fields,arg);
2688 int cmd_set_auto_reconnect(const char* arg)
2690 if(strlen(arg)==0) {
2691 auto_reconnect = ! auto_reconnect;
2692 } else if(strcmp(arg,"on")==0) {
2694 } else if(strcmp(arg,"off")==0) {
2697 printf("Error use on or off\n");
2702 printf("Set auto reconnect enabled.\n");
2704 printf("Set auto reconnect disabled.\n");
2709 int cmd_set_marcdump(const char* arg)
2711 if(marc_file && marc_file != stderr) { /* don't close stdout*/
2715 if (!strcmp(arg, ""))
2717 else if (!strcmp(arg, "-"))
2721 marc_file = fopen(arg, "a");
2723 perror("unable to open marc log file");
2728 int cmd_set_proxy(const char* arg)
2730 if(yazProxy) free(yazProxy);
2733 if(strlen(arg) > 1) {
2734 yazProxy=strdup(arg);
2740 this command takes 3 arge {name class oid}
2742 int cmd_register_oid(const char* args) {
2747 {"appctx",CLASS_APPCTX},
2748 {"absyn",CLASS_ABSYN},
2749 {"attset",CLASS_ATTSET},
2750 {"transyn",CLASS_TRANSYN},
2751 {"diagset",CLASS_DIAGSET},
2752 {"recsyn",CLASS_RECSYN},
2753 {"resform",CLASS_RESFORM},
2754 {"accform",CLASS_ACCFORM},
2755 {"extserv",CLASS_EXTSERV},
2756 {"userinfo",CLASS_USERINFO},
2757 {"elemspec",CLASS_ELEMSPEC},
2758 {"varset",CLASS_VARSET},
2759 {"schema",CLASS_SCHEMA},
2760 {"tagset",CLASS_TAGSET},
2761 {"general",CLASS_GENERAL},
2762 {0,(enum oid_class) 0}
2764 char oname_str[101], oclass_str[101], oid_str[101];
2767 oid_class oidclass = CLASS_GENERAL;
2768 int val = 0, oid[OID_SIZE];
2769 struct oident * new_oident=NULL;
2771 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2772 oname_str,oclass_str, oid_str) < 1) {
2773 printf("Error in regristrate command \n");
2777 for (i = 0; oid_classes[i].className; i++) {
2778 if (!strcmp(oid_classes[i].className, oclass_str))
2780 oidclass=oid_classes[i].oclass;
2785 if(!(oid_classes[i].className)) {
2786 printf("Unknonwn oid class %s\n",oclass_str);
2794 while (isdigit (*name))
2796 val = val*10 + (*name - '0');
2809 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2810 if(strcmp(new_oident->desc,oname_str)) {
2811 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2817 int cmd_push_command(const char* arg)
2819 #if HAVE_READLINE_HISTORY_H
2823 fprintf(stderr,"Not compiled with the readline/history module\n");
2828 void source_rcfile()
2830 /* Look for a $HOME/.yazclientrc and source it if it exists */
2831 struct stat statbuf;
2833 char* homedir=getenv("HOME");
2835 if(!homedir) return;
2837 sprintf(buffer,"%s/.yazclientrc",homedir);
2839 if(stat(buffer,&statbuf)==0) {
2843 if(stat(".yazclientrc",&statbuf)==0) {
2844 cmd_source(".yazclientrc");
2849 static void initialize(void)
2854 if (!(out = odr_createmem(ODR_ENCODE)) ||
2855 !(in = odr_createmem(ODR_DECODE)) ||
2856 !(print = odr_createmem(ODR_PRINT)))
2858 fprintf(stderr, "failed to allocate ODR streams\n");
2863 setvbuf(stdout, 0, _IONBF, 0);
2865 odr_setprint(print, apdu_file);
2867 bibset = ccl_qual_mk ();
2868 inf = fopen (ccl_fields, "r");
2871 ccl_qual_file (bibset, inf);
2874 #if HAVE_READLINE_READLINE_H
2875 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2879 for(i=0; i<maxOtherInfosSupported; ++i) {
2880 extraOtherInfos[i].oidval = -1;
2887 #if HAVE_GETTIMEOFDAY
2888 struct timeval tv_start, tv_end;
2892 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
2896 printf ("Received SRW SearchRetrieveResponse\n");
2898 for (i = 0; i<res->num_diagnostics; i++)
2900 printf ("SRW diagnostic %d %s\n",
2901 *res->diagnostics[i].code,
2902 yaz_diag_srw_str(*res->diagnostics[i].code));
2904 if (res->diagnostics[i].details)
2905 printf ("Details: %s\n", res->diagnostics[i].details);
2907 if (res->numberOfRecords)
2908 printf ("Number of hits: %d\n", *res->numberOfRecords);
2909 for (i = 0; i<res->num_records; i++)
2911 Z_SRW_record *rec = res->records + i;
2913 if (rec->recordPosition)
2915 printf ("pos=%d", *rec->recordPosition);
2916 setno = *rec->recordPosition + 1;
2918 if (rec->recordSchema)
2919 printf (" schema=%s", rec->recordSchema);
2921 if (rec->recordData_buf && rec->recordData_len)
2923 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
2929 static void http_response(Z_HTTP_Response *hres)
2932 const char *content_type = z_HTTP_header_lookup(hres->headers,
2934 const char *connection_head = z_HTTP_header_lookup(hres->headers,
2936 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
2938 Z_SOAP *soap_package = 0;
2939 ODR o = odr_createmem(ODR_DECODE);
2940 Z_SOAP_Handler soap_handlers[2] = {
2941 {"http://www.loc.gov/zing/srw/v1.0/", 0,
2942 (Z_SOAP_fun) yaz_srw_codec},
2945 ret = z_soap_codec(o, &soap_package,
2946 &hres->content_buf, &hres->content_len,
2948 if (!ret && soap_package->which == Z_SOAP_generic &&
2949 soap_package->u.generic->no == 0)
2951 Z_SRW_PDU *sr = soap_package->u.generic->p;
2952 if (sr->which == Z_SRW_searchRetrieve_response)
2953 handle_srw_response(sr->u.response);
2957 else if (!ret && (soap_package->which == Z_SOAP_fault
2958 || soap_package->which == Z_SOAP_error))
2960 printf ("HTTP Error Status=%d\n", hres->code);
2961 printf ("SOAP Fault code %s\n",
2962 soap_package->u.fault->fault_code);
2963 printf ("SOAP Fault string %s\n",
2964 soap_package->u.fault->fault_string);
2972 if (hres->code != 200)
2974 printf ("HTTP Error Status=%d\n", hres->code);
2978 printf ("Decoding of SRW package failed\n");
2982 if (!strcmp(hres->version, "1.0"))
2984 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
2985 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
2990 /* HTTP 1.1: only if no close we stay alive .. */
2991 if (connection_head && !strcmp(connection_head, "close"))
2997 void wait_and_handle_response()
2999 int reconnect_ok = 1;
3002 int netbufferlen = 0;
3007 res = cs_get(conn, &netbuffer, &netbufferlen);
3008 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3019 buf_out = odr_getbuf(out, &len_out, 0);
3021 cs_put(conn, buf_out, len_out);
3029 printf("Target closed connection\n");
3034 odr_reset(in); /* release APDU from last round */
3036 odr_setbuf(in, netbuffer, res, 0);
3038 if (!z_GDU(in, &gdu, 0, 0))
3040 FILE *f = ber_file ? ber_file : stdout;
3041 odr_perror(in, "Decoding incoming APDU");
3042 fprintf(f, "[Near %d]\n", odr_offset(in));
3043 fprintf(f, "Packet dump:\n---------\n");
3044 odr_dumpBER(f, netbuffer, res);
3045 fprintf(f, "---------\n");
3047 z_GDU(print, &gdu, 0, 0);
3052 odr_dumpBER(ber_file, netbuffer, res);
3053 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3055 odr_perror(print, "Failed to print incoming APDU");
3059 if (gdu->which == Z_GDU_Z3950)
3061 Z_APDU *apdu = gdu->u.z3950;
3064 case Z_APDU_initResponse:
3065 process_initResponse(apdu->u.initResponse);
3067 case Z_APDU_searchResponse:
3068 process_searchResponse(apdu->u.searchResponse);
3070 case Z_APDU_scanResponse:
3071 process_scanResponse(apdu->u.scanResponse);
3073 case Z_APDU_presentResponse:
3074 print_refid (apdu->u.presentResponse->referenceId);
3076 *apdu->u.presentResponse->numberOfRecordsReturned;
3077 if (apdu->u.presentResponse->records)
3078 display_records(apdu->u.presentResponse->records);
3080 printf("No records.\n");
3081 printf ("nextResultSetPosition = %d\n",
3082 *apdu->u.presentResponse->nextResultSetPosition);
3084 case Z_APDU_sortResponse:
3085 process_sortResponse(apdu->u.sortResponse);
3087 case Z_APDU_extendedServicesResponse:
3088 printf("Got extended services response\n");
3089 process_ESResponse(apdu->u.extendedServicesResponse);
3092 printf("Target has closed the association.\n");
3093 process_close(apdu->u.close);
3095 case Z_APDU_resourceControlRequest:
3096 process_resourceControlRequest
3097 (apdu->u.resourceControlRequest);
3099 case Z_APDU_deleteResultSetResponse:
3100 process_deleteResultSetResponse(apdu->u.
3101 deleteResultSetResponse);
3104 printf("Received unknown APDU type (%d).\n",
3110 else if (gdu->which == Z_GDU_HTTP_Response)
3112 http_response(gdu->u.HTTP_Response);
3115 if (conn && !cs_more(conn))
3120 #if HAVE_GETTIMEOFDAY
3121 gettimeofday (&tv_end, 0);
3123 printf ("S/U S/U=%ld/%ld %ld/%ld",
3124 (long) tv_start.tv_sec,
3125 (long) tv_start.tv_usec,
3126 (long) tv_end.tv_sec,
3127 (long) tv_end.tv_usec);
3129 printf ("Elapsed: %.6f\n",
3130 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3131 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3138 int cmd_cclparse(const char* arg)
3141 struct ccl_rpn_node *rpn=NULL;
3144 rpn = ccl_find_str (bibset, arg, &error, &pos);
3147 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3148 printf ("%s\n", ccl_err_msg (error));
3154 ccl_pr_tree(rpn, stdout);
3158 ccl_rpn_delete(rpn);
3166 int cmd_set_otherinfo(const char* args)
3168 char oid[101], otherinfoString[101];
3173 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3175 /* reset this otherinfo */
3176 if(otherinfoNo>=maxOtherInfosSupported) {
3177 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3179 extraOtherInfos[otherinfoNo].oidval = -1;
3180 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3184 printf("Error in set_otherinfo command \n");
3188 if(otherinfoNo>=maxOtherInfosSupported) {
3189 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3193 oidval = oid_getvalbyname (oid);
3195 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3198 extraOtherInfos[otherinfoNo].oidval = oidval;
3199 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3200 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3205 int cmd_list_otherinfo(const char* args)
3209 if(strlen(args)>0) {
3211 if( i >= maxOtherInfosSupported ) {
3212 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3216 if(extraOtherInfos[i].oidval != -1)
3217 printf(" otherinfo %d %s %s\n",
3219 yaz_z3950_oid_value_to_str(
3220 (enum oid_value) extraOtherInfos[i].oidval,
3222 extraOtherInfos[i].value);
3225 for(i=0; i<maxOtherInfosSupported; ++i) {
3226 if(extraOtherInfos[i].oidval != -1)
3227 printf(" otherinfo %d %s %s\n",
3229 yaz_z3950_oid_value_to_str(
3230 (enum oid_value) extraOtherInfos[i].oidval,
3232 extraOtherInfos[i].value);
3240 int cmd_list_all(const char* args) {
3243 /* connection options */
3245 printf("Connected to : %s\n",last_open_command);
3247 if(last_open_command)
3248 printf("Not connected to : %s\n",last_open_command);
3250 printf("Not connected : \n");
3253 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3255 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3258 printf("Authentication : none\n");
3260 switch(auth->which) {
3261 case Z_IdAuthentication_idPass:
3262 printf("Authentication : IdPass\n");
3263 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3264 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3265 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3267 case Z_IdAuthentication_open:
3268 printf("Authentication : psOpen\n");
3269 printf(" Open string : %s\n",auth->u.open);
3272 printf("Authentication : Unknown\n");
3275 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
3279 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3283 printf("CCL file : %s\n",ccl_fields);
3284 printf("Query type : %s\n",query_type_as_string(queryType));
3286 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3288 /* piggy back options */
3289 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3291 /* print present related options */
3292 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3293 printf("Schema : %s\n",schema);
3294 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3296 /* loging options */
3297 printf("APDU log : %s\n",apdu_file?"on":"off");
3298 printf("Record log : %s\n",marc_file?"on":"off");
3301 printf("Other Info: \n");
3302 cmd_list_otherinfo("");
3307 int cmd_clear_otherinfo(const char* args)
3309 if(strlen(args)>0) {
3311 otherinfoNo = atoi(args);
3312 if( otherinfoNo >= maxOtherInfosSupported ) {
3313 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3317 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3318 /* only clear if set. */
3319 extraOtherInfos[otherinfoNo].oidval=-1;
3320 free(extraOtherInfos[otherinfoNo].value);
3325 for(i=0; i<maxOtherInfosSupported; ++i) {
3326 if (extraOtherInfos[i].oidval!=-1 ) {
3327 extraOtherInfos[i].oidval=-1;
3328 free(extraOtherInfos[i].value);
3335 static int cmd_help (const char *line);
3337 typedef char *(*completerFunctionType)(const char *text, int state);
3341 int (*fun)(const char *arg);
3343 completerFunctionType rl_completerfunction;
3344 int complete_filenames;
3345 char **local_tabcompletes;
3347 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3348 {"quit", cmd_quit, "",NULL,0,NULL},
3349 {"find", cmd_find, "<query>",NULL,0,NULL},
3350 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3351 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3352 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3353 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3354 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3355 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3356 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3357 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3358 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3359 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3360 {"status", cmd_status, "",NULL,0,NULL},
3361 {"setnames", cmd_setnames, "",NULL,0,NULL},
3362 {"cancel", cmd_cancel, "",NULL,0,NULL},
3363 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3364 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3365 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3366 {"close", cmd_close, "",NULL,0,NULL},
3367 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3368 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3369 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3370 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3371 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3372 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3373 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3374 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3375 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3376 {".", cmd_source, "<filename>",NULL,1,NULL},
3377 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3378 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3379 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3380 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3381 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3382 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3383 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3384 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3385 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3386 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3387 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3388 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3389 {"list_all",cmd_list_all,"",NULL,0,NULL},
3390 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3391 /* Server Admin Functions */
3392 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3393 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3394 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3395 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3396 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3397 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3398 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3399 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3400 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3401 {"help", cmd_help, "", NULL,0,NULL},
3405 static int cmd_help (const char *line)
3411 sscanf (line, "%20s", topic);
3414 printf("Commands:\n");
3415 for (i = 0; cmd_array[i].cmd; i++)
3416 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3417 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3418 if (strcmp (topic, "find") == 0)
3421 printf (" \"term\" Simple Term\n");
3422 printf (" @attr [attset] type=value op Attribute\n");
3423 printf (" @and opl opr And\n");
3424 printf (" @or opl opr Or\n");
3425 printf (" @not opl opr And-Not\n");
3426 printf (" @set set Result set\n");
3428 printf ("Bib-1 attribute types\n");
3430 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3431 printf ("2=Relation: ");
3432 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3433 printf ("3=Position: ");
3434 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3435 printf ("4=Structure: ");
3436 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3437 printf ("5=Truncation: ");
3438 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3439 printf ("6=Completeness:");
3440 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3445 int cmd_register_tab(const char* arg) {
3447 char command[101], tabargument[101];
3452 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3456 /* locate the amdn in the list */
3457 for (i = 0; cmd_array[i].cmd; i++) {
3458 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3463 if(!cmd_array[i].cmd) {
3464 fprintf(stderr,"Unknown command %s\n",command);
3469 if(!cmd_array[i].local_tabcompletes)
3470 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3474 tabslist = cmd_array[i].local_tabcompletes;
3475 for(;tabslist && *tabslist;tabslist++) {
3479 cmd_array[i].local_tabcompletes = (char **)
3480 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3481 tabslist=cmd_array[i].local_tabcompletes;
3482 tabslist[num_of_tabs]=strdup(tabargument);
3483 tabslist[num_of_tabs+1]=NULL;
3488 void process_cmd_line(char* line)
3491 char word[32], arg[1024];
3493 #if HAVE_GETTIMEOFDAY
3494 gettimeofday (&tv_start, 0);
3497 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3499 strcpy(word, last_cmd);
3504 strcpy(last_cmd, word);
3506 /* removed tailing spaces from the arg command */
3509 char* lastnonspace=NULL;
3517 *(++lastnonspace) = 0;
3520 for (i = 0; cmd_array[i].cmd; i++)
3521 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3523 res = (*cmd_array[i].fun)(arg);
3527 if (!cmd_array[i].cmd) /* dump our help-screen */
3529 printf("Unknown command: %s.\n", word);
3530 printf("use help for list of commands\n");
3531 /* cmd_help (""); */
3535 if(apdu_file) fflush(apdu_file);
3538 wait_and_handle_response();
3547 char *command_generator(const char *text, int state)
3553 for( ; cmd_array[idx].cmd; ++idx) {
3554 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3555 ++idx; /* skip this entry on the next run */
3556 return strdup(cmd_array[idx-1].cmd);
3564 This function only known how to complete on the first word
3566 char ** readline_completer(char *text, int start, int end) {
3567 #if HAVE_READLINE_READLINE_H
3569 completerFunctionType completerToUse;
3572 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3573 char** res=rl_completion_matches(text,
3576 char** res=completion_matches(text,
3577 (CPFunction*)command_generator);
3579 rl_attempted_completion_over = 1;
3582 char arg[1024],word[32];
3584 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3585 rl_attempted_completion_over = 1;
3589 for (i = 0; cmd_array[i].cmd; i++) {
3590 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3595 if(!cmd_array[i].cmd) return NULL;
3597 curret_global_list = cmd_array[i].local_tabcompletes;
3599 completerToUse = cmd_array[i].rl_completerfunction;
3600 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3601 completerToUse = default_completer;
3603 if(completerToUse) {
3604 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3606 rl_completion_matches(text,
3610 completion_matches(text,
3611 (CPFunction*)completerToUse);
3613 if(!cmd_array[i].complete_filenames)
3614 rl_attempted_completion_over = 1;
3617 if(!cmd_array[i].complete_filenames)
3618 rl_attempted_completion_over = 1;
3628 static void client(void)
3634 #if HAVE_GETTIMEOFDAY
3635 gettimeofday (&tv_start, 0);
3640 char *line_in = NULL;
3641 #if HAVE_READLINE_READLINE_H
3644 line_in=readline(C_PROMPT);
3647 #if HAVE_READLINE_HISTORY_H
3649 add_history(line_in);
3651 strncpy(line, line_in, 1023);
3660 if (!fgets(line, 1023, stdin))
3662 if ((end_p = strchr (line, '\n')))
3665 process_cmd_line(line);
3669 int main(int argc, char **argv)
3672 char *open_command = 0;
3673 char *auth_command = 0;
3678 if (!setlocale(LC_CTYPE, ""))
3679 fprintf (stderr, "setlocale failed\n");
3683 codeset = nl_langinfo(CODESET);
3687 while ((ret = options("k:c:a:b:m:v:p:u:t:", argv, argc, &arg)) != -2)
3694 open_command = (char *) xmalloc (strlen(arg)+6);
3695 strcpy (open_command, "open ");
3696 strcat (open_command, arg);
3700 kilobytes = atoi(arg);
3703 if (!(marc_file = fopen (arg, "a")))
3713 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3714 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3717 if (!strcmp(arg, "-"))
3720 ber_file=fopen(arg, "a");
3723 if (!strcmp(arg, "-"))
3726 apdu_file=fopen(arg, "a");
3729 yazProxy=strdup(arg);
3734 auth_command = (char *) xmalloc (strlen(arg)+6);
3735 strcpy (auth_command, "auth ");
3736 strcat (auth_command, arg);
3740 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3743 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3744 "[-b berdump] [-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3745 "[-k size] [<server-addr>]\n",
3753 #ifdef HAVE_GETTIMEOFDAY
3754 gettimeofday (&tv_start, 0);
3756 process_cmd_line (auth_command);
3757 #if HAVE_READLINE_HISTORY_H
3758 add_history(auth_command);
3760 xfree(auth_command);
3764 #ifdef HAVE_GETTIMEOFDAY
3765 gettimeofday (&tv_start, 0);
3767 process_cmd_line (open_command);
3768 #if HAVE_READLINE_HISTORY_H
3769 add_history(open_command);
3771 xfree(open_command);
3782 * vim600: sw=4 ts=8 fdm=marker
3783 * vim<600: sw=4 ts=8