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