Use _strtoui64 on Windows
[yaz-moved-to-github.git] / ztest / ztest.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2009 Index Data
3  * See the file LICENSE for details.
4  */
5
6 /** \file
7  * \brief yaz-ztest Generic Frontend Server
8  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <ctype.h>
13 #if HAVE_UNISTD_H
14 #include <unistd.h>
15 #endif
16
17 #include <yaz/log.h>
18 #include <yaz/backend.h>
19 #include <yaz/ill.h>
20 #include <yaz/diagbib1.h>
21
22 #include "ztest.h"
23
24 static int log_level=0;
25 static int log_level_set=0;
26
27 int ztest_search(void *handle, bend_search_rr *rr);
28 int ztest_sort(void *handle, bend_sort_rr *rr);
29 int ztest_present(void *handle, bend_present_rr *rr);
30 int ztest_esrequest(void *handle, bend_esrequest_rr *rr);
31 int ztest_delete(void *handle, bend_delete_rr *rr);
32
33 /** \brief use term value as hit count 
34     \param s RPN structure
35     \return >= 0: search term number or -1: not found
36    
37     Traverse RPN tree 'in order' and use term value as hit count.
38     Only terms  that looks a numeric is used.. Returns -1 if
39     no sub tree has a hit count term
40 */
41 static Odr_int get_term_hit(Z_RPNStructure *s)
42 {
43     Odr_int h = -1;
44     switch(s->which)
45     {
46     case Z_RPNStructure_simple:
47         if (s->u.simple->which == Z_Operand_APT)
48         {
49             Z_AttributesPlusTerm *apt = s->u.simple->u.attributesPlusTerm;
50             if (apt->term->which == Z_Term_general)
51             {
52                 Odr_oct *oct = apt->term->u.general;
53                 if (oct->len > 0 && oct->buf[0] >= '0' && oct->buf[0] <= '9')
54                 {
55                     char *endptr;
56                     WRBUF hits_str = wrbuf_alloc();
57                     wrbuf_write(hits_str, (const char *) oct->buf, oct->len);
58 #ifdef WIN32
59                     h = _strtoui64(wrbuf_cstr(hits_str), &endptr, 10);
60 #else
61                     h = strtoll(wrbuf_cstr(hits_str), &endptr, 10);
62 #endif
63                     wrbuf_destroy(hits_str);
64                 }
65             }
66         }
67         break;
68     case Z_RPNStructure_complex:
69         h = get_term_hit(s->u.complex->s1);
70         if (h == -1)
71             h = get_term_hit(s->u.complex->s2);
72         break;
73     }
74     return h;
75 }
76
77 /** \brief gets hit count for numeric terms in RPN queries
78     \param q RPN Query
79     \return number of hits (random or number for term)
80     
81     This is just for testing.. A real database of course uses
82     the content of a database to establish a value.. In our case, we
83     have a way to trigger a certain hit count. Good for testing of
84     client applications etc
85 */
86 static Odr_int get_hit_count(Z_Query *q)
87 {
88     Odr_int h = -1;
89     if (q->which == Z_Query_type_1 || q->which == Z_Query_type_101)
90         h = get_term_hit(q->u.type_1->RPNStructure);
91     if (h == -1)
92         h = rand() % 24;
93     return h;
94 }
95
96 /** \brief checks if it's a dummy Slow database..
97     \param basename database name to check
98     \param association backend association (or NULL if not available)
99     \retval 1 is slow database
100     \retval 0 is not a slow database
101
102     The Slow database is for testing.. It allows us to simulate
103     a slow server...
104 */
105 static int check_slow(const char *basename, bend_association association)
106 {
107     if (strncmp(basename, "Slow", 4) == 0)
108     {
109 #if HAVE_UNISTD_H
110         int i, w = 3;
111         if (basename[4])
112             sscanf(basename+4, "%d", &w);
113         /* wait up to 3 seconds and check if connection is still alive */
114         for (i = 0; i < w; i++)
115         {
116             if (association && !bend_assoc_is_alive(association))
117             {
118                 yaz_log(YLOG_LOG, "search aborted");
119                 break;
120             }
121             sleep(1);
122         }
123 #endif
124         return 1;
125     }
126     return 0;
127 }
128
129 int ztest_search(void *handle, bend_search_rr *rr)
130 {
131     if (rr->num_bases != 1)
132     {
133         rr->errcode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
134         return 0;
135     }
136     /* Throw Database unavailable if other than Default or Slow */
137     if (!yaz_matchstr(rr->basenames[0], "Default"))
138         ;  /* Default is OK in our test */
139     else if (check_slow(rr->basenames[0], rr->association))
140     {
141         rr->estimated_hit_count = 1;
142     }
143     else
144     {
145         rr->errcode = YAZ_BIB1_DATABASE_UNAVAILABLE;
146         rr->errstring = rr->basenames[0];
147         return 0;
148     }
149
150     if (rr->extra_args)
151     {
152         Z_SRW_extra_arg *a;
153         WRBUF response_xml = wrbuf_alloc();
154         wrbuf_puts(response_xml, "<extra>");
155         for (a = rr->extra_args; a; a = a->next)
156         {
157             wrbuf_puts(response_xml, "<extra name=\"");
158             wrbuf_xmlputs(response_xml, a->name);
159             wrbuf_puts(response_xml, "\"");
160             if (a->value)
161             {
162                 wrbuf_puts(response_xml, " value=\"");
163                 wrbuf_xmlputs(response_xml, a->value);
164                 wrbuf_puts(response_xml, "\"");
165             }
166             wrbuf_puts(response_xml, "/>");
167         }
168         wrbuf_puts(response_xml, "</extra>");
169         rr->extra_response_data =
170             odr_strdup(rr->stream, wrbuf_cstr(response_xml));
171         wrbuf_destroy(response_xml);
172     }
173     rr->hits = get_hit_count(rr->query);
174     return 0;
175 }
176
177
178 /* this huge function handles extended services */
179 int ztest_esrequest(void *handle, bend_esrequest_rr *rr)
180 {
181     /* user-defined handle - created in bend_init */
182     int *counter = (int*) handle;  
183
184     yaz_log(log_level, "ESRequest no %d", *counter);
185
186     (*counter)++;
187
188     if (rr->esr->packageName)
189         yaz_log(log_level, "packagename: %s", rr->esr->packageName);
190     yaz_log(log_level, "Waitaction: " ODR_INT_PRINTF, *rr->esr->waitAction);
191
192
193     yaz_log(log_level, "function: " ODR_INT_PRINTF, *rr->esr->function);
194
195     if (!rr->esr->taskSpecificParameters)
196     {
197         yaz_log(log_level, "No task specific parameters");
198     }
199     else if (rr->esr->taskSpecificParameters->which == Z_External_itemOrder)
200     {
201         Z_ItemOrder *it = rr->esr->taskSpecificParameters->u.itemOrder;
202         yaz_log(log_level, "Received ItemOrder");
203         if (it->which == Z_IOItemOrder_esRequest)
204         {
205             Z_IORequest *ir = it->u.esRequest;
206             Z_IOOriginPartToKeep *k = ir->toKeep;
207             Z_IOOriginPartNotToKeep *n = ir->notToKeep;
208             const char *xml_in_response = 0;
209             
210             if (k && k->contact)
211             {
212                 if (k->contact->name)
213                     yaz_log(log_level, "contact name %s", k->contact->name);
214                 if (k->contact->phone)
215                     yaz_log(log_level, "contact phone %s", k->contact->phone);
216                 if (k->contact->email)
217                     yaz_log(log_level, "contact email %s", k->contact->email);
218             }
219             if (k->addlBilling)
220             {
221                 yaz_log(log_level, "Billing info (not shown)");
222             }
223             
224             if (n->resultSetItem)
225             {
226                 yaz_log(log_level, "resultsetItem");
227                 yaz_log(log_level, "setId: %s", n->resultSetItem->resultSetId);
228                 yaz_log(log_level, "item: " ODR_INT_PRINTF, *n->resultSetItem->item);
229             }
230             if (n->itemRequest)
231             {
232                 Z_External *r = (Z_External*) n->itemRequest;
233                 ILL_ItemRequest *item_req = 0;
234                 ILL_APDU *ill_apdu = 0;
235                 if (r->direct_reference)
236                 {
237                     char oid_name_str[OID_STR_MAX];
238                     oid_class oclass;
239                     const char *oid_name = 
240                         yaz_oid_to_string_buf(r->direct_reference,
241                                               &oclass, oid_name_str);
242                     if (oid_name)
243                         yaz_log(log_level, "OID %s", oid_name);
244                     if (!oid_oidcmp(r->direct_reference, yaz_oid_recsyn_xml))
245                     {
246                         yaz_log(log_level, "ILL XML request");
247                         if (r->which == Z_External_octet)
248                             yaz_log(log_level, "%.*s",
249                                     r->u.octet_aligned->len,
250                                     r->u.octet_aligned->buf); 
251                         xml_in_response = "<dummy>x</dummy>";
252                     }
253                     if (!oid_oidcmp(r->direct_reference, 
254                                     yaz_oid_general_isoill_1))
255                     {
256                         yaz_log(log_level, "Decode ItemRequest begin");
257                         if (r->which == ODR_EXTERNAL_single)
258                         {
259                             odr_setbuf(rr->decode,
260                                        (char *) r->u.single_ASN1_type->buf,
261                                        r->u.single_ASN1_type->len, 0);
262                             
263                             if (!ill_ItemRequest(rr->decode, &item_req, 0, 0))
264                             {
265                                 yaz_log(log_level,
266                                         "Couldn't decode ItemRequest %s near %ld",
267                                         odr_errmsg(odr_geterror(rr->decode)),
268                                         (long) odr_offset(rr->decode));
269                             }
270                             else
271                                 yaz_log(log_level, "Decode ItemRequest OK");
272                             if (rr->print)
273                             {
274                                 ill_ItemRequest(rr->print, &item_req, 0,
275                                                 "ItemRequest");
276                                 odr_reset(rr->print);
277                             }
278                         }
279                         if (!item_req && r->which == ODR_EXTERNAL_single)
280                         {
281                             yaz_log(log_level, "Decode ILL APDU begin");
282                             odr_setbuf(rr->decode,
283                                        (char*) r->u.single_ASN1_type->buf,
284                                        r->u.single_ASN1_type->len, 0);
285                             
286                             if (!ill_APDU(rr->decode, &ill_apdu, 0, 0))
287                             {
288                                 yaz_log(log_level,
289                                         "Couldn't decode ILL APDU %s near %ld",
290                                         odr_errmsg(odr_geterror(rr->decode)),
291                                         (long) odr_offset(rr->decode));
292                                 yaz_log(log_level, "PDU dump:");
293                                 odr_dumpBER(yaz_log_file(),
294                                             (char *) r->u.single_ASN1_type->buf,
295                                             r->u.single_ASN1_type->len);
296                             }
297                             else
298                                 yaz_log(log_level, "Decode ILL APDU OK");
299                             if (rr->print)
300                             {
301                                 ill_APDU(rr->print, &ill_apdu, 0,
302                                          "ILL APDU");
303                                 odr_reset(rr->print);
304                             }
305                         }
306                     }
307                 }
308                 if (item_req)
309                 {
310                     yaz_log(log_level, "ILL protocol version = "
311                             ODR_INT_PRINTF,
312                             *item_req->protocol_version_num);
313                 }
314             }
315             if (k)
316             {
317
318                 Z_External *ext = (Z_External *)
319                     odr_malloc(rr->stream, sizeof(*ext));
320                 Z_IUOriginPartToKeep *keep = (Z_IUOriginPartToKeep *)
321                     odr_malloc(rr->stream, sizeof(*keep));
322                 Z_IOTargetPart *targetPart = (Z_IOTargetPart *)
323                     odr_malloc(rr->stream, sizeof(*targetPart));
324
325                 rr->taskPackage = (Z_TaskPackage *)
326                     odr_malloc(rr->stream, sizeof(*rr->taskPackage));
327                 rr->taskPackage->packageType =
328                     odr_oiddup(rr->stream, rr->esr->packageType);
329                 rr->taskPackage->packageName = 0;
330                 rr->taskPackage->userId = 0;
331                 rr->taskPackage->retentionTime = 0;
332                 rr->taskPackage->permissions = 0;
333                 rr->taskPackage->description = 0;
334                 rr->taskPackage->targetReference = (Odr_oct *)
335                     odr_malloc(rr->stream, sizeof(Odr_oct));
336                 rr->taskPackage->targetReference->buf =
337                     (unsigned char *) odr_strdup(rr->stream, "911");
338                 rr->taskPackage->targetReference->len =
339                     rr->taskPackage->targetReference->size =
340                     strlen((char *) (rr->taskPackage->targetReference->buf));
341                 rr->taskPackage->creationDateTime = 0;
342                 rr->taskPackage->taskStatus = odr_intdup(rr->stream, 0);
343                 rr->taskPackage->packageDiagnostics = 0;
344                 rr->taskPackage->taskSpecificParameters = ext;
345
346                 ext->direct_reference =
347                     odr_oiddup(rr->stream, rr->esr->packageType);
348                 ext->indirect_reference = 0;
349                 ext->descriptor = 0;
350                 ext->which = Z_External_itemOrder;
351                 ext->u.itemOrder = (Z_ItemOrder *)
352                     odr_malloc(rr->stream, sizeof(*ext->u.update));
353                 ext->u.itemOrder->which = Z_IOItemOrder_taskPackage;
354                 ext->u.itemOrder->u.taskPackage =  (Z_IOTaskPackage *)
355                     odr_malloc(rr->stream, sizeof(Z_IOTaskPackage));
356                 ext->u.itemOrder->u.taskPackage->originPart = k;
357                 ext->u.itemOrder->u.taskPackage->targetPart = targetPart;
358
359                 if (xml_in_response)
360                     targetPart->itemRequest =
361                         z_ext_record_xml(rr->stream, xml_in_response,
362                                          strlen(xml_in_response));
363                 else
364                     targetPart->itemRequest = 0;
365                     
366                 targetPart->statusOrErrorReport = 0;
367                 targetPart->auxiliaryStatus = 0;
368             }
369         }
370     }
371     else if (rr->esr->taskSpecificParameters->which == Z_External_update)
372     {
373         Z_IUUpdate *up = rr->esr->taskSpecificParameters->u.update;
374         yaz_log(log_level, "Received DB Update");
375         if (up->which == Z_IUUpdate_esRequest)
376         {
377             Z_IUUpdateEsRequest *esRequest = up->u.esRequest;
378             Z_IUOriginPartToKeep *toKeep = esRequest->toKeep;
379             Z_IUSuppliedRecords *notToKeep = esRequest->notToKeep;
380             
381             yaz_log(log_level, "action");
382             if (toKeep->action)
383             {
384                 switch (*toKeep->action)
385                 {
386                 case Z_IUOriginPartToKeep_recordInsert:
387                     yaz_log(log_level, " recordInsert");
388                     break;
389                 case Z_IUOriginPartToKeep_recordReplace:
390                     yaz_log(log_level, " recordReplace");
391                     break;
392                 case Z_IUOriginPartToKeep_recordDelete:
393                     yaz_log(log_level, " recordDelete");
394                     break;
395                 case Z_IUOriginPartToKeep_elementUpdate:
396                     yaz_log(log_level, " elementUpdate");
397                     break;
398                 case Z_IUOriginPartToKeep_specialUpdate:
399                     yaz_log(log_level, " specialUpdate");
400                     break;
401                 default:
402                     yaz_log(log_level, " unknown (" ODR_INT_PRINTF ")",
403                             *toKeep->action);
404                 }
405             }
406             if (toKeep->databaseName)
407             {
408                 yaz_log(log_level, "database: %s", toKeep->databaseName);
409                 if (!strcmp(toKeep->databaseName, "fault"))
410                 {
411                     rr->errcode = YAZ_BIB1_DATABASE_UNAVAILABLE;
412                     rr->errstring = toKeep->databaseName;
413                 }
414                 if (!strcmp(toKeep->databaseName, "accept"))
415                     rr->errcode = -1;
416             }
417             if (toKeep)
418             {
419                 Z_External *ext = (Z_External *)
420                     odr_malloc(rr->stream, sizeof(*ext));
421                 Z_IUOriginPartToKeep *keep = (Z_IUOriginPartToKeep *)
422                     odr_malloc(rr->stream, sizeof(*keep));
423                 Z_IUTargetPart *targetPart = (Z_IUTargetPart *)
424                     odr_malloc(rr->stream, sizeof(*targetPart));
425
426                 rr->taskPackage = (Z_TaskPackage *)
427                     odr_malloc(rr->stream, sizeof(*rr->taskPackage));
428                 rr->taskPackage->packageType =
429                     odr_oiddup(rr->stream, rr->esr->packageType);
430                 rr->taskPackage->packageName = 0;
431                 rr->taskPackage->userId = 0;
432                 rr->taskPackage->retentionTime = 0;
433                 rr->taskPackage->permissions = 0;
434                 rr->taskPackage->description = 0;
435                 rr->taskPackage->targetReference = (Odr_oct *)
436                     odr_malloc(rr->stream, sizeof(Odr_oct));
437                 rr->taskPackage->targetReference->buf =
438                     (unsigned char *) odr_strdup(rr->stream, "123");
439                 rr->taskPackage->targetReference->len =
440                     rr->taskPackage->targetReference->size =
441                     strlen((char *) (rr->taskPackage->targetReference->buf));
442                 rr->taskPackage->creationDateTime = 0;
443                 rr->taskPackage->taskStatus = odr_intdup(rr->stream, 0);
444                 rr->taskPackage->packageDiagnostics = 0;
445                 rr->taskPackage->taskSpecificParameters = ext;
446
447                 ext->direct_reference =
448                     odr_oiddup(rr->stream, rr->esr->packageType);
449                 ext->indirect_reference = 0;
450                 ext->descriptor = 0;
451                 ext->which = Z_External_update;
452                 ext->u.update = (Z_IUUpdate *)
453                     odr_malloc(rr->stream, sizeof(*ext->u.update));
454                 ext->u.update->which = Z_IUUpdate_taskPackage;
455                 ext->u.update->u.taskPackage =  (Z_IUUpdateTaskPackage *)
456                     odr_malloc(rr->stream, sizeof(Z_IUUpdateTaskPackage));
457                 ext->u.update->u.taskPackage->originPart = keep;
458                 ext->u.update->u.taskPackage->targetPart = targetPart;
459
460                 keep->action = odr_intdup(rr->stream, *toKeep->action);
461                 keep->databaseName =
462                     odr_strdup(rr->stream, toKeep->databaseName);
463                 keep->schema = 0;
464                 keep->elementSetName = 0;
465                 keep->actionQualifier = 0;
466
467                 targetPart->updateStatus = odr_intdup(rr->stream, 1);
468                 targetPart->num_globalDiagnostics = 0;
469                 targetPart->globalDiagnostics = (Z_DiagRec **) odr_nullval();
470                 targetPart->num_taskPackageRecords = 1;
471                 targetPart->taskPackageRecords = 
472                     (Z_IUTaskPackageRecordStructure **)
473                     odr_malloc(rr->stream,
474                                sizeof(Z_IUTaskPackageRecordStructure *));
475                 targetPart->taskPackageRecords[0] =
476                     (Z_IUTaskPackageRecordStructure *)
477                     odr_malloc(rr->stream,
478                                sizeof(Z_IUTaskPackageRecordStructure));
479                 
480                 targetPart->taskPackageRecords[0]->which =
481                     Z_IUTaskPackageRecordStructure_record;
482                 targetPart->taskPackageRecords[0]->u.record = 
483                     z_ext_record_sutrs(rr->stream, "test", 4);
484                 targetPart->taskPackageRecords[0]->correlationInfo = 0; 
485                 targetPart->taskPackageRecords[0]->recordStatus =
486                     odr_intdup(rr->stream,
487                                Z_IUTaskPackageRecordStructure_success);  
488                 targetPart->taskPackageRecords[0]->num_supplementalDiagnostics
489                     = 0;
490
491                 targetPart->taskPackageRecords[0]->supplementalDiagnostics = 0;
492             }
493             if (notToKeep)
494             {
495                 int i;
496                 for (i = 0; i < notToKeep->num; i++)
497                 {
498                     Z_External *rec = notToKeep->elements[i]->record;
499
500                     if (rec->direct_reference)
501                     {
502                         char oid_name_str[OID_STR_MAX];
503                         const char *oid_name 
504                             = oid_name = yaz_oid_to_string_buf(
505                                 rec->direct_reference, 0,
506                                 oid_name_str);
507                         if (oid_name)
508                             yaz_log(log_level, "record %d type %s", i,
509                                     oid_name);
510                     }
511                     switch (rec->which)
512                     {
513                     case Z_External_sutrs:
514                         if (rec->u.octet_aligned->len > 170)
515                             yaz_log(log_level, "%d bytes:\n%.168s ...",
516                                     rec->u.sutrs->len,
517                                     rec->u.sutrs->buf);
518                         else
519                             yaz_log(log_level, "%d bytes:\n%s",
520                                     rec->u.sutrs->len,
521                                     rec->u.sutrs->buf);
522                         break;
523                     case Z_External_octet        :
524                         if (rec->u.octet_aligned->len > 170)
525                             yaz_log(log_level, "%d bytes:\n%.168s ...",
526                                     rec->u.octet_aligned->len,
527                                     rec->u.octet_aligned->buf);
528                         else
529                             yaz_log(log_level, "%d bytes\n%s",
530                                     rec->u.octet_aligned->len,
531                                     rec->u.octet_aligned->buf);
532                     }
533                 }
534             }
535         }
536     }
537     return 0;
538 }
539
540 /* result set delete */
541 int ztest_delete(void *handle, bend_delete_rr *rr)
542 {
543     if (rr->num_setnames == 1 && !strcmp(rr->setnames[0], "1"))
544         rr->delete_status = Z_DeleteStatus_success;
545     else
546         rr->delete_status = Z_DeleteStatus_resultSetDidNotExist;
547     return 0;
548 }
549
550 /* Our sort handler really doesn't sort... */
551 int ztest_sort(void *handle, bend_sort_rr *rr)
552 {
553     rr->errcode = 0;
554     rr->sort_status = Z_SortResponse_success;
555     return 0;
556 }
557
558
559 /* present request handler */
560 int ztest_present(void *handle, bend_present_rr *rr)
561 {
562     return 0;
563 }
564
565 /* retrieval of a single record (present, and piggy back search) */
566 int ztest_fetch(void *handle, bend_fetch_rr *r)
567 {
568     char *cp;
569     const Odr_oid *oid = r->request_format;
570
571     r->last_in_set = 0;
572     r->basename = "Default";
573     r->output_format = r->request_format;
574
575     if (!oid || yaz_oid_is_iso2709(oid))
576     {
577         cp = dummy_marc_record(r->number, r->stream);
578         if (!cp)
579         {
580             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
581             return 0;
582         }
583         else
584         {
585             r->len = strlen(cp);
586             r->record = cp;
587             r->output_format = odr_oiddup(r->stream, yaz_oid_recsyn_usmarc);
588         }
589     }
590     else if (!oid_oidcmp(oid, yaz_oid_recsyn_opac))
591     {
592         cp = dummy_marc_record(r->number, r->stream);
593         if (!cp)
594         {
595             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
596             return 0;
597         }
598         r->record = (char *) dummy_opac(r->number, r->stream, cp);
599         r->len = -1;
600     }
601     else if (!oid_oidcmp(oid, yaz_oid_recsyn_sutrs))
602     {
603         /* this section returns a small record */
604         char buf[100];
605         
606         sprintf(buf, "This is dummy SUTRS record number %d\n", r->number);
607
608         r->len = strlen(buf);
609         r->record = (char *) odr_malloc(r->stream, r->len+1);
610         strcpy(r->record, buf);
611     }
612     else if (!oid_oidcmp(oid, yaz_oid_recsyn_grs_1))
613     {
614         r->len = -1;
615         r->record = (char*) dummy_grs_record(r->number, r->stream);
616         if (!r->record)
617         {
618             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
619             return 0;
620         }
621     }
622     else if (!oid_oidcmp(oid, yaz_oid_recsyn_postscript))
623     {
624         char fname[20];
625         FILE *f;
626         long size;
627
628         sprintf(fname, "part.%d.ps", r->number);
629         f = fopen(fname, "rb");
630         if (!f)
631         {
632             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
633             return 0;
634         }
635         fseek(f, 0L, SEEK_END);
636         size = ftell(f);
637         if (size <= 0 || size >= 5000000)
638         {
639             r->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
640         }
641         fseek(f, 0L, SEEK_SET);
642         r->record = (char*) odr_malloc(r->stream, size);
643         r->len = size;
644         if (fread(r->record, size, 1, f) != 1)
645         {
646             r->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
647         }
648         fclose(f);
649     }
650     else if (!oid_oidcmp(oid, yaz_oid_recsyn_xml))
651     {
652         if ((cp = dummy_xml_record(r->number, r->stream)))
653         {
654             r->len = strlen(cp);
655             r->record = cp;
656         }
657         else 
658         {
659             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
660             r->surrogate_flag = 1;
661             return 0;
662         }
663     }
664     else
665     {
666         char buf[OID_STR_MAX];
667         r->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
668         r->errstring = odr_strdup(r->stream, oid_oid_to_dotstring(oid, buf));
669         return 0;
670     }
671     r->errcode = 0;
672     return 0;
673 }
674
675 /*
676  * silly dummy-scan what reads words from a file.
677  */
678 int ztest_scan(void *handle, bend_scan_rr *q)
679 {
680     static FILE *f = 0;
681     static struct scan_entry list[200];
682     static char entries[200][80];
683     int hits[200];
684     char term[80], *p;
685     int i, pos;
686     int term_position_req = q->term_position;
687     int num_entries_req = q->num_entries;
688
689     /* Throw Database unavailable if other than Default or Slow */
690     if (!yaz_matchstr(q->basenames[0], "Default"))
691         ;  /* Default is OK in our test */
692     else if (check_slow(q->basenames[0], 0 /* no assoc for scan */))
693         ;
694     else
695     {
696         q->errcode = YAZ_BIB1_DATABASE_UNAVAILABLE;
697         q->errstring = q->basenames[0];
698         return 0;
699     }
700
701     q->errcode = 0;
702     q->errstring = 0;
703     q->entries = list;
704     q->status = BEND_SCAN_SUCCESS;
705     if (!f && !(f = fopen("dummy-words", "r")))
706     {
707         perror("dummy-words");
708         exit(1);
709     }
710     if (q->num_entries > 200)
711     {
712         q->errcode = YAZ_BIB1_RESOURCES_EXHAUSTED_NO_RESULTS_AVAILABLE;
713         return 0;
714     }
715     if (q->term)
716     {
717         int len;
718         if (q->term->term->which != Z_Term_general)
719         {
720             q->errcode = YAZ_BIB1_TERM_TYPE_UNSUPP;
721             return 0;
722         }
723         if (*q->step_size != 0)
724         {
725             q->errcode = YAZ_BIB1_ONLY_ZERO_STEP_SIZE_SUPPORTED_FOR_SCAN;
726             return 0;
727         }
728         len = q->term->term->u.general->len;
729         if (len >= sizeof(term))
730             len = sizeof(term)-1;
731         memcpy(term, q->term->term->u.general->buf, len);
732         term[len] = '\0';
733     }
734     else if (q->scanClause)
735     {
736         strncpy(term, q->scanClause, sizeof(term)-1);
737         term[sizeof(term)-1] = '\0';
738     }
739     else
740         strcpy(term, "0");
741
742     for (p = term; *p; p++)
743         if (islower(*(unsigned char *) p))
744             *p = toupper(*p);
745
746     fseek(f, 0, SEEK_SET);
747     q->num_entries = 0;
748
749     for (i = 0, pos = 0; fscanf(f, " %79[^:]:%d", entries[pos], &hits[pos]) == 2;
750          i++, pos < 199 ? pos++ : (pos = 0))
751     {
752         if (!q->num_entries && strcmp(entries[pos], term) >= 0) /* s-point fnd */
753         {
754             if ((q->term_position = term_position_req) > i + 1)
755             {
756                 q->term_position = i + 1;
757                 q->status = BEND_SCAN_PARTIAL;
758             }
759             for (; q->num_entries < q->term_position; q->num_entries++)
760             {
761                 int po;
762
763                 po = pos - q->term_position + q->num_entries+1; /* find pos */
764                 if (po < 0)
765                     po += 200;
766
767                 if (!strcmp(term, "SD") && q->num_entries == 2)
768                 {
769                     list[q->num_entries].term = entries[pos];
770                     list[q->num_entries].occurrences = -1;
771                     list[q->num_entries].errcode =
772                         YAZ_BIB1_SCAN_UNSUPP_VALUE_OF_POSITION_IN_RESPONSE;
773                     list[q->num_entries].errstring = "SD for Scan Term";
774                 }
775                 else
776                 {
777                     list[q->num_entries].term = entries[po];
778                     list[q->num_entries].occurrences = hits[po];
779                 }
780             }
781         }
782         else if (q->num_entries)
783         {
784             list[q->num_entries].term = entries[pos];
785             list[q->num_entries].occurrences = hits[pos];
786             q->num_entries++;
787         }
788         if (q->num_entries >= num_entries_req)
789             break;
790     }
791     if (feof(f))
792         q->status = BEND_SCAN_PARTIAL;
793     return 0;
794 }
795
796 int ztest_explain(void *handle, bend_explain_rr *rr)
797 {
798     if (rr->database && !strcmp(rr->database, "Default"))
799     {
800         rr->explain_buf = "<explain>\n"
801             "\t<serverInfo>\n"
802             "\t\t<host>localhost</host>\n"
803             "\t\t<port>210</port>\n"
804             "\t</serverInfo>\n"
805             "</explain>\n";
806     }
807     return 0;
808 }
809
810 int ztest_update(void *handle, bend_update_rr *rr)
811 {
812     rr->operation_status = "success";
813     return 0;
814 }
815
816 bend_initresult *bend_init(bend_initrequest *q)
817 {
818     bend_initresult *r = (bend_initresult *)
819         odr_malloc(q->stream, sizeof(*r));
820     int *counter = (int *) xmalloc(sizeof(int));
821
822     if (!log_level_set)
823     {
824         log_level=yaz_log_module_level("ztest");
825         log_level_set=1;
826     }
827
828     *counter = 0;
829     r->errcode = 0;
830     r->errstring = 0;
831     r->handle = counter;         /* user handle, in this case a simple int */
832     q->bend_sort = ztest_sort;              /* register sort handler */
833     q->bend_search = ztest_search;          /* register search handler */
834     q->bend_present = ztest_present;        /* register present handle */
835     q->bend_esrequest = ztest_esrequest;
836     q->bend_delete = ztest_delete;
837     q->bend_fetch = ztest_fetch;
838     q->bend_scan = ztest_scan;
839 #if 0
840     q->bend_explain = ztest_explain;
841 #endif
842     q->bend_srw_scan = ztest_scan;
843     q->bend_srw_update = ztest_update;
844
845     q->query_charset = "ISO-8859-1";
846     q->records_in_same_charset = 0;
847
848     return r;
849 }
850
851 void bend_close(void *handle)
852 {
853     xfree(handle);              /* release our user-defined handle */
854     return;
855 }
856
857 int main(int argc, char **argv)
858 {
859     return statserv_main(argc, argv, bend_init, bend_close);
860 }
861 /*
862  * Local variables:
863  * c-basic-offset: 4
864  * c-file-style: "Stroustrup"
865  * indent-tabs-mode: nil
866  * End:
867  * vim: shiftwidth=4 tabstop=8 expandtab
868  */
869