4ad090d14cdd00aefa4b67b8ee073b5c2b00089e
[yaz-moved-to-github.git] / src / zoom-z3950.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file zoom-z3950.c
7  * \brief Implements ZOOM Z39.50 handling
8  */
9 #if HAVE_CONFIG_H
10 #include <config.h>
11 #endif
12
13 #include <assert.h>
14 #include <string.h>
15 #include <errno.h>
16 #include "zoom-p.h"
17
18 #include <yaz/yaz-util.h>
19 #include <yaz/xmalloc.h>
20 #include <yaz/otherinfo.h>
21 #include <yaz/log.h>
22 #include <yaz/pquery.h>
23 #include <yaz/marcdisp.h>
24 #include <yaz/diagbib1.h>
25 #include <yaz/charneg.h>
26 #include <yaz/ill.h>
27 #include <yaz/query-charset.h>
28 #include <yaz/copy_types.h>
29 #include <yaz/snprintf.h>
30 #include <yaz/facet.h>
31
32 #include <yaz/shptr.h>
33
34 /*
35  * This wrapper is just for logging failed lookups.  It would be nicer
36  * if it could cause failure when a lookup fails, but that's hard.
37  */
38 static Odr_oid *zoom_yaz_str_to_z3950oid(ZOOM_connection c,
39                                      oid_class oid_class, const char *str) {
40     Odr_oid *res = yaz_string_to_oid_odr(yaz_oid_std(), oid_class, str,
41                                      c->odr_out);
42     if (res == 0)
43         yaz_log(YLOG_WARN, "%p OID lookup (%d, '%s') failed",
44                 c, (int) oid_class, str);
45     return res;
46 }
47
48 static Z_APDU *create_es_package(ZOOM_package p, const Odr_oid *oid)
49 {
50     const char *str;
51     Z_APDU *apdu = zget_APDU(p->odr_out, Z_APDU_extendedServicesRequest);
52     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
53
54     str = ZOOM_options_get(p->options, "package-name");
55     if (str && *str)
56         req->packageName = odr_strdup(p->odr_out, str);
57
58     str = ZOOM_options_get(p->options, "user-id");
59     if (str)
60         req->userId = odr_strdup_null(p->odr_out, str);
61
62     req->packageType = odr_oiddup(p->odr_out, oid);
63
64     str = ZOOM_options_get(p->options, "function");
65     if (str)
66     {
67         if (!strcmp (str, "create"))
68             *req->function = Z_ExtendedServicesRequest_create;
69         if (!strcmp (str, "delete"))
70             *req->function = Z_ExtendedServicesRequest_delete;
71         if (!strcmp (str, "modify"))
72             *req->function = Z_ExtendedServicesRequest_modify;
73     }
74
75     str = ZOOM_options_get(p->options, "waitAction");
76     if (str)
77     {
78         if (!strcmp (str, "wait"))
79             *req->waitAction = Z_ExtendedServicesRequest_wait;
80         if (!strcmp (str, "waitIfPossible"))
81             *req->waitAction = Z_ExtendedServicesRequest_waitIfPossible;
82         if (!strcmp (str, "dontWait"))
83             *req->waitAction = Z_ExtendedServicesRequest_dontWait;
84         if (!strcmp (str, "dontReturnPackage"))
85             *req->waitAction = Z_ExtendedServicesRequest_dontReturnPackage;
86     }
87     return apdu;
88 }
89
90 static const char *ill_array_lookup(void *clientData, const char *idx)
91 {
92     ZOOM_package p = (ZOOM_package) clientData;
93     return ZOOM_options_get(p->options, idx+4);
94 }
95
96 static Z_External *encode_ill_request(ZOOM_package p)
97 {
98     ODR out = p->odr_out;
99     ILL_Request *req;
100     Z_External *r = 0;
101     struct ill_get_ctl ctl;
102
103     ctl.odr = p->odr_out;
104     ctl.clientData = p;
105     ctl.f = ill_array_lookup;
106
107     req = ill_get_ILLRequest(&ctl, "ill", 0);
108
109     if (!ill_Request(out, &req, 0, 0))
110     {
111         int ill_request_size;
112         char *ill_request_buf = odr_getbuf(out, &ill_request_size, 0);
113         if (ill_request_buf)
114             odr_setbuf(out, ill_request_buf, ill_request_size, 1);
115         return 0;
116     }
117     else
118     {
119         int illRequest_size = 0;
120         char *illRequest_buf = odr_getbuf(out, &illRequest_size, 0);
121
122         r = (Z_External *) odr_malloc(out, sizeof(*r));
123         r->direct_reference = odr_oiddup(out, yaz_oid_general_isoill_1);
124         r->indirect_reference = 0;
125         r->descriptor = 0;
126         r->which = Z_External_single;
127
128         r->u.single_ASN1_type =
129             odr_create_Odr_oct(out, illRequest_buf, illRequest_size);
130     }
131     return r;
132 }
133
134 static Z_ItemOrder *encode_item_order(ZOOM_package p)
135 {
136     Z_ItemOrder *req = (Z_ItemOrder *) odr_malloc(p->odr_out, sizeof(*req));
137     const char *str;
138     int len;
139
140     req->which = Z_IOItemOrder_esRequest;
141     req->u.esRequest = (Z_IORequest *)
142         odr_malloc(p->odr_out,sizeof(Z_IORequest));
143
144     /* to keep part ... */
145     req->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
146         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartToKeep));
147     req->u.esRequest->toKeep->supplDescription = 0;
148     req->u.esRequest->toKeep->contact = (Z_IOContact *)
149         odr_malloc(p->odr_out, sizeof(*req->u.esRequest->toKeep->contact));
150
151     str = ZOOM_options_get(p->options, "contact-name");
152     req->u.esRequest->toKeep->contact->name =
153         odr_strdup_null(p->odr_out, str);
154
155     str = ZOOM_options_get(p->options, "contact-phone");
156     req->u.esRequest->toKeep->contact->phone =
157         odr_strdup_null(p->odr_out, str);
158
159     str = ZOOM_options_get(p->options, "contact-email");
160     req->u.esRequest->toKeep->contact->email =
161         odr_strdup_null(p->odr_out, str);
162
163     req->u.esRequest->toKeep->addlBilling = 0;
164
165     /* not to keep part ... */
166     req->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
167         odr_malloc(p->odr_out,sizeof(Z_IOOriginPartNotToKeep));
168
169     str = ZOOM_options_get(p->options, "itemorder-setname");
170     if (!str)
171         str = "default";
172
173     if (!*str)
174         req->u.esRequest->notToKeep->resultSetItem = 0;
175     else
176     {
177         req->u.esRequest->notToKeep->resultSetItem = (Z_IOResultSetItem *)
178             odr_malloc(p->odr_out, sizeof(Z_IOResultSetItem));
179
180         req->u.esRequest->notToKeep->resultSetItem->resultSetId =
181             odr_strdup(p->odr_out, str);
182         req->u.esRequest->notToKeep->resultSetItem->item =
183             odr_intdup(p->odr_out, 0);
184
185         str = ZOOM_options_get(p->options, "itemorder-item");
186         *req->u.esRequest->notToKeep->resultSetItem->item =
187             (str ? atoi(str) : 1);
188     }
189
190     str = ZOOM_options_getl(p->options, "doc", &len);
191     if (str)
192     {
193         req->u.esRequest->notToKeep->itemRequest =
194             z_ext_record_xml(p->odr_out, str, len);
195     }
196     else
197         req->u.esRequest->notToKeep->itemRequest = encode_ill_request(p);
198
199     return req;
200 }
201
202 Z_APDU *create_admin_package(ZOOM_package p, int type,
203                              Z_ESAdminOriginPartToKeep **toKeepP,
204                              Z_ESAdminOriginPartNotToKeep **notToKeepP)
205 {
206     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_admin);
207     if (apdu)
208     {
209         Z_ESAdminOriginPartToKeep  *toKeep;
210         Z_ESAdminOriginPartNotToKeep  *notToKeep;
211         Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
212         const char *first_db = "Default";
213         int num_db;
214         char **db = ZOOM_connection_get_databases(p->connection,
215                                                   p->options, &num_db,
216                                                   p->odr_out);
217         if (num_db > 0)
218             first_db = db[0];
219
220         r->direct_reference = odr_oiddup(p->odr_out, yaz_oid_extserv_admin);
221         r->descriptor = 0;
222         r->indirect_reference = 0;
223         r->which = Z_External_ESAdmin;
224
225         r->u.adminService = (Z_Admin *)
226             odr_malloc(p->odr_out, sizeof(*r->u.adminService));
227         r->u.adminService->which = Z_Admin_esRequest;
228         r->u.adminService->u.esRequest = (Z_AdminEsRequest *)
229             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest));
230
231         toKeep = r->u.adminService->u.esRequest->toKeep =
232             (Z_ESAdminOriginPartToKeep *)
233             odr_malloc(p->odr_out, sizeof(*r->u.adminService->u.esRequest->toKeep));
234         toKeep->which = type;
235         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
236         toKeep->u.create = odr_nullval();
237         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
238
239         r->u.adminService->u.esRequest->notToKeep = notToKeep =
240             (Z_ESAdminOriginPartNotToKeep *)
241             odr_malloc(p->odr_out,
242                        sizeof(*r->u.adminService->u.esRequest->notToKeep));
243         notToKeep->which = Z_ESAdminOriginPartNotToKeep_recordsWillFollow;
244         notToKeep->u.recordsWillFollow = odr_nullval();
245         if (toKeepP)
246             *toKeepP = toKeep;
247         if (notToKeepP)
248             *notToKeepP = notToKeep;
249     }
250     return apdu;
251 }
252
253 static Z_APDU *create_xmlupdate_package(ZOOM_package p)
254 {
255     Z_APDU *apdu = create_es_package(p, yaz_oid_extserv_xml_es);
256     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
257     Z_External *ext = (Z_External *) odr_malloc(p->odr_out, sizeof(*ext));
258     int len;
259     const char *doc = ZOOM_options_getl(p->options, "doc", &len);
260
261     if (!doc)
262     {
263         doc = "";
264         len = 0;
265     }
266
267     req->taskSpecificParameters = ext;
268     ext->direct_reference = req->packageType;
269     ext->descriptor = 0;
270     ext->indirect_reference = 0;
271
272     ext->which = Z_External_octet;
273     ext->u.single_ASN1_type = odr_create_Odr_oct(p->odr_out, doc, len);
274     return apdu;
275 }
276
277 static Z_APDU *create_update_package(ZOOM_package p)
278 {
279     Z_APDU *apdu = 0;
280     const char *first_db = "Default";
281     int num_db;
282     char **db = ZOOM_connection_get_databases(p->connection, p->options,
283                                               &num_db, p->odr_out);
284     const char *action = ZOOM_options_get(p->options, "action");
285     int recordIdOpaque_len;
286     const char *recordIdOpaque = ZOOM_options_getl(p->options, "recordIdOpaque",
287         &recordIdOpaque_len);
288     const char *recordIdNumber = ZOOM_options_get(p->options, "recordIdNumber");
289     int record_len;
290     const char *record_buf = ZOOM_options_getl(p->options, "record",
291         &record_len);
292     int recordOpaque_len;
293     const char *recordOpaque_buf = ZOOM_options_getl(p->options, "recordOpaque",
294         &recordOpaque_len);
295     const char *syntax_str = ZOOM_options_get(p->options, "syntax");
296     const char *version = ZOOM_options_get(p->options, "updateVersion");
297
298     const char *correlationInfo_note =
299         ZOOM_options_get(p->options, "correlationInfo.note");
300     const char *correlationInfo_id =
301         ZOOM_options_get(p->options, "correlationInfo.id");
302     int action_no = -1;
303     Odr_oid *syntax_oid = 0;
304     const Odr_oid *package_oid = yaz_oid_extserv_database_update;
305
306     if (!version)
307         version = "3";
308     if (!syntax_str)
309         syntax_str = "xml";
310     if (!record_buf && !recordOpaque_buf)
311     {
312         record_buf = "void";
313         record_len = 4;
314         syntax_str = "SUTRS";
315     }
316
317     if (syntax_str)
318     {
319         syntax_oid = yaz_string_to_oid_odr(yaz_oid_std(),
320                                            CLASS_RECSYN, syntax_str,
321                                            p->odr_out);
322     }
323     if (!syntax_oid)
324     {
325         ZOOM_set_error(p->connection, ZOOM_ERROR_ES_INVALID_SYNTAX, syntax_str);
326         return 0;
327     }
328
329     if (num_db > 0)
330         first_db = db[0];
331
332     switch (*version)
333     {
334     case '1':
335         package_oid = yaz_oid_extserv_database_update_first_version;
336         /* old update does not support specialUpdate */
337         if (!action)
338             action = "recordInsert";
339         break;
340     case '2':
341         if (!action)
342             action = "specialUpdate";
343         package_oid = yaz_oid_extserv_database_update_second_version;
344         break;
345     case '3':
346         if (!action)
347             action = "specialUpdate";
348         package_oid = yaz_oid_extserv_database_update;
349         break;
350     default:
351         ZOOM_set_error(p->connection, ZOOM_ERROR_ES_INVALID_VERSION, version);
352         return 0;
353     }
354
355     if (!strcmp(action, "recordInsert"))
356         action_no = Z_IUOriginPartToKeep_recordInsert;
357     else if (!strcmp(action, "recordReplace"))
358         action_no = Z_IUOriginPartToKeep_recordReplace;
359     else if (!strcmp(action, "recordDelete"))
360         action_no = Z_IUOriginPartToKeep_recordDelete;
361     else if (!strcmp(action, "elementUpdate"))
362         action_no = Z_IUOriginPartToKeep_elementUpdate;
363     else if (!strcmp(action, "specialUpdate"))
364         action_no = Z_IUOriginPartToKeep_specialUpdate;
365     else
366     {
367         ZOOM_set_error(p->connection, ZOOM_ERROR_ES_INVALID_ACTION, action);
368         return 0;
369     }
370
371     apdu = create_es_package(p, package_oid);
372     if (apdu)
373     {
374         Z_IUOriginPartToKeep *toKeep;
375         Z_IUSuppliedRecords *notToKeep;
376         Z_External *r = (Z_External *)
377             odr_malloc(p->odr_out, sizeof(*r));
378         const char *elementSetName =
379             ZOOM_options_get(p->options, "elementSetName");
380
381         apdu->u.extendedServicesRequest->taskSpecificParameters = r;
382
383         r->direct_reference = odr_oiddup(p->odr_out, package_oid);
384         r->descriptor = 0;
385         r->which = Z_External_update;
386         r->indirect_reference = 0;
387         r->u.update = (Z_IUUpdate *)
388             odr_malloc(p->odr_out, sizeof(*r->u.update));
389
390         r->u.update->which = Z_IUUpdate_esRequest;
391         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
392             odr_malloc(p->odr_out, sizeof(*r->u.update->u.esRequest));
393         toKeep = r->u.update->u.esRequest->toKeep =
394             (Z_IUOriginPartToKeep *)
395             odr_malloc(p->odr_out, sizeof(*toKeep));
396
397         toKeep->databaseName = odr_strdup(p->odr_out, first_db);
398         toKeep->schema = 0;
399
400         toKeep->elementSetName = odr_strdup_null(p->odr_out, elementSetName);
401
402         toKeep->actionQualifier = 0;
403         toKeep->action = odr_intdup(p->odr_out, action_no);
404
405         notToKeep = r->u.update->u.esRequest->notToKeep =
406             (Z_IUSuppliedRecords *)
407             odr_malloc(p->odr_out, sizeof(*notToKeep));
408         notToKeep->num = 1;
409         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
410             odr_malloc(p->odr_out, sizeof(*notToKeep->elements));
411         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
412             odr_malloc(p->odr_out, sizeof(**notToKeep->elements));
413         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
414         if (recordIdOpaque)
415         {
416             notToKeep->elements[0]->u.opaque =
417                 odr_create_Odr_oct(p->odr_out, recordIdOpaque,
418                                    recordIdOpaque_len);
419         }
420         else if (recordIdNumber)
421         {
422             notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_number;
423
424             notToKeep->elements[0]->u.number =
425                 odr_intdup(p->odr_out, atoi(recordIdNumber));
426         }
427         else
428             notToKeep->elements[0]->u.opaque = 0;
429         notToKeep->elements[0]->supplementalId = 0;
430         if (correlationInfo_note || correlationInfo_id)
431         {
432             Z_IUCorrelationInfo *ci;
433             ci = notToKeep->elements[0]->correlationInfo =
434                 (Z_IUCorrelationInfo *) odr_malloc(p->odr_out, sizeof(*ci));
435             ci->note = odr_strdup_null(p->odr_out, correlationInfo_note);
436             ci->id = correlationInfo_id ?
437                 odr_intdup(p->odr_out, atoi(correlationInfo_id)) : 0;
438         }
439         else
440             notToKeep->elements[0]->correlationInfo = 0;
441         if (recordOpaque_buf)
442         {
443             notToKeep->elements[0]->record =
444                 z_ext_record_oid_any(p->odr_out, syntax_oid,
445                                  recordOpaque_buf, recordOpaque_len);
446         }
447         else
448         {
449             notToKeep->elements[0]->record =
450                 z_ext_record_oid(p->odr_out, syntax_oid,
451                                  record_buf, record_len);
452         }
453     }
454     if (0 && apdu)
455     {
456         ODR print = odr_createmem(ODR_PRINT);
457
458         z_APDU(print, &apdu, 0, 0);
459         odr_destroy(print);
460     }
461     return apdu;
462 }
463
464
465 static void otherInfo_attach(ZOOM_connection c, Z_APDU *a, ODR out)
466 {
467     int i;
468     for (i = 0; i<200; i++)
469     {
470         size_t len;
471         Odr_oid *oid;
472         Z_OtherInformation **oi;
473         char buf[80];
474         const char *val;
475         const char *cp;
476
477         sprintf(buf, "otherInfo%d", i);
478         val = ZOOM_options_get(c->options, buf);
479         if (!val)
480             break;
481         cp = strchr(val, ':');
482         if (!cp)
483             continue;
484         len = cp - val;
485         if (len >= sizeof(buf))
486             len = sizeof(buf)-1;
487         memcpy(buf, val, len);
488         buf[len] = '\0';
489
490         oid = yaz_string_to_oid_odr(yaz_oid_std(), CLASS_USERINFO,
491                                     buf, out);
492         if (!oid)
493             continue;
494
495         yaz_oi_APDU(a, &oi);
496         yaz_oi_set_string_oid(oi, out, oid, 1, cp+1);
497     }
498 }
499
500
501
502 static int encode_APDU(ZOOM_connection c, Z_APDU *a, ODR out)
503 {
504     assert(a);
505     if (c->cookie_out)
506     {
507         Z_OtherInformation **oi;
508         yaz_oi_APDU(a, &oi);
509         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_cookie,
510                               1, c->cookie_out);
511     }
512     if (c->client_IP)
513     {
514         Z_OtherInformation **oi;
515         yaz_oi_APDU(a, &oi);
516         yaz_oi_set_string_oid(oi, out, yaz_oid_userinfo_client_ip,
517                               1, c->client_IP);
518     }
519     otherInfo_attach(c, a, out);
520     if (!z_APDU(out, &a, 0, 0))
521     {
522         FILE *outf = fopen("/tmp/apdu.txt", "a");
523         if (a && outf)
524         {
525             ODR odr_pr = odr_createmem(ODR_PRINT);
526             fprintf(outf, "a=%p\n", a);
527             odr_setprint(odr_pr, outf);
528             z_APDU(odr_pr, &a, 0, 0);
529             odr_destroy(odr_pr);
530         }
531         yaz_log(c->log_api, "%p encoding_APDU: encoding failed", c);
532         ZOOM_set_error(c, ZOOM_ERROR_ENCODE, 0);
533         odr_reset(out);
534         return -1;
535     }
536     if (c->odr_print)
537         z_APDU(c->odr_print, &a, 0, 0);
538     if (c->odr_save)
539         z_APDU(c->odr_save, &a, 0, 0);
540     yaz_log(c->log_details, "%p encoding_APDU encoding OK", c);
541     return 0;
542 }
543
544 static zoom_ret send_APDU(ZOOM_connection c, Z_APDU *a)
545 {
546     ZOOM_Event event;
547     assert(a);
548     if (encode_APDU(c, a, c->odr_out))
549         return zoom_complete;
550     yaz_log(c->log_details, "%p send APDU type=%d", c, a->which);
551     c->buf_out = odr_getbuf(c->odr_out, &c->len_out, 0);
552     event = ZOOM_Event_create(ZOOM_EVENT_SEND_APDU);
553     ZOOM_connection_put_event(c, event);
554     odr_reset(c->odr_out);
555     return ZOOM_send_buf(c);
556 }
557
558 zoom_ret ZOOM_connection_Z3950_send_init(ZOOM_connection c)
559 {
560     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_initRequest);
561     Z_InitRequest *ireq = apdu->u.initRequest;
562     Z_IdAuthentication *auth = (Z_IdAuthentication *)
563         odr_malloc(c->odr_out, sizeof(*auth));
564
565     ODR_MASK_SET(ireq->options, Z_Options_search);
566     ODR_MASK_SET(ireq->options, Z_Options_present);
567     ODR_MASK_SET(ireq->options, Z_Options_scan);
568     ODR_MASK_SET(ireq->options, Z_Options_sort);
569     ODR_MASK_SET(ireq->options, Z_Options_extendedServices);
570     ODR_MASK_SET(ireq->options, Z_Options_namedResultSets);
571
572     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_1);
573     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_2);
574     ODR_MASK_SET(ireq->protocolVersion, Z_ProtocolVersion_3);
575
576     ireq->implementationId =
577         odr_prepend(c->odr_out,
578                     ZOOM_options_get(c->options, "implementationId"),
579                     ireq->implementationId);
580
581     ireq->implementationName =
582         odr_prepend(c->odr_out,
583                     ZOOM_options_get(c->options, "implementationName"),
584                     odr_prepend(c->odr_out, "ZOOM-C",
585                                 ireq->implementationName));
586
587     ireq->implementationVersion =
588         odr_prepend(c->odr_out,
589                     ZOOM_options_get(c->options, "implementationVersion"),
590                                 ireq->implementationVersion);
591
592     *ireq->maximumRecordSize = c->maximum_record_size;
593     *ireq->preferredMessageSize = c->preferred_message_size;
594
595     if (c->group || c->password)
596     {
597         Z_IdPass *pass = (Z_IdPass *) odr_malloc(c->odr_out, sizeof(*pass));
598         pass->groupId = odr_strdup_null(c->odr_out, c->group);
599         pass->userId = odr_strdup_null(c->odr_out, c->user);
600         pass->password = odr_strdup_null(c->odr_out, c->password);
601         auth->which = Z_IdAuthentication_idPass;
602         auth->u.idPass = pass;
603         ireq->idAuthentication = auth;
604     }
605     else if (c->user)
606     {
607         auth->which = Z_IdAuthentication_open;
608         auth->u.open = odr_strdup(c->odr_out, c->user);
609         ireq->idAuthentication = auth;
610     }
611     if (c->proxy)
612     {
613         yaz_oi_set_string_oid(&ireq->otherInfo, c->odr_out,
614                               yaz_oid_userinfo_proxy, 1, c->host_port);
615     }
616     if (c->charset || c->lang)
617     {
618         Z_OtherInformation **oi;
619         Z_OtherInformationUnit *oi_unit;
620
621         yaz_oi_APDU(apdu, &oi);
622
623         if ((oi_unit = yaz_oi_update(oi, c->odr_out, NULL, 0, 0)))
624         {
625             ODR_MASK_SET(ireq->options, Z_Options_negotiationModel);
626             oi_unit->which = Z_OtherInfo_externallyDefinedInfo;
627             oi_unit->information.externallyDefinedInfo =
628                 yaz_set_proposal_charneg_list(c->odr_out, " ",
629                                               c->charset, c->lang, 1);
630         }
631     }
632     assert(apdu);
633     return send_APDU(c, apdu);
634 }
635
636 zoom_ret ZOOM_connection_Z3950_send_search(ZOOM_connection c)
637 {
638     ZOOM_resultset r;
639     int lslb, ssub, mspn;
640     const char *syntax;
641     const char *schema;
642     Z_APDU *apdu;
643     Z_SearchRequest *search_req;
644     const char *elementSetName;
645     const char *smallSetElementSetName;
646     const char *mediumSetElementSetName;
647     const char *facets;
648
649     if (!c->tasks)
650         return zoom_complete;
651
652     assert(c->tasks->which == ZOOM_TASK_SEARCH);
653     r = c->tasks->u.search.resultset;
654     if (r->live_set)
655         return send_Z3950_present(c);
656
657     apdu = zget_APDU(c->odr_out, Z_APDU_searchRequest);
658     search_req = apdu->u.searchRequest;
659
660     yaz_log(c->log_details, "%p ZOOM_connection_send_search set=%p", c, r);
661
662     elementSetName =
663         ZOOM_options_get(r->options, "elementSetName");
664     smallSetElementSetName  =
665         ZOOM_options_get(r->options, "smallSetElementSetName");
666     mediumSetElementSetName =
667         ZOOM_options_get(r->options, "mediumSetElementSetName");
668
669     if (!smallSetElementSetName)
670         smallSetElementSetName = elementSetName;
671
672     if (!mediumSetElementSetName)
673         mediumSetElementSetName = elementSetName;
674
675     facets = ZOOM_options_get(r->options, "facets");
676     if (facets) {
677         Z_FacetList *facet_list = yaz_pqf_parse_facet_list(c->odr_out, facets);
678         if (facet_list) {
679             Z_OtherInformation **oi = &search_req->additionalSearchInfo;
680             yaz_oi_set_facetlist(oi, c->odr_out, facet_list);
681         }
682         else
683             yaz_log(YLOG_WARN, "Unable to parse facets: %s", facets);
684     }
685
686     assert(r);
687     assert(r->query);
688
689     /* prepare query for the search request */
690     search_req->query = ZOOM_query_get_Z_Query(r->query);
691     if (!search_req->query)
692     {
693         ZOOM_set_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
694         return zoom_complete;
695     }
696     if (search_req->query->which == Z_Query_type_1 ||
697         search_req->query->which == Z_Query_type_101)
698     {
699         const char *cp = ZOOM_options_get(r->options, "rpnCharset");
700         if (cp)
701         {
702             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
703             if (cd)
704             {
705                 int r;
706                 search_req->query = yaz_copy_Z_Query(search_req->query,
707                                                      c->odr_out);
708
709                 r = yaz_query_charset_convert_rpnquery_check(
710                     search_req->query->u.type_1,
711                     c->odr_out, cd);
712                 yaz_iconv_close(cd);
713                 if (r)
714                 {  /* query could not be char converted */
715                     ZOOM_set_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
716                     return zoom_complete;
717                 }
718             }
719         }
720     }
721     search_req->databaseNames = r->databaseNames;
722     search_req->num_databaseNames = r->num_databaseNames;
723
724     /* get syntax (no need to provide unless piggyback is in effect) */
725     syntax = c->tasks->u.search.syntax;
726
727     schema = c->tasks->u.search.schema;
728
729     lslb = ZOOM_options_get_int(r->options, "largeSetLowerBound", -1);
730     ssub = ZOOM_options_get_int(r->options, "smallSetUpperBound", -1);
731     mspn = ZOOM_options_get_int(r->options, "mediumSetPresentNumber", -1);
732     if (lslb != -1 && ssub != -1 && mspn != -1)
733     {
734         /* So're a Z39.50 expert? Let's hope you don't do sort */
735         *search_req->largeSetLowerBound = lslb;
736         *search_req->smallSetUpperBound = ssub;
737         *search_req->mediumSetPresentNumber = mspn;
738     }
739     else if (c->tasks->u.search.start == 0 && c->tasks->u.search.count > 0
740              && r->piggyback && !r->r_sort_spec && !schema)
741     {
742         /* Regular piggyback - do it unless we're going to do sort */
743         *search_req->largeSetLowerBound = 2000000000;
744         *search_req->smallSetUpperBound = 1;
745         *search_req->mediumSetPresentNumber =
746             r->step>0 ? r->step : c->tasks->u.search.count;
747     }
748     else
749     {
750         /* non-piggyback. Need not provide elementsets or syntaxes .. */
751         smallSetElementSetName = 0;
752         mediumSetElementSetName = 0;
753         syntax = 0;
754     }
755     if (smallSetElementSetName && *smallSetElementSetName)
756     {
757         Z_ElementSetNames *esn = (Z_ElementSetNames *)
758             odr_malloc(c->odr_out, sizeof(*esn));
759
760         esn->which = Z_ElementSetNames_generic;
761         esn->u.generic = odr_strdup(c->odr_out, smallSetElementSetName);
762         search_req->smallSetElementSetNames = esn;
763     }
764     if (mediumSetElementSetName && *mediumSetElementSetName)
765     {
766         Z_ElementSetNames *esn =(Z_ElementSetNames *)
767             odr_malloc(c->odr_out, sizeof(*esn));
768
769         esn->which = Z_ElementSetNames_generic;
770         esn->u.generic = odr_strdup(c->odr_out, mediumSetElementSetName);
771         search_req->mediumSetElementSetNames = esn;
772     }
773     if (syntax)
774         search_req->preferredRecordSyntax =
775             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
776
777     if (!r->setname)
778     {
779         if (c->support_named_resultsets)
780         {
781             char setname[14];
782             int ord;
783             /* find the lowest unused ordinal so that we re-use
784                result sets on the server. */
785             for (ord = 1; ; ord++)
786             {
787                 ZOOM_resultset rp;
788                 sprintf(setname, "%d", ord);
789                 for (rp = c->resultsets; rp; rp = rp->next)
790                     if (rp->setname && !strcmp(rp->setname, setname))
791                         break;
792                 if (!rp)
793                     break;
794             }
795             r->setname = xstrdup(setname);
796             yaz_log(c->log_details, "%p ZOOM_connection_send_search: "
797                     "allocating set %s", c, r->setname);
798         }
799         else
800         {
801             yaz_log(c->log_details, "%p ZOOM_connection_send_search: using "
802                     "default set", c);
803             r->setname = xstrdup("default");
804         }
805         ZOOM_options_set(r->options, "setname", r->setname);
806     }
807     search_req->resultSetName = odr_strdup(c->odr_out, r->setname);
808     return send_APDU(c, apdu);
809 }
810
811 zoom_ret ZOOM_connection_Z3950_send_scan(ZOOM_connection c)
812 {
813     ZOOM_scanset scan;
814     Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_scanRequest);
815     Z_ScanRequest *req = apdu->u.scanRequest;
816     Z_Query *z_query;
817
818     yaz_log(c->log_details, "%p send_scan", c);
819     if (!c->tasks)
820         return zoom_complete;
821     assert (c->tasks->which == ZOOM_TASK_SCAN);
822     scan = c->tasks->u.scan.scan;
823
824     z_query = ZOOM_query_get_Z_Query(scan->query);
825
826     /* Z39.50 scan can only carry RPN */
827     if (z_query->which == Z_Query_type_1 ||
828         z_query->which == Z_Query_type_101)
829     {
830         Z_RPNQuery *rpn = z_query->u.type_1;
831         const char *cp = ZOOM_options_get(scan->options, "rpnCharset");
832         if (cp)
833         {
834             yaz_iconv_t cd = yaz_iconv_open(cp, "UTF-8");
835             if (cd)
836             {
837                 rpn = yaz_copy_z_RPNQuery(rpn, c->odr_out);
838
839                 yaz_query_charset_convert_rpnquery(
840                     rpn, c->odr_out, cd);
841                 yaz_iconv_close(cd);
842             }
843         }
844         req->attributeSet = rpn->attributeSetId;
845         if (!req->attributeSet)
846             req->attributeSet = odr_oiddup(c->odr_out, yaz_oid_attset_bib_1);
847         if (rpn->RPNStructure->which == Z_RPNStructure_simple &&
848             rpn->RPNStructure->u.simple->which == Z_Operand_APT)
849         {
850             req->termListAndStartPoint =
851                 rpn->RPNStructure->u.simple->u.attributesPlusTerm;
852         }
853         else
854         {
855             ZOOM_set_error(c, ZOOM_ERROR_INVALID_QUERY, 0);
856             return zoom_complete;
857         }
858     }
859     else
860     {
861         ZOOM_set_error(c, ZOOM_ERROR_UNSUPPORTED_QUERY, 0);
862         return zoom_complete;
863     }
864
865     *req->numberOfTermsRequested =
866         ZOOM_options_get_int(scan->options, "number", 20);
867
868     req->preferredPositionInResponse =
869         odr_intdup(c->odr_out,
870                    ZOOM_options_get_int(scan->options, "position", 1));
871
872     req->stepSize =
873         odr_intdup(c->odr_out,
874                    ZOOM_options_get_int(scan->options, "stepSize", 0));
875
876     req->databaseNames = scan->databaseNames;
877     req->num_databaseNames = scan->num_databaseNames;
878
879     return send_APDU(c, apdu);
880 }
881
882 ZOOM_API(void)
883     ZOOM_package_send(ZOOM_package p, const char *type)
884 {
885     Z_APDU *apdu = 0;
886     ZOOM_connection c;
887     if (!p)
888         return;
889     c = p->connection;
890     odr_reset(p->odr_out);
891     xfree(p->buf_out);
892     p->buf_out = 0;
893     if (!strcmp(type, "itemorder"))
894     {
895         apdu = create_es_package(p, yaz_oid_extserv_item_order);
896         if (apdu)
897         {
898             Z_External *r = (Z_External *) odr_malloc(p->odr_out, sizeof(*r));
899
900             r->direct_reference =
901                 odr_oiddup(p->odr_out, yaz_oid_extserv_item_order);
902             r->descriptor = 0;
903             r->which = Z_External_itemOrder;
904             r->indirect_reference = 0;
905             r->u.itemOrder = encode_item_order(p);
906
907             apdu->u.extendedServicesRequest->taskSpecificParameters = r;
908         }
909     }
910     else if (!strcmp(type, "create"))  /* create database */
911     {
912         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_create,
913                                     0, 0);
914     }
915     else if (!strcmp(type, "drop"))  /* drop database */
916     {
917         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_drop,
918                                     0, 0);
919     }
920     else if (!strcmp(type, "commit"))  /* commit changes */
921     {
922         apdu = create_admin_package(p, Z_ESAdminOriginPartToKeep_commit,
923                                     0, 0);
924     }
925     else if (!strcmp(type, "update")) /* update record(s) */
926     {
927         apdu = create_update_package(p);
928     }
929     else if (!strcmp(type, "xmlupdate"))
930     {
931         apdu = create_xmlupdate_package(p);
932     }
933     if (apdu)
934     {
935         if (encode_APDU(p->connection, apdu, p->odr_out) == 0)
936         {
937             char *buf;
938
939             ZOOM_task task = ZOOM_connection_add_task(c, ZOOM_TASK_PACKAGE);
940             task->u.package = p;
941             buf = odr_getbuf(p->odr_out, &p->len_out, 0);
942             p->buf_out = (char *) xmalloc(p->len_out);
943             memcpy(p->buf_out, buf, p->len_out);
944
945             (p->refcount)++;
946             if (!c->async)
947             {
948                 while (ZOOM_event(1, &c))
949                     ;
950             }
951         }
952     }
953 }
954
955 static void handle_Z3950_records(ZOOM_connection c, Z_Records *sr,
956                                  int present_phase);
957
958 static void response_default_diag(ZOOM_connection c, Z_DefaultDiagFormat *r)
959 {
960     char oid_name_buf[OID_STR_MAX];
961     const char *oid_name;
962     char *addinfo = 0;
963
964     oid_name = yaz_oid_to_string_buf(r->diagnosticSetId, 0, oid_name_buf);
965     switch (r->which)
966     {
967     case Z_DefaultDiagFormat_v2Addinfo:
968         addinfo = r->u.v2Addinfo;
969         break;
970     case Z_DefaultDiagFormat_v3Addinfo:
971         addinfo = r->u.v3Addinfo;
972         break;
973     }
974     xfree(c->addinfo);
975     c->addinfo = 0;
976     ZOOM_set_dset_error(c, *r->condition, oid_name, addinfo, 0);
977 }
978
979 static void response_diag(ZOOM_connection c, Z_DiagRec *p)
980 {
981     if (p->which != Z_DiagRec_defaultFormat)
982         ZOOM_set_error(c, ZOOM_ERROR_DECODE, 0);
983     else
984         response_default_diag(c, p->u.defaultFormat);
985 }
986
987 static int es_response_taskpackage_update(ZOOM_connection c,
988                                           Z_IUUpdateTaskPackage *utp)
989 {
990     if (utp && utp->targetPart)
991     {
992         Z_IUTargetPart *targetPart = utp->targetPart;
993         switch ( *targetPart->updateStatus ) {
994         case Z_IUTargetPart_success:
995             ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "success");
996             break;
997         case Z_IUTargetPart_partial:
998             ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "partial");
999             break;
1000         case Z_IUTargetPart_failure:
1001             ZOOM_options_set(c->tasks->u.package->options,"updateStatus", "failure");
1002             if (targetPart->globalDiagnostics && targetPart->num_globalDiagnostics > 0)
1003                 response_diag(c, targetPart->globalDiagnostics[0]);
1004             break;
1005         }
1006         /* NOTE: Individual record status, surrogate diagnostics, and supplemental diagnostics ARE NOT REPORTED. */
1007     }
1008     return 1;
1009 }
1010
1011 static int es_response_taskpackage(ZOOM_connection c,
1012                                    Z_TaskPackage *taskPackage)
1013 {
1014     Odr_oct *id = taskPackage->targetReference;
1015     if (id)
1016         ZOOM_options_setl(c->tasks->u.package->options,
1017                           "targetReference", (char*) id->buf, id->len);
1018
1019     switch ( *taskPackage->taskStatus ) {
1020     case Z_TaskPackage_pending:
1021         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "pending");
1022         break;
1023     case Z_TaskPackage_active:
1024         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "active");
1025         break;
1026     case Z_TaskPackage_complete:
1027         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "complete");
1028         break;
1029     case Z_TaskPackage_aborted:
1030         ZOOM_options_set(c->tasks->u.package->options,"taskStatus", "aborted");
1031         if ( taskPackage->num_packageDiagnostics && taskPackage->packageDiagnostics )
1032             response_diag(c, taskPackage->packageDiagnostics[0]);
1033         break;
1034     }
1035     /* NOTE: Only Update implemented, no others. */
1036     if ( taskPackage->taskSpecificParameters->which == Z_External_update )
1037     {
1038         Z_IUUpdateTaskPackage *utp = taskPackage->taskSpecificParameters->u.update->u.taskPackage;
1039         es_response_taskpackage_update(c, utp);
1040     }
1041     return 1;
1042 }
1043
1044 static void handle_Z3950_es_response(ZOOM_connection c,
1045                                      Z_ExtendedServicesResponse *res)
1046 {
1047     if (!c->tasks)
1048         return;
1049     assert(c->tasks->which == ZOOM_TASK_PACKAGE);
1050     switch (*res->operationStatus)
1051     {
1052     case Z_ExtendedServicesResponse_done:
1053         ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "done");
1054         break;
1055     case Z_ExtendedServicesResponse_accepted:
1056         ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "accepted");
1057         break;
1058     case Z_ExtendedServicesResponse_failure:
1059         ZOOM_options_set(c->tasks->u.package->options,"operationStatus", "failure");
1060         if (res->diagnostics && res->num_diagnostics > 0)
1061             response_diag(c, res->diagnostics[0]);
1062         break;
1063     }
1064     if (res->taskPackage &&
1065         res->taskPackage->which == Z_External_extendedService)
1066     {
1067         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1068         es_response_taskpackage(c, taskPackage);
1069     }
1070     if (res->taskPackage &&
1071         res->taskPackage->which == Z_External_octet)
1072     {
1073         Odr_oct *doc = res->taskPackage->u.octet_aligned;
1074         ZOOM_options_setl(c->tasks->u.package->options,
1075                           "xmlUpdateDoc", (char*) doc->buf, doc->len);
1076     }
1077 }
1078
1079 static char *get_term_cstr(ODR odr, Z_Term *term) {
1080
1081     switch (term->which) {
1082     case Z_Term_general:
1083             return odr_strdupn(odr, (const char *) term->u.general->buf, (size_t) term->u.general->len);
1084         break;
1085     case Z_Term_characterString:
1086         return odr_strdup(odr, term->u.characterString);
1087     }
1088     return 0;
1089 }
1090
1091 static ZOOM_facet_field get_zoom_facet_field(ODR odr, Z_FacetField *facet) {
1092     int term_index;
1093     struct yaz_facet_attr attr_values;
1094     ZOOM_facet_field facet_field = odr_malloc(odr, sizeof(*facet_field));
1095     yaz_facet_attr_init(&attr_values);
1096     yaz_facet_attr_get_z_attributes(facet->attributes, &attr_values);
1097     facet_field->facet_name = odr_strdup(odr, attr_values.useattr);
1098     facet_field->num_terms = facet->num_terms;
1099     yaz_log(YLOG_DEBUG, "ZOOM_facet_field %s %d terms %d", attr_values.useattr, attr_values.limit, facet->num_terms);
1100     facet_field->facet_terms = odr_malloc(odr, facet_field->num_terms * sizeof(*facet_field->facet_terms));
1101     for (term_index = 0 ; term_index < facet->num_terms; term_index++) {
1102         Z_FacetTerm *facetTerm = facet->terms[term_index];
1103         facet_field->facet_terms[term_index].frequency = *facetTerm->count;
1104         facet_field->facet_terms[term_index].term = get_term_cstr(odr, facetTerm->term);
1105         yaz_log(YLOG_DEBUG, "    term[%d] %s %d",
1106                 term_index, facet_field->facet_terms[term_index].term, facet_field->facet_terms[term_index].frequency);
1107     }
1108     return facet_field;
1109 }
1110
1111 /* Can be share with SOLR/SRU/SRW requests */
1112 void ZOOM_handle_facet_list(ZOOM_resultset r, Z_FacetList *fl)
1113 {
1114     int j;
1115     r->num_facets   = fl->num;
1116     yaz_log(YLOG_DEBUG, "Facets found: %d", fl->num);
1117     r->facets       =  odr_malloc(r->odr, r->num_facets * sizeof(*r->facets));
1118     r->facets_names =  odr_malloc(r->odr, r->num_facets * sizeof(*r->facets_names));
1119     for (j = 0; j < fl->num; j++)
1120     {
1121         r->facets[j] = get_zoom_facet_field(r->odr, fl->elements[j]);
1122         if (!r->facets[j])
1123             yaz_log(YLOG_DEBUG, "Facet field missing on index %d !", j);
1124         r->facets_names[j] = (char *) ZOOM_facet_field_name(r->facets[j]);
1125     }
1126 }
1127
1128 static void handle_facet_result(ZOOM_connection c, ZOOM_resultset r,
1129                                 Z_OtherInformation *o)
1130 {
1131     int i;
1132     for (i = 0; o && i < o->num_elements; i++)
1133     {
1134         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1135         {
1136             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1137             if (ext->which == Z_External_userFacets)
1138             {
1139                 ZOOM_handle_facet_list(r, ext->u.facetList);
1140             }
1141         }
1142     }
1143 }
1144
1145 static void handle_queryExpressionTerm(ZOOM_options opt, const char *name,
1146                                        Z_Term *term)
1147 {
1148     switch (term->which)
1149     {
1150     case Z_Term_general:
1151         ZOOM_options_setl(opt, name,
1152                           (const char *)(term->u.general->buf),
1153                           term->u.general->len);
1154         break;
1155     case Z_Term_characterString:
1156         ZOOM_options_set(opt, name, term->u.characterString);
1157         break;
1158     case Z_Term_numeric:
1159         ZOOM_options_set_int(opt, name, *term->u.numeric);
1160         break;
1161     }
1162 }
1163
1164 static void handle_queryExpression(ZOOM_options opt, const char *name,
1165                                    Z_QueryExpression *exp)
1166 {
1167     char opt_name[80];
1168
1169     switch (exp->which)
1170     {
1171     case Z_QueryExpression_term:
1172         if (exp->u.term && exp->u.term->queryTerm)
1173         {
1174             sprintf(opt_name, "%s.term", name);
1175             handle_queryExpressionTerm(opt, opt_name, exp->u.term->queryTerm);
1176         }
1177         break;
1178     case Z_QueryExpression_query:
1179         break;
1180     }
1181 }
1182
1183
1184 static void handle_search_result(ZOOM_connection c, ZOOM_resultset resultset,
1185                                 Z_OtherInformation *o)
1186 {
1187     int i;
1188     for (i = 0; o && i < o->num_elements; i++)
1189     {
1190         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1191         {
1192             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1193
1194             if (ext->which == Z_External_searchResult1)
1195             {
1196                 int j;
1197                 Z_SearchInfoReport *sr = ext->u.searchResult1;
1198
1199                 if (sr->num)
1200                     ZOOM_options_set_int(
1201                         resultset->options, "searchresult.size", sr->num);
1202
1203                 for (j = 0; j < sr->num; j++)
1204                 {
1205                     Z_SearchInfoReport_s *ent =
1206                         ext->u.searchResult1->elements[j];
1207                     char pref[80];
1208
1209                     sprintf(pref, "searchresult.%d", j);
1210
1211                     if (ent->subqueryId)
1212                     {
1213                         char opt_name[80];
1214                         sprintf(opt_name, "%s.id", pref);
1215                         ZOOM_options_set(resultset->options, opt_name,
1216                                          ent->subqueryId);
1217                     }
1218                     if (ent->subqueryExpression)
1219                     {
1220                         char opt_name[80];
1221                         sprintf(opt_name, "%s.subquery", pref);
1222                         handle_queryExpression(resultset->options, opt_name,
1223                                                ent->subqueryExpression);
1224                     }
1225                     if (ent->subqueryInterpretation)
1226                     {
1227                         char opt_name[80];
1228                         sprintf(opt_name, "%s.interpretation", pref);
1229                         handle_queryExpression(resultset->options, opt_name,
1230                                                ent->subqueryInterpretation);
1231                     }
1232                     if (ent->subqueryRecommendation)
1233                     {
1234                         char opt_name[80];
1235                         sprintf(opt_name, "%s.recommendation", pref);
1236                         handle_queryExpression(resultset->options, opt_name,
1237                                                ent->subqueryRecommendation);
1238                     }
1239                     if (ent->subqueryCount)
1240                     {
1241                         char opt_name[80];
1242                         sprintf(opt_name, "%s.count", pref);
1243                         ZOOM_options_set_int(resultset->options, opt_name,
1244                                              *ent->subqueryCount);
1245                     }
1246                 }
1247             }
1248         }
1249     }
1250 }
1251
1252 static void handle_Z3950_search_response(ZOOM_connection c,
1253                                          Z_SearchResponse *sr)
1254 {
1255     ZOOM_resultset resultset;
1256     ZOOM_Event event;
1257
1258     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1259         return;
1260
1261     event = ZOOM_Event_create(ZOOM_EVENT_RECV_SEARCH);
1262     ZOOM_connection_put_event(c, event);
1263
1264     resultset = c->tasks->u.search.resultset;
1265
1266     if (sr->resultSetStatus)
1267     {
1268         ZOOM_options_set_int(resultset->options, "resultSetStatus",
1269                              *sr->resultSetStatus);
1270     }
1271     if (sr->presentStatus)
1272     {
1273         ZOOM_options_set_int(resultset->options, "presentStatus",
1274                              *sr->presentStatus);
1275     }
1276     handle_search_result(c, resultset, sr->additionalSearchInfo);
1277
1278     handle_facet_result(c, resultset, sr->additionalSearchInfo);
1279
1280     resultset->size = *sr->resultCount;
1281     resultset->live_set = 1;
1282
1283 #if HAVE_LIBMEMCACHED_MEMCACHED_H
1284     if (c->mc_st)
1285     {
1286         uint32_t flags = 0;
1287         memcached_return_t rc;
1288         time_t expiration = 36000;
1289         char str[40];
1290
1291         sprintf(str, ODR_INT_PRINTF, *sr->resultCount);
1292         rc = memcached_set(c->mc_st,
1293                            wrbuf_buf(resultset->mc_key),wrbuf_len(resultset->mc_key),
1294                            str, strlen(str), expiration, flags);
1295         yaz_log(YLOG_LOG, "Store hit count key=%s value=%s rc=%u %s",
1296                 wrbuf_cstr(resultset->mc_key), str, (unsigned) rc,
1297                 memcached_last_error_message(c->mc_st));
1298     }
1299 #endif
1300     handle_Z3950_records(c, sr->records, 0);
1301 }
1302
1303 static void handle_Z3950_sort_response(ZOOM_connection c, Z_SortResponse *res)
1304 {
1305     if (res->diagnostics && res->num_diagnostics > 0)
1306         response_diag(c, res->diagnostics[0]);
1307 }
1308
1309 static void handle_Z3950_scan_response(ZOOM_connection c, Z_ScanResponse *res)
1310 {
1311     NMEM nmem = odr_extract_mem(c->odr_in);
1312     ZOOM_scanset scan;
1313
1314     if (!c->tasks || c->tasks->which != ZOOM_TASK_SCAN)
1315         return;
1316     scan = c->tasks->u.scan.scan;
1317
1318     if (res->entries && res->entries->nonsurrogateDiagnostics)
1319         response_diag(c, res->entries->nonsurrogateDiagnostics[0]);
1320     scan->scan_response = res;
1321     scan->srw_scan_response = 0;
1322     nmem_transfer(odr_getmem(scan->odr), nmem);
1323     if (res->stepSize)
1324         ZOOM_options_set_int(scan->options, "stepSize", *res->stepSize);
1325     if (res->positionOfTerm)
1326         ZOOM_options_set_int(scan->options, "position", *res->positionOfTerm);
1327     if (res->scanStatus)
1328         ZOOM_options_set_int(scan->options, "scanStatus", *res->scanStatus);
1329     if (res->numberOfEntriesReturned)
1330         ZOOM_options_set_int(scan->options, "number",
1331                              *res->numberOfEntriesReturned);
1332     nmem_destroy(nmem);
1333 }
1334
1335 static void handle_Z3950_records(ZOOM_connection c, Z_Records *sr,
1336                                  int present_phase)
1337 {
1338     ZOOM_resultset resultset;
1339     int *start, *count;
1340     const char *syntax = 0, *elementSetName = 0, *schema = 0;
1341
1342     if (!c->tasks || c->tasks->which != ZOOM_TASK_SEARCH)
1343         return ;
1344
1345     resultset = c->tasks->u.search.resultset;
1346     start = &c->tasks->u.search.start;
1347     count = &c->tasks->u.search.count;
1348     syntax = c->tasks->u.search.syntax;
1349     elementSetName = c->tasks->u.search.elementSetName;
1350     schema =  c->tasks->u.search.schema;
1351
1352     if (sr && sr->which == Z_Records_NSD)
1353         response_default_diag(c, sr->u.nonSurrogateDiagnostic);
1354     else if (sr && sr->which == Z_Records_multipleNSD)
1355     {
1356         if (sr->u.multipleNonSurDiagnostics->num_diagRecs >= 1)
1357             response_diag(c, sr->u.multipleNonSurDiagnostics->diagRecs[0]);
1358         else
1359             ZOOM_set_error(c, ZOOM_ERROR_DECODE, 0);
1360     }
1361     else
1362     {
1363         if (*count + *start > resultset->size)
1364             *count = resultset->size - *start;
1365         if (*count < 0)
1366             *count = 0;
1367         if (sr && sr->which == Z_Records_DBOSD)
1368         {
1369             int i;
1370             NMEM nmem = odr_extract_mem(c->odr_in);
1371             Z_NamePlusRecordList *p =
1372                 sr->u.databaseOrSurDiagnostics;
1373             for (i = 0; i<p->num_records; i++)
1374             {
1375                 ZOOM_record_cache_add(resultset, p->records[i], i + *start,
1376                                       syntax, elementSetName, schema, 0);
1377             }
1378             *count -= i;
1379             if (*count < 0)
1380                 *count = 0;
1381             *start += i;
1382             yaz_log(c->log_details,
1383                     "handle_records resultset=%p start=%d count=%d",
1384                     resultset, *start, *count);
1385
1386             /* transfer our response to search_nmem .. we need it later */
1387             nmem_transfer(odr_getmem(resultset->odr), nmem);
1388             nmem_destroy(nmem);
1389             if (present_phase && p->num_records == 0)
1390             {
1391                 /* present response and we didn't get any records! */
1392                 Z_NamePlusRecord *myrec =
1393                     zget_surrogateDiagRec(
1394                         resultset->odr, 0,
1395                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1396                         "ZOOM C generated. Present phase and no records");
1397                 ZOOM_record_cache_add(resultset, myrec, *start,
1398                                       syntax, elementSetName, schema, 0);
1399                 *count = 0;
1400             }
1401         }
1402         else if (present_phase)
1403         {
1404             /* present response and we didn't get any records! */
1405             Z_NamePlusRecord *myrec =
1406                 zget_surrogateDiagRec(
1407                     resultset->odr, 0,
1408                     YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1409                     "ZOOM C generated: Present response and no records");
1410             ZOOM_record_cache_add(resultset, myrec, *start,
1411                                   syntax, elementSetName, schema, 0);
1412             *count = 0;
1413         }
1414     }
1415 }
1416
1417 static void handle_Z3950_present_response(ZOOM_connection c,
1418                                           Z_PresentResponse *pr)
1419 {
1420     handle_Z3950_records(c, pr->records, 1);
1421 }
1422
1423 static void set_init_option(const char *name, void *clientData)
1424 {
1425     ZOOM_connection c = (ZOOM_connection) clientData;
1426     char buf[80];
1427
1428     sprintf(buf, "init_opt_%.70s", name);
1429     ZOOM_connection_option_set(c, buf, "1");
1430 }
1431
1432
1433 zoom_ret send_Z3950_sort(ZOOM_connection c, ZOOM_resultset resultset)
1434 {
1435     if (c->error)
1436         resultset->r_sort_spec = 0;
1437     if (resultset->r_sort_spec)
1438     {
1439         Z_APDU *apdu = zget_APDU(c->odr_out, Z_APDU_sortRequest);
1440         Z_SortRequest *req = apdu->u.sortRequest;
1441
1442         req->num_inputResultSetNames = 1;
1443         req->inputResultSetNames = (Z_InternationalString **)
1444             odr_malloc(c->odr_out, sizeof(*req->inputResultSetNames));
1445         req->inputResultSetNames[0] =
1446             odr_strdup(c->odr_out, resultset->setname);
1447         req->sortedResultSetName = odr_strdup(c->odr_out, resultset->setname);
1448         req->sortSequence = resultset->r_sort_spec;
1449         resultset->r_sort_spec = 0;
1450         return send_APDU(c, apdu);
1451     }
1452     return zoom_complete;
1453 }
1454
1455 zoom_ret send_Z3950_present(ZOOM_connection c)
1456 {
1457     Z_APDU *apdu = 0;
1458     Z_PresentRequest *req = 0;
1459     int i = 0;
1460     const char *syntax = 0;
1461     const char *elementSetName = 0;
1462     const char *schema = 0;
1463     ZOOM_resultset resultset;
1464     int *start, *count;
1465
1466     if (!c->tasks)
1467         return zoom_complete;
1468     assert(c->tasks->which == ZOOM_TASK_SEARCH);
1469     resultset = c->tasks->u.search.resultset;
1470     start = &c->tasks->u.search.start;
1471     count = &c->tasks->u.search.count;
1472     syntax = c->tasks->u.search.syntax;
1473     elementSetName = c->tasks->u.search.elementSetName;
1474     schema =  c->tasks->u.search.schema;
1475
1476     yaz_log(c->log_details, "%p send_present start=%d count=%d",
1477             c, *start, *count);
1478
1479     if (*start < 0 || *count < 0 || *start + *count > resultset->size)
1480     {
1481         ZOOM_set_dset_error(c, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, "Bib-1",
1482                        "", 0);
1483     }
1484     if (c->error)                  /* don't continue on error */
1485         return zoom_complete;
1486     yaz_log(c->log_details, "send_present resultset=%p start=%d count=%d",
1487             resultset, *start, *count);
1488
1489     for (i = 0; i < *count; i++)
1490     {
1491         ZOOM_record rec =
1492             ZOOM_record_cache_lookup(resultset, i + *start,
1493                                      syntax, elementSetName, schema);
1494         if (!rec)
1495             break;
1496         else
1497         {
1498             ZOOM_Event event = ZOOM_Event_create(ZOOM_EVENT_RECV_RECORD);
1499             ZOOM_connection_put_event(c, event);
1500         }
1501     }
1502     *start += i;
1503     *count -= i;
1504
1505     if (*count == 0)
1506     {
1507         yaz_log(c->log_details, "%p send_present skip=%d no more to fetch", c, i);
1508         return zoom_complete;
1509     }
1510
1511     apdu = zget_APDU(c->odr_out, Z_APDU_presentRequest);
1512     req = apdu->u.presentRequest;
1513
1514     if (i)
1515         yaz_log(c->log_details, "%p send_present skip=%d", c, i);
1516
1517     *req->resultSetStartPoint = *start + 1;
1518
1519     if (resultset->step > 0 && resultset->step < *count)
1520         *req->numberOfRecordsRequested = resultset->step;
1521     else
1522         *req->numberOfRecordsRequested = *count;
1523
1524     if (*req->numberOfRecordsRequested + *start > resultset->size)
1525         *req->numberOfRecordsRequested = resultset->size - *start;
1526     assert(*req->numberOfRecordsRequested > 0);
1527
1528     if (syntax && *syntax)
1529         req->preferredRecordSyntax =
1530             zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, syntax);
1531
1532     if (schema && *schema)
1533     {
1534         Z_RecordComposition *compo = (Z_RecordComposition *)
1535             odr_malloc(c->odr_out, sizeof(*compo));
1536
1537         req->recordComposition = compo;
1538         compo->which = Z_RecordComp_complex;
1539         compo->u.complex = (Z_CompSpec *)
1540             odr_malloc(c->odr_out, sizeof(*compo->u.complex));
1541         compo->u.complex->selectAlternativeSyntax = (bool_t *)
1542             odr_malloc(c->odr_out, sizeof(bool_t));
1543         *compo->u.complex->selectAlternativeSyntax = 0;
1544
1545         compo->u.complex->generic = (Z_Specification *)
1546             odr_malloc(c->odr_out, sizeof(*compo->u.complex->generic));
1547
1548         compo->u.complex->generic->which = Z_Schema_oid;
1549         compo->u.complex->generic->schema.oid = (Odr_oid *)
1550             zoom_yaz_str_to_z3950oid(c, CLASS_SCHEMA, schema);
1551
1552         if (!compo->u.complex->generic->schema.oid)
1553         {
1554             /* OID wasn't a schema! Try record syntax instead. */
1555
1556             compo->u.complex->generic->schema.oid = (Odr_oid *)
1557                 zoom_yaz_str_to_z3950oid(c, CLASS_RECSYN, schema);
1558         }
1559         if (elementSetName && *elementSetName)
1560         {
1561             compo->u.complex->generic->elementSpec = (Z_ElementSpec *)
1562                 odr_malloc(c->odr_out, sizeof(Z_ElementSpec));
1563             compo->u.complex->generic->elementSpec->which =
1564                 Z_ElementSpec_elementSetName;
1565             compo->u.complex->generic->elementSpec->u.elementSetName =
1566                 odr_strdup(c->odr_out, elementSetName);
1567         }
1568         else
1569             compo->u.complex->generic->elementSpec = 0;
1570         compo->u.complex->num_dbSpecific = 0;
1571         compo->u.complex->dbSpecific = 0;
1572         compo->u.complex->num_recordSyntax = 0;
1573         compo->u.complex->recordSyntax = 0;
1574     }
1575     else if (elementSetName && *elementSetName)
1576     {
1577         Z_ElementSetNames *esn = (Z_ElementSetNames *)
1578             odr_malloc(c->odr_out, sizeof(*esn));
1579         Z_RecordComposition *compo = (Z_RecordComposition *)
1580             odr_malloc(c->odr_out, sizeof(*compo));
1581
1582         esn->which = Z_ElementSetNames_generic;
1583         esn->u.generic = odr_strdup(c->odr_out, elementSetName);
1584         compo->which = Z_RecordComp_simple;
1585         compo->u.simple = esn;
1586         req->recordComposition = compo;
1587     }
1588     req->resultSetId = odr_strdup(c->odr_out, resultset->setname);
1589     return send_APDU(c, apdu);
1590 }
1591
1592 static zoom_ret send_Z3950_sort_present(ZOOM_connection c)
1593 {
1594     zoom_ret r = zoom_complete;
1595
1596     if (c->tasks && c->tasks->which == ZOOM_TASK_SEARCH)
1597         r = send_Z3950_sort(c, c->tasks->u.search.resultset);
1598     if (r == zoom_complete)
1599         r = send_Z3950_present(c);
1600     return r;
1601 }
1602
1603 void ZOOM_handle_Z3950_apdu(ZOOM_connection c, Z_APDU *apdu)
1604 {
1605     Z_InitResponse *initrs;
1606
1607     ZOOM_connection_set_mask(c, 0);
1608     yaz_log(c->log_details, "%p handle_Z3950_apdu apdu->which=%d",
1609             c, apdu->which);
1610     switch (apdu->which)
1611     {
1612     case Z_APDU_initResponse:
1613         yaz_log(c->log_api, "%p handle_Z3950_apdu: Received Init response", c);
1614         initrs = apdu->u.initResponse;
1615         ZOOM_connection_option_set(c, "serverImplementationId",
1616                                    initrs->implementationId ?
1617                                    initrs->implementationId : "");
1618         ZOOM_connection_option_set(c, "serverImplementationName",
1619                                    initrs->implementationName ?
1620                                    initrs->implementationName : "");
1621         ZOOM_connection_option_set(c, "serverImplementationVersion",
1622                                    initrs->implementationVersion ?
1623                                    initrs->implementationVersion : "");
1624         /* Set the three old options too, for old applications */
1625         ZOOM_connection_option_set(c, "targetImplementationId",
1626                                    initrs->implementationId ?
1627                                    initrs->implementationId : "");
1628         ZOOM_connection_option_set(c, "targetImplementationName",
1629                                    initrs->implementationName ?
1630                                    initrs->implementationName : "");
1631         ZOOM_connection_option_set(c, "targetImplementationVersion",
1632                                    initrs->implementationVersion ?
1633                                    initrs->implementationVersion : "");
1634
1635         /* Make initrs->options available as ZOOM-level options */
1636         yaz_init_opt_decode(initrs->options, set_init_option, (void*) c);
1637
1638         if (!*initrs->result)
1639         {
1640             Z_DefaultDiagFormat *df = yaz_decode_init_diag(0, initrs);
1641             if (df)
1642                 response_default_diag(c, df);
1643             else
1644                 ZOOM_set_error(c, ZOOM_ERROR_INIT, 0); /* default error */
1645         }
1646         else
1647         {
1648             char *cookie =
1649                 yaz_oi_get_string_oid(&apdu->u.initResponse->otherInfo,
1650                                       yaz_oid_userinfo_cookie, 1, 0);
1651             xfree(c->cookie_in);
1652             c->cookie_in = 0;
1653             if (cookie)
1654                 c->cookie_in = xstrdup(cookie);
1655             if (ODR_MASK_GET(initrs->options, Z_Options_namedResultSets) &&
1656                 ODR_MASK_GET(initrs->protocolVersion, Z_ProtocolVersion_3))
1657                 c->support_named_resultsets = 1;
1658             if (c->tasks)
1659             {
1660                 assert(c->tasks->which == ZOOM_TASK_CONNECT);
1661                 ZOOM_connection_remove_task(c);
1662             }
1663             ZOOM_connection_exec_task(c);
1664         }
1665         if (ODR_MASK_GET(initrs->options, Z_Options_negotiationModel))
1666         {
1667             NMEM tmpmem = nmem_create();
1668             Z_CharSetandLanguageNegotiation *p =
1669                 yaz_get_charneg_record(initrs->otherInfo);
1670
1671             if (p)
1672             {
1673                 char *charset = NULL, *lang = NULL;
1674                 int sel;
1675
1676                 yaz_get_response_charneg(tmpmem, p, &charset, &lang, &sel);
1677                 yaz_log(c->log_details, "%p handle_Z3950_apdu target accepted: "
1678                         "charset %s, language %s, select %d",
1679                         c,
1680                         charset ? charset : "none", lang ? lang : "none", sel);
1681                 if (charset)
1682                     ZOOM_connection_option_set(c, "negotiation-charset",
1683                                                charset);
1684                 if (lang)
1685                     ZOOM_connection_option_set(c, "negotiation-lang",
1686                                                lang);
1687
1688                 ZOOM_connection_option_set(
1689                     c,  "negotiation-charset-in-effect-for-records",
1690                     (sel != 0) ? "1" : "0");
1691                 nmem_destroy(tmpmem);
1692             }
1693         }
1694         break;
1695     case Z_APDU_searchResponse:
1696         yaz_log(c->log_api, "%p handle_Z3950_apdu Search response", c);
1697         handle_Z3950_search_response(c, apdu->u.searchResponse);
1698         if (send_Z3950_sort_present(c) == zoom_complete)
1699             ZOOM_connection_remove_task(c);
1700         break;
1701     case Z_APDU_presentResponse:
1702         yaz_log(c->log_api, "%p handle_Z3950_apdu Present response", c);
1703         handle_Z3950_present_response(c, apdu->u.presentResponse);
1704         if (send_Z3950_present(c) == zoom_complete)
1705             ZOOM_connection_remove_task(c);
1706         break;
1707     case Z_APDU_sortResponse:
1708         yaz_log(c->log_api, "%p handle_Z3950_apdu Sort response", c);
1709         handle_Z3950_sort_response(c, apdu->u.sortResponse);
1710         if (send_Z3950_present(c) == zoom_complete)
1711             ZOOM_connection_remove_task(c);
1712         break;
1713     case Z_APDU_scanResponse:
1714         yaz_log(c->log_api, "%p handle_Z3950_apdu Scan response", c);
1715         handle_Z3950_scan_response(c, apdu->u.scanResponse);
1716         ZOOM_connection_remove_task(c);
1717         break;
1718     case Z_APDU_extendedServicesResponse:
1719         yaz_log(c->log_api, "%p handle_Z3950_apdu Extended Services response", c);
1720         handle_Z3950_es_response(c, apdu->u.extendedServicesResponse);
1721         ZOOM_connection_remove_task(c);
1722         break;
1723     case Z_APDU_close:
1724         yaz_log(c->log_api, "%p handle_Z3950_apdu Close PDU", c);
1725         if (!ZOOM_test_reconnect(c))
1726         {
1727             ZOOM_set_dset_error(c, ZOOM_ERROR_CONNECTION_LOST, "ZOOM", c->host_port, apdu->u.close->diagnosticInformation);
1728             ZOOM_connection_close(c);
1729         }
1730         break;
1731     default:
1732         yaz_log(c->log_api, "%p Received unknown PDU", c);
1733         ZOOM_set_error(c, ZOOM_ERROR_DECODE, 0);
1734         ZOOM_connection_close(c);
1735     }
1736 }
1737
1738 /*
1739  * Local variables:
1740  * c-basic-offset: 4
1741  * c-file-style: "Stroustrup"
1742  * indent-tabs-mode: nil
1743  * End:
1744  * vim: shiftwidth=4 tabstop=8 expandtab
1745  */
1746