2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.194 2003-05-20 19:55:29 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 *negotiationCharset = 0;
92 static char *outputCharset = 0;
93 static char *marcCharset = 0;
94 static char* yazLang = 0;
96 static char last_cmd[32] = "?";
97 static FILE *marc_file = 0;
98 static char *refid = NULL;
99 static char *last_open_command = NULL;
100 static int auto_reconnect = 0;
109 static QueryType queryType = QueryType_Prefix;
111 static CCL_bibset bibset; /* CCL bibset handle */
113 #if HAVE_READLINE_COMPLETION_OVER
116 /* readline doesn't have this var. Define it ourselves. */
117 int rl_attempted_completion_over = 0;
120 /* set this one to 1, to avoid decode of unknown MARCs */
121 #define AVOID_MARC_DECODE 1
123 #define maxOtherInfosSupported 10
127 } extraOtherInfos[maxOtherInfosSupported];
130 void process_cmd_line(char* line);
131 char ** readline_completer(char *text, int start, int end);
132 char *command_generator(const char *text, int state);
133 char** curret_global_list=NULL;
134 int cmd_register_tab(const char* arg);
136 static void close_session (void);
138 ODR getODROutputStream()
143 const char* query_type_as_string(QueryType q)
146 case QueryType_Prefix: return "prefix (RPN sent to server)";
147 case QueryType_CCL: return "CCL (CCL sent to server) ";
148 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
149 case QueryType_CQL: return "CQL (CQL sent to server)";
151 return "unknown Query type internal yaz-client error";
156 void do_hex_dump(char* buf,int len)
160 for( i=0; i<len ; i=i+16 )
163 for(x=0 ; i+x<len && x<16; ++x)
165 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
172 void add_otherInfos(Z_APDU *a)
174 Z_OtherInformation **oi;
178 for(i=0; i<maxOtherInfosSupported; ++i)
180 if(extraOtherInfos[i].oidval != -1)
181 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
182 1, extraOtherInfos[i].value);
186 int send_apdu(Z_APDU *a)
195 z_APDU(print, &a, 0, 0);
198 if (!z_APDU(out, &a, 0, 0))
200 odr_perror(out, "Encoding APDU");
204 buf = odr_getbuf(out, &len, 0);
206 odr_dumpBER(ber_file, buf, len);
207 /* printf ("sending APDU of size %d\n", len); */
208 if (cs_put(conn, buf, len) < 0)
210 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
214 do_hex_dump(buf,len);
215 odr_reset(out); /* release the APDU structure */
219 static void print_stringn(const unsigned char *buf, size_t len)
222 for (i = 0; i<len; i++)
223 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
224 printf ("%c", buf[i]);
226 printf ("\\X%02X", buf[i]);
229 static void print_refid (Z_ReferenceId *id)
233 printf ("Reference Id: ");
234 print_stringn (id->buf, id->len);
239 static Z_ReferenceId *set_refid (ODR out)
244 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
245 id->size = id->len = strlen(refid);
246 id->buf = (unsigned char *) odr_malloc (out, id->len);
247 memcpy (id->buf, refid, id->len);
251 /* INIT SERVICE ------------------------------- */
253 static void send_initRequest(const char* type_and_host)
255 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
256 Z_InitRequest *req = apdu->u.initRequest;
258 ODR_MASK_SET(req->options, Z_Options_search);
259 ODR_MASK_SET(req->options, Z_Options_present);
260 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
261 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
262 ODR_MASK_SET(req->options, Z_Options_scan);
263 ODR_MASK_SET(req->options, Z_Options_sort);
264 ODR_MASK_SET(req->options, Z_Options_extendedServices);
265 ODR_MASK_SET(req->options, Z_Options_delSet);
267 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
268 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
269 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
271 *req->maximumRecordSize = 1024*kilobytes;
272 *req->preferredMessageSize = 1024*kilobytes;
274 req->idAuthentication = auth;
276 req->referenceId = set_refid (out);
279 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
282 if (negotiationCharset || yazLang) {
283 Z_OtherInformation **p;
284 Z_OtherInformationUnit *p0;
286 yaz_oi_APDU(apdu, &p);
288 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
289 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
291 p0->which = Z_OtherInfo_externallyDefinedInfo;
292 p0->information.externallyDefinedInfo =
293 yaz_set_proposal_charneg(
295 (const char**)&negotiationCharset,
296 negotiationCharset ? 1 : 0,
297 (const char**)&yazLang, yazLang ? 1 : 0, 1);
302 printf("Sent initrequest.\n");
305 static int process_initResponse(Z_InitResponse *res)
308 /* save session parameters for later use */
309 session_mem = odr_extract_mem(in);
312 for (ver = 0; ver<5; ver++)
313 if (!ODR_MASK_GET(res->protocolVersion, ver))
317 printf("Connection rejected by v%d target.\n", ver);
319 printf("Connection accepted by v%d target.\n", ver);
320 if (res->implementationId)
321 printf("ID : %s\n", res->implementationId);
322 if (res->implementationName)
323 printf("Name : %s\n", res->implementationName);
324 if (res->implementationVersion)
325 printf("Version: %s\n", res->implementationVersion);
326 if (res->userInformationField)
328 printf("UserInformationfield:\n");
329 if (!z_External(print, (Z_External**)&res-> userInformationField,
332 odr_perror(print, "Printing userinfo\n");
335 if (res->userInformationField->which == Z_External_octet)
337 printf("Guessing visiblestring:\n");
338 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
343 if (ODR_MASK_GET(res->options, Z_Options_search))
345 if (ODR_MASK_GET(res->options, Z_Options_present))
347 if (ODR_MASK_GET(res->options, Z_Options_delSet))
349 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
350 printf (" resourceReport");
351 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
352 printf (" resourceCtrl");
353 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
354 printf (" accessCtrl");
355 if (ODR_MASK_GET(res->options, Z_Options_scan))
357 if (ODR_MASK_GET(res->options, Z_Options_sort))
359 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
360 printf (" extendedServices");
361 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
362 printf (" level1Segmentation");
363 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
364 printf (" level2Segmentation");
365 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
366 printf (" concurrentOperations");
367 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
369 printf (" namedResultSets");
372 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
373 printf (" encapsulation");
374 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
375 printf (" resultCount");
376 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
377 printf (" negotiationModel");
378 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
379 printf (" duplicateDetection");
380 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
381 printf (" queryType104");
384 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
386 Z_CharSetandLanguageNegotiation *p =
387 yaz_get_charneg_record(res->otherInfo);
391 char *charset=NULL, *lang=NULL;
394 yaz_get_response_charneg(session_mem, p, &charset, &lang,
397 printf("Accepted character set : %s\n", charset);
398 printf("Accepted code language : %s\n", lang ? lang : "none");
399 printf("Accepted records in ...: %d\n", selected );
406 static int set_base(const char *arg)
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++)
434 if (num_databaseNames == 0)
436 num_databaseNames = 1;
437 databaseNames[0] = xstrdup("");
442 static int cmd_base(const char *arg)
446 printf("Usage: base <database> <database> ...\n");
449 return set_base(arg);
452 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
454 if(last_open_command != arg)
456 if(last_open_command) xfree(last_open_command);
457 last_open_command = xstrdup(new_open_command);
461 int session_connect(const char *arg)
464 char type_and_host[101];
465 const char *basep = 0;
472 nmem_destroy (session_mem);
476 cs_get_host_args(arg, &basep);
478 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
479 type_and_host[sizeof(type_and_host)-1] = '\0';
481 cmd_open_remember_last_open_command(arg,type_and_host);
484 conn = cs_create_host(yazProxy, 1, &add);
486 conn = cs_create_host(arg, 1, &add);
489 printf ("Couldn't create comstack\n");
494 if (conn->protocol == PROTO_HTTP)
496 printf ("SRW/HTTP not enabled in this YAZ\n");
502 protocol = conn->protocol;
503 if (conn->protocol == PROTO_HTTP)
507 printf("Connecting...");
509 if (cs_connect(conn, add) < 0)
511 printf ("error = %s\n", cs_strerror(conn));
512 if (conn->cerrno == CSYSERR)
515 yaz_strerror(msg, sizeof(msg));
516 printf ("%s\n", msg);
525 if (protocol == PROTO_Z3950)
527 send_initRequest(type_and_host);
533 int cmd_open(const char *arg)
535 static char cur_host[200];
538 strncpy (cur_host, arg, sizeof(cur_host)-1);
539 cur_host[sizeof(cur_host)-1] = 0;
541 return session_connect(cur_host);
548 if(!( auto_reconnect && last_open_command) ) return ;
550 open_command = (char *) xmalloc (strlen(last_open_command)+6);
551 strcpy (open_command, "open ");
553 strcat (open_command, last_open_command);
555 process_cmd_line(open_command);
560 int cmd_authentication(const char *arg)
562 static Z_IdAuthentication au;
563 static char user[40], group[40], pass[40];
564 static Z_IdPass idPass;
569 printf("Auth field set to null\n");
573 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
576 printf("Auth field set to null\n");
582 au.which = Z_IdAuthentication_open;
588 au.which = Z_IdAuthentication_idPass;
589 au.u.idPass = &idPass;
590 idPass.groupId = NULL;
591 idPass.userId = user;
592 idPass.password = group;
597 au.which = Z_IdAuthentication_idPass;
598 au.u.idPass = &idPass;
599 idPass.groupId = group;
600 idPass.userId = user;
601 idPass.password = pass;
606 /* SEARCH SERVICE ------------------------------ */
607 static void display_record(Z_External *r);
609 static void print_record(const unsigned char *buf, size_t len)
612 print_stringn (buf, len);
613 /* add newline if not already added ... */
614 if (i <= 0 || buf[i-1] != '\n')
618 static void display_record(Z_External *r)
620 oident *ent = oid_getentbyoid(r->direct_reference);
624 * Tell the user what we got.
626 if (r->direct_reference)
628 printf("Record type: ");
630 printf("%s\n", ent->desc);
631 else if (!odr_oid(print, &r->direct_reference, 0, 0))
633 odr_perror(print, "print oid");
637 /* Check if this is a known, ASN.1 type tucked away in an octet string */
638 if (ent && r->which == Z_External_octet)
640 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
646 * Call the given decoder to process the record.
648 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
649 r->u.octet_aligned->len, 0);
650 if (!(*type->fun)(in, (char **)&rr, 0, 0))
652 odr_perror(in, "Decoding constructed record.");
653 fprintf(stdout, "[Near %d]\n", odr_offset(in));
654 fprintf(stdout, "Packet dump:\n---------\n");
655 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
656 r->u.octet_aligned->len);
657 fprintf(stdout, "---------\n");
659 /* note just ignores the error ant print the bytes form the octet_aligned later */
662 * Note: we throw away the original, BER-encoded record here.
663 * Do something else with it if you want to keep it.
665 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
666 r->which = type->what;
670 if (ent && ent->oclass != CLASS_RECSYN)
672 if (ent && ent->value == VAL_SOIF)
673 print_record((const unsigned char *) r->u.octet_aligned->buf,
674 r->u.octet_aligned->len);
675 else if (r->which == Z_External_octet)
677 const char *octet_buf = (char*)r->u.octet_aligned->buf;
678 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
679 ent->value == VAL_HTML)
681 print_record((const unsigned char *) octet_buf,
682 r->u.octet_aligned->len);
684 else if (ent->value == VAL_POSTSCRIPT)
686 int size = r->u.octet_aligned->len;
689 print_record((const unsigned char *) octet_buf, size);
694 #if AVOID_MARC_DECODE
695 /* primitive check for a marc OID 5.1-29 except 16 */
696 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
697 ent->oidsuffix[1] != 16
706 yaz_marc_t mt = yaz_marc_create();
708 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
712 if (marcCharset && strcmp(marcCharset, "auto"))
716 if (ent->value == VAL_USMARC)
718 if (octet_buf[9] == 'a')
726 if (outputCharset && from)
728 printf ("convert from %s to %s\n", from,
730 cd = yaz_iconv_open(outputCharset, from);
733 fwrite (result, 1, rlen, stdout);
737 size_t inbytesleft = rlen;
738 const char *inp = result;
742 size_t outbytesleft = sizeof(outbuf);
744 size_t r = yaz_iconv (cd, (char**) &inp,
746 &outp, &outbytesleft);
747 if (r == (size_t) (-1))
749 int e = yaz_iconv_error(cd);
750 if (e != YAZ_ICONV_E2BIG)
753 fwrite (outbuf, outp - outbuf, 1, stdout);
759 printf ("bad MARC. Dumping as it is:\n");
760 print_record((const unsigned char*) octet_buf,
761 r->u.octet_aligned->len);
763 yaz_marc_destroy(mt);
769 print_record((const unsigned char*) octet_buf,
770 r->u.octet_aligned->len);
774 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
776 else if (ent && ent->value == VAL_SUTRS)
778 if (r->which != Z_External_sutrs)
780 printf("Expecting single SUTRS type for SUTRS.\n");
783 print_record(r->u.sutrs->buf, r->u.sutrs->len);
785 else if (ent && ent->value == VAL_GRS1)
788 if (r->which != Z_External_grs1)
790 printf("Expecting single GRS type for GRS.\n");
794 yaz_display_grs1(w, r->u.grs1, 0);
800 printf("Unknown record representation.\n");
801 if (!z_External(print, &r, 0, 0))
803 odr_perror(print, "Printing external");
809 static void display_diagrecs(Z_DiagRec **pp, int num)
813 Z_DefaultDiagFormat *r;
815 printf("Diagnostic message(s) from database:\n");
816 for (i = 0; i<num; i++)
818 Z_DiagRec *p = pp[i];
819 if (p->which != Z_DiagRec_defaultFormat)
821 printf("Diagnostic record not in default format.\n");
825 r = p->u.defaultFormat;
826 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
827 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
828 printf("Missing or unknown diagset\n");
829 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
832 case Z_DefaultDiagFormat_v2Addinfo:
833 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
835 case Z_DefaultDiagFormat_v3Addinfo:
836 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
843 static void display_nameplusrecord(Z_NamePlusRecord *p)
846 printf("[%s]", p->databaseName);
847 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
848 display_diagrecs(&p->u.surrogateDiagnostic, 1);
849 else if (p->which == Z_NamePlusRecord_databaseRecord)
850 display_record(p->u.databaseRecord);
853 static void display_records(Z_Records *p)
857 if (p->which == Z_Records_NSD)
859 Z_DiagRec dr, *dr_p = &dr;
860 dr.which = Z_DiagRec_defaultFormat;
861 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
862 display_diagrecs (&dr_p, 1);
864 else if (p->which == Z_Records_multipleNSD)
865 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
866 p->u.multipleNonSurDiagnostics->num_diagRecs);
869 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
870 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
871 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
875 static int send_deleteResultSetRequest(const char *arg)
880 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
881 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
883 req->referenceId = set_refid (out);
885 req->num_resultSetList =
886 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
887 names[0], names[1], names[2], names[3],
888 names[4], names[5], names[6], names[7]);
890 req->deleteFunction = (int *)
891 odr_malloc (out, sizeof(*req->deleteFunction));
892 if (req->num_resultSetList > 0)
894 *req->deleteFunction = Z_DeleteRequest_list;
895 req->resultSetList = (char **)
896 odr_malloc (out, sizeof(*req->resultSetList)*
897 req->num_resultSetList);
898 for (i = 0; i<req->num_resultSetList; i++)
899 req->resultSetList[i] = names[i];
903 *req->deleteFunction = Z_DeleteRequest_all;
904 req->resultSetList = 0;
908 printf("Sent deleteResultSetRequest.\n");
913 static int send_srw(Z_SRW_PDU *sr)
915 const char *charset = negotiationCharset;
916 const char *host_port = 0;
919 Z_SOAP_Handler h[2] = {
920 {"http://www.loc.gov/zing/srw/v1.0/", 0, (Z_SOAP_fun) yaz_srw_codec},
923 ODR o = odr_createmem(ODR_ENCODE);
925 Z_SOAP *p = odr_malloc(o, sizeof(*p));
928 path = odr_malloc(out, strlen(databaseNames[0])+2);
930 strcpy(path+1, databaseNames[0]);
932 gdu = z_get_HTTP_Request(out);
933 gdu->u.HTTP_Request->path = odr_strdup(out, path);
937 const char *cp0 = strstr(host_port, "://");
944 cp1 = strchr(cp0, '/');
946 cp1 = cp0+strlen(cp0);
950 char *h = odr_malloc(out, cp1 - cp0 + 1);
951 memcpy (h, cp0, cp1 - cp0);
953 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
958 strcpy(ctype, "text/xml");
959 if (charset && strlen(charset) < 20)
961 strcat(ctype, "; charset=");
962 strcat(ctype, charset);
964 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
965 "Content-Type", ctype);
966 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
967 "SOAPAction", "\"\"");
968 p->which = Z_SOAP_generic;
969 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
970 p->u.generic->no = 0;
971 p->u.generic->ns = 0;
972 p->u.generic->p = sr;
973 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
975 ret = z_soap_codec_enc(o, &p,
976 &gdu->u.HTTP_Request->content_buf,
977 &gdu->u.HTTP_Request->content_len, h,
980 if (z_GDU(out, &gdu, 0, 0))
986 buf_out = odr_getbuf(out, &len_out, 0);
988 /* we don't odr_reset(out), since we may need the buffer again */
990 r = cs_put(conn, buf_out, len_out);
1002 static int send_SRW_searchRequest(const char *arg)
1008 assert(srw_sr_odr_out == 0);
1009 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1011 odr_reset(srw_sr_odr_out);
1015 /* save this for later .. when fetching individual records */
1016 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1017 sr->u.request->query_type = Z_SRW_query_type_cql;
1018 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1020 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1021 sr->u.request->query_type = Z_SRW_query_type_cql;
1022 sr->u.request->query.cql = odr_strdup(out, arg);
1024 sr->u.request->recordSchema = schema;
1025 return send_srw(sr);
1029 static int send_searchRequest(const char *arg)
1031 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1032 Z_SearchRequest *req = apdu->u.searchRequest;
1035 struct ccl_rpn_node *rpn = NULL;
1037 char setstring[100];
1038 Z_RPNQuery *RPNquery;
1040 YAZ_PQF_Parser pqf_parser;
1043 if (queryType == QueryType_CCL2RPN)
1045 rpn = ccl_find_str(bibset, arg, &error, &pos);
1048 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1052 req->referenceId = set_refid (out);
1053 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1055 static unsigned char big[2100];
1056 static Odr_oct bigo;
1058 /* send a very big referenceid to test transport stack etc. */
1059 memset(big, 'A', 2100);
1060 bigo.len = bigo.size = 2100;
1062 req->referenceId = &bigo;
1067 sprintf(setstring, "%d", ++setnumber);
1068 req->resultSetName = setstring;
1070 *req->smallSetUpperBound = smallSetUpperBound;
1071 *req->largeSetLowerBound = largeSetLowerBound;
1072 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1073 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1074 mediumSetPresentNumber > 0))
1078 prefsyn.proto = protocol;
1079 prefsyn.oclass = CLASS_RECSYN;
1080 prefsyn.value = recordsyntax;
1081 req->preferredRecordSyntax =
1082 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1083 req->smallSetElementSetNames =
1084 req->mediumSetElementSetNames = elementSetNames;
1086 req->num_databaseNames = num_databaseNames;
1087 req->databaseNames = databaseNames;
1089 req->query = &query;
1093 case QueryType_Prefix:
1094 query.which = Z_Query_type_1;
1095 pqf_parser = yaz_pqf_create ();
1096 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1099 const char *pqf_msg;
1101 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1102 printf("%*s^\n", off+4, "");
1103 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1105 yaz_pqf_destroy (pqf_parser);
1108 yaz_pqf_destroy (pqf_parser);
1109 query.u.type_1 = RPNquery;
1112 query.which = Z_Query_type_2;
1113 query.u.type_2 = &ccl_query;
1114 ccl_query.buf = (unsigned char*) arg;
1115 ccl_query.len = strlen(arg);
1117 case QueryType_CCL2RPN:
1118 query.which = Z_Query_type_1;
1119 RPNquery = ccl_rpn_query(out, rpn);
1122 printf ("Couldn't convert from CCL to RPN\n");
1125 query.u.type_1 = RPNquery;
1126 ccl_rpn_delete (rpn);
1129 query.which = Z_Query_type_104;
1130 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1131 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1132 ext->indirect_reference = 0;
1133 ext->descriptor = 0;
1134 ext->which = Z_External_CQL;
1135 ext->u.cql = odr_strdup(out, arg);
1136 query.u.type_104 = ext;
1139 printf ("Unsupported query type\n");
1142 if (send_apdu(apdu))
1143 printf("Sent searchRequest.\n");
1148 /* display Query Expression as part of searchResult-1 */
1149 static void display_queryExpression (Z_QueryExpression *qe)
1153 if (qe->which == Z_QueryExpression_term)
1155 if (qe->u.term->queryTerm)
1157 Z_Term *term = qe->u.term->queryTerm;
1158 switch (term->which)
1160 case Z_Term_general:
1161 printf (" %.*s", term->u.general->len, term->u.general->buf);
1163 case Z_Term_characterString:
1164 printf (" %s", term->u.characterString);
1166 case Z_Term_numeric:
1167 printf (" %d", *term->u.numeric);
1177 /* see if we can find USR:SearchResult-1 */
1178 static void display_searchResult (Z_OtherInformation *o)
1183 for (i = 0; i < o->num_elements; i++)
1185 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1187 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1189 if (ext->which == Z_External_searchResult1)
1192 Z_SearchInfoReport *sr = ext->u.searchResult1;
1193 printf ("SearchResult-1:");
1194 for (j = 0; j < sr->num; j++)
1196 if (!sr->elements[j]->subqueryExpression)
1198 display_queryExpression (
1199 sr->elements[j]->subqueryExpression);
1200 display_queryExpression (
1201 sr->elements[j]->subqueryInterpretation);
1202 display_queryExpression (
1203 sr->elements[j]->subqueryRecommendation);
1204 if (sr->elements[j]->subqueryCount)
1205 printf ("(%d)", *sr->elements[j]->subqueryCount);
1213 static int process_searchResponse(Z_SearchResponse *res)
1215 printf ("Received SearchResponse.\n");
1216 print_refid (res->referenceId);
1217 if (*res->searchStatus)
1218 printf("Search was a success.\n");
1220 printf("Search was a bloomin' failure.\n");
1221 printf("Number of hits: %d", *res->resultCount);
1223 printf (", setno %d", setnumber);
1225 display_searchResult (res->additionalSearchInfo);
1226 printf("records returned: %d\n",
1227 *res->numberOfRecordsReturned);
1228 setno += *res->numberOfRecordsReturned;
1230 display_records(res->records);
1234 static void print_level(int iLevel)
1237 for (i = 0; i < iLevel * 4; i++)
1241 static void print_int(int iLevel, const char *pTag, int *pInt)
1245 print_level(iLevel);
1246 printf("%s: %d\n", pTag, *pInt);
1250 static void print_string(int iLevel, const char *pTag, const char *pString)
1252 if (pString != NULL)
1254 print_level(iLevel);
1255 printf("%s: %s\n", pTag, pString);
1259 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1265 print_level(iLevel);
1266 printf("%s:", pTag);
1267 for (; *pInt != -1; pInt++)
1268 printf(" %d", *pInt);
1273 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1275 if (referenceId != NULL)
1279 print_level(iLevel);
1280 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1281 for (i = 0; i < referenceId->len; i++)
1282 printf("%c", referenceId->buf[i]);
1287 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1289 if (pStringNumeric != NULL)
1291 switch (pStringNumeric->which)
1293 case Z_StringOrNumeric_string:
1294 print_string(iLevel, pTag, pStringNumeric->u.string);
1297 case Z_StringOrNumeric_numeric:
1298 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1302 print_level(iLevel);
1303 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1309 static void print_universe_report_duplicate(
1311 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1313 if (pUniverseReportDuplicate != NULL)
1315 print_level(iLevel);
1316 printf("Universe Report Duplicate: \n");
1318 print_string_or_numeric(iLevel, "Hit No",
1319 pUniverseReportDuplicate->hitno);
1323 static void print_universe_report_hits(
1325 Z_UniverseReportHits *pUniverseReportHits)
1327 if (pUniverseReportHits != NULL)
1329 print_level(iLevel);
1330 printf("Universe Report Hits: \n");
1332 print_string_or_numeric(iLevel, "Database",
1333 pUniverseReportHits->database);
1334 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1338 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1340 if (pUniverseReport != NULL)
1342 print_level(iLevel);
1343 printf("Universe Report: \n");
1345 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1346 switch (pUniverseReport->which)
1348 case Z_UniverseReport_databaseHits:
1349 print_universe_report_hits(iLevel,
1350 pUniverseReport->u.databaseHits);
1353 case Z_UniverseReport_duplicate:
1354 print_universe_report_duplicate(iLevel,
1355 pUniverseReport->u.duplicate);
1359 print_level(iLevel);
1360 printf("Type: %d\n", pUniverseReport->which);
1366 static void print_external(int iLevel, Z_External *pExternal)
1368 if (pExternal != NULL)
1370 print_level(iLevel);
1371 printf("External: \n");
1373 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1374 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1375 print_string(iLevel, "Descriptor", pExternal->descriptor);
1376 switch (pExternal->which)
1378 case Z_External_universeReport:
1379 print_universe_report(iLevel, pExternal->u.universeReport);
1383 print_level(iLevel);
1384 printf("Type: %d\n", pExternal->which);
1390 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1392 printf ("Received ResourceControlRequest.\n");
1393 print_referenceId(1, req->referenceId);
1394 print_int(1, "Suspended Flag", req->suspendedFlag);
1395 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1396 print_int(1, "Response Required", req->responseRequired);
1397 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1398 print_external(1, req->resourceReport);
1402 void process_ESResponse(Z_ExtendedServicesResponse *res)
1405 switch (*res->operationStatus)
1407 case Z_ExtendedServicesResponse_done:
1410 case Z_ExtendedServicesResponse_accepted:
1411 printf ("accepted\n");
1413 case Z_ExtendedServicesResponse_failure:
1414 printf ("failure\n");
1415 display_diagrecs(res->diagnostics, res->num_diagnostics);
1418 printf ("unknown\n");
1420 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1421 (res->num_diagnostics != 0) ) {
1422 display_diagrecs(res->diagnostics, res->num_diagnostics);
1424 print_refid (res->referenceId);
1425 if (res->taskPackage &&
1426 res->taskPackage->which == Z_External_extendedService)
1428 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1429 Odr_oct *id = taskPackage->targetReference;
1430 Z_External *ext = taskPackage->taskSpecificParameters;
1434 printf ("Target Reference: ");
1435 print_stringn (id->buf, id->len);
1438 if (ext->which == Z_External_update)
1440 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1441 if (utp && utp->targetPart)
1443 Z_IUTargetPart *targetPart = utp->targetPart;
1446 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1449 Z_IUTaskPackageRecordStructure *tpr =
1450 targetPart->taskPackageRecords[i];
1451 printf ("task package record %d\n", i+1);
1452 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1454 display_record (tpr->u.record);
1458 printf ("other type\n");
1466 const char *get_ill_element (void *clientData, const char *element)
1471 static Z_External *create_external_itemRequest()
1473 struct ill_get_ctl ctl;
1474 ILL_ItemRequest *req;
1476 int item_request_size = 0;
1477 char *item_request_buf = 0;
1481 ctl.f = get_ill_element;
1483 req = ill_get_ItemRequest(&ctl, "ill", 0);
1485 printf ("ill_get_ItemRequest failed\n");
1487 if (!ill_ItemRequest (out, &req, 0, 0))
1491 ill_ItemRequest(print, &req, 0, 0);
1494 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1495 if (item_request_buf)
1496 odr_setbuf (out, item_request_buf, item_request_size, 1);
1497 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1504 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1505 oid.proto = PROTO_GENERAL;
1506 oid.oclass = CLASS_GENERAL;
1507 oid.value = VAL_ISO_ILL_1;
1509 r = (Z_External *) odr_malloc (out, sizeof(*r));
1510 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1511 r->indirect_reference = 0;
1513 r->which = Z_External_single;
1515 r->u.single_ASN1_type = (Odr_oct *)
1516 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1517 r->u.single_ASN1_type->buf = (unsigned char *)
1518 odr_malloc (out, item_request_size);
1519 r->u.single_ASN1_type->len = item_request_size;
1520 r->u.single_ASN1_type->size = item_request_size;
1521 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1524 do_hex_dump(item_request_buf,item_request_size);
1529 static Z_External *create_external_ILL_APDU(int which)
1531 struct ill_get_ctl ctl;
1534 int ill_request_size = 0;
1535 char *ill_request_buf = 0;
1539 ctl.f = get_ill_element;
1541 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1543 if (!ill_APDU (out, &ill_apdu, 0, 0))
1547 printf ("-------------------\n");
1548 ill_APDU(print, &ill_apdu, 0, 0);
1550 printf ("-------------------\n");
1552 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1553 if (ill_request_buf)
1554 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1555 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1561 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1563 oid.proto = PROTO_GENERAL;
1564 oid.oclass = CLASS_GENERAL;
1565 oid.value = VAL_ISO_ILL_1;
1567 r = (Z_External *) odr_malloc (out, sizeof(*r));
1568 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1569 r->indirect_reference = 0;
1571 r->which = Z_External_single;
1573 r->u.single_ASN1_type = (Odr_oct *)
1574 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1575 r->u.single_ASN1_type->buf = (unsigned char *)
1576 odr_malloc (out, ill_request_size);
1577 r->u.single_ASN1_type->len = ill_request_size;
1578 r->u.single_ASN1_type->size = ill_request_size;
1579 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1580 /* printf ("len = %d\n", ill_request_size); */
1581 /* do_hex_dump(ill_request_buf,ill_request_size); */
1582 /* printf("--- end of extenal\n"); */
1589 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1591 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1592 oident ItemOrderRequest;
1594 ItemOrderRequest.proto = PROTO_Z3950;
1595 ItemOrderRequest.oclass = CLASS_EXTSERV;
1596 ItemOrderRequest.value = VAL_ITEMORDER;
1598 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1599 r->indirect_reference = 0;
1602 r->which = Z_External_itemOrder;
1604 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1605 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1606 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1608 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1609 odr_malloc(out,sizeof(Z_IORequest));
1610 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1612 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1613 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1614 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1615 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1616 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1617 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1619 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1620 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1621 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1623 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1624 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1625 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1626 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1628 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1629 (int *) odr_malloc(out, sizeof(int));
1630 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1632 if (!strcmp (type, "item") || !strcmp(type, "2"))
1634 printf ("using item-request\n");
1635 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1636 create_external_itemRequest();
1638 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1640 printf ("using ILL-request\n");
1641 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1642 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1644 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1646 const char *xml_buf =
1648 " <type>request</type>\n"
1649 " <libraryNo>000200</libraryNo>\n"
1650 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1652 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1653 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1656 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1661 static int send_itemorder(const char *type, int itemno)
1663 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1664 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1665 oident ItemOrderRequest;
1667 ItemOrderRequest.proto = PROTO_Z3950;
1668 ItemOrderRequest.oclass = CLASS_EXTSERV;
1669 ItemOrderRequest.value = VAL_ITEMORDER;
1670 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1671 req->packageName = esPackageName;
1673 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1679 static int only_z3950()
1681 if (protocol == PROTO_HTTP)
1683 printf ("Not supported by SRW\n");
1689 static int cmd_update(const char *arg)
1691 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1692 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1695 Z_IUOriginPartToKeep *toKeep;
1696 Z_IUSuppliedRecords *notToKeep;
1698 char action[20], recid[20], fname[80];
1700 Z_External *record_this = 0;
1707 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1709 if (!strcmp (action, "insert"))
1710 action_no = Z_IUOriginPartToKeep_recordInsert;
1711 else if (!strcmp (action, "replace"))
1712 action_no = Z_IUOriginPartToKeep_recordReplace;
1713 else if (!strcmp (action, "delete"))
1714 action_no = Z_IUOriginPartToKeep_recordDelete;
1715 else if (!strcmp (action, "update"))
1716 action_no = Z_IUOriginPartToKeep_specialUpdate;
1719 printf ("Bad action: %s\n", action);
1720 printf ("Possible values: insert, replace, delete, update\n");
1728 stat (fname, &status);
1729 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1731 size_t len = status.st_size;
1732 char *buf = (char *) xmalloc (len);
1734 fread (buf, 1, len, inf);
1738 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1744 printf ("File %s doesn't exist\n", fname);
1752 printf ("No last record (update ignored)\n");
1755 record_this = record_last;
1758 update_oid.proto = PROTO_Z3950;
1759 update_oid.oclass = CLASS_EXTSERV;
1760 update_oid.value = VAL_DBUPDATE;
1761 oid_ent_to_oid (&update_oid, oid);
1762 req->packageType = odr_oiddup(out,oid);
1763 req->packageName = esPackageName;
1765 req->referenceId = set_refid (out);
1767 r = req->taskSpecificParameters = (Z_External *)
1768 odr_malloc (out, sizeof(*r));
1769 r->direct_reference = odr_oiddup(out,oid);
1770 r->indirect_reference = 0;
1772 r->which = Z_External_update;
1773 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1774 r->u.update->which = Z_IUUpdate_esRequest;
1775 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1776 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1777 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1778 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1779 toKeep->databaseName = databaseNames[0];
1781 toKeep->elementSetName = 0;
1782 toKeep->actionQualifier = 0;
1783 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1784 *toKeep->action = action_no;
1786 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1787 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1789 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1790 odr_malloc(out, sizeof(*notToKeep->elements));
1791 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1792 odr_malloc(out, sizeof(**notToKeep->elements));
1793 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1796 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1797 odr_malloc (out, sizeof(Odr_oct));
1798 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1799 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1800 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1803 notToKeep->elements[0]->u.opaque = 0;
1804 notToKeep->elements[0]->supplementalId = 0;
1805 notToKeep->elements[0]->correlationInfo = 0;
1806 notToKeep->elements[0]->record = record_this;
1813 static int cmd_itemorder(const char *arg)
1820 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1823 printf("Item order request\n");
1825 send_itemorder(type, itemno);
1829 static int cmd_find(const char *arg)
1833 printf("Find what?\n");
1836 if (protocol == PROTO_HTTP)
1841 if (!send_SRW_searchRequest(arg))
1854 printf("Not connected yet\n");
1858 if (!send_searchRequest(arg))
1864 static int cmd_delete(const char *arg)
1868 printf("Not connected yet\n");
1873 if (!send_deleteResultSetRequest(arg))
1878 static int cmd_ssub(const char *arg)
1880 if (!(smallSetUpperBound = atoi(arg)))
1885 static int cmd_lslb(const char *arg)
1889 if (!(largeSetLowerBound = atoi(arg)))
1894 static int cmd_mspn(const char *arg)
1898 if (!(mediumSetPresentNumber = atoi(arg)))
1903 static int cmd_status(const char *arg)
1905 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1906 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1907 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1911 static int cmd_setnames(const char *arg)
1913 if (*arg == '1') /* enable ? */
1915 else if (*arg == '0') /* disable ? */
1917 else if (setnumber < 0) /* no args, toggle .. */
1923 printf("Set numbering enabled.\n");
1925 printf("Set numbering disabled.\n");
1929 /* PRESENT SERVICE ----------------------------- */
1931 static void parse_show_args(const char *arg_c, char *setstring,
1932 int *start, int *number)
1937 strncpy(arg, arg_c, sizeof(arg)-1);
1938 arg[sizeof(arg)-1] = '\0';
1940 if ((p = strchr(arg, '+')))
1942 *number = atoi(p + 1);
1947 if (p && (p=strchr(p+1, '+')))
1948 strcpy (setstring, p+1);
1949 else if (setnumber >= 0)
1950 sprintf(setstring, "%d", setnumber);
1955 static int send_presentRequest(const char *arg)
1957 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1958 Z_PresentRequest *req = apdu->u.presentRequest;
1959 Z_RecordComposition compo;
1963 char setstring[100];
1965 req->referenceId = set_refid (out);
1967 parse_show_args(arg, setstring, &setno, &nos);
1969 req->resultSetId = setstring;
1971 req->resultSetStartPoint = &setno;
1972 req->numberOfRecordsRequested = &nos;
1973 prefsyn.proto = protocol;
1974 prefsyn.oclass = CLASS_RECSYN;
1975 prefsyn.value = recordsyntax;
1976 req->preferredRecordSyntax =
1977 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1983 prefschema.proto = protocol;
1984 prefschema.oclass = CLASS_SCHEMA;
1985 prefschema.value = oid_getvalbyname(schema);
1987 req->recordComposition = &compo;
1988 compo.which = Z_RecordComp_complex;
1989 compo.u.complex = (Z_CompSpec *)
1990 odr_malloc(out, sizeof(*compo.u.complex));
1991 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1992 odr_malloc(out, sizeof(bool_t));
1993 *compo.u.complex->selectAlternativeSyntax = 0;
1995 compo.u.complex->generic = (Z_Specification *)
1996 odr_malloc(out, sizeof(*compo.u.complex->generic));
1997 compo.u.complex->generic->which = Z_Schema_oid;
1998 compo.u.complex->generic->schema.oid = (Odr_oid *)
1999 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2000 if (!compo.u.complex->generic->schema.oid)
2002 /* OID wasn't a schema! Try record syntax instead. */
2003 prefschema.oclass = CLASS_RECSYN;
2004 compo.u.complex->generic->schema.oid = (Odr_oid *)
2005 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2007 if (!elementSetNames)
2008 compo.u.complex->generic->elementSpec = 0;
2011 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2012 odr_malloc(out, sizeof(Z_ElementSpec));
2013 compo.u.complex->generic->elementSpec->which =
2014 Z_ElementSpec_elementSetName;
2015 compo.u.complex->generic->elementSpec->u.elementSetName =
2016 elementSetNames->u.generic;
2018 compo.u.complex->num_dbSpecific = 0;
2019 compo.u.complex->dbSpecific = 0;
2020 compo.u.complex->num_recordSyntax = 0;
2021 compo.u.complex->recordSyntax = 0;
2023 else if (elementSetNames)
2025 req->recordComposition = &compo;
2026 compo.which = Z_RecordComp_simple;
2027 compo.u.simple = elementSetNames;
2030 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2035 static int send_SRW_presentRequest(const char *arg)
2037 char setstring[100];
2039 Z_SRW_PDU *sr = srw_sr;
2043 parse_show_args(arg, setstring, &setno, &nos);
2044 sr->u.request->startRecord = odr_intdup(out, setno);
2045 sr->u.request->maximumRecords = odr_intdup(out, nos);
2047 sr->u.request->recordSchema = schema;
2048 return send_srw(sr);
2052 static void close_session (void)
2059 nmem_destroy (session_mem);
2068 void process_close(Z_Close *req)
2070 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2071 Z_Close *res = apdu->u.close;
2073 static char *reasons[] =
2078 "cost limit reached",
2080 "security violation",
2087 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2088 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2093 *res->closeReason = Z_Close_finished;
2095 printf("Sent response.\n");
2100 static int cmd_show(const char *arg)
2102 if (protocol == PROTO_HTTP)
2107 if (!send_SRW_presentRequest(arg))
2117 printf("Not connected yet\n");
2120 if (!send_presentRequest(arg))
2126 int cmd_quit(const char *arg)
2128 printf("See you later, alligator.\n");
2134 int cmd_cancel(const char *arg)
2136 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2137 Z_TriggerResourceControlRequest *req =
2138 apdu->u.triggerResourceControlRequest;
2143 printf("Session not initialized yet\n");
2148 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2150 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2153 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2154 req->resultSetWanted = &rfalse;
2157 printf("Sent cancel request\n");
2161 int send_scanrequest(const char *query, int pp, int num, const char *term)
2163 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2164 Z_ScanRequest *req = apdu->u.scanRequest;
2169 if (queryType == QueryType_CCL2RPN)
2173 struct ccl_rpn_node *rpn;
2175 rpn = ccl_find_str (bibset, query, &error, &pos);
2178 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2181 bib1.proto = PROTO_Z3950;
2182 bib1.oclass = CLASS_ATTSET;
2183 bib1.value = VAL_BIB1;
2184 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2185 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2187 printf("Couldn't convert CCL to Scan term\n");
2190 ccl_rpn_delete (rpn);
2194 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2196 if (!(req->termListAndStartPoint =
2197 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2199 const char *pqf_msg;
2201 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2202 printf("%*s^\n", off+7, "");
2203 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2204 yaz_pqf_destroy (pqf_parser);
2207 yaz_pqf_destroy (pqf_parser);
2211 if (req->termListAndStartPoint->term &&
2212 req->termListAndStartPoint->term->which == Z_Term_general &&
2213 req->termListAndStartPoint->term->u.general)
2215 req->termListAndStartPoint->term->u.general->buf =
2216 (unsigned char *) odr_strdup(out, term);
2217 req->termListAndStartPoint->term->u.general->len =
2218 req->termListAndStartPoint->term->u.general->size =
2222 req->referenceId = set_refid (out);
2223 req->num_databaseNames = num_databaseNames;
2224 req->databaseNames = databaseNames;
2225 req->numberOfTermsRequested = #
2226 req->preferredPositionInResponse = &pp;
2231 int send_sortrequest(const char *arg, int newset)
2233 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2234 Z_SortRequest *req = apdu->u.sortRequest;
2235 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2236 odr_malloc (out, sizeof(*sksl));
2242 sprintf (setstring, "%d", setnumber);
2244 sprintf (setstring, "default");
2246 req->referenceId = set_refid (out);
2248 req->num_inputResultSetNames = 1;
2249 req->inputResultSetNames = (Z_InternationalString **)
2250 odr_malloc (out, sizeof(*req->inputResultSetNames));
2251 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2253 if (newset && setnumber >= 0)
2254 sprintf (setstring, "%d", ++setnumber);
2256 req->sortedResultSetName = odr_strdup (out, setstring);
2258 req->sortSequence = yaz_sort_spec (out, arg);
2259 if (!req->sortSequence)
2261 printf ("Missing sort specifications\n");
2268 void display_term(Z_TermInfo *t)
2270 if (t->term->which == Z_Term_general)
2272 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2273 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2274 t->term->u.general->buf);
2277 printf("Term (not general)");
2278 if (t->globalOccurrences)
2279 printf (" (%d)\n", *t->globalOccurrences);
2284 void process_scanResponse(Z_ScanResponse *res)
2287 Z_Entry **entries = NULL;
2288 int num_entries = 0;
2290 printf("Received ScanResponse\n");
2291 print_refid (res->referenceId);
2292 printf("%d entries", *res->numberOfEntriesReturned);
2293 if (res->positionOfTerm)
2294 printf (", position=%d", *res->positionOfTerm);
2296 if (*res->scanStatus != Z_Scan_success)
2297 printf("Scan returned code %d\n", *res->scanStatus);
2300 if ((entries = res->entries->entries))
2301 num_entries = res->entries->num_entries;
2302 for (i = 0; i < num_entries; i++)
2304 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2305 if (entries[i]->which == Z_Entry_termInfo)
2307 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2308 display_term(entries[i]->u.termInfo);
2311 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2313 if (res->entries->nonsurrogateDiagnostics)
2314 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2315 res->entries->num_nonsurrogateDiagnostics);
2318 void process_sortResponse(Z_SortResponse *res)
2320 printf("Received SortResponse: status=");
2321 switch (*res->sortStatus)
2323 case Z_SortStatus_success:
2324 printf ("success"); break;
2325 case Z_SortStatus_partial_1:
2326 printf ("partial"); break;
2327 case Z_SortStatus_failure:
2328 printf ("failure"); break;
2330 printf ("unknown (%d)", *res->sortStatus);
2333 print_refid (res->referenceId);
2334 if (res->diagnostics)
2335 display_diagrecs(res->diagnostics,
2336 res->num_diagnostics);
2339 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2341 printf("Got deleteResultSetResponse status=%d\n",
2342 *res->deleteOperationStatus);
2343 if (res->deleteListStatuses)
2346 for (i = 0; i < res->deleteListStatuses->num; i++)
2348 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2349 *res->deleteListStatuses->elements[i]->status);
2354 int cmd_sort_generic(const char *arg, int newset)
2358 printf("Session not initialized yet\n");
2363 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2365 printf("Target doesn't support sort\n");
2370 if (send_sortrequest(arg, newset) < 0)
2377 int cmd_sort(const char *arg)
2379 return cmd_sort_generic (arg, 0);
2382 int cmd_sort_newset (const char *arg)
2384 return cmd_sort_generic (arg, 1);
2387 int cmd_scan(const char *arg)
2396 printf("Session not initialized yet\n");
2400 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2402 printf("Target doesn't support scan\n");
2407 strcpy (last_scan_query, arg);
2408 if (send_scanrequest(arg, 1, 20, 0) < 0)
2413 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2419 int cmd_schema(const char *arg)
2424 schema = xstrdup(arg);
2428 int cmd_format(const char *arg)
2433 printf("Usage: format <recordsyntax>\n");
2436 nsyntax = oid_getvalbyname (arg);
2437 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2439 printf ("unknown record syntax\n");
2442 recordsyntax = nsyntax;
2446 int cmd_elements(const char *arg)
2448 static Z_ElementSetNames esn;
2449 static char what[100];
2453 elementSetNames = 0;
2457 esn.which = Z_ElementSetNames_generic;
2458 esn.u.generic = what;
2459 elementSetNames = &esn;
2463 int cmd_attributeset(const char *arg)
2469 printf("Usage: attributeset <setname>\n");
2472 sscanf(arg, "%s", what);
2473 if (p_query_attset (what))
2475 printf("Unknown attribute set name\n");
2481 int cmd_querytype (const char *arg)
2483 if (!strcmp (arg, "ccl"))
2484 queryType = QueryType_CCL;
2485 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2486 queryType = QueryType_Prefix;
2487 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2488 queryType = QueryType_CCL2RPN;
2489 else if (!strcmp(arg, "cql"))
2490 queryType = QueryType_CQL;
2493 printf ("Querytype must be one of:\n");
2494 printf (" prefix - Prefix query\n");
2495 printf (" ccl - CCL query\n");
2496 printf (" ccl2rpn - CCL query converted to RPN\n");
2497 printf (" cql - CQL\n");
2503 int cmd_refid (const char *arg)
2509 refid = (char *) xmalloc (strlen(arg)+1);
2510 strcpy (refid, arg);
2515 int cmd_close(const char *arg)
2524 apdu = zget_APDU(out, Z_APDU_close);
2525 req = apdu->u.close;
2526 *req->closeReason = Z_Close_finished;
2528 printf("Sent close request.\n");
2533 int cmd_packagename(const char* arg)
2535 xfree (esPackageName);
2536 esPackageName = NULL;
2538 esPackageName = xstrdup(arg);
2542 int cmd_proxy(const char* arg)
2547 yazProxy = xstrdup (arg);
2551 int cmd_marccharset(const char *arg)
2556 if (sscanf(arg, "%29s", l1) < 1)
2558 xfree (marcCharset);
2560 if (strcmp(l1, "-"))
2561 marcCharset = xstrdup(l1);
2565 int cmd_charset(const char* arg)
2567 char l1[30], l2[30];
2570 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2572 printf("Current negotiation character set is `%s'\n",
2573 negotiationCharset ? negotiationCharset: "none");
2574 printf("Current output character set is `%s'\n",
2575 outputCharset ? outputCharset: "none");
2578 xfree (negotiationCharset);
2579 negotiationCharset = NULL;
2580 if (*l1 && strcmp(l1, "-"))
2582 negotiationCharset = xstrdup(l1);
2583 printf ("Character set negotiation : %s\n", negotiationCharset);
2586 printf ("Character set negotiation disabled\n");
2589 xfree (outputCharset);
2591 if (!strcmp(l2, "auto") && codeset)
2595 printf ("output charset: %s\n", codeset);
2596 outputCharset = xstrdup(codeset);
2601 printf ("No codeset found on this system\n");
2603 else if (strcmp(l2, "-"))
2604 outputCharset = xstrdup(l2);
2606 printf ("Output charset conversion disabled\n");
2608 if (outputCharset && negotiationCharset)
2610 odr_set_charset (out, negotiationCharset, outputCharset);
2611 odr_set_charset (in, outputCharset, negotiationCharset);
2615 odr_set_charset (out, 0, 0);
2616 odr_set_charset (in, 0, 0);
2621 int cmd_lang(const char* arg)
2624 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2631 yazLang = (char *) xmalloc (strlen(arg)+1);
2632 strcpy (yazLang, arg);
2637 int cmd_source(const char* arg)
2639 /* first should open the file and read one line at a time.. */
2641 char line[1024], *cp;
2644 fprintf(stderr,"Error in source command use a filename\n");
2648 includeFile = fopen (arg, "r");
2651 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2655 while(!feof(includeFile)) {
2656 memset(line,0,sizeof(line));
2657 fgets(line,sizeof(line),includeFile);
2659 if(strlen(line) < 2) continue;
2660 if(line[0] == '#') continue;
2662 if ((cp = strrchr (line, '\n')))
2665 process_cmd_line(line);
2668 if(fclose(includeFile)<0) {
2669 perror("unable to close include file");
2675 int cmd_subshell(const char* args)
2680 system(getenv("SHELL"));
2686 int cmd_set_berfile(const char *arg)
2688 if (ber_file && ber_file != stdout && ber_file != stderr)
2690 if (!strcmp(arg, ""))
2692 else if (!strcmp(arg, "-"))
2695 ber_file = fopen(arg, "a");
2699 int cmd_set_apdufile(const char *arg)
2701 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2703 if (!strcmp(arg, ""))
2705 else if (!strcmp(arg, "-"))
2709 apdu_file = fopen(arg, "a");
2711 perror("unable to open apdu log file");
2714 odr_setprint(print, apdu_file);
2718 int cmd_set_cclfile(const char* arg)
2722 bibset = ccl_qual_mk ();
2723 inf = fopen (arg, "r");
2725 perror("unable to open CCL file");
2728 ccl_qual_file (bibset, inf);
2731 strcpy(ccl_fields,arg);
2735 int cmd_set_auto_reconnect(const char* arg)
2737 if(strlen(arg)==0) {
2738 auto_reconnect = ! auto_reconnect;
2739 } else if(strcmp(arg,"on")==0) {
2741 } else if(strcmp(arg,"off")==0) {
2744 printf("Error use on or off\n");
2749 printf("Set auto reconnect enabled.\n");
2751 printf("Set auto reconnect disabled.\n");
2756 int cmd_set_marcdump(const char* arg)
2758 if(marc_file && marc_file != stderr) { /* don't close stdout*/
2762 if (!strcmp(arg, ""))
2764 else if (!strcmp(arg, "-"))
2768 marc_file = fopen(arg, "a");
2770 perror("unable to open marc log file");
2775 int cmd_set_proxy(const char* arg)
2777 if(yazProxy) free(yazProxy);
2780 if(strlen(arg) > 1) {
2781 yazProxy=strdup(arg);
2787 this command takes 3 arge {name class oid}
2789 int cmd_register_oid(const char* args) {
2794 {"appctx",CLASS_APPCTX},
2795 {"absyn",CLASS_ABSYN},
2796 {"attset",CLASS_ATTSET},
2797 {"transyn",CLASS_TRANSYN},
2798 {"diagset",CLASS_DIAGSET},
2799 {"recsyn",CLASS_RECSYN},
2800 {"resform",CLASS_RESFORM},
2801 {"accform",CLASS_ACCFORM},
2802 {"extserv",CLASS_EXTSERV},
2803 {"userinfo",CLASS_USERINFO},
2804 {"elemspec",CLASS_ELEMSPEC},
2805 {"varset",CLASS_VARSET},
2806 {"schema",CLASS_SCHEMA},
2807 {"tagset",CLASS_TAGSET},
2808 {"general",CLASS_GENERAL},
2809 {0,(enum oid_class) 0}
2811 char oname_str[101], oclass_str[101], oid_str[101];
2814 oid_class oidclass = CLASS_GENERAL;
2815 int val = 0, oid[OID_SIZE];
2816 struct oident * new_oident=NULL;
2818 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2819 oname_str,oclass_str, oid_str) < 1) {
2820 printf("Error in regristrate command \n");
2824 for (i = 0; oid_classes[i].className; i++) {
2825 if (!strcmp(oid_classes[i].className, oclass_str))
2827 oidclass=oid_classes[i].oclass;
2832 if(!(oid_classes[i].className)) {
2833 printf("Unknonwn oid class %s\n",oclass_str);
2841 while (isdigit (*name))
2843 val = val*10 + (*name - '0');
2856 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2857 if(strcmp(new_oident->desc,oname_str)) {
2858 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2864 int cmd_push_command(const char* arg)
2866 #if HAVE_READLINE_HISTORY_H
2870 fprintf(stderr,"Not compiled with the readline/history module\n");
2875 void source_rcfile()
2877 /* Look for a $HOME/.yazclientrc and source it if it exists */
2878 struct stat statbuf;
2880 char* homedir=getenv("HOME");
2882 if(!homedir) return;
2884 sprintf(buffer,"%s/.yazclientrc",homedir);
2886 if(stat(buffer,&statbuf)==0) {
2890 if(stat(".yazclientrc",&statbuf)==0) {
2891 cmd_source(".yazclientrc");
2896 static void initialize(void)
2901 if (!(out = odr_createmem(ODR_ENCODE)) ||
2902 !(in = odr_createmem(ODR_DECODE)) ||
2903 !(print = odr_createmem(ODR_PRINT)))
2905 fprintf(stderr, "failed to allocate ODR streams\n");
2910 setvbuf(stdout, 0, _IONBF, 0);
2912 odr_setprint(print, apdu_file);
2914 bibset = ccl_qual_mk ();
2915 inf = fopen (ccl_fields, "r");
2918 ccl_qual_file (bibset, inf);
2921 #if HAVE_READLINE_READLINE_H
2922 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2926 for(i=0; i<maxOtherInfosSupported; ++i) {
2927 extraOtherInfos[i].oidval = -1;
2934 #if HAVE_GETTIMEOFDAY
2935 struct timeval tv_start, tv_end;
2939 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
2943 printf ("Received SRW SearchRetrieve Response\n");
2945 for (i = 0; i<res->num_diagnostics; i++)
2947 printf ("SRW diagnostic %d %s\n",
2948 *res->diagnostics[i].code,
2949 yaz_diag_srw_str(*res->diagnostics[i].code));
2951 if (res->diagnostics[i].details)
2952 printf ("Details: %s\n", res->diagnostics[i].details);
2954 if (res->numberOfRecords)
2955 printf ("Number of hits: %d\n", *res->numberOfRecords);
2956 for (i = 0; i<res->num_records; i++)
2958 Z_SRW_record *rec = res->records + i;
2960 if (rec->recordPosition)
2962 printf ("pos=%d", *rec->recordPosition);
2963 setno = *rec->recordPosition + 1;
2965 if (rec->recordSchema)
2966 printf (" schema=%s", rec->recordSchema);
2968 if (rec->recordData_buf && rec->recordData_len)
2970 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
2976 static void http_response(Z_HTTP_Response *hres)
2979 const char *content_type = z_HTTP_header_lookup(hres->headers,
2981 const char *connection_head = z_HTTP_header_lookup(hres->headers,
2983 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
2985 Z_SOAP *soap_package = 0;
2986 ODR o = odr_createmem(ODR_DECODE);
2987 Z_SOAP_Handler soap_handlers[2] = {
2988 {"http://www.loc.gov/zing/srw/v1.0/", 0,
2989 (Z_SOAP_fun) yaz_srw_codec},
2992 ret = z_soap_codec(o, &soap_package,
2993 &hres->content_buf, &hres->content_len,
2995 if (!ret && soap_package->which == Z_SOAP_generic &&
2996 soap_package->u.generic->no == 0)
2998 Z_SRW_PDU *sr = soap_package->u.generic->p;
2999 if (sr->which == Z_SRW_searchRetrieve_response)
3000 handle_srw_response(sr->u.response);
3004 else if (!ret && (soap_package->which == Z_SOAP_fault
3005 || soap_package->which == Z_SOAP_error))
3007 printf ("HTTP Error Status=%d\n", hres->code);
3008 printf ("SOAP Fault code %s\n",
3009 soap_package->u.fault->fault_code);
3010 printf ("SOAP Fault string %s\n",
3011 soap_package->u.fault->fault_string);
3019 if (hres->code != 200)
3021 printf ("HTTP Error Status=%d\n", hres->code);
3025 printf ("Decoding of SRW package failed\n");
3029 if (!strcmp(hres->version, "1.0"))
3031 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3032 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3037 /* HTTP 1.1: only if no close we stay alive .. */
3038 if (connection_head && !strcmp(connection_head, "close"))
3044 void wait_and_handle_response()
3046 int reconnect_ok = 1;
3049 int netbufferlen = 0;
3054 res = cs_get(conn, &netbuffer, &netbufferlen);
3055 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3066 buf_out = odr_getbuf(out, &len_out, 0);
3068 cs_put(conn, buf_out, len_out);
3076 printf("Target closed connection\n");
3081 odr_reset(in); /* release APDU from last round */
3083 odr_setbuf(in, netbuffer, res, 0);
3085 if (!z_GDU(in, &gdu, 0, 0))
3087 FILE *f = ber_file ? ber_file : stdout;
3088 odr_perror(in, "Decoding incoming APDU");
3089 fprintf(f, "[Near %d]\n", odr_offset(in));
3090 fprintf(f, "Packet dump:\n---------\n");
3091 odr_dumpBER(f, netbuffer, res);
3092 fprintf(f, "---------\n");
3094 z_GDU(print, &gdu, 0, 0);
3099 odr_dumpBER(ber_file, netbuffer, res);
3100 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3102 odr_perror(print, "Failed to print incoming APDU");
3106 if (gdu->which == Z_GDU_Z3950)
3108 Z_APDU *apdu = gdu->u.z3950;
3111 case Z_APDU_initResponse:
3112 process_initResponse(apdu->u.initResponse);
3114 case Z_APDU_searchResponse:
3115 process_searchResponse(apdu->u.searchResponse);
3117 case Z_APDU_scanResponse:
3118 process_scanResponse(apdu->u.scanResponse);
3120 case Z_APDU_presentResponse:
3121 print_refid (apdu->u.presentResponse->referenceId);
3123 *apdu->u.presentResponse->numberOfRecordsReturned;
3124 if (apdu->u.presentResponse->records)
3125 display_records(apdu->u.presentResponse->records);
3127 printf("No records.\n");
3128 printf ("nextResultSetPosition = %d\n",
3129 *apdu->u.presentResponse->nextResultSetPosition);
3131 case Z_APDU_sortResponse:
3132 process_sortResponse(apdu->u.sortResponse);
3134 case Z_APDU_extendedServicesResponse:
3135 printf("Got extended services response\n");
3136 process_ESResponse(apdu->u.extendedServicesResponse);
3139 printf("Target has closed the association.\n");
3140 process_close(apdu->u.close);
3142 case Z_APDU_resourceControlRequest:
3143 process_resourceControlRequest
3144 (apdu->u.resourceControlRequest);
3146 case Z_APDU_deleteResultSetResponse:
3147 process_deleteResultSetResponse(apdu->u.
3148 deleteResultSetResponse);
3151 printf("Received unknown APDU type (%d).\n",
3157 else if (gdu->which == Z_GDU_HTTP_Response)
3159 http_response(gdu->u.HTTP_Response);
3162 if (conn && !cs_more(conn))
3167 #if HAVE_GETTIMEOFDAY
3168 gettimeofday (&tv_end, 0);
3170 printf ("S/U S/U=%ld/%ld %ld/%ld",
3171 (long) tv_start.tv_sec,
3172 (long) tv_start.tv_usec,
3173 (long) tv_end.tv_sec,
3174 (long) tv_end.tv_usec);
3176 printf ("Elapsed: %.6f\n",
3177 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3178 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3185 int cmd_cclparse(const char* arg)
3188 struct ccl_rpn_node *rpn=NULL;
3191 rpn = ccl_find_str (bibset, arg, &error, &pos);
3194 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3195 printf ("%s\n", ccl_err_msg (error));
3201 ccl_pr_tree(rpn, stdout);
3205 ccl_rpn_delete(rpn);
3213 int cmd_set_otherinfo(const char* args)
3215 char oid[101], otherinfoString[101];
3220 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3222 /* reset this otherinfo */
3223 if(otherinfoNo>=maxOtherInfosSupported) {
3224 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3226 extraOtherInfos[otherinfoNo].oidval = -1;
3227 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3231 printf("Error in set_otherinfo command \n");
3235 if(otherinfoNo>=maxOtherInfosSupported) {
3236 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3240 oidval = oid_getvalbyname (oid);
3242 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3245 extraOtherInfos[otherinfoNo].oidval = oidval;
3246 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3247 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3252 int cmd_list_otherinfo(const char* args)
3256 if(strlen(args)>0) {
3258 if( i >= maxOtherInfosSupported ) {
3259 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3263 if(extraOtherInfos[i].oidval != -1)
3264 printf(" otherinfo %d %s %s\n",
3266 yaz_z3950_oid_value_to_str(
3267 (enum oid_value) extraOtherInfos[i].oidval,
3269 extraOtherInfos[i].value);
3272 for(i=0; i<maxOtherInfosSupported; ++i) {
3273 if(extraOtherInfos[i].oidval != -1)
3274 printf(" otherinfo %d %s %s\n",
3276 yaz_z3950_oid_value_to_str(
3277 (enum oid_value) extraOtherInfos[i].oidval,
3279 extraOtherInfos[i].value);
3287 int cmd_list_all(const char* args) {
3290 /* connection options */
3292 printf("Connected to : %s\n",last_open_command);
3294 if(last_open_command)
3295 printf("Not connected to : %s\n",last_open_command);
3297 printf("Not connected : \n");
3300 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3302 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3305 printf("Authentication : none\n");
3307 switch(auth->which) {
3308 case Z_IdAuthentication_idPass:
3309 printf("Authentication : IdPass\n");
3310 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3311 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3312 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3314 case Z_IdAuthentication_open:
3315 printf("Authentication : psOpen\n");
3316 printf(" Open string : %s\n",auth->u.open);
3319 printf("Authentication : Unknown\n");
3322 if (negotiationCharset)
3323 printf("Neg. Character set : `%s'\n", negotiationCharset);
3327 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3331 printf("CCL file : %s\n",ccl_fields);
3332 printf("Query type : %s\n",query_type_as_string(queryType));
3334 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3336 /* piggy back options */
3337 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3339 /* print present related options */
3340 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3341 printf("Schema : %s\n",schema);
3342 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3344 /* loging options */
3345 printf("APDU log : %s\n",apdu_file?"on":"off");
3346 printf("Record log : %s\n",marc_file?"on":"off");
3349 printf("Other Info: \n");
3350 cmd_list_otherinfo("");
3355 int cmd_clear_otherinfo(const char* args)
3357 if(strlen(args)>0) {
3359 otherinfoNo = atoi(args);
3360 if( otherinfoNo >= maxOtherInfosSupported ) {
3361 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3365 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3366 /* only clear if set. */
3367 extraOtherInfos[otherinfoNo].oidval=-1;
3368 free(extraOtherInfos[otherinfoNo].value);
3373 for(i=0; i<maxOtherInfosSupported; ++i) {
3374 if (extraOtherInfos[i].oidval!=-1 ) {
3375 extraOtherInfos[i].oidval=-1;
3376 free(extraOtherInfos[i].value);
3383 static int cmd_help (const char *line);
3385 typedef char *(*completerFunctionType)(const char *text, int state);
3389 int (*fun)(const char *arg);
3391 completerFunctionType rl_completerfunction;
3392 int complete_filenames;
3393 char **local_tabcompletes;
3395 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3396 {"quit", cmd_quit, "",NULL,0,NULL},
3397 {"find", cmd_find, "<query>",NULL,0,NULL},
3398 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3399 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3400 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3401 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3402 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3403 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3404 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3405 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3406 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3407 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3408 {"status", cmd_status, "",NULL,0,NULL},
3409 {"setnames", cmd_setnames, "",NULL,0,NULL},
3410 {"cancel", cmd_cancel, "",NULL,0,NULL},
3411 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3412 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3413 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3414 {"close", cmd_close, "",NULL,0,NULL},
3415 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3416 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3417 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3418 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3419 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3420 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3421 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3422 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3423 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3424 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3425 {".", cmd_source, "<filename>",NULL,1,NULL},
3426 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3427 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3428 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3429 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3430 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3431 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3432 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3433 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3434 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3435 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3436 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3437 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3438 {"list_all",cmd_list_all,"",NULL,0,NULL},
3439 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3440 /* Server Admin Functions */
3441 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3442 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3443 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3444 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3445 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3446 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3447 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3448 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3449 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3450 {"help", cmd_help, "", NULL,0,NULL},
3454 static int cmd_help (const char *line)
3460 sscanf (line, "%20s", topic);
3463 printf("Commands:\n");
3464 for (i = 0; cmd_array[i].cmd; i++)
3465 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3466 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3467 if (strcmp (topic, "find") == 0)
3470 printf (" \"term\" Simple Term\n");
3471 printf (" @attr [attset] type=value op Attribute\n");
3472 printf (" @and opl opr And\n");
3473 printf (" @or opl opr Or\n");
3474 printf (" @not opl opr And-Not\n");
3475 printf (" @set set Result set\n");
3477 printf ("Bib-1 attribute types\n");
3479 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3480 printf ("2=Relation: ");
3481 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3482 printf ("3=Position: ");
3483 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3484 printf ("4=Structure: ");
3485 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3486 printf ("5=Truncation: ");
3487 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3488 printf ("6=Completeness:");
3489 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3494 int cmd_register_tab(const char* arg) {
3496 char command[101], tabargument[101];
3501 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3505 /* locate the amdn in the list */
3506 for (i = 0; cmd_array[i].cmd; i++) {
3507 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3512 if(!cmd_array[i].cmd) {
3513 fprintf(stderr,"Unknown command %s\n",command);
3518 if(!cmd_array[i].local_tabcompletes)
3519 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3523 tabslist = cmd_array[i].local_tabcompletes;
3524 for(;tabslist && *tabslist;tabslist++) {
3528 cmd_array[i].local_tabcompletes = (char **)
3529 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3530 tabslist=cmd_array[i].local_tabcompletes;
3531 tabslist[num_of_tabs]=strdup(tabargument);
3532 tabslist[num_of_tabs+1]=NULL;
3537 void process_cmd_line(char* line)
3540 char word[32], arg[1024];
3542 #if HAVE_GETTIMEOFDAY
3543 gettimeofday (&tv_start, 0);
3546 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3548 strcpy(word, last_cmd);
3553 strcpy(last_cmd, word);
3555 /* removed tailing spaces from the arg command */
3558 char* lastnonspace=NULL;
3566 *(++lastnonspace) = 0;
3569 for (i = 0; cmd_array[i].cmd; i++)
3570 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3572 res = (*cmd_array[i].fun)(arg);
3576 if (!cmd_array[i].cmd) /* dump our help-screen */
3578 printf("Unknown command: %s.\n", word);
3579 printf("use help for list of commands\n");
3580 /* cmd_help (""); */
3584 if(apdu_file) fflush(apdu_file);
3587 wait_and_handle_response();
3596 char *command_generator(const char *text, int state)
3602 for( ; cmd_array[idx].cmd; ++idx) {
3603 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3604 ++idx; /* skip this entry on the next run */
3605 return strdup(cmd_array[idx-1].cmd);
3613 This function only known how to complete on the first word
3615 char ** readline_completer(char *text, int start, int end) {
3616 #if HAVE_READLINE_READLINE_H
3618 completerFunctionType completerToUse;
3621 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3622 char** res=rl_completion_matches(text,
3625 char** res=completion_matches(text,
3626 (CPFunction*)command_generator);
3628 rl_attempted_completion_over = 1;
3631 char arg[1024],word[32];
3633 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3634 rl_attempted_completion_over = 1;
3638 for (i = 0; cmd_array[i].cmd; i++) {
3639 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3644 if(!cmd_array[i].cmd) return NULL;
3646 curret_global_list = cmd_array[i].local_tabcompletes;
3648 completerToUse = cmd_array[i].rl_completerfunction;
3649 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3650 completerToUse = default_completer;
3652 if(completerToUse) {
3653 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3655 rl_completion_matches(text,
3659 completion_matches(text,
3660 (CPFunction*)completerToUse);
3662 if(!cmd_array[i].complete_filenames)
3663 rl_attempted_completion_over = 1;
3666 if(!cmd_array[i].complete_filenames)
3667 rl_attempted_completion_over = 1;
3677 static void client(void)
3683 #if HAVE_GETTIMEOFDAY
3684 gettimeofday (&tv_start, 0);
3689 char *line_in = NULL;
3690 #if HAVE_READLINE_READLINE_H
3693 line_in=readline(C_PROMPT);
3696 #if HAVE_READLINE_HISTORY_H
3698 add_history(line_in);
3700 strncpy(line, line_in, 1023);
3709 if (!fgets(line, 1023, stdin))
3711 if ((end_p = strchr (line, '\n')))
3714 process_cmd_line(line);
3718 static void show_version(void)
3722 yaz_version(vstr, 0);
3723 printf ("YAZ version: %s\n", YAZ_VERSION);
3724 if (strcmp(vstr, YAZ_VERSION))
3725 printf ("YAZ DLL/SO: %s\n", vstr);
3729 int main(int argc, char **argv)
3732 char *open_command = 0;
3733 char *auth_command = 0;
3738 if (!setlocale(LC_CTYPE, ""))
3739 fprintf (stderr, "setlocale failed\n");
3743 codeset = nl_langinfo(CODESET);
3747 while ((ret = options("k:c:a:b:m:v:p:u:t:V", argv, argc, &arg)) != -2)
3754 open_command = (char *) xmalloc (strlen(arg)+6);
3755 strcpy (open_command, "open ");
3756 strcat (open_command, arg);
3760 kilobytes = atoi(arg);
3763 if (!(marc_file = fopen (arg, "a")))
3770 outputCharset = xstrdup(arg);
3773 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3774 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3777 if (!strcmp(arg, "-"))
3780 ber_file=fopen(arg, "a");
3783 if (!strcmp(arg, "-"))
3786 apdu_file=fopen(arg, "a");
3789 yazProxy=strdup(arg);
3794 auth_command = (char *) xmalloc (strlen(arg)+6);
3795 strcpy (auth_command, "auth ");
3796 strcat (auth_command, arg);
3800 yaz_log_init(yaz_log_mask_str(arg), "", 0);
3806 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3807 "[-b berdump] [-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3808 "[-k size] [-V] [<server-addr>]\n",
3816 #ifdef HAVE_GETTIMEOFDAY
3817 gettimeofday (&tv_start, 0);
3819 process_cmd_line (auth_command);
3820 #if HAVE_READLINE_HISTORY_H
3821 add_history(auth_command);
3823 xfree(auth_command);
3827 #ifdef HAVE_GETTIMEOFDAY
3828 gettimeofday (&tv_start, 0);
3830 process_cmd_line (open_command);
3831 #if HAVE_READLINE_HISTORY_H
3832 add_history(open_command);
3834 xfree(open_command);
3845 * vim600: sw=4 ts=8 fdm=marker
3846 * vim<600: sw=4 ts=8