2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.188 2003-04-29 21:13:08 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 cmd_base(const char *arg)
408 printf("Usage: base <database> <database> ...\n");
411 for (i = 0; i<num_databaseNames; i++)
412 xfree (databaseNames[i]);
413 num_databaseNames = 0;
417 if (!(cp = strchr(arg, ' ')))
418 cp = arg + strlen(arg);
421 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
422 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
423 databaseNames[num_databaseNames][cp - arg] = '\0';
425 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
437 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
439 if(last_open_command != arg)
441 if(last_open_command) xfree(last_open_command);
442 last_open_command = xstrdup(new_open_command);
446 int cmd_open(const char *arg)
448 static char cur_host[200];
451 strncpy (cur_host, arg, sizeof(cur_host)-1);
452 cur_host[sizeof(cur_host)-1] = 0;
454 return session_connect(cur_host);
457 int session_connect(const char *arg)
460 char type_and_host[101];
461 const char *basep = 0;
464 printf("Already connected.\n");
470 nmem_destroy (session_mem);
474 cs_get_host_args(arg, &basep);
476 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
477 type_and_host[sizeof(type_and_host)-1] = '\0';
479 cmd_open_remember_last_open_command(arg,type_and_host);
482 conn = cs_create_host(yazProxy, 1, &add);
484 conn = cs_create_host(arg, 1, &add);
487 printf ("Couldn't create comstack\n");
492 if (conn->protocol == PROTO_Z3950)
494 printf ("SRW not enabled in this YAZ\n");
500 printf("Connecting...");
502 if (cs_connect(conn, add) < 0)
504 printf ("error = %s\n", cs_strerror(conn));
505 if (conn->cerrno == CSYSERR)
508 yaz_strerror(msg, sizeof(msg));
509 printf ("%s\n", msg);
518 if (conn->protocol == PROTO_Z3950)
520 send_initRequest(type_and_host);
530 if(!( auto_reconnect && last_open_command) ) return ;
532 open_command = (char *) xmalloc (strlen(last_open_command)+6);
533 strcpy (open_command, "open ");
535 strcat (open_command, last_open_command);
537 process_cmd_line(open_command);
542 int cmd_authentication(const char *arg)
544 static Z_IdAuthentication au;
545 static char user[40], group[40], pass[40];
546 static Z_IdPass idPass;
551 printf("Auth field set to null\n");
555 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
558 printf("Auth field set to null\n");
564 au.which = Z_IdAuthentication_open;
570 au.which = Z_IdAuthentication_idPass;
571 au.u.idPass = &idPass;
572 idPass.groupId = NULL;
573 idPass.userId = user;
574 idPass.password = group;
579 au.which = Z_IdAuthentication_idPass;
580 au.u.idPass = &idPass;
581 idPass.groupId = group;
582 idPass.userId = user;
583 idPass.password = pass;
588 /* SEARCH SERVICE ------------------------------ */
589 static void display_record(Z_External *r);
591 static void print_record(const unsigned char *buf, size_t len)
594 print_stringn (buf, len);
595 /* add newline if not already added ... */
596 if (i <= 0 || buf[i-1] != '\n')
600 static void display_record(Z_External *r)
602 oident *ent = oid_getentbyoid(r->direct_reference);
606 * Tell the user what we got.
608 if (r->direct_reference)
610 printf("Record type: ");
612 printf("%s\n", ent->desc);
613 else if (!odr_oid(print, &r->direct_reference, 0, 0))
615 odr_perror(print, "print oid");
619 /* Check if this is a known, ASN.1 type tucked away in an octet string */
620 if (ent && r->which == Z_External_octet)
622 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
628 * Call the given decoder to process the record.
630 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
631 r->u.octet_aligned->len, 0);
632 if (!(*type->fun)(in, (char **)&rr, 0, 0))
634 odr_perror(in, "Decoding constructed record.");
635 fprintf(stdout, "[Near %d]\n", odr_offset(in));
636 fprintf(stdout, "Packet dump:\n---------\n");
637 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
638 r->u.octet_aligned->len);
639 fprintf(stdout, "---------\n");
641 /* note just ignores the error ant print the bytes form the octet_aligned later */
644 * Note: we throw away the original, BER-encoded record here.
645 * Do something else with it if you want to keep it.
647 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
648 r->which = type->what;
652 if (ent && ent->oclass != CLASS_RECSYN)
654 if (ent && ent->value == VAL_SOIF)
655 print_record((const unsigned char *) r->u.octet_aligned->buf,
656 r->u.octet_aligned->len);
657 else if (r->which == Z_External_octet)
659 const char *octet_buf = (char*)r->u.octet_aligned->buf;
660 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
661 ent->value == VAL_HTML)
663 print_record((const unsigned char *) octet_buf,
664 r->u.octet_aligned->len);
666 else if (ent->value == VAL_POSTSCRIPT)
668 int size = r->u.octet_aligned->len;
671 print_record((const unsigned char *) octet_buf, size);
676 #if AVOID_MARC_DECODE
677 /* primitive check for a marc OID 5.1-29 except 16 */
678 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
679 ent->oidsuffix[1] != 16
688 yaz_marc_t mt = yaz_marc_create();
690 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
694 if (ent->value == VAL_USMARC)
696 if (octet_buf[9] == 'a')
706 printf ("convert from %s to %s\n", from, codeset);
707 cd = yaz_iconv_open(codeset, from);
710 fwrite (result, 1, rlen, stdout);
714 size_t inbytesleft = rlen;
715 const char *inp = result;
719 size_t outbytesleft = sizeof(outbuf);
721 size_t r = yaz_iconv (cd, (char**) &inp,
723 &outp, &outbytesleft);
724 if (r == (size_t) (-1))
726 int e = yaz_iconv_error(cd);
727 if (e != YAZ_ICONV_E2BIG)
730 fwrite (outbuf, outp - outbuf, 1, stdout);
736 printf ("bad MARC. Dumping as it is:\n");
737 print_record((const unsigned char*) octet_buf,
738 r->u.octet_aligned->len);
740 yaz_marc_destroy(mt);
746 print_record((const unsigned char*) octet_buf,
747 r->u.octet_aligned->len);
751 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
753 else if (ent && ent->value == VAL_SUTRS)
755 if (r->which != Z_External_sutrs)
757 printf("Expecting single SUTRS type for SUTRS.\n");
760 print_record(r->u.sutrs->buf, r->u.sutrs->len);
762 else if (ent && ent->value == VAL_GRS1)
765 if (r->which != Z_External_grs1)
767 printf("Expecting single GRS type for GRS.\n");
771 yaz_display_grs1(w, r->u.grs1, 0);
777 printf("Unknown record representation.\n");
778 if (!z_External(print, &r, 0, 0))
780 odr_perror(print, "Printing external");
786 static void display_diagrecs(Z_DiagRec **pp, int num)
790 Z_DefaultDiagFormat *r;
792 printf("Diagnostic message(s) from database:\n");
793 for (i = 0; i<num; i++)
795 Z_DiagRec *p = pp[i];
796 if (p->which != Z_DiagRec_defaultFormat)
798 printf("Diagnostic record not in default format.\n");
802 r = p->u.defaultFormat;
803 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
804 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
805 printf("Missing or unknown diagset\n");
806 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
809 case Z_DefaultDiagFormat_v2Addinfo:
810 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
812 case Z_DefaultDiagFormat_v3Addinfo:
813 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
820 static void display_nameplusrecord(Z_NamePlusRecord *p)
823 printf("[%s]", p->databaseName);
824 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
825 display_diagrecs(&p->u.surrogateDiagnostic, 1);
826 else if (p->which == Z_NamePlusRecord_databaseRecord)
827 display_record(p->u.databaseRecord);
830 static void display_records(Z_Records *p)
834 if (p->which == Z_Records_NSD)
836 Z_DiagRec dr, *dr_p = &dr;
837 dr.which = Z_DiagRec_defaultFormat;
838 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
839 display_diagrecs (&dr_p, 1);
841 else if (p->which == Z_Records_multipleNSD)
842 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
843 p->u.multipleNonSurDiagnostics->num_diagRecs);
846 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
847 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
848 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
852 static int send_deleteResultSetRequest(const char *arg)
857 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
858 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
860 req->referenceId = set_refid (out);
862 req->num_resultSetList =
863 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
864 names[0], names[1], names[2], names[3],
865 names[4], names[5], names[6], names[7]);
867 req->deleteFunction = (int *)
868 odr_malloc (out, sizeof(*req->deleteFunction));
869 if (req->num_resultSetList > 0)
871 *req->deleteFunction = Z_DeleteRequest_list;
872 req->resultSetList = (char **)
873 odr_malloc (out, sizeof(*req->resultSetList)*
874 req->num_resultSetList);
875 for (i = 0; i<req->num_resultSetList; i++)
876 req->resultSetList[i] = names[i];
880 *req->deleteFunction = Z_DeleteRequest_all;
881 req->resultSetList = 0;
885 printf("Sent deleteResultSetRequest.\n");
890 static int send_srw(Z_SRW_PDU *sr)
892 const char *charset = 0;
893 const char *host_port = 0;
894 const char *path = "/";
896 Z_SOAP_Handler h[2] = {
897 {"http://www.loc.gov/zing/srw/v1.0/", 0, (Z_SOAP_fun) yaz_srw_codec},
900 ODR o = odr_createmem(ODR_ENCODE);
902 Z_SOAP *p = odr_malloc(o, sizeof(*p));
906 gdu = z_get_HTTP_Request(out);
907 gdu->u.HTTP_Request->path = odr_strdup(out, path);
911 const char *cp0 = strstr(host_port, "://");
918 cp1 = strchr(cp0, '/');
920 cp1 = cp0+strlen(cp0);
924 char *h = odr_malloc(out, cp1 - cp0 + 1);
925 memcpy (h, cp0, cp1 - cp0);
927 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
932 strcpy(ctype, "text/xml");
933 if (charset && strlen(charset) < 20)
935 strcat(ctype, "; charset=");
936 strcat(ctype, charset);
938 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
939 "Content-Type", ctype);
940 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
941 "SOAPAction", "\"\"");
942 p->which = Z_SOAP_generic;
943 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
944 p->u.generic->no = 0;
945 p->u.generic->ns = 0;
946 p->u.generic->p = sr;
947 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
949 ret = z_soap_codec_enc(o, &p,
950 &gdu->u.HTTP_Request->content_buf,
951 &gdu->u.HTTP_Request->content_len, h,
954 if (z_GDU(out, &gdu, 0, 0))
960 buf_out = odr_getbuf(out, &len_out, 0);
962 /* we don't odr_reset(out), since we may need the buffer again */
964 r = cs_put(conn, buf_out, len_out);
976 static int send_SRW_searchRequest(const char *arg)
982 assert(srw_sr_odr_out == 0);
983 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
985 odr_reset(srw_sr_odr_out);
987 /* save this for later .. when fetching individual records */
988 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
989 sr->u.request->query_type = Z_SRW_query_type_cql;
990 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
992 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
993 sr->u.request->query_type = Z_SRW_query_type_cql;
994 sr->u.request->query.cql = odr_strdup(out, arg);
996 sr->u.request->recordSchema = schema;
1001 static int send_searchRequest(const char *arg)
1003 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1004 Z_SearchRequest *req = apdu->u.searchRequest;
1007 struct ccl_rpn_node *rpn = NULL;
1009 char setstring[100];
1010 Z_RPNQuery *RPNquery;
1012 YAZ_PQF_Parser pqf_parser;
1015 if (queryType == QueryType_CCL2RPN)
1017 rpn = ccl_find_str(bibset, arg, &error, &pos);
1020 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1024 req->referenceId = set_refid (out);
1025 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1027 static unsigned char big[2100];
1028 static Odr_oct bigo;
1030 /* send a very big referenceid to test transport stack etc. */
1031 memset(big, 'A', 2100);
1032 bigo.len = bigo.size = 2100;
1034 req->referenceId = &bigo;
1039 sprintf(setstring, "%d", ++setnumber);
1040 req->resultSetName = setstring;
1042 *req->smallSetUpperBound = smallSetUpperBound;
1043 *req->largeSetLowerBound = largeSetLowerBound;
1044 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1045 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1046 mediumSetPresentNumber > 0))
1050 prefsyn.proto = protocol;
1051 prefsyn.oclass = CLASS_RECSYN;
1052 prefsyn.value = recordsyntax;
1053 req->preferredRecordSyntax =
1054 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1055 req->smallSetElementSetNames =
1056 req->mediumSetElementSetNames = elementSetNames;
1058 req->num_databaseNames = num_databaseNames;
1059 req->databaseNames = databaseNames;
1061 req->query = &query;
1065 case QueryType_Prefix:
1066 query.which = Z_Query_type_1;
1067 pqf_parser = yaz_pqf_create ();
1068 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1071 const char *pqf_msg;
1073 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1074 printf("%*s^\n", off+4, "");
1075 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1077 yaz_pqf_destroy (pqf_parser);
1080 yaz_pqf_destroy (pqf_parser);
1081 query.u.type_1 = RPNquery;
1084 query.which = Z_Query_type_2;
1085 query.u.type_2 = &ccl_query;
1086 ccl_query.buf = (unsigned char*) arg;
1087 ccl_query.len = strlen(arg);
1089 case QueryType_CCL2RPN:
1090 query.which = Z_Query_type_1;
1091 RPNquery = ccl_rpn_query(out, rpn);
1094 printf ("Couldn't convert from CCL to RPN\n");
1097 query.u.type_1 = RPNquery;
1098 ccl_rpn_delete (rpn);
1101 query.which = Z_Query_type_104;
1102 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1103 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1104 ext->indirect_reference = 0;
1105 ext->descriptor = 0;
1106 ext->which = Z_External_CQL;
1107 ext->u.cql = odr_strdup(out, arg);
1108 query.u.type_104 = ext;
1111 printf ("Unsupported query type\n");
1116 printf("Sent searchRequest.\n");
1120 /* display Query Expression as part of searchResult-1 */
1121 static void display_queryExpression (Z_QueryExpression *qe)
1125 if (qe->which == Z_QueryExpression_term)
1127 if (qe->u.term->queryTerm)
1129 Z_Term *term = qe->u.term->queryTerm;
1130 switch (term->which)
1132 case Z_Term_general:
1133 printf (" %.*s", term->u.general->len, term->u.general->buf);
1135 case Z_Term_characterString:
1136 printf (" %s", term->u.characterString);
1138 case Z_Term_numeric:
1139 printf (" %d", *term->u.numeric);
1149 /* see if we can find USR:SearchResult-1 */
1150 static void display_searchResult (Z_OtherInformation *o)
1155 for (i = 0; i < o->num_elements; i++)
1157 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1159 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1161 if (ext->which == Z_External_searchResult1)
1164 Z_SearchInfoReport *sr = ext->u.searchResult1;
1165 printf ("SearchResult-1:");
1166 for (j = 0; j < sr->num; j++)
1168 if (!sr->elements[j]->subqueryExpression)
1170 display_queryExpression (
1171 sr->elements[j]->subqueryExpression);
1172 display_queryExpression (
1173 sr->elements[j]->subqueryInterpretation);
1174 display_queryExpression (
1175 sr->elements[j]->subqueryRecommendation);
1176 if (sr->elements[j]->subqueryCount)
1177 printf ("(%d)", *sr->elements[j]->subqueryCount);
1185 static int process_searchResponse(Z_SearchResponse *res)
1187 printf ("Received SearchResponse.\n");
1188 print_refid (res->referenceId);
1189 if (*res->searchStatus)
1190 printf("Search was a success.\n");
1192 printf("Search was a bloomin' failure.\n");
1193 printf("Number of hits: %d", *res->resultCount);
1195 printf (", setno %d", setnumber);
1197 display_searchResult (res->additionalSearchInfo);
1198 printf("records returned: %d\n",
1199 *res->numberOfRecordsReturned);
1200 setno += *res->numberOfRecordsReturned;
1202 display_records(res->records);
1206 static void print_level(int iLevel)
1209 for (i = 0; i < iLevel * 4; i++)
1213 static void print_int(int iLevel, const char *pTag, int *pInt)
1217 print_level(iLevel);
1218 printf("%s: %d\n", pTag, *pInt);
1222 static void print_string(int iLevel, const char *pTag, const char *pString)
1224 if (pString != NULL)
1226 print_level(iLevel);
1227 printf("%s: %s\n", pTag, pString);
1231 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1237 print_level(iLevel);
1238 printf("%s:", pTag);
1239 for (; *pInt != -1; pInt++)
1240 printf(" %d", *pInt);
1245 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1247 if (referenceId != NULL)
1251 print_level(iLevel);
1252 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1253 for (i = 0; i < referenceId->len; i++)
1254 printf("%c", referenceId->buf[i]);
1259 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1261 if (pStringNumeric != NULL)
1263 switch (pStringNumeric->which)
1265 case Z_StringOrNumeric_string:
1266 print_string(iLevel, pTag, pStringNumeric->u.string);
1269 case Z_StringOrNumeric_numeric:
1270 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1274 print_level(iLevel);
1275 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1281 static void print_universe_report_duplicate(
1283 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1285 if (pUniverseReportDuplicate != NULL)
1287 print_level(iLevel);
1288 printf("Universe Report Duplicate: \n");
1290 print_string_or_numeric(iLevel, "Hit No",
1291 pUniverseReportDuplicate->hitno);
1295 static void print_universe_report_hits(
1297 Z_UniverseReportHits *pUniverseReportHits)
1299 if (pUniverseReportHits != NULL)
1301 print_level(iLevel);
1302 printf("Universe Report Hits: \n");
1304 print_string_or_numeric(iLevel, "Database",
1305 pUniverseReportHits->database);
1306 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1310 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1312 if (pUniverseReport != NULL)
1314 print_level(iLevel);
1315 printf("Universe Report: \n");
1317 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1318 switch (pUniverseReport->which)
1320 case Z_UniverseReport_databaseHits:
1321 print_universe_report_hits(iLevel,
1322 pUniverseReport->u.databaseHits);
1325 case Z_UniverseReport_duplicate:
1326 print_universe_report_duplicate(iLevel,
1327 pUniverseReport->u.duplicate);
1331 print_level(iLevel);
1332 printf("Type: %d\n", pUniverseReport->which);
1338 static void print_external(int iLevel, Z_External *pExternal)
1340 if (pExternal != NULL)
1342 print_level(iLevel);
1343 printf("External: \n");
1345 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1346 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1347 print_string(iLevel, "Descriptor", pExternal->descriptor);
1348 switch (pExternal->which)
1350 case Z_External_universeReport:
1351 print_universe_report(iLevel, pExternal->u.universeReport);
1355 print_level(iLevel);
1356 printf("Type: %d\n", pExternal->which);
1362 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1364 printf ("Received ResourceControlRequest.\n");
1365 print_referenceId(1, req->referenceId);
1366 print_int(1, "Suspended Flag", req->suspendedFlag);
1367 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1368 print_int(1, "Response Required", req->responseRequired);
1369 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1370 print_external(1, req->resourceReport);
1374 void process_ESResponse(Z_ExtendedServicesResponse *res)
1377 switch (*res->operationStatus)
1379 case Z_ExtendedServicesResponse_done:
1382 case Z_ExtendedServicesResponse_accepted:
1383 printf ("accepted\n");
1385 case Z_ExtendedServicesResponse_failure:
1386 printf ("failure\n");
1387 display_diagrecs(res->diagnostics, res->num_diagnostics);
1390 printf ("unknown\n");
1392 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1393 (res->num_diagnostics != 0) ) {
1394 display_diagrecs(res->diagnostics, res->num_diagnostics);
1396 print_refid (res->referenceId);
1397 if (res->taskPackage &&
1398 res->taskPackage->which == Z_External_extendedService)
1400 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1401 Odr_oct *id = taskPackage->targetReference;
1402 Z_External *ext = taskPackage->taskSpecificParameters;
1406 printf ("Target Reference: ");
1407 print_stringn (id->buf, id->len);
1410 if (ext->which == Z_External_update)
1412 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1413 if (utp && utp->targetPart)
1415 Z_IUTargetPart *targetPart = utp->targetPart;
1418 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1421 Z_IUTaskPackageRecordStructure *tpr =
1422 targetPart->taskPackageRecords[i];
1423 printf ("task package record %d\n", i+1);
1424 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1426 display_record (tpr->u.record);
1430 printf ("other type\n");
1438 const char *get_ill_element (void *clientData, const char *element)
1443 static Z_External *create_external_itemRequest()
1445 struct ill_get_ctl ctl;
1446 ILL_ItemRequest *req;
1448 int item_request_size = 0;
1449 char *item_request_buf = 0;
1453 ctl.f = get_ill_element;
1455 req = ill_get_ItemRequest(&ctl, "ill", 0);
1457 printf ("ill_get_ItemRequest failed\n");
1459 if (!ill_ItemRequest (out, &req, 0, 0))
1463 ill_ItemRequest(print, &req, 0, 0);
1466 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1467 if (item_request_buf)
1468 odr_setbuf (out, item_request_buf, item_request_size, 1);
1469 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1476 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1477 oid.proto = PROTO_GENERAL;
1478 oid.oclass = CLASS_GENERAL;
1479 oid.value = VAL_ISO_ILL_1;
1481 r = (Z_External *) odr_malloc (out, sizeof(*r));
1482 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1483 r->indirect_reference = 0;
1485 r->which = Z_External_single;
1487 r->u.single_ASN1_type = (Odr_oct *)
1488 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1489 r->u.single_ASN1_type->buf = (unsigned char *)
1490 odr_malloc (out, item_request_size);
1491 r->u.single_ASN1_type->len = item_request_size;
1492 r->u.single_ASN1_type->size = item_request_size;
1493 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1496 do_hex_dump(item_request_buf,item_request_size);
1501 static Z_External *create_external_ILL_APDU(int which)
1503 struct ill_get_ctl ctl;
1506 int ill_request_size = 0;
1507 char *ill_request_buf = 0;
1511 ctl.f = get_ill_element;
1513 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1515 if (!ill_APDU (out, &ill_apdu, 0, 0))
1519 printf ("-------------------\n");
1520 ill_APDU(print, &ill_apdu, 0, 0);
1522 printf ("-------------------\n");
1524 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1525 if (ill_request_buf)
1526 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1527 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1533 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1535 oid.proto = PROTO_GENERAL;
1536 oid.oclass = CLASS_GENERAL;
1537 oid.value = VAL_ISO_ILL_1;
1539 r = (Z_External *) odr_malloc (out, sizeof(*r));
1540 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1541 r->indirect_reference = 0;
1543 r->which = Z_External_single;
1545 r->u.single_ASN1_type = (Odr_oct *)
1546 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1547 r->u.single_ASN1_type->buf = (unsigned char *)
1548 odr_malloc (out, ill_request_size);
1549 r->u.single_ASN1_type->len = ill_request_size;
1550 r->u.single_ASN1_type->size = ill_request_size;
1551 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1552 /* printf ("len = %d\n", ill_request_size); */
1553 /* do_hex_dump(ill_request_buf,ill_request_size); */
1554 /* printf("--- end of extenal\n"); */
1561 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1563 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1564 oident ItemOrderRequest;
1566 ItemOrderRequest.proto = PROTO_Z3950;
1567 ItemOrderRequest.oclass = CLASS_EXTSERV;
1568 ItemOrderRequest.value = VAL_ITEMORDER;
1570 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1571 r->indirect_reference = 0;
1574 r->which = Z_External_itemOrder;
1576 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1577 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1578 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1580 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1581 odr_malloc(out,sizeof(Z_IORequest));
1582 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1584 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1585 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1586 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1587 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1588 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1589 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1591 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1592 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1593 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1595 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1596 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1597 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1598 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1600 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1601 (int *) odr_malloc(out, sizeof(int));
1602 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1604 if (!strcmp (type, "item") || !strcmp(type, "2"))
1606 printf ("using item-request\n");
1607 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1608 create_external_itemRequest();
1610 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1612 printf ("using ILL-request\n");
1613 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1614 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1616 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1618 const char *xml_buf =
1620 " <type>request</type>\n"
1621 " <libraryNo>000200</libraryNo>\n"
1622 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1624 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1625 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1628 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1633 static int send_itemorder(const char *type, int itemno)
1635 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1636 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1637 oident ItemOrderRequest;
1639 ItemOrderRequest.proto = PROTO_Z3950;
1640 ItemOrderRequest.oclass = CLASS_EXTSERV;
1641 ItemOrderRequest.value = VAL_ITEMORDER;
1642 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1643 req->packageName = esPackageName;
1645 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1651 static int only_z3950()
1653 if (conn && conn->protocol == PROTO_HTTP)
1655 printf ("Not supported by SRW\n");
1661 static int cmd_update(const char *arg)
1663 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1664 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1667 Z_IUOriginPartToKeep *toKeep;
1668 Z_IUSuppliedRecords *notToKeep;
1670 char action[20], recid[20], fname[80];
1672 Z_External *record_this = 0;
1679 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1681 if (!strcmp (action, "insert"))
1682 action_no = Z_IUOriginPartToKeep_recordInsert;
1683 else if (!strcmp (action, "replace"))
1684 action_no = Z_IUOriginPartToKeep_recordReplace;
1685 else if (!strcmp (action, "delete"))
1686 action_no = Z_IUOriginPartToKeep_recordDelete;
1687 else if (!strcmp (action, "update"))
1688 action_no = Z_IUOriginPartToKeep_specialUpdate;
1691 printf ("Bad action: %s\n", action);
1692 printf ("Possible values: insert, replace, delete, update\n");
1700 stat (fname, &status);
1701 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1703 size_t len = status.st_size;
1704 char *buf = (char *) xmalloc (len);
1706 fread (buf, 1, len, inf);
1710 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1716 printf ("File %s doesn't exist\n", fname);
1724 printf ("No last record (update ignored)\n");
1727 record_this = record_last;
1730 update_oid.proto = PROTO_Z3950;
1731 update_oid.oclass = CLASS_EXTSERV;
1732 update_oid.value = VAL_DBUPDATE;
1733 oid_ent_to_oid (&update_oid, oid);
1734 req->packageType = odr_oiddup(out,oid);
1735 req->packageName = esPackageName;
1737 req->referenceId = set_refid (out);
1739 r = req->taskSpecificParameters = (Z_External *)
1740 odr_malloc (out, sizeof(*r));
1741 r->direct_reference = odr_oiddup(out,oid);
1742 r->indirect_reference = 0;
1744 r->which = Z_External_update;
1745 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1746 r->u.update->which = Z_IUUpdate_esRequest;
1747 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1748 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1749 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1750 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1751 toKeep->databaseName = databaseNames[0];
1753 toKeep->elementSetName = 0;
1754 toKeep->actionQualifier = 0;
1755 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1756 *toKeep->action = action_no;
1758 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1759 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1761 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1762 odr_malloc(out, sizeof(*notToKeep->elements));
1763 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1764 odr_malloc(out, sizeof(**notToKeep->elements));
1765 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1768 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1769 odr_malloc (out, sizeof(Odr_oct));
1770 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1771 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1772 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1775 notToKeep->elements[0]->u.opaque = 0;
1776 notToKeep->elements[0]->supplementalId = 0;
1777 notToKeep->elements[0]->correlationInfo = 0;
1778 notToKeep->elements[0]->record = record_this;
1785 static int cmd_itemorder(const char *arg)
1792 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1795 printf("Item order request\n");
1797 send_itemorder(type, itemno);
1801 static int cmd_find(const char *arg)
1805 printf("Find what?\n");
1813 printf("Not connected yet\n");
1817 if (conn->protocol == PROTO_HTTP)
1820 if (!send_SRW_searchRequest(arg))
1828 if (!send_searchRequest(arg))
1834 static int cmd_delete(const char *arg)
1838 printf("Not connected yet\n");
1843 if (!send_deleteResultSetRequest(arg))
1848 static int cmd_ssub(const char *arg)
1850 if (!(smallSetUpperBound = atoi(arg)))
1855 static int cmd_lslb(const char *arg)
1859 if (!(largeSetLowerBound = atoi(arg)))
1864 static int cmd_mspn(const char *arg)
1868 if (!(mediumSetPresentNumber = atoi(arg)))
1873 static int cmd_status(const char *arg)
1875 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1876 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1877 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1881 static int cmd_setnames(const char *arg)
1883 if (*arg == '1') /* enable ? */
1885 else if (*arg == '0') /* disable ? */
1887 else if (setnumber < 0) /* no args, toggle .. */
1893 printf("Set numbering enabled.\n");
1895 printf("Set numbering disabled.\n");
1899 /* PRESENT SERVICE ----------------------------- */
1901 static void parse_show_args(const char *arg_c, char *setstring,
1902 int *start, int *number)
1907 strncpy(arg, arg_c, sizeof(arg)-1);
1908 arg[sizeof(arg)-1] = '\0';
1910 if ((p = strchr(arg, '+')))
1912 *number = atoi(p + 1);
1917 if (p && (p=strchr(p+1, '+')))
1918 strcpy (setstring, p+1);
1919 else if (setnumber >= 0)
1920 sprintf(setstring, "%d", setnumber);
1925 static int send_presentRequest(const char *arg)
1927 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1928 Z_PresentRequest *req = apdu->u.presentRequest;
1929 Z_RecordComposition compo;
1934 char setstring[100];
1936 req->referenceId = set_refid (out);
1938 parse_show_args(arg, setstring, &setno, &nos);
1940 req->resultSetId = setstring;
1942 req->resultSetStartPoint = &setno;
1943 req->numberOfRecordsRequested = &nos;
1944 prefsyn.proto = protocol;
1945 prefsyn.oclass = CLASS_RECSYN;
1946 prefsyn.value = recordsyntax;
1947 req->preferredRecordSyntax =
1948 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1954 prefschema.proto = protocol;
1955 prefschema.oclass = CLASS_SCHEMA;
1956 prefschema.value = oid_getvalbyname(schema);
1958 req->recordComposition = &compo;
1959 compo.which = Z_RecordComp_complex;
1960 compo.u.complex = (Z_CompSpec *)
1961 odr_malloc(out, sizeof(*compo.u.complex));
1962 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1963 odr_malloc(out, sizeof(bool_t));
1964 *compo.u.complex->selectAlternativeSyntax = 0;
1966 compo.u.complex->generic = (Z_Specification *)
1967 odr_malloc(out, sizeof(*compo.u.complex->generic));
1968 compo.u.complex->generic->which = Z_Schema_oid;
1969 compo.u.complex->generic->schema.oid = (Odr_oid *)
1970 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1971 if (!compo.u.complex->generic->schema.oid)
1973 /* OID wasn't a schema! Try record syntax instead. */
1974 prefschema.oclass = CLASS_RECSYN;
1975 compo.u.complex->generic->schema.oid = (Odr_oid *)
1976 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1978 if (!elementSetNames)
1979 compo.u.complex->generic->elementSpec = 0;
1982 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1983 odr_malloc(out, sizeof(Z_ElementSpec));
1984 compo.u.complex->generic->elementSpec->which =
1985 Z_ElementSpec_elementSetName;
1986 compo.u.complex->generic->elementSpec->u.elementSetName =
1987 elementSetNames->u.generic;
1989 compo.u.complex->num_dbSpecific = 0;
1990 compo.u.complex->dbSpecific = 0;
1991 compo.u.complex->num_recordSyntax = 0;
1992 compo.u.complex->recordSyntax = 0;
1994 else if (elementSetNames)
1996 req->recordComposition = &compo;
1997 compo.which = Z_RecordComp_simple;
1998 compo.u.simple = elementSetNames;
2001 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2006 static int send_SRW_presentRequest(const char *arg)
2008 char setstring[100];
2010 Z_SRW_PDU *sr = srw_sr;
2014 parse_show_args(arg, setstring, &setno, &nos);
2015 sr->u.request->startRecord = odr_intdup(out, setno);
2016 sr->u.request->maximumRecords = odr_intdup(out, nos);
2018 sr->u.request->recordSchema = schema;
2019 return send_srw(sr);
2023 static void close_session (void)
2029 nmem_destroy (session_mem);
2034 odr_destroy(srw_sr_odr_out);
2038 assert (srw_sr_odr_out == 0);
2045 void process_close(Z_Close *req)
2047 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2048 Z_Close *res = apdu->u.close;
2050 static char *reasons[] =
2055 "cost limit reached",
2057 "security violation",
2064 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2065 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2070 *res->closeReason = Z_Close_finished;
2072 printf("Sent response.\n");
2077 static int cmd_show(const char *arg)
2081 printf("Not connected yet\n");
2084 if (conn->protocol == PROTO_HTTP)
2087 if (!send_SRW_presentRequest(arg))
2095 if (!send_presentRequest(arg))
2101 int cmd_quit(const char *arg)
2103 printf("See you later, alligator.\n");
2109 int cmd_cancel(const char *arg)
2111 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2112 Z_TriggerResourceControlRequest *req =
2113 apdu->u.triggerResourceControlRequest;
2118 printf("Session not initialized yet\n");
2123 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2125 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2128 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2129 req->resultSetWanted = &rfalse;
2132 printf("Sent cancel request\n");
2136 int send_scanrequest(const char *query, int pp, int num, const char *term)
2138 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2139 Z_ScanRequest *req = apdu->u.scanRequest;
2144 if (queryType == QueryType_CCL2RPN)
2148 struct ccl_rpn_node *rpn;
2150 rpn = ccl_find_str (bibset, query, &error, &pos);
2153 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2156 bib1.proto = PROTO_Z3950;
2157 bib1.oclass = CLASS_ATTSET;
2158 bib1.value = VAL_BIB1;
2159 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2160 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2162 printf("Couldn't convert CCL to Scan term\n");
2165 ccl_rpn_delete (rpn);
2169 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2171 if (!(req->termListAndStartPoint =
2172 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2174 const char *pqf_msg;
2176 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2177 printf("%*s^\n", off+7, "");
2178 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2179 yaz_pqf_destroy (pqf_parser);
2182 yaz_pqf_destroy (pqf_parser);
2186 if (req->termListAndStartPoint->term &&
2187 req->termListAndStartPoint->term->which == Z_Term_general &&
2188 req->termListAndStartPoint->term->u.general)
2190 req->termListAndStartPoint->term->u.general->buf =
2191 (unsigned char *) odr_strdup(out, term);
2192 req->termListAndStartPoint->term->u.general->len =
2193 req->termListAndStartPoint->term->u.general->size =
2197 req->referenceId = set_refid (out);
2198 req->num_databaseNames = num_databaseNames;
2199 req->databaseNames = databaseNames;
2200 req->numberOfTermsRequested = #
2201 req->preferredPositionInResponse = &pp;
2206 int send_sortrequest(const char *arg, int newset)
2208 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2209 Z_SortRequest *req = apdu->u.sortRequest;
2210 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2211 odr_malloc (out, sizeof(*sksl));
2217 sprintf (setstring, "%d", setnumber);
2219 sprintf (setstring, "default");
2221 req->referenceId = set_refid (out);
2223 req->num_inputResultSetNames = 1;
2224 req->inputResultSetNames = (Z_InternationalString **)
2225 odr_malloc (out, sizeof(*req->inputResultSetNames));
2226 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2228 if (newset && setnumber >= 0)
2229 sprintf (setstring, "%d", ++setnumber);
2231 req->sortedResultSetName = odr_strdup (out, setstring);
2233 req->sortSequence = yaz_sort_spec (out, arg);
2234 if (!req->sortSequence)
2236 printf ("Missing sort specifications\n");
2243 void display_term(Z_TermInfo *t)
2245 if (t->term->which == Z_Term_general)
2247 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2248 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2249 t->term->u.general->buf);
2252 printf("Term (not general)");
2253 if (t->globalOccurrences)
2254 printf (" (%d)\n", *t->globalOccurrences);
2259 void process_scanResponse(Z_ScanResponse *res)
2262 Z_Entry **entries = NULL;
2263 int num_entries = 0;
2265 printf("Received ScanResponse\n");
2266 print_refid (res->referenceId);
2267 printf("%d entries", *res->numberOfEntriesReturned);
2268 if (res->positionOfTerm)
2269 printf (", position=%d", *res->positionOfTerm);
2271 if (*res->scanStatus != Z_Scan_success)
2272 printf("Scan returned code %d\n", *res->scanStatus);
2275 if ((entries = res->entries->entries))
2276 num_entries = res->entries->num_entries;
2277 for (i = 0; i < num_entries; i++)
2279 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2280 if (entries[i]->which == Z_Entry_termInfo)
2282 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2283 display_term(entries[i]->u.termInfo);
2286 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2288 if (res->entries->nonsurrogateDiagnostics)
2289 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2290 res->entries->num_nonsurrogateDiagnostics);
2293 void process_sortResponse(Z_SortResponse *res)
2295 printf("Received SortResponse: status=");
2296 switch (*res->sortStatus)
2298 case Z_SortStatus_success:
2299 printf ("success"); break;
2300 case Z_SortStatus_partial_1:
2301 printf ("partial"); break;
2302 case Z_SortStatus_failure:
2303 printf ("failure"); break;
2305 printf ("unknown (%d)", *res->sortStatus);
2308 print_refid (res->referenceId);
2309 if (res->diagnostics)
2310 display_diagrecs(res->diagnostics,
2311 res->num_diagnostics);
2314 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2316 printf("Got deleteResultSetResponse status=%d\n",
2317 *res->deleteOperationStatus);
2318 if (res->deleteListStatuses)
2321 for (i = 0; i < res->deleteListStatuses->num; i++)
2323 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2324 *res->deleteListStatuses->elements[i]->status);
2329 int cmd_sort_generic(const char *arg, int newset)
2333 printf("Session not initialized yet\n");
2338 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2340 printf("Target doesn't support sort\n");
2345 if (send_sortrequest(arg, newset) < 0)
2352 int cmd_sort(const char *arg)
2354 return cmd_sort_generic (arg, 0);
2357 int cmd_sort_newset (const char *arg)
2359 return cmd_sort_generic (arg, 1);
2362 int cmd_scan(const char *arg)
2371 printf("Session not initialized yet\n");
2375 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2377 printf("Target doesn't support scan\n");
2382 strcpy (last_scan_query, arg);
2383 if (send_scanrequest(arg, 1, 20, 0) < 0)
2388 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2394 int cmd_schema(const char *arg)
2399 schema = xstrdup(arg);
2403 int cmd_format(const char *arg)
2408 printf("Usage: format <recordsyntax>\n");
2411 nsyntax = oid_getvalbyname (arg);
2412 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2414 printf ("unknown record syntax\n");
2417 recordsyntax = nsyntax;
2421 int cmd_elements(const char *arg)
2423 static Z_ElementSetNames esn;
2424 static char what[100];
2428 elementSetNames = 0;
2432 esn.which = Z_ElementSetNames_generic;
2433 esn.u.generic = what;
2434 elementSetNames = &esn;
2438 int cmd_attributeset(const char *arg)
2444 printf("Usage: attributeset <setname>\n");
2447 sscanf(arg, "%s", what);
2448 if (p_query_attset (what))
2450 printf("Unknown attribute set name\n");
2456 int cmd_querytype (const char *arg)
2458 if (!strcmp (arg, "ccl"))
2459 queryType = QueryType_CCL;
2460 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2461 queryType = QueryType_Prefix;
2462 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2463 queryType = QueryType_CCL2RPN;
2464 else if (!strcmp(arg, "cql"))
2465 queryType = QueryType_CQL;
2468 printf ("Querytype must be one of:\n");
2469 printf (" prefix - Prefix query\n");
2470 printf (" ccl - CCL query\n");
2471 printf (" ccl2rpn - CCL query converted to RPN\n");
2472 printf (" cql - CQL\n");
2478 int cmd_refid (const char *arg)
2484 refid = (char *) xmalloc (strlen(arg)+1);
2485 strcpy (refid, arg);
2490 int cmd_close(const char *arg)
2499 apdu = zget_APDU(out, Z_APDU_close);
2500 req = apdu->u.close;
2501 *req->closeReason = Z_Close_finished;
2503 printf("Sent close request.\n");
2508 int cmd_packagename(const char* arg)
2510 xfree (esPackageName);
2511 esPackageName = NULL;
2514 esPackageName = (char *) xmalloc (strlen(arg)+1);
2515 strcpy (esPackageName, arg);
2520 int cmd_proxy(const char* arg)
2531 yazProxy = (char *) xmalloc (strlen(arg)+1);
2532 strcpy (yazProxy, arg);
2537 int cmd_charset(const char* arg)
2539 char l1[30], l2[30];
2542 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2544 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2550 yazCharset = xstrdup(l1);
2553 odr_set_charset (out, l1, l2);
2554 odr_set_charset (in, l2, l1);
2559 int cmd_lang(const char* arg)
2562 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2569 yazLang = (char *) xmalloc (strlen(arg)+1);
2570 strcpy (yazLang, arg);
2575 int cmd_source(const char* arg)
2577 /* first should open the file and read one line at a time.. */
2579 char line[1024], *cp;
2582 fprintf(stderr,"Error in source command use a filename\n");
2586 includeFile = fopen (arg, "r");
2589 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2593 while(!feof(includeFile)) {
2594 memset(line,0,sizeof(line));
2595 fgets(line,sizeof(line),includeFile);
2597 if(strlen(line) < 2) continue;
2598 if(line[0] == '#') continue;
2600 if ((cp = strrchr (line, '\n')))
2603 process_cmd_line(line);
2606 if(fclose(includeFile)<0) {
2607 perror("unable to close include file");
2613 int cmd_subshell(const char* args)
2618 system(getenv("SHELL"));
2624 int cmd_set_berfile(const char *arg)
2626 if (ber_file && ber_file != stdout && ber_file != stderr)
2628 if (!strcmp(arg, ""))
2630 else if (!strcmp(arg, "-"))
2633 ber_file = fopen(arg, "a");
2637 int cmd_set_apdufile(const char *arg)
2639 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2641 if (!strcmp(arg, ""))
2643 else if (!strcmp(arg, "-"))
2647 apdu_file = fopen(arg, "a");
2649 perror("unable to open apdu log file");
2652 odr_setprint(print, apdu_file);
2656 int cmd_set_cclfile(const char* arg)
2660 bibset = ccl_qual_mk ();
2661 inf = fopen (arg, "r");
2663 perror("unable to open CCL file");
2666 ccl_qual_file (bibset, inf);
2669 strcpy(ccl_fields,arg);
2673 int cmd_set_auto_reconnect(const char* arg)
2675 if(strlen(arg)==0) {
2676 auto_reconnect = ! auto_reconnect;
2677 } else if(strcmp(arg,"on")==0) {
2679 } else if(strcmp(arg,"off")==0) {
2682 printf("Error use on or off\n");
2687 printf("Set auto reconnect enabled.\n");
2689 printf("Set auto reconnect disabled.\n");
2694 int cmd_set_marcdump(const char* arg)
2696 if(marc_file && marc_file != stderr) { /* don't close stdout*/
2700 if (!strcmp(arg, ""))
2702 else if (!strcmp(arg, "-"))
2706 marc_file = fopen(arg, "a");
2708 perror("unable to open marc log file");
2713 int cmd_set_proxy(const char* arg)
2715 if(yazProxy) free(yazProxy);
2718 if(strlen(arg) > 1) {
2719 yazProxy=strdup(arg);
2725 this command takes 3 arge {name class oid}
2727 int cmd_register_oid(const char* args) {
2732 {"appctx",CLASS_APPCTX},
2733 {"absyn",CLASS_ABSYN},
2734 {"attset",CLASS_ATTSET},
2735 {"transyn",CLASS_TRANSYN},
2736 {"diagset",CLASS_DIAGSET},
2737 {"recsyn",CLASS_RECSYN},
2738 {"resform",CLASS_RESFORM},
2739 {"accform",CLASS_ACCFORM},
2740 {"extserv",CLASS_EXTSERV},
2741 {"userinfo",CLASS_USERINFO},
2742 {"elemspec",CLASS_ELEMSPEC},
2743 {"varset",CLASS_VARSET},
2744 {"schema",CLASS_SCHEMA},
2745 {"tagset",CLASS_TAGSET},
2746 {"general",CLASS_GENERAL},
2747 {0,(enum oid_class) 0}
2749 char oname_str[101], oclass_str[101], oid_str[101];
2752 oid_class oidclass = CLASS_GENERAL;
2753 int val = 0, oid[OID_SIZE];
2754 struct oident * new_oident=NULL;
2756 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2757 oname_str,oclass_str, oid_str) < 1) {
2758 printf("Error in regristrate command \n");
2762 for (i = 0; oid_classes[i].className; i++) {
2763 if (!strcmp(oid_classes[i].className, oclass_str))
2765 oidclass=oid_classes[i].oclass;
2770 if(!(oid_classes[i].className)) {
2771 printf("Unknonwn oid class %s\n",oclass_str);
2779 while (isdigit (*name))
2781 val = val*10 + (*name - '0');
2794 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2795 if(strcmp(new_oident->desc,oname_str)) {
2796 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2802 int cmd_push_command(const char* arg)
2804 #if HAVE_READLINE_HISTORY_H
2808 fprintf(stderr,"Not compiled with the readline/history module\n");
2813 void source_rcfile()
2815 /* Look for a $HOME/.yazclientrc and source it if it exists */
2816 struct stat statbuf;
2818 char* homedir=getenv("HOME");
2820 if(!homedir) return;
2822 sprintf(buffer,"%s/.yazclientrc",homedir);
2824 if(stat(buffer,&statbuf)==0) {
2828 if(stat(".yazclientrc",&statbuf)==0) {
2829 cmd_source(".yazclientrc");
2834 static void initialize(void)
2839 if (!(out = odr_createmem(ODR_ENCODE)) ||
2840 !(in = odr_createmem(ODR_DECODE)) ||
2841 !(print = odr_createmem(ODR_PRINT)))
2843 fprintf(stderr, "failed to allocate ODR streams\n");
2848 setvbuf(stdout, 0, _IONBF, 0);
2850 odr_setprint(print, apdu_file);
2852 bibset = ccl_qual_mk ();
2853 inf = fopen (ccl_fields, "r");
2856 ccl_qual_file (bibset, inf);
2859 cmd_base("Default");
2861 #if HAVE_READLINE_READLINE_H
2862 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2866 for(i=0; i<maxOtherInfosSupported; ++i) {
2867 extraOtherInfos[i].oidval = -1;
2874 #if HAVE_GETTIMEOFDAY
2875 struct timeval tv_start, tv_end;
2879 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
2883 printf ("Received SRW SearchRetrieveResponse\n");
2885 for (i = 0; i<res->num_diagnostics; i++)
2887 printf ("SRW diagnostic %d %s\nDetails: %s\n",
2888 *res->diagnostics[i].code,
2889 yaz_diag_srw_str(*res->diagnostics[i].code),
2890 res->diagnostics[i].details);
2892 if (res->numberOfRecords)
2893 printf ("Number of hits: %d\n", *res->numberOfRecords);
2894 for (i = 0; i<res->num_records; i++)
2897 Z_SRW_record *rec = res->records + i;
2899 if (rec->recordPosition)
2901 printf ("pos=%d", *rec->recordPosition);
2902 setno = *rec->recordPosition + 1;
2904 if (rec->recordSchema)
2905 printf (" scheam=%d", *rec->recordSchema);
2907 if (rec->recordData_buf && rec->recordData_len)
2909 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
2915 static void set_HTTP_error (int error,
2916 const char *addinfo, const char *addinfo2)
2923 static void http_response(Z_HTTP_Response *hres)
2926 const char *content_type = z_HTTP_header_lookup(hres->headers,
2928 const char *connection_head = z_HTTP_header_lookup(hres->headers,
2930 yaz_log (LOG_LOG, "http_response");
2932 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
2934 Z_SOAP *soap_package = 0;
2935 ODR o = odr_createmem(ODR_DECODE);
2936 Z_SOAP_Handler soap_handlers[2] = {
2937 {"http://www.loc.gov/zing/srw/v1.0/", 0,
2938 (Z_SOAP_fun) yaz_srw_codec},
2941 ret = z_soap_codec(o, &soap_package,
2942 &hres->content_buf, &hres->content_len,
2944 if (!ret && soap_package->which == Z_SOAP_generic &&
2945 soap_package->u.generic->no == 0)
2947 Z_SRW_PDU *sr = soap_package->u.generic->p;
2948 if (sr->which == Z_SRW_searchRetrieve_response)
2949 handle_srw_response(sr->u.response);
2953 else if (!ret && (soap_package->which == Z_SOAP_fault
2954 || soap_package->which == Z_SOAP_error))
2956 printf ("HTTP Error Status=%d\n", hres->code);
2957 printf ("SOAP Fault code %s\n",
2958 soap_package->u.fault->fault_code);
2959 printf ("SOAP Fault string %s\n",
2960 soap_package->u.fault->fault_string);
2968 if (hres->code != 200)
2969 set_HTTP_error(hres->code, 0, 0);
2972 printf ("decoding of SRW package failed\n");
2976 if (!strcmp(hres->version, "1.0"))
2978 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
2979 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
2984 /* HTTP 1.1: only if no close we stay alive .. */
2985 if (connection_head && !strcmp(connection_head, "close"))
2991 void wait_and_handle_response()
2993 int reconnect_ok = 1;
2996 int netbufferlen = 0;
3001 printf ("cs_get....\n");
3002 res = cs_get(conn, &netbuffer, &netbufferlen);
3003 if (reconnect_ok && res <= 0 && conn->protocol == PROTO_HTTP)
3014 buf_out = odr_getbuf(out, &len_out, 0);
3016 cs_put(conn, buf_out, len_out);
3024 printf("Target closed connection\n");
3029 odr_reset(in); /* release APDU from last round */
3031 odr_setbuf(in, netbuffer, res, 0);
3033 printf ("got input packet %d bytes\n", res);
3034 if (!z_GDU(in, &gdu, 0, 0))
3036 FILE *f = ber_file ? ber_file : stdout;
3037 odr_perror(in, "Decoding incoming APDU");
3038 fprintf(f, "[Near %d]\n", odr_offset(in));
3039 fprintf(f, "Packet dump:\n---------\n");
3040 odr_dumpBER(f, netbuffer, res);
3041 fprintf(f, "---------\n");
3043 z_GDU(print, &gdu, 0, 0);
3048 odr_dumpBER(ber_file, netbuffer, res);
3049 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3051 odr_perror(print, "Failed to print incoming APDU");
3055 if (gdu->which == Z_GDU_Z3950)
3057 Z_APDU *apdu = gdu->u.z3950;
3060 case Z_APDU_initResponse:
3061 process_initResponse(apdu->u.initResponse);
3063 case Z_APDU_searchResponse:
3064 process_searchResponse(apdu->u.searchResponse);
3066 case Z_APDU_scanResponse:
3067 process_scanResponse(apdu->u.scanResponse);
3069 case Z_APDU_presentResponse:
3070 print_refid (apdu->u.presentResponse->referenceId);
3072 *apdu->u.presentResponse->numberOfRecordsReturned;
3073 if (apdu->u.presentResponse->records)
3074 display_records(apdu->u.presentResponse->records);
3076 printf("No records.\n");
3077 printf ("nextResultSetPosition = %d\n",
3078 *apdu->u.presentResponse->nextResultSetPosition);
3080 case Z_APDU_sortResponse:
3081 process_sortResponse(apdu->u.sortResponse);
3083 case Z_APDU_extendedServicesResponse:
3084 printf("Got extended services response\n");
3085 process_ESResponse(apdu->u.extendedServicesResponse);
3088 printf("Target has closed the association.\n");
3089 process_close(apdu->u.close);
3091 case Z_APDU_resourceControlRequest:
3092 process_resourceControlRequest
3093 (apdu->u.resourceControlRequest);
3095 case Z_APDU_deleteResultSetResponse:
3096 process_deleteResultSetResponse(apdu->u.
3097 deleteResultSetResponse);
3100 printf("Received unknown APDU type (%d).\n",
3106 else if (gdu->which == Z_GDU_HTTP_Response)
3108 http_response(gdu->u.HTTP_Response);
3111 if (conn && !cs_more(conn))
3116 #if HAVE_GETTIMEOFDAY
3117 gettimeofday (&tv_end, 0);
3119 printf ("S/U S/U=%ld/%ld %ld/%ld",
3120 (long) tv_start.tv_sec,
3121 (long) tv_start.tv_usec,
3122 (long) tv_end.tv_sec,
3123 (long) tv_end.tv_usec);
3125 printf ("Elapsed: %.6f\n",
3126 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3127 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3134 int cmd_cclparse(const char* arg)
3137 struct ccl_rpn_node *rpn=NULL;
3140 rpn = ccl_find_str (bibset, arg, &error, &pos);
3143 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3144 printf ("%s\n", ccl_err_msg (error));
3150 ccl_pr_tree(rpn, stdout);
3154 ccl_rpn_delete(rpn);
3162 int cmd_set_otherinfo(const char* args)
3164 char oid[101], otherinfoString[101];
3169 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3171 /* reset this otherinfo */
3172 if(otherinfoNo>=maxOtherInfosSupported) {
3173 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3175 extraOtherInfos[otherinfoNo].oidval = -1;
3176 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3180 printf("Error in set_otherinfo command \n");
3184 if(otherinfoNo>=maxOtherInfosSupported) {
3185 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3189 oidval = oid_getvalbyname (oid);
3191 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3194 extraOtherInfos[otherinfoNo].oidval = oidval;
3195 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3196 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3201 int cmd_list_otherinfo(const char* args)
3205 if(strlen(args)>0) {
3207 if( i >= maxOtherInfosSupported ) {
3208 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3212 if(extraOtherInfos[i].oidval != -1)
3213 printf(" otherinfo %d %s %s\n",
3215 yaz_z3950_oid_value_to_str(
3216 (enum oid_value) extraOtherInfos[i].oidval,
3218 extraOtherInfos[i].value);
3221 for(i=0; i<maxOtherInfosSupported; ++i) {
3222 if(extraOtherInfos[i].oidval != -1)
3223 printf(" otherinfo %d %s %s\n",
3225 yaz_z3950_oid_value_to_str(
3226 (enum oid_value) extraOtherInfos[i].oidval,
3228 extraOtherInfos[i].value);
3236 int cmd_list_all(const char* args) {
3239 /* connection options */
3241 printf("Connected to : %s\n",last_open_command);
3243 if(last_open_command)
3244 printf("Not connected to : %s\n",last_open_command);
3246 printf("Not connected : \n");
3249 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3251 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3254 printf("Authentication : none\n");
3256 switch(auth->which) {
3257 case Z_IdAuthentication_idPass:
3258 printf("Authentication : IdPass\n");
3259 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3260 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3261 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3263 case Z_IdAuthentication_open:
3264 printf("Authentication : psOpen\n");
3265 printf(" Open string : %s\n",auth->u.open);
3268 printf("Authentication : Unknown\n");
3271 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
3275 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3279 printf("CCL file : %s\n",ccl_fields);
3280 printf("Query type : %s\n",query_type_as_string(queryType));
3282 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3284 /* piggy back options */
3285 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3287 /* print present related options */
3288 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3289 printf("Schema : %s\n",schema);
3290 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3292 /* loging options */
3293 printf("APDU log : %s\n",apdu_file?"on":"off");
3294 printf("Record log : %s\n",marc_file?"on":"off");
3297 printf("Other Info: \n");
3298 cmd_list_otherinfo("");
3303 int cmd_clear_otherinfo(const char* args)
3305 if(strlen(args)>0) {
3307 otherinfoNo = atoi(args);
3308 if( otherinfoNo >= maxOtherInfosSupported ) {
3309 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3313 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3314 /* only clear if set. */
3315 extraOtherInfos[otherinfoNo].oidval=-1;
3316 free(extraOtherInfos[otherinfoNo].value);
3321 for(i=0; i<maxOtherInfosSupported; ++i) {
3322 if (extraOtherInfos[i].oidval!=-1 ) {
3323 extraOtherInfos[i].oidval=-1;
3324 free(extraOtherInfos[i].value);
3331 static int cmd_help (const char *line);
3333 typedef char *(*completerFunctionType)(const char *text, int state);
3337 int (*fun)(const char *arg);
3339 completerFunctionType rl_completerfunction;
3340 int complete_filenames;
3341 char **local_tabcompletes;
3343 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3344 {"quit", cmd_quit, "",NULL,0,NULL},
3345 {"find", cmd_find, "<query>",NULL,0,NULL},
3346 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3347 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3348 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3349 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3350 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3351 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3352 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3353 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3354 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3355 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3356 {"status", cmd_status, "",NULL,0,NULL},
3357 {"setnames", cmd_setnames, "",NULL,0,NULL},
3358 {"cancel", cmd_cancel, "",NULL,0,NULL},
3359 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3360 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3361 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3362 {"close", cmd_close, "",NULL,0,NULL},
3363 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3364 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3365 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3366 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3367 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3368 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3369 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3370 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3371 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3372 {".", cmd_source, "<filename>",NULL,1,NULL},
3373 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3374 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3375 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3376 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3377 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3378 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3379 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3380 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3381 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3382 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3383 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3384 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3385 {"list_all",cmd_list_all,"",NULL,0,NULL},
3386 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3387 /* Server Admin Functions */
3388 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3389 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3390 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3391 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3392 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3393 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3394 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3395 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3396 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3397 {"help", cmd_help, "", NULL,0,NULL},
3401 static int cmd_help (const char *line)
3407 sscanf (line, "%20s", topic);
3410 printf("Commands:\n");
3411 for (i = 0; cmd_array[i].cmd; i++)
3412 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3413 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3414 if (strcmp (topic, "find") == 0)
3417 printf (" \"term\" Simple Term\n");
3418 printf (" @attr [attset] type=value op Attribute\n");
3419 printf (" @and opl opr And\n");
3420 printf (" @or opl opr Or\n");
3421 printf (" @not opl opr And-Not\n");
3422 printf (" @set set Result set\n");
3424 printf ("Bib-1 attribute types\n");
3426 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3427 printf ("2=Relation: ");
3428 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3429 printf ("3=Position: ");
3430 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3431 printf ("4=Structure: ");
3432 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3433 printf ("5=Truncation: ");
3434 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3435 printf ("6=Completeness:");
3436 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3441 int cmd_register_tab(const char* arg) {
3443 char command[101], tabargument[101];
3448 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3452 /* locate the amdn in the list */
3453 for (i = 0; cmd_array[i].cmd; i++) {
3454 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3459 if(!cmd_array[i].cmd) {
3460 fprintf(stderr,"Unknown command %s\n",command);
3465 if(!cmd_array[i].local_tabcompletes)
3466 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3470 tabslist = cmd_array[i].local_tabcompletes;
3471 for(;tabslist && *tabslist;tabslist++) {
3475 cmd_array[i].local_tabcompletes = (char **)
3476 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3477 tabslist=cmd_array[i].local_tabcompletes;
3478 tabslist[num_of_tabs]=strdup(tabargument);
3479 tabslist[num_of_tabs+1]=NULL;
3484 void process_cmd_line(char* line)
3487 char word[32], arg[1024];
3489 #if HAVE_GETTIMEOFDAY
3490 gettimeofday (&tv_start, 0);
3493 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3495 strcpy(word, last_cmd);
3500 strcpy(last_cmd, word);
3502 /* removed tailing spaces from the arg command */
3505 char* lastnonspace=NULL;
3513 *(++lastnonspace) = 0;
3516 for (i = 0; cmd_array[i].cmd; i++)
3517 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3519 res = (*cmd_array[i].fun)(arg);
3523 if (!cmd_array[i].cmd) /* dump our help-screen */
3525 printf("Unknown command: %s.\n", word);
3526 printf("use help for list of commands\n");
3527 /* cmd_help (""); */
3531 if(apdu_file) fflush(apdu_file);
3534 wait_and_handle_response();
3543 char *command_generator(const char *text, int state)
3549 for( ; cmd_array[idx].cmd; ++idx) {
3550 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3551 ++idx; /* skip this entry on the next run */
3552 return strdup(cmd_array[idx-1].cmd);
3560 This function only known how to complete on the first word
3562 char ** readline_completer(char *text, int start, int end) {
3563 #if HAVE_READLINE_READLINE_H
3565 completerFunctionType completerToUse;
3568 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3569 char** res=rl_completion_matches(text,
3572 char** res=completion_matches(text,
3573 (CPFunction*)command_generator);
3575 rl_attempted_completion_over = 1;
3578 char arg[1024],word[32];
3580 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3581 rl_attempted_completion_over = 1;
3585 for (i = 0; cmd_array[i].cmd; i++) {
3586 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3591 if(!cmd_array[i].cmd) return NULL;
3593 curret_global_list = cmd_array[i].local_tabcompletes;
3595 completerToUse = cmd_array[i].rl_completerfunction;
3596 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3597 completerToUse = default_completer;
3599 if(completerToUse) {
3600 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3602 rl_completion_matches(text,
3606 completion_matches(text,
3607 (CPFunction*)completerToUse);
3609 if(!cmd_array[i].complete_filenames)
3610 rl_attempted_completion_over = 1;
3613 if(!cmd_array[i].complete_filenames)
3614 rl_attempted_completion_over = 1;
3624 static void client(void)
3630 #if HAVE_GETTIMEOFDAY
3631 gettimeofday (&tv_start, 0);
3636 char *line_in = NULL;
3637 #if HAVE_READLINE_READLINE_H
3640 line_in=readline(C_PROMPT);
3643 #if HAVE_READLINE_HISTORY_H
3645 add_history(line_in);
3647 strncpy(line, line_in, 1023);
3656 if (!fgets(line, 1023, stdin))
3658 if ((end_p = strchr (line, '\n')))
3661 process_cmd_line(line);
3665 int main(int argc, char **argv)
3668 char *open_command = 0;
3669 char *auth_command = 0;
3674 if (!setlocale(LC_CTYPE, ""))
3675 fprintf (stderr, "setlocale failed\n");
3679 codeset = nl_langinfo(CODESET);
3683 while ((ret = options("k:c:a:b:m:v:p:u:t:", argv, argc, &arg)) != -2)
3690 open_command = (char *) xmalloc (strlen(arg)+6);
3691 strcpy (open_command, "open ");
3692 strcat (open_command, arg);
3696 kilobytes = atoi(arg);
3699 if (!(marc_file = fopen (arg, "a")))
3709 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3710 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3713 if (!strcmp(arg, "-"))
3716 ber_file=fopen(arg, "a");
3719 if (!strcmp(arg, "-"))
3722 apdu_file=fopen(arg, "a");
3725 yazProxy=strdup(arg);
3730 auth_command = (char *) xmalloc (strlen(arg)+6);
3731 strcpy (auth_command, "auth ");
3732 strcat (auth_command, arg);
3736 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3739 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3740 "[-b berdump] [-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3741 "[-k size] [<server-addr>]\n",
3749 #ifdef HAVE_GETTIMEOFDAY
3750 gettimeofday (&tv_start, 0);
3752 process_cmd_line (auth_command);
3753 #if HAVE_READLINE_HISTORY_H
3754 add_history(auth_command);
3756 xfree(auth_command);
3760 #ifdef HAVE_GETTIMEOFDAY
3761 gettimeofday (&tv_start, 0);
3763 process_cmd_line (open_command);
3764 #if HAVE_READLINE_HISTORY_H
3765 add_history(open_command);
3767 xfree(open_command);
3778 * vim600: sw=4 ts=8 fdm=marker
3779 * vim<600: sw=4 ts=8