Pavel Roskin <proski@gnu.org> just found a nasty memory
[oweals/busybox.git] / loadacm.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Derived from
4  * mapscrn.c - version 0.92
5  *
6  * Was taken from console-tools and adapted by 
7  * Peter Novodvorsky <petya@logic.ru>
8  */
9
10 #include "internal.h"
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <memory.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <fcntl.h>
17 #include <assert.h>
18 #include <errno.h>
19 #include <signal.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/ioctl.h>
23 #include <sys/kd.h>
24
25 static const char loadacm_usage[] = "loadacm\n"
26 #ifndef BB_FEATURE_TRIVIAL_HELP
27         "\nLoads an acm from standard input.\n"
28 #endif
29         ;
30
31 typedef unsigned short unicode;
32
33 static long int ctoi(unsigned char *s, int *is_unicode);
34 int old_screen_map_read_ascii(FILE * fp, unsigned char buf[]);
35 int uni_screen_map_read_ascii(FILE * fp, unicode buf[], int *is_unicode);
36 unicode utf8_to_ucs2(char *buf);
37 int screen_map_load(int fd, FILE * fp);
38
39 int loadacm_main(int argc, char **argv)
40 {
41         int fd;
42
43         if (argc>=2 && *argv[1]=='-') {
44                 usage(loadacm_usage);
45         }
46
47         fd = open("/dev/tty", O_RDWR);
48         if (fd < 0) {
49                 fprintf(stderr, "Error opening /dev/tty1: %s\n", strerror(errno));
50                 return( FALSE);
51         }
52
53         if (screen_map_load(fd, stdin)) {
54                 fprintf(stderr, "Error loading acm: %s\n", strerror(errno));
55                 return( FALSE);
56         }
57
58         write(fd, "\033(K", 3);
59
60         return( TRUE);
61 }
62
63 int screen_map_load(int fd, FILE * fp)
64 {
65         struct stat stbuf;
66         unicode wbuf[E_TABSZ];
67         unsigned char buf[E_TABSZ];
68         int parse_failed = 0;
69         int is_unicode;
70
71         if (fstat(fp->_fileno, &stbuf))
72                 perror("Cannot stat map file"), exit(1);
73
74         /* first try a UTF screen-map: either ASCII (no restriction) or binary (regular file) */
75         if (!
76                 (parse_failed =
77                  (-1 == uni_screen_map_read_ascii(fp, wbuf, &is_unicode)))
78 || (S_ISREG(stbuf.st_mode) && (stbuf.st_size == (sizeof(unicode) * E_TABSZ)))) {        /* test for binary UTF map by size */
79                 if (parse_failed) {
80                         if (-1 == fseek(fp, 0, SEEK_SET)) {
81                                 if (errno == ESPIPE)
82                                         fprintf(stderr,
83                                                         "16bit screen-map MUST be a regular file.\n"),
84                                                 exit(1);
85                                 else
86                                         perror("fseek failed reading binary 16bit screen-map"),
87                                                 exit(1);
88                         }
89
90                         if (fread(wbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1)
91                                 perror("Cannot read [new] map from file"), exit(1);
92 #if 0
93                         else
94                                 fprintf(stderr, "Input screen-map is binary.\n");
95 #endif
96                 }
97
98                 /* if it was effectively a 16-bit ASCII, OK, else try to read as 8-bit map */
99                 /* same if it was binary, ie. if parse_failed */
100                 if (parse_failed || is_unicode) {
101                         if (ioctl(fd, PIO_UNISCRNMAP, wbuf))
102                                 perror("PIO_UNISCRNMAP ioctl"), exit(1);
103                         else
104                                 return 0;
105                 }
106         }
107
108         /* rewind... */
109         if (-1 == fseek(fp, 0, SEEK_SET)) {
110                 if (errno == ESPIPE)
111                         fprintf(stderr,
112                                         "Assuming 8bit screen-map - MUST be a regular file.\n"),
113                                 exit(1);
114                 else
115                         perror("fseek failed assuming 8bit screen-map"), exit(1);
116         }
117
118         /* ... and try an old 8-bit screen-map */
119         if (!(parse_failed = (-1 == old_screen_map_read_ascii(fp, buf))) ||
120                 (S_ISREG(stbuf.st_mode) && (stbuf.st_size == E_TABSZ))) {       /* test for binary old 8-bit map by size */
121                 if (parse_failed) {
122                         if (-1 == fseek(fp, 0, SEEK_SET)) {
123                                 if (errno == ESPIPE)
124                                         /* should not - it succedeed above */
125                                         fprintf(stderr, "fseek() returned ESPIPE !\n"),
126                                                 exit(1);
127                                 else
128                                         perror("fseek for binary 8bit screen-map"), exit(1);
129                         }
130
131                         if (fread(buf, E_TABSZ, 1, fp) != 1)
132                                 perror("Cannot read [old] map from file"), exit(1);
133 #if 0
134                         else
135                                 fprintf(stderr, "Input screen-map is binary.\n");
136 #endif
137                 }
138
139                 if (ioctl(fd, PIO_SCRNMAP, buf))
140                         perror("PIO_SCRNMAP ioctl"), exit(1);
141                 else
142                         return 0;
143         }
144         fprintf(stderr, "Error parsing symbolic map\n");
145         return(1);
146 }
147
148
149 /*
150  * - reads `fp' as a 16-bit ASCII SFM file.
151  * - returns -1 on error.
152  * - returns it in `unicode' in an E_TABSZ-elements array.
153  * - sets `*is_unicode' flagiff there were any non-8-bit
154  *   (ie. real 16-bit) mapping.
155  *
156  * FIXME: ignores everything after second word
157  */
158 int uni_screen_map_read_ascii(FILE * fp, unicode buf[], int *is_unicode)
159 {
160         char buffer[256];                       /* line buffer reading file */
161         char *p, *q;                            /* 1st + 2nd words in line */
162         int in, on;                                     /* the same, as numbers */
163         int tmp_is_unicode;                     /* tmp for is_unicode calculation */
164         int i;                                          /* loop index - result holder */
165         int ret_code = 0;                       /* return code */
166         sigset_t sigset, old_sigset;
167
168         assert(is_unicode);
169
170         *is_unicode = 0;
171
172         /* first 128 codes defaults to ASCII */
173         for (i = 0; i < 128; i++)
174                 buf[i] = i;
175         /* remaining defaults to replacement char (usually E_TABSZ = 256) */
176         for (; i < E_TABSZ; i++)
177                 buf[i] = 0xfffd;
178
179         /* block SIGCHLD */
180         sigemptyset(&sigset);
181         sigaddset(&sigset, SIGCHLD);
182         sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
183
184         do {
185                 if (NULL == fgets(buffer, sizeof(buffer), fp)) {
186                         if (feof(fp))
187                                 break;
188                         else {
189                                 perror("uni_screen_map_read_ascii() can't read line");
190                                 exit(2);
191                         }
192                 }
193
194                 /* get "charset-relative charcode", stripping leading spaces */
195                 p = strtok(buffer, " \t\n");
196
197                 /* skip empty lines and comments */
198                 if (!p || *p == '#')
199                         continue;
200
201                 /* get unicode mapping */
202                 q = strtok(NULL, " \t\n");
203                 if (q) {
204                         in = ctoi(p, NULL);
205                         if (in < 0 || in > 255) {
206                                 ret_code = -1;
207                                 break;
208                         }
209
210                         on = ctoi(q, &tmp_is_unicode);
211                         if (in < 0 && on > 65535) {
212                                 ret_code = -1;
213                                 break;
214                         }
215
216                         *is_unicode |= tmp_is_unicode;
217                         buf[in] = on;
218                 } else {
219                         ret_code = -1;
220                         break;
221                 }
222         }
223         while (1);                                      /* terminated by break on feof() */
224
225         /* restore sig mask */
226         sigprocmask(SIG_SETMASK, &old_sigset, NULL);
227
228         return ret_code;
229 }
230
231
232 int old_screen_map_read_ascii(FILE * fp, unsigned char buf[])
233 {
234         char buffer[256];
235         int in, on;
236         char *p, *q;
237
238         for (in = 0; in < 256; in++)
239                 buf[in] = in;
240
241         while (fgets(buffer, sizeof(buffer) - 1, fp)) {
242                 p = strtok(buffer, " \t\n");
243
244                 if (!p || *p == '#')
245                         continue;
246
247                 q = strtok(NULL, " \t\n#");
248                 if (q) {
249                         in = ctoi(p, NULL);
250                         if (in < 0 || in > 255)
251                                 return -1;
252
253                         on = ctoi(q, NULL);
254                         if (in < 0 && on > 255)
255                                 return -1;
256
257                         buf[in] = on;
258                 } else
259                         return -1;
260         }
261
262         return (0);
263 }
264
265
266 /*
267  * - converts a string into an int.
268  * - supports dec and hex bytes, hex UCS2, single-quoted byte and UTF8 chars.
269  * - returns the converted value
270  * - if `is_unicode != NULL', use it to tell whether it was unicode
271  *
272  * CAVEAT: will report valid UTF mappings using only 1 byte as 8-bit ones.
273  */
274 long int ctoi(unsigned char *s, int *is_unicode)
275 {
276         int i;
277         size_t ls;
278
279         ls = strlen(s);
280         if (is_unicode)
281                 *is_unicode = 0;
282
283         /* hex-specified UCS2 */
284         if ((strncmp(s, "U+", 2) == 0) &&
285                 (strspn(s + 2, "0123456789abcdefABCDEF") == ls - 2)) {
286                 sscanf(s + 2, "%x", &i);
287                 if (is_unicode)
288                         *is_unicode = 1;
289         }
290
291         /* hex-specified byte */
292         else if ((ls <= 4) && (strncmp(s, "0x", 2) == 0) &&
293                          (strspn(s + 2, "0123456789abcdefABCDEF") == ls - 2))
294                 sscanf(s + 2, "%x", &i);
295
296         /* oct-specified number (byte) */
297         else if ((*s == '0') && (strspn(s, "01234567") == ls))
298                 sscanf(s, "%o", &i);
299
300         /* dec-specified number (byte) */
301         else if (strspn(s, "0123456789") == ls)
302                 sscanf(s, "%d", &i);
303
304         /* single-byte quoted char */
305         else if ((strlen(s) == 3) && (s[0] == '\'') && (s[2] == '\''))
306                 i = s[1];
307
308         /* multi-byte UTF8 quoted char */
309         else if ((s[0] == '\'') && (s[ls - 1] == '\'')) {
310                 s[ls - 1] = 0;                  /* ensure we'll not "parse UTF too far" */
311                 i = utf8_to_ucs2(s + 1);
312                 if (is_unicode)
313                         *is_unicode = 1;
314         } else
315                 return (-1);
316
317         return (i);
318 }
319
320
321 void saveoldmap(int fd, char *omfil)
322 {
323         FILE *fp;
324         char buf[E_TABSZ];
325
326 #ifdef GIO_UNISCRNMAP
327         unicode xbuf[E_TABSZ];
328         int is_old_map = 0;
329
330         if (ioctl(fd, GIO_UNISCRNMAP, xbuf)) {
331                 perror("GIO_UNISCRNMAP ioctl error");
332 #endif
333                 if (ioctl(fd, GIO_SCRNMAP, buf)) {
334                         perror("GIO_SCRNMAP ioctl error");
335                         exit(1);
336                 } else
337                         is_old_map = 1;
338 #ifdef GIO_UNISCRNMAP
339         }
340 #endif
341
342         if ((fp = fopen(omfil, "w")) == NULL) {
343                 perror(omfil);
344                 exit(1);
345         }
346 #ifdef GIO_UNISCRNMAP
347         if (is_old_map) {
348 #endif
349                 if (fwrite(buf, E_TABSZ, 1, fp) != 1) {
350                         perror("Error writing map to file");
351                         exit(1);
352                 }
353 #ifdef GIO_UNISCRNMAP
354         } else if (fwrite(xbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1) {
355                 perror("Error writing map to file");
356                 exit(1);
357         }
358 #endif
359
360         fclose(fp);
361 }
362
363 unicode utf8_to_ucs2(char *buf)
364 {
365         int utf_count = 0;
366         long utf_char = 0;
367         unicode tc = 0;
368         unsigned char c;
369
370         do {
371                 c = *buf;
372                 buf++;
373
374                 /* if byte should be part of multi-byte sequence */
375                 if (c & 0x80) {
376                         /* if we have already started to parse a UTF8 sequence */
377                         if (utf_count > 0 && (c & 0xc0) == 0x80) {
378                                 utf_char = (utf_char << 6) | (c & 0x3f);
379                                 utf_count--;
380                                 if (utf_count == 0)
381                                         tc = utf_char;
382                                 else
383                                         continue;
384                         } else {                        /* Possibly 1st char of a UTF8 sequence */
385
386                                 if ((c & 0xe0) == 0xc0) {
387                                         utf_count = 1;
388                                         utf_char = (c & 0x1f);
389                                 } else if ((c & 0xf0) == 0xe0) {
390                                         utf_count = 2;
391                                         utf_char = (c & 0x0f);
392                                 } else if ((c & 0xf8) == 0xf0) {
393                                         utf_count = 3;
394                                         utf_char = (c & 0x07);
395                                 } else if ((c & 0xfc) == 0xf8) {
396                                         utf_count = 4;
397                                         utf_char = (c & 0x03);
398                                 } else if ((c & 0xfe) == 0xfc) {
399                                         utf_count = 5;
400                                         utf_char = (c & 0x01);
401                                 } else
402                                         utf_count = 0;
403                                 continue;
404                         }
405                 } else {                                /* not part of multi-byte sequence - treat as ASCII
406                                                                    * this makes incomplete sequences to be ignored
407                                                                  */
408                         tc = c;
409                         utf_count = 0;
410                 }
411         }
412         while (utf_count);
413
414         return tc;
415 }