d1403230a208c2776876ef83e902001a64a83bc8
[idzebra-moved-to-github.git] / recctrl / xmlread.c
1 /* $Id: xmlread.c,v 1.13 2004-08-11 13:36:13 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004
3    Index Data Aps
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23 #if HAVE_EXPAT_H
24
25 #include <assert.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #if HAVE_ICONV_H
29 #include <errno.h>
30 #include <iconv.h>
31 #endif
32
33 #include <yaz/log.h>
34
35 #include "grsread.h"
36
37 #include <yaz/xmalloc.h>
38 #include <yaz/log.h>
39 #include <data1.h>
40
41 #include <expat.h>
42
43 #define XML_CHUNK 1024
44
45 struct user_info {
46     data1_node *d1_stack[256];
47     int level;
48     data1_handle dh;
49     NMEM nmem;
50     int loglevel;
51 };
52
53 static void cb_start (void *user, const char *el, const char **attr)
54 {
55     struct user_info *ui = (struct user_info*) user;
56     if (ui->level == 1)
57         data1_set_root (ui->dh, ui->d1_stack[0], ui->nmem, el);
58     ui->d1_stack[ui->level] = data1_mk_tag (ui->dh, ui->nmem, el, attr,
59                                                 ui->d1_stack[ui->level-1]);
60     ui->level++;
61     yaz_log (ui->loglevel, "cb_start %s", el);
62 }
63
64 static void cb_end (void *user, const char *el)
65 {
66     struct user_info *ui = (struct user_info*) user;
67
68     ui->level--;
69     yaz_log (ui->loglevel, "cb_end %s", el);
70 }
71
72 static void cb_chardata (void *user, const char *s, int len)
73 {
74     struct user_info *ui = (struct user_info*) user;
75 #if 0
76     yaz_log (ui->loglevel, "cb_chardata %.*s", len, s);
77 #endif
78     ui->d1_stack[ui->level] = data1_mk_text_n (ui->dh, ui->nmem, s, len,
79                                                    ui->d1_stack[ui->level -1]);
80 }
81
82 static void cb_decl (void *user, const char *version, const char *encoding,
83                      int standalone)
84 {
85     struct user_info *ui = (struct user_info*) user;
86     const char *attr_list[7];
87
88     attr_list[0] = "version";
89     attr_list[1] = version;
90
91     attr_list[2] = "encoding";
92     attr_list[3] = "UTF-8"; /* internally it's always UTF-8 */
93
94     attr_list[4] = "standalone";
95     attr_list[5] = standalone  ? "yes" : "no";
96
97     attr_list[6] = 0;
98     
99     data1_mk_preprocess (ui->dh, ui->nmem, "xml", attr_list,
100                              ui->d1_stack[ui->level-1]);
101 #if 0
102     yaz_log (LOG_LOG, "decl version=%s encoding=%s",
103              version ? version : "null",
104              encoding ? encoding : "null");
105 #endif
106 }
107     
108 static void cb_processing (void *user, const char *target,
109                            const char *data)
110 {
111     struct user_info *ui = (struct user_info*) user;
112     data1_node *res =
113         data1_mk_preprocess (ui->dh, ui->nmem, target, 0,
114                              ui->d1_stack[ui->level-1]);
115     data1_mk_text_nf (ui->dh, ui->nmem, data, strlen(data), res);
116     
117     yaz_log (ui->loglevel, "decl processing target=%s data=%s",
118              target ? target : "null",
119              data ? data : "null");
120 }
121
122 static void cb_comment (void *user, const char *data)
123 {
124     struct user_info *ui = (struct user_info*) user;
125     yaz_log (ui->loglevel, "decl comment data=%s", data ? data : "null");
126     data1_mk_comment (ui->dh, ui->nmem, data, ui->d1_stack[ui->level-1]);
127 }
128
129 static void cb_doctype_start (void *userData, const char *doctypeName,
130                               const char *sysid, const char *pubid,
131                               int has_internal_subset)
132 {
133     struct user_info *ui = (struct user_info*) userData;
134     yaz_log (ui->loglevel, "doctype start doctype=%s sysid=%s pubid=%s",
135              doctypeName, sysid, pubid);
136 }
137
138 static void cb_doctype_end (void *userData)
139 {
140     struct user_info *ui = (struct user_info*) userData;
141     yaz_log (ui->loglevel, "doctype end");
142 }
143
144
145 static void cb_entity_decl (void *userData, const char *entityName,
146                             int is_parameter_entity,
147                             const char *value, int value_length,
148                             const char *base, const char *systemId,
149                             const char *publicId, const char *notationName)
150 {
151     struct user_info *ui = (struct user_info*) userData;
152     yaz_log (ui->loglevel,
153              "entity decl %s is_para_entry=%d value=%.*s base=%s systemId=%s"
154              " publicId=%s notationName=%s",
155              entityName, is_parameter_entity, value_length, value,
156              base, systemId, publicId, notationName);
157     
158 }
159
160 static int cb_external_entity (XML_Parser pparser,
161                                const char *context,
162                                const char *base,
163                                const char *systemId,
164                                const char *publicId)
165 {
166     struct user_info *ui = (struct user_info*) XML_GetUserData(pparser);
167     FILE *inf;
168     int done = 0;
169     XML_Parser parser;
170
171     yaz_log (ui->loglevel,
172              "external entity context=%s base=%s systemid=%s publicid=%s",
173              context, base, systemId, publicId);
174     if (!systemId)
175         return 1;
176
177     if (!(inf = fopen (systemId, "rb")))
178     {
179         yaz_log (LOG_WARN|LOG_ERRNO, "fopen %s", systemId);
180         return 0;
181     }
182
183     parser = XML_ExternalEntityParserCreate (pparser, "", 0);
184     while (!done)
185     {
186         int r;
187         void *buf = XML_GetBuffer (parser, XML_CHUNK);
188         if (!buf)
189         {
190             yaz_log (LOG_WARN, "XML_GetBuffer fail");
191             break;
192         }
193         r = fread (buf, 1, XML_CHUNK, inf);
194         if (r == 0)
195         {
196             if (ferror(inf))
197             {
198                 yaz_log (LOG_WARN|LOG_ERRNO, "fread %s", systemId);
199                 break;
200             }
201             done = 1;
202         }
203         if (!XML_ParseBuffer (parser, r, done))
204         {
205             done = 1;
206             yaz_log (LOG_WARN, "%s:%d:%d:XML error: %s",
207                      systemId,
208                      XML_GetCurrentLineNumber(parser),
209                      XML_GetCurrentColumnNumber(parser),
210                      XML_ErrorString(XML_GetErrorCode(parser)));
211         }
212     }
213     fclose (inf);
214     XML_ParserFree (parser);
215     return done;
216 }
217
218
219 #if HAVE_ICONV_H
220 static int cb_encoding_convert (void *data, const char *s)
221 {
222     iconv_t t = (iconv_t) data;
223     size_t ret;
224     size_t outleft = 2;
225     char outbuf_[2], *outbuf = outbuf_;
226     size_t inleft = 4;
227     char *inbuf = (char *) s;
228     unsigned short code;
229
230 #if 1
231     yaz_log(LOG_LOG, "------------------------- cb_encoding_convert --- ");
232 #endif
233     ret = iconv (t, &inbuf, &inleft, &outbuf, &outleft);
234     if (ret == (size_t) (-1) && errno != E2BIG)
235     {
236         iconv (t, 0, 0, 0, 0);
237         return -1;
238     }
239     if (outleft != 0)
240         return -1;
241     memcpy (&code, outbuf_, sizeof(short));
242     return code;
243 }
244
245 static void cb_encoding_release (void *data)
246 {
247     iconv_t t = (iconv_t) data;
248     iconv_close (t);
249 }
250
251 static int cb_encoding_handler (void *userData, const char *name,
252                                 XML_Encoding *info)
253 {
254     int i = 0;
255     int no_ok = 0;
256     struct user_info *ui = (struct user_info*) userData;
257
258     iconv_t t = iconv_open ("UNICODE", name);
259     if (t == (iconv_t) (-1))
260         return 0;
261    
262     info->data = 0;  /* signal that multibyte is not in use */
263     yaz_log (ui->loglevel, "Encoding handler of %s", name);
264     for (i = 0; i<256; i++)
265     {
266         size_t ret;
267         char outbuf_[5];
268         char inbuf_[5];
269         char *inbuf = inbuf_;
270         char *outbuf = outbuf_;
271         size_t inleft = 1;
272         size_t outleft = 2;
273         inbuf_[0] = i;
274
275         iconv (t, 0, 0, 0, 0);  /* reset iconv */
276
277         ret = iconv(t, &inbuf, &inleft, &outbuf, &outleft);
278         if (ret == (size_t) (-1))
279         {
280             if (errno == EILSEQ)
281             {
282                 yaz_log (ui->loglevel, "Encoding %d: invalid sequence", i);
283                 info->map[i] = -1;  /* invalid sequence */
284             }
285             if (errno == EINVAL)
286             {                       /* multi byte input */
287                 int len = 2;
288                 int j = 0;
289                 info->map[i] = -1;
290                 
291                 while (len <= 4)
292                 {
293                     char sbuf[80];
294                     int k;
295                     inbuf = inbuf_;
296                     inleft = len;
297                     outbuf = outbuf_;
298                     outleft = 2;
299
300                     inbuf_[len-1] = j;
301                     iconv (t, 0,0,0,0);
302
303                     assert (i >= 0 && i<255);
304
305                     *sbuf = 0;
306                     for (k = 0; k<len; k++)
307                     {
308                         sprintf (sbuf+strlen(sbuf), "%d ", inbuf_[k]&255);
309                     }
310                     ret = iconv (t, &inbuf, &inleft, &outbuf, &outleft);
311                     if (ret == (size_t) (-1))
312                     {
313                         if (errno == EILSEQ || errno == E2BIG)
314                         {
315                             j++;
316                             if (j > 255)
317                                 break;
318                         }
319                         else if (errno == EINVAL)
320                         {
321                             len++;
322                             j = 7;
323                         }
324                     }
325                     else if (outleft == 0)
326                     {
327                         info->map[i] = -len;
328                         info->data = t;  /* signal that multibyte is in use */
329                         break;
330                     }
331                     else
332                     {
333                         break;
334                     }
335                 }
336                 if (info->map[i] < -1)
337                     yaz_log (ui->loglevel, "Encoding %d: multibyte input %d",
338                              i, -info->map[i]);
339                 else
340                     yaz_log (ui->loglevel, "Encoding %d: multibyte input failed",
341                              i);
342             }
343             if (errno == E2BIG)
344             {
345                 info->map[i] = -1;  /* no room for output */
346                 if (i != 0)
347                     yaz_log (LOG_WARN, "Encoding %d: no room for output",
348                              i);
349             }
350         }
351         else if (outleft == 0)
352         {
353             unsigned short code;
354             memcpy (&code, outbuf_, sizeof(short));
355             info->map[i] = code;
356             no_ok++;
357         }
358         else
359         {   /* should never happen */
360             info->map[i] = -1;
361             yaz_log (LOG_DEBUG, "Encoding %d: bad state", i);
362         }
363     }
364     if (info->data)
365     {   /* at least one multi byte */
366         info->convert = cb_encoding_convert;
367         info->release = cb_encoding_release;
368     }
369     else
370     {
371         /* no multi byte - we no longer need iconv handler */
372         iconv_close(t);
373         info->convert = 0;
374         info->release = 0;
375     }
376     if (!no_ok)
377         return 0;
378     return 1;
379 }
380 /* HAVE_ICONV_H */
381 #endif
382
383 static void cb_ns_start(void *userData, const char *prefix, const char *uri)
384 {
385     struct user_info *ui = (struct user_info*) userData;
386     if (prefix && uri)
387         yaz_log(ui->loglevel, "cb_ns_start %s %s", prefix, uri);
388 }
389
390 static void cb_ns_end(void *userData, const char *prefix)
391 {
392     struct user_info *ui = (struct user_info*) userData;
393     if (prefix)
394         yaz_log(ui->loglevel, "cb_ns_end %s", prefix);
395 }
396 data1_node *zebra_read_xml (data1_handle dh,
397                             int (*rf)(void *, char *, size_t), void *fh,
398                             NMEM m)
399 {
400     XML_Parser parser;
401     struct user_info uinfo;
402     int done = 0;
403     data1_node *first_node;
404
405     uinfo.loglevel = LOG_DEBUG;
406     uinfo.level = 1;
407     uinfo.dh = dh;
408     uinfo.nmem = m;
409     uinfo.d1_stack[0] = data1_mk_node2 (dh, m, DATA1N_root, 0);
410     uinfo.d1_stack[1] = 0; /* indicate no children (see end of routine) */
411     
412     parser = XML_ParserCreate (0 /* encoding */);
413     
414     XML_SetElementHandler (parser, cb_start, cb_end);
415     XML_SetCharacterDataHandler (parser, cb_chardata);
416     XML_SetXmlDeclHandler (parser, cb_decl);
417     XML_SetProcessingInstructionHandler (parser, cb_processing);
418     XML_SetUserData (parser, &uinfo);
419     XML_SetCommentHandler (parser, cb_comment);
420     XML_SetDoctypeDeclHandler (parser, cb_doctype_start, cb_doctype_end);
421     XML_SetEntityDeclHandler (parser, cb_entity_decl);
422     XML_SetExternalEntityRefHandler (parser, cb_external_entity);
423     XML_SetNamespaceDeclHandler(parser, cb_ns_start, cb_ns_end);
424 #if HAVE_ICONV_H
425     XML_SetUnknownEncodingHandler (parser, cb_encoding_handler, &uinfo);
426 #endif
427     while (!done)
428     {
429         int r;
430         void *buf = XML_GetBuffer (parser, XML_CHUNK);
431         if (!buf)
432         {
433             /* error */
434             yaz_log (LOG_WARN, "XML_GetBuffer fail");
435             break;
436         }
437         r = (*rf)(fh, buf, XML_CHUNK);
438         if (r < 0)
439         {
440             /* error */
441             yaz_log (LOG_WARN, "XML read fail");
442             break;
443         }
444         else if (r == 0)
445             done = 1;
446         if (!XML_ParseBuffer (parser, r, done))
447         {
448             done = 1;
449             yaz_log (LOG_WARN, "%d:%d:XML error: %s",
450                      XML_GetCurrentLineNumber(parser),
451                      XML_GetCurrentColumnNumber(parser),
452                      XML_ErrorString(XML_GetErrorCode(parser)));
453         }
454     }
455     XML_ParserFree (parser);
456     if (!uinfo.d1_stack[1] || !done)
457         return 0;
458     /* insert XML header if not present .. */
459     first_node = uinfo.d1_stack[0]->child;
460     if (first_node->which != DATA1N_preprocess ||
461         strcmp(first_node->u.preprocess.target, "xml"))
462     {
463         const char *attr_list[5];
464
465         attr_list[0] = "version";
466         attr_list[1] = "1.0";
467
468         attr_list[2] = "encoding";
469         attr_list[3] = "UTF-8"; /* encoding */
470
471         attr_list[4] = 0;
472     
473         data1_insert_preprocess (uinfo.dh, uinfo.nmem, "xml", attr_list,
474                                  uinfo.d1_stack[0]);
475     }
476     return uinfo.d1_stack[0];
477 }
478
479 struct xml_info {
480     XML_Expat_Version expat_version;
481 };
482
483 static void *grs_init_xml(void)
484 {
485     struct xml_info *p = (struct xml_info *) xmalloc (sizeof(*p));
486
487     p->expat_version = XML_ExpatVersionInfo();
488
489     return p;
490 }
491
492 static data1_node *grs_read_xml (struct grs_read_info *p)
493 {
494     return zebra_read_xml (p->dh, p->readf, p->fh, p->mem);
495 }
496
497 static void grs_destroy_xml(void *clientData)
498 {
499     struct xml_info *p = (struct xml_info *) clientData;
500
501     xfree (p);
502 }
503
504 static struct recTypeGrs xml_type = {
505     "xml",
506     grs_init_xml,
507     grs_destroy_xml,
508     grs_read_xml
509 };
510
511 RecTypeGrs recTypeGrs_xml = &xml_type;
512
513 /* HAVE_EXPAT_H */
514 #endif
515