Zebra uses yaz_iconv
[idzebra-moved-to-github.git] / util / charmap.c
1 /* $Id: charmap.c,v 1.26 2002-08-28 19:52:29 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002
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
24
25 /*
26  * Support module to handle character-conversions into and out of the
27  * Zebra dictionary.
28  */
29
30 #include <ctype.h>
31 #include <string.h>
32 #include <assert.h>
33
34 typedef unsigned ucs4_t;
35
36 #include <yaz/yaz-util.h>
37 #include <charmap.h>
38
39
40 #define CHR_MAXSTR 1024
41 #define CHR_MAXEQUIV 32
42
43 const char *CHR_UNKNOWN = "\001";
44 const char *CHR_SPACE   = "\002";
45 const char *CHR_BASE    = "\003";
46
47 struct chrmaptab_info
48 {
49     chr_t_entry *input;         /* mapping table for input data */
50     chr_t_entry *q_input;       /* mapping table for queries */
51     unsigned char *output[256]; /* return mapping - for display of registers */
52     int base_uppercase;         /* Start of upper-case ordinals */
53     NMEM nmem;
54 };
55
56 /*
57  * Character map trie node.
58  */
59 struct chr_t_entry
60 {
61     chr_t_entry **children;  /* array of children */
62     unsigned char **target;  /* target for this node, if any */
63 };
64
65 /*
66  * General argument structure for callback functions (internal use only)
67  */
68 typedef struct chrwork 
69 {
70     chrmaptab map;
71     char string[CHR_MAXSTR+1];
72 } chrwork;
73
74 /*
75  * Add an entry to the character map.
76  */
77 static chr_t_entry *set_map_string(chr_t_entry *root, NMEM nmem,
78                                    const char *from, int len, char *to,
79                                    const char *from_0)
80 {
81     if (!from_0)
82         from_0 = from;
83     if (!root)
84     {
85         root = (chr_t_entry *) nmem_malloc(nmem, sizeof(*root));
86         root->children = 0;
87         root->target = 0;
88     }
89     if (!len)
90     {
91         if (!root->target || !root->target[0] || strcmp(root->target[0], to))
92         {
93             if (from_0 && 
94                 root->target && root->target[0] && root->target[0][0] &&
95                 strcmp (root->target[0], CHR_UNKNOWN))
96             {
97                 yaz_log (LOG_WARN, "duplicate entry for charmap from '%s'",
98                          from_0);
99             }
100             root->target = (unsigned char **)
101                 nmem_malloc(nmem, sizeof(*root->target)*2);
102             root->target[0] = (unsigned char *) nmem_strdup(nmem, to);
103             root->target[1] = 0;
104         }
105     }
106     else
107     {
108         if (!root->children)
109         {
110             int i;
111
112             root->children = (chr_t_entry **)
113                 nmem_malloc(nmem, sizeof(chr_t_entry*) * 256);
114             for (i = 0; i < 256; i++)
115                 root->children[i] = 0;
116         }
117         if (!(root->children[(unsigned char) *from] =
118             set_map_string(root->children[(unsigned char) *from], nmem,
119                            from + 1, len - 1, to, from_0)))
120             return 0;
121     }
122     return root;
123 }
124
125 static chr_t_entry *find_entry(chr_t_entry *t, const char **from, int len)
126 {
127     chr_t_entry *res;
128
129     if (len && t->children && t->children[(unsigned char) **from])
130     {
131         const char *pos = *from;
132
133         (*from)++;
134         if ((res = find_entry(t->children[(unsigned char) *pos],
135             from, len - 1)))
136             return res;
137         /* no match */
138         *from = pos;
139     }
140     /* no children match. use ourselves, if we have a target */
141     return t->target ? t : 0;
142 }
143
144 static chr_t_entry *find_entry_x(chr_t_entry *t, const char **from, int *len)
145 {
146     chr_t_entry *res;
147
148     while (*len <= 0)
149     {   /* switch to next buffer */
150         if (*len < 0)
151             break;
152         from++;
153         len++;
154     }
155     if (*len > 0 && t->children && t->children[(unsigned char) **from])
156     {
157         const char *old_from = *from;
158         int old_len = *len;
159         
160         (*len)--;
161         (*from)++;
162         if ((res = find_entry_x(t->children[(unsigned char) *old_from],
163                                 from, len)))
164             return res;
165         /* no match */
166         *len = old_len;
167         *from = old_from;
168     }
169     /* no children match. use ourselves, if we have a target */
170     return t->target ? t : 0;
171 }
172
173 const char **chr_map_input_x(chrmaptab maptab, const char **from, int *len)
174 {
175     chr_t_entry *t = maptab->input;
176     chr_t_entry *res;
177
178     if (!(res = find_entry_x(t, from, len)))
179         abort();
180     return (const char **) (res->target);
181 }
182
183 const char **chr_map_input(chrmaptab maptab, const char **from, int len)
184 {
185     chr_t_entry *t = maptab->input;
186     chr_t_entry *res;
187     int len_tmp[2];
188
189     len_tmp[0] = len;
190     len_tmp[1] = -1;
191     if (!(res = find_entry_x(t, from, len_tmp)))
192         abort();
193     return (const char **) (res->target);
194 }
195
196 const char *chr_map_output(chrmaptab maptab, const char **from, int len)
197 {
198     unsigned char c = ** (unsigned char **) from;
199     (*from)++;
200     return (const char*) maptab->output[c];
201 }
202
203 unsigned char zebra_prim(char **s)
204 {
205     unsigned char c;
206     unsigned int i = 0;
207
208     yaz_log (LOG_DEBUG, "prim %.3s", *s);
209     if (**s == '\\')
210     {
211         (*s)++;
212         c = **s;
213         switch (c)
214         {
215         case '\\': c = '\\'; (*s)++; break;
216         case 'r': c = '\r'; (*s)++; break;
217         case 'n': c = '\n'; (*s)++; break;
218         case 't': c = '\t'; (*s)++; break;
219         case 's': c = ' '; (*s)++; break;
220         case 'x': sscanf(*s, "x%2x", &i); c = i; *s += 3; break;
221         case '0':
222         case '1':
223         case '2':
224         case '3':
225         case '4':
226         case '5':
227         case '6':
228         case '7':
229         case '8':
230         case '9':
231             sscanf(*s, "%3o", &i);
232             c = i;
233             *s += 3;
234             break;
235         default:
236             (*s)++;
237         }
238     }
239     else
240     {
241         c = **s;
242         ++(*s);
243     }
244     return c;
245 }
246
247 ucs4_t zebra_prim_w(ucs4_t **s)
248 {
249     ucs4_t c;
250     ucs4_t i = 0;
251     char fmtstr[8];
252
253     yaz_log (LOG_DEBUG, "prim %.3s", (char *) *s);
254     if (**s == '\\')
255     {
256         (*s)++;
257         c = **s;
258         switch (c)
259         {
260         case '\\': c = '\\'; (*s)++; break;
261         case 'r': c = '\r'; (*s)++; break;
262         case 'n': c = '\n'; (*s)++; break;
263         case 't': c = '\t'; (*s)++; break;
264         case 's': c = ' '; (*s)++; break;
265         case 'x': 
266             fmtstr[0] = (*s)[0];
267             fmtstr[1] = (*s)[1];
268             fmtstr[2] = (*s)[2];
269             fmtstr[3] = 0;
270             sscanf(fmtstr, "x%2x", &i);
271             c = i;
272             *s += 3; break;
273         case '0':
274         case '1':
275         case '2':
276         case '3':
277         case '4':
278         case '5':
279         case '6':
280         case '7':
281         case '8':
282         case '9':
283             fmtstr[0] = (*s)[0];
284             fmtstr[1] = (*s)[1];
285             fmtstr[2] = (*s)[2];
286             fmtstr[3] = 0;
287             sscanf(fmtstr, "%3o", &i);
288             c = i;
289             *s += 3;
290             break;
291         default:
292             (*s)++;
293         }
294     }
295     else
296     {
297         c = **s;
298         ++(*s);
299     }
300     yaz_log (LOG_DEBUG, "out %d", c);
301     return c;
302 }
303
304 /*
305  * Callback function.
306  * Add an entry to the value space.
307  */
308 static void fun_addentry(const char *s, void *data, int num)
309 {
310     chrmaptab tab = (chrmaptab) data;
311     char tmp[2];
312     
313     tmp[0] = num; tmp[1] = '\0';
314     tab->input = set_map_string(tab->input, tab->nmem, s, strlen(s), tmp, 0);
315     tab->output[num + tab->base_uppercase] =
316         (unsigned char *) nmem_strdup(tab->nmem, s);
317 }
318
319 /* 
320  * Callback function.
321  * Add a space-entry to the value space.
322  */
323 static void fun_addspace(const char *s, void *data, int num)
324 {
325     chrmaptab tab = (chrmaptab) data;
326     tab->input = set_map_string(tab->input, tab->nmem, s, strlen(s),
327                                 (char*) CHR_SPACE, 0);
328 }
329
330 /*
331  * Create a string containing the mapped characters provided.
332  */
333 static void fun_mkstring(const char *s, void *data, int num)
334 {
335     chrwork *arg = (chrwork *) data;
336     const char **res, *p = s;
337
338     res = chr_map_input(arg->map, &s, strlen(s));
339     if (*res == (char*) CHR_UNKNOWN)
340         logf(LOG_WARN, "Map: '%s' has no mapping", p);
341     strncat(arg->string, *res, CHR_MAXSTR - strlen(arg->string));
342     arg->string[CHR_MAXSTR] = '\0';
343 }
344
345 /*
346  * Add a map to the string contained in the argument.
347  */
348 static void fun_add_map(const char *s, void *data, int num)
349 {
350     chrwork *arg = (chrwork *) data;
351
352     assert(arg->map->input);
353     logf (LOG_DEBUG, "set map %.*s", (int) strlen(s), s);
354     set_map_string(arg->map->input, arg->map->nmem, s, strlen(s), arg->string,
355                    0);
356     for (s = arg->string; *s; s++)
357         logf (LOG_DEBUG, " %3d", (unsigned char) *s);
358 }
359
360 /*
361  * Add a query map to the string contained in the argument.
362  */
363 static void fun_add_qmap(const char *s, void *data, int num)
364 {
365     chrwork *arg = (chrwork *) data;
366
367     assert(arg->map->q_input);
368     logf (LOG_DEBUG, "set qmap %.*s", (int) strlen(s), s);
369     set_map_string(arg->map->q_input, arg->map->nmem, s,
370                    strlen(s), arg->string, 0);
371     for (s = arg->string; *s; s++)
372         logf (LOG_DEBUG, " %3d", (unsigned char) *s);
373 }
374
375 static int scan_to_utf8 (yaz_iconv_t t, ucs4_t *from, size_t inlen,
376                         char *outbuf, size_t outbytesleft)
377 {
378     size_t inbytesleft = inlen * sizeof(ucs4_t);
379     char *inbuf = (char*) from;
380     size_t ret;
381    
382     if (t == 0)
383         *outbuf++ = *from;  /* ISO-8859-1 is OK here */
384     else
385     {
386         ret = yaz_iconv (t, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
387         if (ret == (size_t) (-1))
388         {
389             yaz_log (LOG_WARN|LOG_ERRNO, "bad unicode sequence");
390             return -1;
391         }
392     }
393     *outbuf = '\0';
394     return 0;
395 }
396
397 static int scan_string(char *s_native,
398                        yaz_iconv_t t_unicode, yaz_iconv_t t_utf8,
399                        void (*fun)(const char *c, void *data, int num),
400                        void *data, int *num)
401 {
402     char str[1024];
403
404     ucs4_t arg[512];
405     ucs4_t *s0, *s = arg;
406     ucs4_t c, begin, end;
407     size_t i;
408
409     if (t_unicode != 0)
410     {
411         char *outbuf = (char *) arg;
412         char *inbuf = s_native;
413         size_t outbytesleft = sizeof(arg)-4;
414         size_t inbytesleft = strlen(s_native);
415         size_t ret;
416         ret = yaz_iconv(t_unicode, &inbuf, &inbytesleft,
417                         &outbuf, &outbytesleft);
418         if (ret == (size_t)(-1))
419             return -1;
420         i = (outbuf - (char*) arg)/sizeof(ucs4_t);
421     }
422     else
423     { 
424         for (i = 0; s_native[i]; i++)
425             arg[i] = s_native[i] & 255; /* ISO-8859-1 conversion */
426     }
427     arg[i] = 0;      /* terminate */
428     if (s[0] == 0xfeff || s[0] == 0xfeff)  /* skip byte Order Mark */
429         s++;
430     while (*s)
431     {
432         switch (*s)
433         {
434         case '{':
435             s++;
436             begin = zebra_prim_w(&s);
437             if (*s != '-')
438             {
439                 logf(LOG_FATAL, "Bad range in char-map");
440                 return -1;
441             }
442             s++;
443             end = zebra_prim_w(&s);
444             if (end <= begin)
445             {
446                 logf(LOG_FATAL, "Bad range in char-map");
447                 return -1;
448             }
449             s++;
450             for (c = begin; c <= end; c++)
451             {
452                 if (scan_to_utf8 (t_utf8, &c, 1, str, sizeof(str)-1))
453                     return -1;
454                 (*fun)(str, data, num ? (*num)++ : 0);
455             }
456             break;
457         case '[': s++; abort(); break;
458         case '(':
459             ++s;
460             s0 = s;
461             while (*s != ')' || s[-1] == '\\')
462                 s++;
463             *s = 0;
464             if (scan_to_utf8 (t_utf8, s0, s - s0, str, sizeof(str)-1))
465                 return -1;
466             (*fun)(str, data, num ? (*num)++ : 0);
467             s++;
468             break;
469         default:
470             c = zebra_prim_w(&s);
471             if (scan_to_utf8 (t_utf8, &c, 1, str, sizeof(str)-1))
472                 return -1;
473             (*fun)(str, data, num ? (*num)++ : 0);
474         }
475     }
476     return 0;
477 }
478
479 chrmaptab chrmaptab_create(const char *tabpath, const char *name, int map_only,
480                            const char *tabroot)
481 {
482     FILE *f;
483     char line[512], *argv[50];
484     chrmaptab res;
485     int lineno = 0;
486     int errors = 0;
487     int argc, num = (int) *CHR_BASE, i;
488     NMEM nmem;
489     yaz_iconv_t t_unicode = 0;
490     yaz_iconv_t t_utf8 = 0;
491     unsigned endian = 31;
492     const char *ucs4_native = "UCS-4";
493
494     if (*(char*) &endian == 31)      /* little endian? */
495         ucs4_native = "UCS-4LE";
496
497     t_utf8 = yaz_iconv_open ("UTF-8", ucs4_native);
498     logf (LOG_DEBUG, "maptab %s open", name);
499     if (!(f = yaz_fopen(tabpath, name, "r", tabroot)))
500     {
501         logf(LOG_WARN|LOG_ERRNO, "%s", name);
502         return 0;
503     }
504     nmem = nmem_create ();
505     res = (chrmaptab) nmem_malloc(nmem, sizeof(*res));
506     res->nmem = nmem;
507     res->input = (chr_t_entry *) nmem_malloc(res->nmem, sizeof(*res->input));
508     res->input->target = (unsigned char **)
509         nmem_malloc(res->nmem, sizeof(*res->input->target) * 2);
510     res->input->target[0] = (unsigned char*) CHR_UNKNOWN;
511     res->input->target[1] = 0;
512     res->input->children = (chr_t_entry **)
513         nmem_malloc(res->nmem, sizeof(res->input) * 256);
514     for (i = 0; i < 256; i++)
515     {
516         res->input->children[i] = (chr_t_entry *)
517             nmem_malloc(res->nmem, sizeof(*res->input));
518         res->input->children[i]->children = 0;
519         res->input->children[i]->target = (unsigned char **)
520             nmem_malloc (res->nmem, 2 * sizeof(unsigned char *));
521         res->input->children[i]->target[1] = 0;
522         if (map_only)
523         {
524             res->input->children[i]->target[0] = (unsigned char *)
525                 nmem_malloc (res->nmem, 2 * sizeof(unsigned char));
526             res->input->children[i]->target[0][0] = i;
527             res->input->children[i]->target[0][1] = 0;
528         }
529         else
530             res->input->children[i]->target[0] = (unsigned char*) CHR_UNKNOWN;
531     }
532     res->q_input = (chr_t_entry *)
533         nmem_malloc(res->nmem, sizeof(*res->q_input));
534     res->q_input->target = 0;
535     res->q_input->children = 0;
536
537     for (i = *CHR_BASE; i < 256; i++)
538         res->output[i] = 0;
539     res->output[(int) *CHR_SPACE] = (unsigned char *) " ";
540     res->output[(int) *CHR_UNKNOWN] = (unsigned char*) "@";
541     res->base_uppercase = 0;
542
543     while (!errors && (argc = readconf_line(f, &lineno, line, 512, argv, 50)))
544         if (!map_only && !yaz_matchstr(argv[0], "lowercase"))
545         {
546             if (argc != 2)
547             {
548                 logf(LOG_FATAL, "Syntax error in charmap");
549                 ++errors;
550             }
551             if (scan_string(argv[1], t_unicode, t_utf8, fun_addentry,
552                             res, &num) < 0)
553             {
554                 logf(LOG_FATAL, "Bad value-set specification");
555                 ++errors;
556             }
557             res->base_uppercase = num;
558             res->output[(int) *CHR_SPACE + num] = (unsigned char *) " ";
559             res->output[(int) *CHR_UNKNOWN + num] = (unsigned char*) "@";
560             num = (int) *CHR_BASE;
561         }
562         else if (!map_only && !yaz_matchstr(argv[0], "uppercase"))
563         {
564             if (!res->base_uppercase)
565             {
566                 logf(LOG_FATAL, "Uppercase directive with no lowercase set");
567                 ++errors;
568             }
569             if (argc != 2)
570             {
571                 logf(LOG_FATAL, "Missing arg for uppercase directive");
572                 ++errors;
573             }
574             if (scan_string(argv[1], t_unicode, t_utf8, fun_addentry,
575                             res, &num) < 0)
576             {
577                 logf(LOG_FATAL, "Bad value-set specification");
578                 ++errors;
579             }
580         }
581         else if (!map_only && !yaz_matchstr(argv[0], "space"))
582         {
583             if (argc != 2)
584             {
585                 logf(LOG_FATAL, "Syntax error in charmap");
586                 ++errors;
587             }
588             if (scan_string(argv[1], t_unicode, t_utf8,
589                             fun_addspace, res, 0) < 0)
590             {
591                 logf(LOG_FATAL, "Bad space specification");
592                 ++errors;
593             }
594         }
595         else if (!yaz_matchstr(argv[0], "map"))
596         {
597             chrwork buf;
598
599             if (argc != 3)
600             {
601                 logf(LOG_FATAL, "charmap directive map requires 2 args");
602                 ++errors;
603             }
604             buf.map = res;
605             buf.string[0] = '\0';
606             if (scan_string(argv[2], t_unicode, t_utf8,
607                             fun_mkstring, &buf, 0) < 0)
608             {
609                 logf(LOG_FATAL, "Bad map target");
610                 ++errors;
611             }
612             if (scan_string(argv[1], t_unicode, t_utf8,
613                             fun_add_map, &buf, 0) < 0)
614             {
615                 logf(LOG_FATAL, "Bad map source");
616                 ++errors;
617             }
618         }
619         else if (!yaz_matchstr(argv[0], "qmap"))
620         {
621             chrwork buf;
622
623             if (argc != 3)
624             {
625                 logf(LOG_FATAL, "charmap directive qmap requires 2 args");
626                 ++errors;
627             }
628             buf.map = res;
629             buf.string[0] = '\0';
630             if (scan_string(argv[2], t_unicode, t_utf8, 
631                             fun_mkstring, &buf, 0) < 0)
632             {
633                 logf(LOG_FATAL, "Bad qmap target");
634                 ++errors;
635             }
636             if (scan_string(argv[1], t_unicode, t_utf8, 
637                             fun_add_qmap, &buf, 0) < 0)
638             {
639                 logf(LOG_FATAL, "Bad qmap source");
640                 ++errors;
641             }
642         }
643         else if (!yaz_matchstr(argv[0], "encoding"))
644         {
645             if (t_unicode != 0)
646                 yaz_iconv_close (t_unicode);
647             t_unicode = yaz_iconv_open (ucs4_native, argv[1]);
648         }
649         else
650         {
651             logf(LOG_WARN, "Syntax error at '%s' in %s", line, name);
652         }
653     
654     yaz_fclose(f);
655     if (errors)
656     {
657         chrmaptab_destroy(res);
658         res = 0;
659     }
660     logf (LOG_DEBUG, "maptab %s close %d errors", name, errors);
661     if (t_utf8 != 0)
662         yaz_iconv_close(t_utf8);
663     if (t_unicode != 0)
664         yaz_iconv_close(t_unicode);
665     return res;
666 }
667
668 void chrmaptab_destroy(chrmaptab tab)
669 {
670     if (tab)
671         nmem_destroy (tab->nmem);
672 }
673
674