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