Fixed behaviour of Zebra in one-byte environment (see comments in file).
[idzebra-moved-to-github.git] / util / charmap.c
1 /* $Id: charmap.c,v 1.27 2003-01-13 10:53:16 oleg 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
499     logf (LOG_DEBUG, "maptab %s open", name);
500     if (!(f = yaz_fopen(tabpath, name, "r", tabroot)))
501     {
502         logf(LOG_WARN|LOG_ERRNO, "%s", name);
503         return 0;
504     }
505     nmem = nmem_create ();
506     res = (chrmaptab) nmem_malloc(nmem, sizeof(*res));
507     res->nmem = nmem;
508     res->input = (chr_t_entry *) nmem_malloc(res->nmem, sizeof(*res->input));
509     res->input->target = (unsigned char **)
510         nmem_malloc(res->nmem, sizeof(*res->input->target) * 2);
511     res->input->target[0] = (unsigned char*) CHR_UNKNOWN;
512     res->input->target[1] = 0;
513     res->input->children = (chr_t_entry **)
514         nmem_malloc(res->nmem, sizeof(res->input) * 256);
515     for (i = 0; i < 256; i++)
516     {
517         res->input->children[i] = (chr_t_entry *)
518             nmem_malloc(res->nmem, sizeof(*res->input));
519         res->input->children[i]->children = 0;
520         res->input->children[i]->target = (unsigned char **)
521             nmem_malloc (res->nmem, 2 * sizeof(unsigned char *));
522         res->input->children[i]->target[1] = 0;
523         if (map_only)
524         {
525             res->input->children[i]->target[0] = (unsigned char *)
526                 nmem_malloc (res->nmem, 2 * sizeof(unsigned char));
527             res->input->children[i]->target[0][0] = i;
528             res->input->children[i]->target[0][1] = 0;
529         }
530         else
531             res->input->children[i]->target[0] = (unsigned char*) CHR_UNKNOWN;
532     }
533     res->q_input = (chr_t_entry *)
534         nmem_malloc(res->nmem, sizeof(*res->q_input));
535     res->q_input->target = 0;
536     res->q_input->children = 0;
537
538     for (i = *CHR_BASE; i < 256; i++)
539         res->output[i] = 0;
540     res->output[(int) *CHR_SPACE] = (unsigned char *) " ";
541     res->output[(int) *CHR_UNKNOWN] = (unsigned char*) "@";
542     res->base_uppercase = 0;
543
544     while (!errors && (argc = readconf_line(f, &lineno, line, 512, argv, 50)))
545         if (!map_only && !yaz_matchstr(argv[0], "lowercase"))
546         {
547             if (argc != 2)
548             {
549                 logf(LOG_FATAL, "Syntax error in charmap");
550                 ++errors;
551             }
552             if (scan_string(argv[1], t_unicode, t_utf8, fun_addentry,
553                             res, &num) < 0)
554             {
555                 logf(LOG_FATAL, "Bad value-set specification");
556                 ++errors;
557             }
558             res->base_uppercase = num;
559             res->output[(int) *CHR_SPACE + num] = (unsigned char *) " ";
560             res->output[(int) *CHR_UNKNOWN + num] = (unsigned char*) "@";
561             num = (int) *CHR_BASE;
562         }
563         else if (!map_only && !yaz_matchstr(argv[0], "uppercase"))
564         {
565             if (!res->base_uppercase)
566             {
567                 logf(LOG_FATAL, "Uppercase directive with no lowercase set");
568                 ++errors;
569             }
570             if (argc != 2)
571             {
572                 logf(LOG_FATAL, "Missing arg for uppercase directive");
573                 ++errors;
574             }
575             if (scan_string(argv[1], t_unicode, t_utf8, fun_addentry,
576                             res, &num) < 0)
577             {
578                 logf(LOG_FATAL, "Bad value-set specification");
579                 ++errors;
580             }
581         }
582         else if (!map_only && !yaz_matchstr(argv[0], "space"))
583         {
584             if (argc != 2)
585             {
586                 logf(LOG_FATAL, "Syntax error in charmap");
587                 ++errors;
588             }
589             if (scan_string(argv[1], t_unicode, t_utf8,
590                             fun_addspace, res, 0) < 0)
591             {
592                 logf(LOG_FATAL, "Bad space specification");
593                 ++errors;
594             }
595         }
596         else if (!yaz_matchstr(argv[0], "map"))
597         {
598             chrwork buf;
599
600             if (argc != 3)
601             {
602                 logf(LOG_FATAL, "charmap directive map requires 2 args");
603                 ++errors;
604             }
605             buf.map = res;
606             buf.string[0] = '\0';
607             if (scan_string(argv[2], t_unicode, t_utf8,
608                             fun_mkstring, &buf, 0) < 0)
609             {
610                 logf(LOG_FATAL, "Bad map target");
611                 ++errors;
612             }
613             if (scan_string(argv[1], t_unicode, t_utf8,
614                             fun_add_map, &buf, 0) < 0)
615             {
616                 logf(LOG_FATAL, "Bad map source");
617                 ++errors;
618             }
619         }
620         else if (!yaz_matchstr(argv[0], "qmap"))
621         {
622             chrwork buf;
623
624             if (argc != 3)
625             {
626                 logf(LOG_FATAL, "charmap directive qmap requires 2 args");
627                 ++errors;
628             }
629             buf.map = res;
630             buf.string[0] = '\0';
631             if (scan_string(argv[2], t_unicode, t_utf8, 
632                             fun_mkstring, &buf, 0) < 0)
633             {
634                 logf(LOG_FATAL, "Bad qmap target");
635                 ++errors;
636             }
637             if (scan_string(argv[1], t_unicode, t_utf8, 
638                             fun_add_qmap, &buf, 0) < 0)
639             {
640                 logf(LOG_FATAL, "Bad qmap source");
641                 ++errors;
642             }
643         }
644         else if (!yaz_matchstr(argv[0], "encoding"))
645         {
646             /*
647              * Fix me. When t_unicode==0 and use encoding directive in *.chr file the beheviour of the
648              * zebra need to comment next part of code.
649              */
650
651             /*
652             if (t_unicode != 0)
653                 yaz_iconv_close (t_unicode);
654             t_unicode = yaz_iconv_open (ucs4_native, argv[1]);
655             */
656             
657             /*
658              * Fix me. It is additional staff for conversion of characters from local encoding
659              * of *.chr file to UTF-8 (internal encoding).
660              * NOTE: The derective encoding must be first directive in *.chr file.
661              */
662             if (t_utf8 != 0)
663                 yaz_iconv_close(t_utf8);
664             t_utf8 = yaz_iconv_open ("UTF-8", argv[1]);
665         }
666         else
667         {
668             logf(LOG_WARN, "Syntax error at '%s' in %s", line, name);
669         }
670     
671     yaz_fclose(f);
672     if (errors)
673     {
674         chrmaptab_destroy(res);
675         res = 0;
676     }
677     logf (LOG_DEBUG, "maptab %s close %d errors", name, errors);
678     if (t_utf8 != 0)
679         yaz_iconv_close(t_utf8);
680     if (t_unicode != 0)
681         yaz_iconv_close(t_unicode);
682     return res;
683 }
684
685 void chrmaptab_destroy(chrmaptab tab)
686 {
687     if (tab)
688         nmem_destroy (tab->nmem);
689 }
690
691