Zdist layer moved to new sub directory.
[egate.git] / zlayer-zdist / zaccess.c
1 /*
2  * Copyright (c) 1995, the EUROPAGATE consortium (see below).
3  *
4  * The EUROPAGATE consortium members are:
5  *
6  *    University College Dublin
7  *    Danmarks Teknologiske Videnscenter
8  *    An Chomhairle Leabharlanna
9  *    Consejo Superior de Investigaciones Cientificas
10  *
11  * Permission to use, copy, modify, distribute, and sell this software and
12  * its documentation, in whole or in part, for any purpose, is hereby granted,
13  * provided that:
14  *
15  * 1. This copyright and permission notice appear in all copies of the
16  * software and its documentation. Notices of copyright or attribution
17  * which appear at the beginning of any file must remain unchanged.
18  *
19  * 2. The names of EUROPAGATE or the project partners may not be used to
20  * endorse or promote products derived from this software without specific
21  * prior written permission.
22  *
23  * 3. Users of this software (implementors and gateway operators) agree to
24  * inform the EUROPAGATE consortium of their use of the software. This
25  * information will be used to evaluate the EUROPAGATE project and the
26  * software, and to plan further developments. The consortium may use
27  * the information in later publications.
28  * 
29  * 4. Users of this software agree to make their best efforts, when
30  * documenting their use of the software, to acknowledge the EUROPAGATE
31  * consortium, and the role played by the software in their work.
32  *
33  * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND,
34  * EXPRESS, IMPLIED, OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
35  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
36  * IN NO EVENT SHALL THE EUROPAGATE CONSORTIUM OR ITS MEMBERS BE LIABLE
37  * FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF
38  * ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
39  * OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND
40  * ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
41  * USE OR PERFORMANCE OF THIS SOFTWARE.
42  *
43  */
44 /*
45  * Europagate, 1995
46  *
47  * Z39.50 API for the Email gateway
48  *
49  * $Log: zaccess.c,v $
50  * Revision 1.1  1995/07/03 08:21:43  adam
51  * Zdist layer moved to new sub directory.
52  *
53  * Revision 1.17  1995/05/16  09:41:47  adam
54  * LICENSE. Uses new versions of odr_{set,get}buf.
55  *
56  * Revision 1.16  1995/04/20  15:25:34  quinn
57  * Asynch. API
58  *
59  * Revision 1.15  1995/04/17  11:26:55  quinn
60  * Added YAZ version of zaccess
61  *
62  * Revision 1.14  1995/02/23  08:32:26  adam
63  * Changed header.
64  *
65  * Revision 1.12  1995/02/20  20:35:37  quinn
66  * Pull present status from presresp.
67  *
68  * Revision 1.11  1995/02/20  18:58:05  quinn
69  * Added hack for record in ANY
70  *
71  * Revision 1.10  1995/02/20  18:19:30  quinn
72  * More relaxed about record types.
73  *
74  * Revision 1.9  1995/02/17  15:17:51  quinn
75  * Bug fix
76  *
77  * Revision 1.8  1995/02/17  14:48:41  quinn
78  * 'nother bug in present
79  *
80  * Revision 1.7  1995/02/17  14:42:21  quinn
81  * Trivial bug in fetch-loop.
82  *
83  * Revision 1.6  1995/02/17  14:41:22  quinn
84  * Debugging.
85  *
86  * Revision 1.5  1995/02/17  13:58:01  quinn
87  * First kick at present handling
88  *
89  * Revision 1.4  1995/02/16  15:33:45  quinn
90  * Fixed bug in KWAQS generator
91  *
92  * Revision 1.3  1995/02/16  15:20:45  quinn
93  * Added initialization of response from search
94  *
95  * Revision 1.2  1995/02/16  15:14:53  quinn
96  * Fixed KWAQS-generator
97  *
98  * Revision 1.1  1995/02/16  14:47:55  quinn
99  * First kick.
100  *
101  */
102
103 /*
104  * Interface to the Z39.50 toolkit. Primary function is to hide Zdist, or
105  * whatever lower-layer we decide to use later. The decision to add a
106  * layer atop the toolkit was twofold: It vastly simplifies the
107  * implementation of the protocol persistence, and it hides Zdist. The
108  * latter is useful after Zdist has gone and changed their fine API after
109  * we went through all the trouble of documenting it in our Design. Don't
110  * want that to happen again.
111  *
112  * For the time being at least, we'll have these routines hang (or err) if
113  * they get a WOULDBLOCK on a write. That seems safe since, under normal
114  * circumstances, the network buffers should always be able to absorb
115  * the small request packages.
116  */
117
118 #include <stdlib.h>
119 #include <assert.h>
120
121 #include <z3950.h>
122 #include <z3950sup.h>
123 #include <zutil.h>
124
125 #include <gw-log.h>
126
127 #include <ccl.h>
128 #include <zaccess.h>
129
130 struct zass    /* Z-assoc */
131 {
132     NETBOXPROFILE *ass;              /* ZDIST association handle */
133     int fd;                         /* low-level socket (for select only) */
134     int maxrecordsize;
135     int preferredmessagesize;
136     char *buf;                      /* intermediary buffer */
137 };
138
139 int rpn2kwaqs(struct ccl_rpn_node *q, char **p)
140 {
141     struct ccl_rpn_attr *i;
142     static char *ops[] = {"and", "or", "not"};
143
144     assert(!CCL_RPN_AND);
145     switch (q->kind)
146     {
147         case CCL_RPN_TERM:
148             strcpy(*p, q->u.t.term);
149             (*p) += strlen(q->u.t.term);
150             if (q->u.t.attr_list)
151             {
152                 strcat(*p, "[");
153                 (*p)++;
154                 for (i = q->u.t.attr_list; i; i = i->next)
155                 {
156                     sprintf(*p, "%d,%d%s", i->type, i->value, i->next ?
157                         "," : "");
158                     *p += strlen(*p);
159                 }
160                 strcat(*p, "]");
161                 (*p)++;
162             }
163             return 0;
164         case CCL_RPN_SET:
165             gw_log(GW_LOG_FATAL, ZASS_TYPE, "KWAQS Doesn't support set refs");
166             return -1;
167         case CCL_RPN_AND: case CCL_RPN_OR: case CCL_RPN_NOT:
168             strcpy(*p, ops[q->kind]);
169             *p += strlen(ops[q->kind]);
170             strcat(*p, "(");
171             (*p)++;
172             if (rpn2kwaqs(q->u.p[0], p) < 0)
173                 return -1;
174             strcat(*p, ",");
175             (*p)++;
176             if (rpn2kwaqs(q->u.p[1], p) < 0)
177                 return -1;
178             strcat(*p, ")");
179             (*p)++;
180             return 0;
181         default:
182             gw_log(GW_LOG_FATAL, ZASS_TYPE, "Unknown RPN node");
183             return -1;
184     }
185 }
186
187 int zass_openresult(ZASS p, int *complete)
188 {
189     int len;
190     PINITRESPONSE ires;
191
192     if ((len = zutil_GetBERFromNet(p->ass, (unsigned char*)p->buf,
193         p->maxrecordsize)) <= 0)
194     {
195         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to receive initresponse");
196         return 0;
197     }
198     ires = (PINITRESPONSE) zutil_CreateFromData((unsigned char*)p->buf, len);
199     if (InitResponse_GetTag(ires) != INITRESPONSE_TAG)
200     {
201         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Expected initresponse from target");
202         return 0;
203     }
204     gw_log(ZASS_DEBUG, ZASS_TYPE, "Got initresponse");
205     if (!InitResponse_GetResult(ires))
206     {
207         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Access to target denied.");
208         return 0;
209     }
210     gw_log(ZASS_DEBUG, ZASS_TYPE, "Connected OK");
211     p->preferredmessagesize = InitResponse_GetPreferredMessageSize(ires);
212     p->maxrecordsize = InitResponse_GetExceptionalRecordSize(ires);
213     InitResponse_Destroy(ires);
214     *complete = 1;
215     return 0;
216 }
217
218 ZASS zass_open(char *host, int port, int *complete)
219 {
220     struct zass *p;
221     PINITREQUEST ireq;
222     PINITRESPONSE ires;
223     int len;
224     char name[512];
225
226     if (!(p = malloc(sizeof(*p))))
227     {
228         gw_log(GW_LOG_FATAL, ZASS_TYPE, "memory alloc failed");
229         return 0;
230     }
231     p->maxrecordsize = ZASS_MAXRECORDSIZE;
232     p->preferredmessagesize = ZASS_PREFERREDMESSAGESIZE;
233     if (!(p->buf = malloc(ZASS_MAXRECORDSIZE + 100)))
234     {
235         gw_log(GW_LOG_FATAL, ZASS_TYPE, "alloc zass-buffer");
236         return 0;
237     }
238     if (!(p->ass = NEWSTRUCT(NETBOXPROFILE)))
239     {
240         gw_log(GW_LOG_FATAL, ZASS_TYPE, "memory alloc failed");
241         return 0;
242     }
243     p->ass->TimeOutSec = 120;
244     p->ass->TimeOutUSec = 0;
245     strcpy(p->ass->HostName, host);
246     p->ass->Port = port;
247
248     if (netbox_Open(p->ass) != 1)
249     {
250         gw_log(GW_LOG_WARN, ZASS_TYPE, "netbox_Open failed");
251         return 0;
252     }
253     gw_log(ZASS_DEBUG, ZASS_TYPE, "Opened connection to %s:%d",
254          p->ass->HostName, p->ass->Port);
255     sprintf(name, "%s (ZDIST protocol layer)", ZASS_NAME);
256     ireq = InitRequest_CreateInitAllASCII(0, "yy", "yy", p->maxrecordsize,
257         p->preferredmessagesize, ZASS_ID, name, ZASS_VERSION, 0);
258     if (!ireq)
259     {
260         gw_log(GW_LOG_FATAL, "ZASS_TYPE", "failed to create initrequest");
261         return 0;
262     }
263     zutil_GetBEREncodedBuffer(ireq, (unsigned char*)p->buf, &len,
264         p->maxrecordsize);
265     if (len <= 0)
266     {
267         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to encode initrequest");
268         return 0;
269     }
270     InitRequest_Destroy(ireq);
271     if (netbox_SendBuffer(p->ass, p->buf, len) != len)
272     {
273         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to send initrequest");
274         return 0;
275     }
276     gw_log(ZASS_DEBUG, ZASS_TYPE, "Sent initrequest.");
277
278     if (zass_openresult(p, complete) < 0 && (!complete || *complete))
279         return 0;
280     else
281         return p;
282
283 }
284
285 const struct zass_searchent *zass_search(ZASS a, struct ccl_rpn_node *query,
286     char *resname, char *databases)
287 {
288     static struct zass_searchent r;
289     char kwaqs[512], *p;
290     DATA_DIR *pdu, *record;
291     int len;
292
293     p = kwaqs;
294     if (rpn2kwaqs(query, &p) < 0)
295     {
296         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to encode query");
297         return 0;
298     }
299     gw_log(ZASS_DEBUG, ZASS_TYPE, "Query: KWAQS: '%s'", kwaqs);
300     pdu = SearchRequest_CreateInitAllASCII(0, 0, 2, 0, 1, resname, databases,
301         0, 0, 0, kwaqs, BIB1_OID);
302     if (!pdu)
303     {
304         gw_log(GW_LOG_FATAL, "ZASS_TYPE", "failed to create searchrequest");
305         return 0;
306     }
307     zutil_GetBEREncodedBuffer(pdu, (unsigned char*)a->buf, &len,
308         a->maxrecordsize);
309     if (len <= 0)
310     {
311         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to encode initrequest");
312         return 0;
313     }
314     SearchRequest_Destroy(pdu);
315     if (netbox_SendBuffer(a->ass, a->buf, len) != len)
316     {
317         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to send initrequest");
318         return 0;
319     }
320     gw_log(ZASS_DEBUG, ZASS_TYPE, "Sent searchrequest.");
321     if ((len = zutil_GetBERFromNet(a->ass, (unsigned char*)a->buf,
322         a->maxrecordsize)) <= 0)
323     {
324         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to receive searchresponse");
325         return 0;
326     }
327     pdu = zutil_CreateFromData((unsigned char*)a->buf, len);
328     if (zutil_GetTag(pdu) != SEARCHRESPONSE_TAG)
329     {
330         gw_log(GW_LOG_FATAL, ZASS_TYPE, "Expected serchresponse from target");
331         return 0;
332     }
333     gw_log(ZASS_DEBUG, ZASS_TYPE, "Got searchresponse");
334     r.status = SearchResponse_GetSearchStatus(pdu);
335     r.num = SearchResponse_GetResultCount(pdu);
336     r.status = SearchResponse_GetResultSetStatus(pdu);
337     r.errcode = -1;
338     *r.errstring = '\0';
339     if ((record = SearchResponse_GetRecords(pdu)))
340     {
341         if (zutil_GetTag(record) == NONSURROGATEDIAGNOSTIC_TAG)
342         {
343             DATA_DIR *ad;
344
345             r.errcode = zutil_GetTaggedInt(record, ASN1_INTEGER);
346             if ((ad = zutil_GetTaggedObject(record, ASN1_VISIBLESTRING)))
347             {
348                 char *s;
349
350                 if ((s = OctetString_GetASCIIString(ad)))
351                 {
352                     strcpy(r.errstring, s);
353                     FREE(s);
354                 }
355             }
356         }
357         else
358             gw_log(GW_LOG_WARN, ZASS_TYPE, "Got real record in SRCHRESP");
359     }
360     SearchResponse_Destroy(pdu);
361
362     return &r;
363 }
364
365 /*
366  * Triple indirection - that's kinda heavy. We'll fix it later.
367  * There are worse things around, though. Like ZDist.
368  */
369 void get_diagrec(zass_record ***p, DATA_DIR *rec)
370 {
371     DATA_DIR *ad;
372
373     **p = malloc(sizeof(***p));
374     (**p)->next = 0;
375     (**p)->errcode = zutil_GetTaggedInt(rec, ASN1_INTEGER);
376     if ((ad = zutil_GetTaggedObject(rec, ASN1_VISIBLESTRING)))
377     {
378         char *s;
379
380         if ((s = OctetString_GetASCIIString(ad)))
381         {
382             strcpy((**p)->errstring, s);
383             FREE(s);
384         }
385     }
386     (**p)->which = ZASS_REC_DIAG;
387     *p = &(**p)->next;
388 }
389
390 void get_responserecords(zass_record ***p, DATA_DIR *rec)
391 {
392     int num, recsyntaxlen, i;
393     DATA_DIR *record, *retrec, *align;
394     PEXTERNAL ext;
395     POBJECTIDENTIFIER oid;
396     char recsyntax[256];
397
398     num = ResponseRecords_GetCount(rec);
399     for (i = 1; i <= num; i++)
400     {
401         record = ResponseRecords_GetRecord(rec, i);
402         if (!record)
403         {
404             gw_log(GW_LOG_WARN, ZASS_TYPE, "Failed to get record.");
405             return;
406         }
407         retrec = NamePlusRecord_GetRetrievalRecord(record);
408         if (!retrec)
409         {
410             /* check if it's a diagrec */
411             if (record->ptr.child->fldid == 2)
412                 get_diagrec(p, record->ptr.child);
413             else
414             {
415                 gw_log(GW_LOG_WARN, ZASS_TYPE, "Illegal record.");
416                 return;
417             }
418         }
419         ext = RetrievalRecord_GetExternal(retrec);
420         if (!ext)
421         {
422             gw_log(GW_LOG_WARN, ZASS_TYPE, "No external in record");
423             return;
424         }
425         oid = External_GetDirectReference(ext);
426         if (!oid)
427         {
428             gw_log(GW_LOG_WARN, ZASS_TYPE, "Unknown record type.");
429             return;
430         }
431         recsyntaxlen = DirectReference_GetLength(oid);
432         memcpy(recsyntax, DirectReference_GetData(oid), recsyntaxlen);
433         recsyntax[recsyntaxlen] = '\0';
434         **p = malloc(sizeof(***p));
435         (**p)->next = 0;
436         if (!strcmp(recsyntax, USMARC_OID))
437             (**p)->which = ZASS_REC_USMARC;
438         else
439         {
440             gw_log(GW_LOG_WARN, ZASS_TYPE, "ZLAYER only knows USMARC at this point.");
441             gw_log(GW_LOG_WARN, ZASS_TYPE, "Type was '%d'", (**p)->which);
442         }
443         align = External_GetEncodingAligned(ext);
444         if (!align)
445         {
446             gw_log(GW_LOG_WARN, ZASS_TYPE, "Record wasn't octet-aligned");
447             align = External_GetEncodingSingle(ext);
448             if (!align)
449             {
450                 gw_log(GW_LOG_WARN, ZASS_TYPE, "Record wasn't ANY");
451                 return;
452             }
453             align = align->ptr.child;
454         }
455         if (!((**p)->record = malloc(align->count + 1)))
456         {
457             gw_log(GW_LOG_FATAL, ZASS_TYPE, "malloc");
458             return;
459         }
460         memcpy((**p)->record, align->ptr.data, align->count);
461         (**p)->record[align->count] = '\0';
462         gw_log(ZASS_DEBUG, ZASS_TYPE, "Got a record of %d bytes",
463             align->count);
464
465         (*p) = &(**p)->next;
466     }
467 }
468
469 static void zass_records_free(zass_record *p)
470 {
471 }
472
473 /*
474  * Note that 1== first record.
475  */
476 const struct zass_presentent *zass_present(ZASS a, char *resname, int start,
477     int num)
478 {
479     static struct zass_presentent r = {0, 0, 0, 0};
480     zass_record **rec = &r.records;
481     DATA_DIR *pdu;
482     int len;
483
484     r.num = 0;
485     if (r.records)
486     {
487         zass_records_free(r.records);
488         r.records = 0;
489     }
490     do
491     {
492         gw_log(ZASS_DEBUG, ZASS_TYPE, "Fetching %d records from # %d", num - r.num,
493             start);
494         pdu = PresentRequest_CreateInitAllASCII(0, resname, start, num - r.num, "F",
495             USMARC_OID);
496         if (!pdu)
497         {
498             gw_log(GW_LOG_FATAL, "ZASS_TYPE", "failed to create presentrequest");
499             return 0;
500         }
501         zutil_GetBEREncodedBuffer(pdu, (unsigned char*)a->buf, &len,
502             a->maxrecordsize);
503         if (len <= 0)
504         {
505             gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to encode presentrequest");
506             return 0;
507         }
508         PresentRequest_Destroy(pdu);
509         if (netbox_SendBuffer(a->ass, a->buf, len) != len)
510         {
511             gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to send presentrequest");
512             return 0;
513         }
514         gw_log(ZASS_DEBUG, ZASS_TYPE, "Sent presentrequest.");
515         if ((len = zutil_GetBERFromNet(a->ass, (unsigned char*)a->buf,
516             a->maxrecordsize)) <= 0)
517         {
518             gw_log(GW_LOG_FATAL, ZASS_TYPE, "Failed to receive presentresponse");
519             return 0;
520         }
521         pdu = zutil_CreateFromData((unsigned char*)a->buf, len);
522         if (zutil_GetTag(pdu) != PRESENTRESPONSE_TAG)
523         {
524             gw_log(GW_LOG_FATAL, ZASS_TYPE, "Expected presentresponse from target");
525             return 0;
526         }
527         gw_log(ZASS_DEBUG, ZASS_TYPE, "Got presentresponse");
528         r.num += PresentResponse_GetNumberOfRecordsReturned(pdu);
529         r.presentstatus = PresentResponse_GetPresentStatus(pdu);
530         if (r.num == 0)
531         {
532             gw_log(GW_LOG_WARN, ZASS_TYPE, "Got 0 records from target.");
533             return 0;
534         }
535         r.nextpos = PresentResponse_GetNextResultSetPosition(pdu);
536         start = r.nextpos;
537         switch(PresentResponse_GetRecordType(pdu))
538         {
539             case RESPONSERECORDS_TAG:
540                 get_responserecords(&rec, PresentResponse_GetResponseRecords(pdu));
541                 break;
542             case NONSURROGATEDIAGNOSTIC_TAG:
543                 get_diagrec(&rec, PresentResponse_GetNonSurrogateDiagnostic(pdu));
544                 break;
545             default:
546                 gw_log(GW_LOG_WARN, ZASS_TYPE, "Bad tag in response rec.");
547         }
548         PresentResponse_Destroy(pdu);
549     }
550     while (num - r.num && start);
551     *rec = 0;
552         
553     return &r;
554 }