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