Fixed problem with 'encoding' directive for .chr files. Added \LXXXX
[idzebra-moved-to-github.git] / util / charmap.c
1 /* $Id: charmap.c,v 1.28 2004-03-09 15:12:15 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
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 static int zebra_ucs4_strlen(ucs4_t *s)
248 {
249     int i = 0;
250     while (*s++)
251         i++;
252     return i;
253 }
254
255 ucs4_t zebra_prim_w(ucs4_t **s)
256 {
257     ucs4_t c;
258     ucs4_t i = 0;
259     char fmtstr[8];
260
261     yaz_log (LOG_DEBUG, "prim %.3s", (char *) *s);
262     if (**s == '\\')
263     {
264         (*s)++;
265         c = **s;
266         switch (c)
267         {
268         case '\\': c = '\\'; (*s)++; break;
269         case 'r': c = '\r'; (*s)++; break;
270         case 'n': c = '\n'; (*s)++; break;
271         case 't': c = '\t'; (*s)++; break;
272         case 's': c = ' '; (*s)++; break;
273         case 'x': 
274             if (zebra_ucs4_strlen(*s) >= 3)
275             {
276                 fmtstr[0] = (*s)[1];
277                 fmtstr[1] = (*s)[2];
278                 fmtstr[2] = 0;
279                 sscanf(fmtstr, "%x", &i);
280                 c = i;
281                 *s += 3;
282             }
283             break;
284         case '0':
285         case '1':
286         case '2':
287         case '3':
288         case '4':
289         case '5':
290         case '6':
291         case '7':
292         case '8':
293         case '9':
294             if (zebra_ucs4_strlen(*s) >= 3)
295             {
296                 fmtstr[0] = (*s)[0];
297                 fmtstr[1] = (*s)[1];
298                 fmtstr[2] = (*s)[2];
299                 fmtstr[3] = 0;
300                 sscanf(fmtstr, "%o", &i);
301                 c = i;
302                 *s += 3;
303             }
304             break;
305         case 'L':
306             if (zebra_ucs4_strlen(*s) >= 5)
307             {
308                 fmtstr[0] = (*s)[1];
309                 fmtstr[1] = (*s)[2];
310                 fmtstr[2] = (*s)[3];
311                 fmtstr[3] = (*s)[4];
312                 fmtstr[4] = 0;
313                 sscanf(fmtstr, "%x", &i);
314                 c = i;
315                 *s += 5;
316             }
317             break;
318         default:
319             (*s)++;
320         }
321     }
322     else
323     {
324         c = **s;
325         ++(*s);
326     }
327     yaz_log (LOG_DEBUG, "out %d", c);
328     return c;
329 }
330
331 /*
332  * Callback function.
333  * Add an entry to the value space.
334  */
335 static void fun_addentry(const char *s, void *data, int num)
336 {
337     chrmaptab tab = (chrmaptab) data;
338     char tmp[2];
339     
340     tmp[0] = num; tmp[1] = '\0';
341     tab->input = set_map_string(tab->input, tab->nmem, s, strlen(s), tmp, 0);
342     tab->output[num + tab->base_uppercase] =
343         (unsigned char *) nmem_strdup(tab->nmem, s);
344 }
345
346 /* 
347  * Callback function.
348  * Add a space-entry to the value space.
349  */
350 static void fun_addspace(const char *s, void *data, int num)
351 {
352     chrmaptab tab = (chrmaptab) data;
353     tab->input = set_map_string(tab->input, tab->nmem, s, strlen(s),
354                                 (char*) CHR_SPACE, 0);
355 }
356
357 /*
358  * Create a string containing the mapped characters provided.
359  */
360 static void fun_mkstring(const char *s, void *data, int num)
361 {
362     chrwork *arg = (chrwork *) data;
363     const char **res, *p = s;
364
365     res = chr_map_input(arg->map, &s, strlen(s));
366     if (*res == (char*) CHR_UNKNOWN)
367         logf(LOG_WARN, "Map: '%s' has no mapping", p);
368     strncat(arg->string, *res, CHR_MAXSTR - strlen(arg->string));
369     arg->string[CHR_MAXSTR] = '\0';
370 }
371
372 /*
373  * Add a map to the string contained in the argument.
374  */
375 static void fun_add_map(const char *s, void *data, int num)
376 {
377     chrwork *arg = (chrwork *) data;
378
379     assert(arg->map->input);
380     logf (LOG_DEBUG, "set map %.*s", (int) strlen(s), s);
381     set_map_string(arg->map->input, arg->map->nmem, s, strlen(s), arg->string,
382                    0);
383     for (s = arg->string; *s; s++)
384         logf (LOG_DEBUG, " %3d", (unsigned char) *s);
385 }
386
387 /*
388  * Add a query map to the string contained in the argument.
389  */
390 static void fun_add_qmap(const char *s, void *data, int num)
391 {
392     chrwork *arg = (chrwork *) data;
393
394     assert(arg->map->q_input);
395     logf (LOG_DEBUG, "set qmap %.*s", (int) strlen(s), s);
396     set_map_string(arg->map->q_input, arg->map->nmem, s,
397                    strlen(s), arg->string, 0);
398     for (s = arg->string; *s; s++)
399         logf (LOG_DEBUG, " %3d", (unsigned char) *s);
400 }
401
402 static int scan_to_utf8 (yaz_iconv_t t, ucs4_t *from, size_t inlen,
403                         char *outbuf, size_t outbytesleft)
404 {
405     size_t inbytesleft = inlen * sizeof(ucs4_t);
406     char *inbuf = (char*) from;
407     size_t ret;
408    
409     if (t == 0)
410         *outbuf++ = *from;  /* ISO-8859-1 is OK here */
411     else
412     {
413         ret = yaz_iconv (t, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
414         if (ret == (size_t) (-1))
415         {
416             yaz_log(LOG_LOG, "from: %2X %2X %2X %2X",
417                     from[0], from[1], from[2], from[3]);
418             yaz_log (LOG_WARN|LOG_ERRNO, "bad unicode sequence");
419             return -1;
420         }
421     }
422     *outbuf = '\0';
423     return 0;
424 }
425
426 static int scan_string(char *s_native,
427                        yaz_iconv_t t_unicode, yaz_iconv_t t_utf8,
428                        void (*fun)(const char *c, void *data, int num),
429                        void *data, int *num)
430 {
431     char str[1024];
432
433     ucs4_t arg[512];
434     ucs4_t *s0, *s = arg;
435     ucs4_t c, begin, end;
436     size_t i;
437
438     if (t_unicode != 0)
439     {
440         char *outbuf = (char *) arg;
441         char *inbuf = s_native;
442         size_t outbytesleft = sizeof(arg)-4;
443         size_t inbytesleft = strlen(s_native);
444         size_t ret;             
445         ret = yaz_iconv(t_unicode, &inbuf, &inbytesleft,
446                         &outbuf, &outbytesleft);
447         if (ret == (size_t)(-1))
448             return -1;
449         i = (outbuf - (char*) arg)/sizeof(ucs4_t);
450     }
451     else
452     { 
453         for (i = 0; s_native[i]; i++)
454             arg[i] = s_native[i] & 255; /* ISO-8859-1 conversion */
455     }
456     arg[i] = 0;      /* terminate */
457     if (s[0] == 0xfeff || s[0] == 0xfeff)  /* skip byte Order Mark */
458         s++;
459     while (*s)
460     {
461         switch (*s)
462         {
463         case '{':
464             s++;
465             begin = zebra_prim_w(&s);
466             if (*s != '-')
467             {
468                 logf(LOG_FATAL, "Bad range in char-map");
469                 return -1;
470             }
471             s++;
472             end = zebra_prim_w(&s);
473             if (end <= begin)
474             {
475                 logf(LOG_FATAL, "Bad range in char-map");
476                 return -1;
477             }
478             s++;
479             for (c = begin; c <= end; c++)
480             {
481                 if (scan_to_utf8 (t_utf8, &c, 1, str, sizeof(str)-1))
482                     return -1;
483                 (*fun)(str, data, num ? (*num)++ : 0);
484             }
485             break;
486         case '[': s++; abort(); break;
487         case '(':
488             ++s;
489             s0 = s;
490             while (*s != ')' || s[-1] == '\\')
491                 s++;
492             *s = 0;
493             if (scan_to_utf8 (t_utf8, s0, s - s0, str, sizeof(str)-1))
494                 return -1;
495             (*fun)(str, data, num ? (*num)++ : 0);
496             s++;
497             break;
498         default:
499             c = zebra_prim_w(&s);
500             if (scan_to_utf8 (t_utf8, &c, 1, str, sizeof(str)-1))
501                 return -1;
502             (*fun)(str, data, num ? (*num)++ : 0);
503         }
504     }
505     return 0;
506 }
507
508 chrmaptab chrmaptab_create(const char *tabpath, const char *name, int map_only,
509                            const char *tabroot)
510 {
511     FILE *f;
512     char line[512], *argv[50];
513     chrmaptab res;
514     int lineno = 0;
515     int errors = 0;
516     int argc, num = (int) *CHR_BASE, i;
517     NMEM nmem;
518     yaz_iconv_t t_unicode = 0;
519     yaz_iconv_t t_utf8 = 0;
520     unsigned endian = 31;
521     const char *ucs4_native = "UCS-4";
522
523     if (*(char*) &endian == 31)      /* little endian? */
524         ucs4_native = "UCS-4LE";
525
526     t_utf8 = yaz_iconv_open ("UTF-8", ucs4_native);
527
528     logf (LOG_DEBUG, "maptab %s open", name);
529     if (!(f = yaz_fopen(tabpath, name, "r", tabroot)))
530     {
531         logf(LOG_WARN|LOG_ERRNO, "%s", name);
532         return 0;
533     }
534     nmem = nmem_create ();
535     res = (chrmaptab) nmem_malloc(nmem, sizeof(*res));
536     res->nmem = nmem;
537     res->input = (chr_t_entry *) nmem_malloc(res->nmem, sizeof(*res->input));
538     res->input->target = (unsigned char **)
539         nmem_malloc(res->nmem, sizeof(*res->input->target) * 2);
540     res->input->target[0] = (unsigned char*) CHR_UNKNOWN;
541     res->input->target[1] = 0;
542     res->input->children = (chr_t_entry **)
543         nmem_malloc(res->nmem, sizeof(res->input) * 256);
544     for (i = 0; i < 256; i++)
545     {
546         res->input->children[i] = (chr_t_entry *)
547             nmem_malloc(res->nmem, sizeof(*res->input));
548         res->input->children[i]->children = 0;
549         res->input->children[i]->target = (unsigned char **)
550             nmem_malloc (res->nmem, 2 * sizeof(unsigned char *));
551         res->input->children[i]->target[1] = 0;
552         if (map_only)
553         {
554             res->input->children[i]->target[0] = (unsigned char *)
555                 nmem_malloc (res->nmem, 2 * sizeof(unsigned char));
556             res->input->children[i]->target[0][0] = i;
557             res->input->children[i]->target[0][1] = 0;
558         }
559         else
560             res->input->children[i]->target[0] = (unsigned char*) CHR_UNKNOWN;
561     }
562     res->q_input = (chr_t_entry *)
563         nmem_malloc(res->nmem, sizeof(*res->q_input));
564     res->q_input->target = 0;
565     res->q_input->children = 0;
566
567     for (i = *CHR_BASE; i < 256; i++)
568         res->output[i] = 0;
569     res->output[(int) *CHR_SPACE] = (unsigned char *) " ";
570     res->output[(int) *CHR_UNKNOWN] = (unsigned char*) "@";
571     res->base_uppercase = 0;
572
573     while (!errors && (argc = readconf_line(f, &lineno, line, 512, argv, 50)))
574         if (!map_only && !yaz_matchstr(argv[0], "lowercase"))
575         {
576             if (argc != 2)
577             {
578                 logf(LOG_FATAL, "Syntax error in charmap");
579                 ++errors;
580             }
581             if (scan_string(argv[1], t_unicode, t_utf8, fun_addentry,
582                             res, &num) < 0)
583             {
584                 logf(LOG_FATAL, "Bad value-set specification");
585                 ++errors;
586             }
587             res->base_uppercase = num;
588             res->output[(int) *CHR_SPACE + num] = (unsigned char *) " ";
589             res->output[(int) *CHR_UNKNOWN + num] = (unsigned char*) "@";
590             num = (int) *CHR_BASE;
591         }
592         else if (!map_only && !yaz_matchstr(argv[0], "uppercase"))
593         {
594             if (!res->base_uppercase)
595             {
596                 logf(LOG_FATAL, "Uppercase directive with no lowercase set");
597                 ++errors;
598             }
599             if (argc != 2)
600             {
601                 logf(LOG_FATAL, "Missing arg for uppercase directive");
602                 ++errors;
603             }
604             if (scan_string(argv[1], t_unicode, t_utf8, fun_addentry,
605                             res, &num) < 0)
606             {
607                 logf(LOG_FATAL, "Bad value-set specification");
608                 ++errors;
609             }
610         }
611         else if (!map_only && !yaz_matchstr(argv[0], "space"))
612         {
613             if (argc != 2)
614             {
615                 logf(LOG_FATAL, "Syntax error in charmap");
616                 ++errors;
617             }
618             if (scan_string(argv[1], t_unicode, t_utf8,
619                             fun_addspace, res, 0) < 0)
620             {
621                 logf(LOG_FATAL, "Bad space specification");
622                 ++errors;
623             }
624         }
625         else if (!yaz_matchstr(argv[0], "map"))
626         {
627             chrwork buf;
628
629             if (argc != 3)
630             {
631                 logf(LOG_FATAL, "charmap directive map requires 2 args");
632                 ++errors;
633             }
634             buf.map = res;
635             buf.string[0] = '\0';
636             if (scan_string(argv[2], t_unicode, t_utf8,
637                             fun_mkstring, &buf, 0) < 0)
638             {
639                 logf(LOG_FATAL, "Bad map target");
640                 ++errors;
641             }
642             if (scan_string(argv[1], t_unicode, t_utf8,
643                             fun_add_map, &buf, 0) < 0)
644             {
645                 logf(LOG_FATAL, "Bad map source");
646                 ++errors;
647             }
648         }
649         else if (!yaz_matchstr(argv[0], "qmap"))
650         {
651             chrwork buf;
652
653             if (argc != 3)
654             {
655                 logf(LOG_FATAL, "charmap directive qmap requires 2 args");
656                 ++errors;
657             }
658             buf.map = res;
659             buf.string[0] = '\0';
660             if (scan_string(argv[2], t_unicode, t_utf8, 
661                             fun_mkstring, &buf, 0) < 0)
662             {
663                 logf(LOG_FATAL, "Bad qmap target");
664                 ++errors;
665             }
666             if (scan_string(argv[1], t_unicode, t_utf8, 
667                             fun_add_qmap, &buf, 0) < 0)
668             {
669                 logf(LOG_FATAL, "Bad qmap source");
670                 ++errors;
671             }
672         }
673         else if (!yaz_matchstr(argv[0], "encoding"))
674         {
675             /*
676              * Fix me. When t_unicode==0 and use encoding directive in *.chr file the beheviour of the
677              * zebra need to comment next part of code.
678              */
679
680             /* Original code */
681 #if 1
682             if (t_unicode != 0)
683                 yaz_iconv_close (t_unicode);
684             t_unicode = yaz_iconv_open (ucs4_native, argv[1]);
685 #endif
686             /*
687              * Fix me. It is additional staff for conversion of characters from local encoding
688              * of *.chr file to UTF-8 (internal encoding).
689              * NOTE: The derective encoding must be first directive in *.chr file.
690              */
691             /* For whatever reason Oleg enabled this.. */
692 #if 0
693             if (t_utf8 != 0)
694                 yaz_iconv_close(t_utf8);
695             t_utf8 = yaz_iconv_open ("UTF-8", argv[1]);
696 #endif
697         }
698         else
699         {
700             logf(LOG_WARN, "Syntax error at '%s' in %s", line, name);
701         }
702     
703     yaz_fclose(f);
704     if (errors)
705     {
706         chrmaptab_destroy(res);
707         res = 0;
708     }
709     logf (LOG_DEBUG, "maptab %s close %d errors", name, errors);
710     if (t_utf8 != 0)
711         yaz_iconv_close(t_utf8);
712     if (t_unicode != 0)
713         yaz_iconv_close(t_unicode);
714     return res;
715 }
716
717 void chrmaptab_destroy(chrmaptab tab)
718 {
719     if (tab)
720         nmem_destroy (tab->nmem);
721 }
722
723