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