tar: store negative mtime as 0; pack very large files using base-256 encoding
[oweals/busybox.git] / console-tools / loadfont.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * loadfont.c - Eugene Crosser & Andries Brouwer
4  *
5  * Version 0.96bb
6  *
7  * Loads the console font, and possibly the corresponding screen map(s).
8  * (Adapted for busybox by Matej Vela.)
9  *
10  * Licensed under GPLv2, see file LICENSE in this source tree.
11  */
12
13 //usage:#define loadfont_trivial_usage
14 //usage:       "< font"
15 //usage:#define loadfont_full_usage "\n\n"
16 //usage:       "Load a console font from stdin"
17 /* //usage:     "\n     -C TTY  Affect TTY instead of /dev/tty" */
18 //usage:
19 //usage:#define loadfont_example_usage
20 //usage:       "$ loadfont < /etc/i18n/fontname\n"
21 //usage:
22 //usage:#define setfont_trivial_usage
23 //usage:       "FONT [-m MAPFILE] [-C TTY]"
24 //usage:#define setfont_full_usage "\n\n"
25 //usage:       "Load a console font\n"
26 //usage:     "\nOptions:"
27 //usage:     "\n        -m MAPFILE      Load console screen map"
28 //usage:     "\n        -C TTY          Affect TTY instead of /dev/tty"
29 //usage:
30 //usage:#define setfont_example_usage
31 //usage:       "$ setfont -m koi8-r /etc/i18n/fontname\n"
32
33 #include "libbb.h"
34 #include <sys/kd.h>
35
36 #ifndef KDFONTOP
37 # define KDFONTOP 0x4B72
38 struct console_font_op {
39         unsigned op;            /* KD_FONT_OP_* */
40         unsigned flags;         /* KD_FONT_FLAG_* */
41         unsigned width, height;
42         unsigned charcount;
43         unsigned char *data;    /* font data with height fixed to 32 */
44 };
45 # define KD_FONT_OP_SET          0  /* Set font */
46 # define KD_FONT_OP_GET          1  /* Get font */
47 # define KD_FONT_OP_SET_DEFAULT  2  /* Set font to default, data points to name / NULL */
48 # define KD_FONT_OP_COPY         3  /* Copy from another console */
49 # define KD_FONT_FLAG_OLD        0x80000000 /* Invoked via old interface */
50 # define KD_FONT_FLAG_DONT_RECALC 1 /* Don't call adjust_height() */
51                                    /* (Used internally for PIO_FONT support) */
52 #endif /* KDFONTOP */
53
54
55 enum {
56         PSF1_MAGIC0 = 0x36,
57         PSF1_MAGIC1 = 0x04,
58         PSF1_MODE512 = 0x01,
59         PSF1_MODEHASTAB = 0x02,
60         PSF1_MODEHASSEQ = 0x04,
61         PSF1_MAXMODE = 0x05,
62         PSF1_STARTSEQ = 0xfffe,
63         PSF1_SEPARATOR = 0xffff,
64 };
65
66 struct psf1_header {
67         unsigned char magic[2];         /* Magic number */
68         unsigned char mode;             /* PSF font mode */
69         unsigned char charsize;         /* Character size */
70 };
71
72 #define psf1h(x) ((struct psf1_header*)(x))
73
74 #define PSF1_MAGIC_OK(x) ( \
75      (x)->magic[0] == PSF1_MAGIC0 \
76   && (x)->magic[1] == PSF1_MAGIC1 \
77 )
78
79 #if ENABLE_FEATURE_LOADFONT_PSF2
80 enum {
81         PSF2_MAGIC0 = 0x72,
82         PSF2_MAGIC1 = 0xb5,
83         PSF2_MAGIC2 = 0x4a,
84         PSF2_MAGIC3 = 0x86,
85         PSF2_HAS_UNICODE_TABLE = 0x01,
86         PSF2_MAXVERSION = 0,
87         PSF2_STARTSEQ = 0xfe,
88         PSF2_SEPARATOR = 0xff
89 };
90
91 struct psf2_header {
92         unsigned char magic[4];
93         unsigned int version;
94         unsigned int headersize;    /* offset of bitmaps in file */
95         unsigned int flags;
96         unsigned int length;        /* number of glyphs */
97         unsigned int charsize;      /* number of bytes for each character */
98         unsigned int height;        /* max dimensions of glyphs */
99         unsigned int width;         /* charsize = height * ((width + 7) / 8) */
100 };
101
102 #define psf2h(x) ((struct psf2_header*)(x))
103
104 #define PSF2_MAGIC_OK(x) ( \
105      (x)->magic[0] == PSF2_MAGIC0 \
106   && (x)->magic[1] == PSF2_MAGIC1 \
107   && (x)->magic[2] == PSF2_MAGIC2 \
108   && (x)->magic[3] == PSF2_MAGIC3 \
109 )
110 #endif /* ENABLE_FEATURE_LOADFONT_PSF2 */
111
112
113 static void do_loadfont(int fd, unsigned char *inbuf, int height, int width, int charsize, int fontsize)
114 {
115         unsigned char *buf;
116         int charwidth = 32 * ((width+7)/8);
117         int i;
118
119         if (height < 1 || height > 32 || width < 1 || width > 32)
120                 bb_error_msg_and_die("bad character size %dx%d", height, width);
121
122         buf = xzalloc(charwidth * ((fontsize < 128) ? 128 : fontsize));
123         for (i = 0; i < fontsize; i++)
124                 memcpy(buf + (i*charwidth), inbuf + (i*charsize), charsize);
125
126         { /* KDFONTOP */
127                 struct console_font_op cfo;
128                 cfo.op = KD_FONT_OP_SET;
129                 cfo.flags = 0;
130                 cfo.width = width;
131                 cfo.height = height;
132                 cfo.charcount = fontsize;
133                 cfo.data = buf;
134                 xioctl(fd, KDFONTOP, &cfo);
135         }
136
137         free(buf);
138 }
139
140 /*
141  * Format of the Unicode information:
142  *
143  * For each font position <uc>*<seq>*<term>
144  * where <uc> is a 2-byte little endian Unicode value (PSF1)
145  * or an UTF-8 coded value (PSF2),
146  * <seq> = <ss><uc><uc>*, <ss> = psf1 ? 0xFFFE : 0xFE,
147  * <term> = psf1 ? 0xFFFF : 0xFF.
148  * and * denotes zero or more occurrences of the preceding item.
149  *
150  * Semantics:
151  * The leading <uc>* part gives Unicode symbols that are all
152  * represented by this font position. The following sequences
153  * are sequences of Unicode symbols - probably a symbol
154  * together with combining accents - also represented by
155  * this font position.
156  *
157  * Example:
158  * At the font position for a capital A-ring glyph, we
159  * may have:
160  *   00C5,212B,FFFE,0041,030A,FFFF
161  * Some font positions may be described by sequences only,
162  * namely when there is no precomposed Unicode value for the glyph.
163  */
164 #if !ENABLE_FEATURE_LOADFONT_PSF2
165 #define do_loadtable(fd, inbuf, tailsz, fontsize, psf2) \
166         do_loadtable(fd, inbuf, tailsz, fontsize)
167 #endif
168 static void do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize, int psf2)
169 {
170 #if !ENABLE_FEATURE_LOADFONT_PSF2
171 /* gcc 4.3.1 code size: */
172 # define psf2 0 /* +0 bytes */
173 //      const int psf2 = 0; /* +8 bytes */
174 //      enum { psf2 = 0 }; /* +13 bytes */
175 #endif
176         struct unimapinit advice;
177         struct unimapdesc ud;
178         struct unipair *up;
179         int ct = 0, maxct;
180         int glyph;
181         uint16_t unicode;
182
183         maxct = tailsz; /* more than enough */
184         up = xmalloc(maxct * sizeof(*up));
185
186         for (glyph = 0; glyph < fontsize; glyph++) {
187                 while (tailsz > 0) {
188                         if (!psf2) { /* PSF1 */
189                                 unicode = (((uint16_t) inbuf[1]) << 8) + inbuf[0];
190                                 tailsz -= 2;
191                                 inbuf += 2;
192                                 if (unicode == PSF1_SEPARATOR)
193                                         break;
194                         } else { /* PSF2 */
195 #if ENABLE_FEATURE_LOADFONT_PSF2
196                                 --tailsz;
197                                 unicode = *inbuf++;
198                                 if (unicode == PSF2_SEPARATOR) {
199                                         break;
200                                 } else if (unicode == PSF2_STARTSEQ) {
201                                         bb_error_msg_and_die("unicode sequences not implemented");
202                                 } else if (unicode >= 0xC0) {
203                                         if (unicode >= 0xFC)
204                                                 unicode &= 0x01, maxct = 5;
205                                         else if (unicode >= 0xF8)
206                                                 unicode &= 0x03, maxct = 4;
207                                         else if (unicode >= 0xF0)
208                                                 unicode &= 0x07, maxct = 3;
209                                         else if (unicode >= 0xE0)
210                                                 unicode &= 0x0F, maxct = 2;
211                                         else
212                                                 unicode &= 0x1F, maxct = 1;
213                                         do {
214                                                 if (tailsz <= 0 || *inbuf < 0x80 || *inbuf > 0xBF)
215                                                         bb_error_msg_and_die("illegal UTF-8 character");
216                                                 --tailsz;
217                                                 unicode = (unicode << 6) + (*inbuf++ & 0x3F);
218                                         } while (--maxct > 0);
219                                 } else if (unicode >= 0x80) {
220                                         bb_error_msg_and_die("illegal UTF-8 character");
221                                 }
222 #else
223                                 return;
224 #endif
225                         }
226                         up[ct].unicode = unicode;
227                         up[ct].fontpos = glyph;
228                         ct++;
229                 }
230         }
231
232         /* Note: after PIO_UNIMAPCLR and before PIO_UNIMAP
233            this printf did not work on many kernels */
234
235         advice.advised_hashsize = 0;
236         advice.advised_hashstep = 0;
237         advice.advised_hashlevel = 0;
238         xioctl(fd, PIO_UNIMAPCLR, &advice);
239         ud.entry_ct = ct;
240         ud.entries = up;
241         xioctl(fd, PIO_UNIMAP, &ud);
242 #undef psf2
243 }
244
245 static void do_load(int fd, unsigned char *buffer, size_t len)
246 {
247         int height;
248         int width = 8;
249         int charsize;
250         int fontsize = 256;
251         int has_table = 0;
252         unsigned char *font = buffer;
253         unsigned char *table;
254
255         if (len >= sizeof(struct psf1_header) && PSF1_MAGIC_OK(psf1h(buffer))) {
256                 if (psf1h(buffer)->mode > PSF1_MAXMODE)
257                         bb_error_msg_and_die("unsupported psf file mode");
258                 if (psf1h(buffer)->mode & PSF1_MODE512)
259                         fontsize = 512;
260                 if (psf1h(buffer)->mode & PSF1_MODEHASTAB)
261                         has_table = 1;
262                 height = charsize = psf1h(buffer)->charsize;
263                 font += sizeof(struct psf1_header);
264         } else
265 #if ENABLE_FEATURE_LOADFONT_PSF2
266         if (len >= sizeof(struct psf2_header) && PSF2_MAGIC_OK(psf2h(buffer))) {
267                 if (psf2h(buffer)->version > PSF2_MAXVERSION)
268                         bb_error_msg_and_die("unsupported psf file version");
269                 fontsize = psf2h(buffer)->length;
270                 if (psf2h(buffer)->flags & PSF2_HAS_UNICODE_TABLE)
271                         has_table = 2;
272                 charsize = psf2h(buffer)->charsize;
273                 height = psf2h(buffer)->height;
274                 width = psf2h(buffer)->width;
275                 font += psf2h(buffer)->headersize;
276         } else
277 #endif
278 #if ENABLE_FEATURE_LOADFONT_RAW
279         if (len == 9780) {  /* file with three code pages? */
280                 charsize = height = 16;
281                 font += 40;
282         } else if ((len & 0377) == 0) {  /* bare font */
283                 charsize = height = len / 256;
284         } else
285 #endif
286         {
287                 bb_error_msg_and_die("input file: bad length or unsupported font type");
288         }
289
290 #if !defined(PIO_FONTX) || defined(__sparc__)
291         if (fontsize != 256)
292                 bb_error_msg_and_die("only fontsize 256 supported");
293 #endif
294
295         table = font + fontsize * charsize;
296         buffer += len;
297
298         if (table > buffer || (!has_table && table != buffer))
299                 bb_error_msg_and_die("input file: bad length");
300
301         do_loadfont(fd, font, height, width, charsize, fontsize);
302
303         if (has_table)
304                 do_loadtable(fd, table, buffer - table, fontsize, has_table - 1);
305 }
306
307
308 #if ENABLE_LOADFONT
309 int loadfont_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
310 int loadfont_main(int argc UNUSED_PARAM, char **argv)
311 {
312         size_t len;
313         unsigned char *buffer;
314
315         // no arguments allowed!
316         opt_complementary = "=0";
317         getopt32(argv, "");
318
319         /*
320          * We used to look at the length of the input file
321          * with stat(); now that we accept compressed files,
322          * just read the entire file.
323          */
324         len = 32*1024; // can't be larger
325         buffer = xmalloc_read(STDIN_FILENO, &len);
326         // xmalloc_open_zipped_read_close(filename, &len);
327         if (!buffer)
328                 bb_perror_msg_and_die("error reading input font");
329         do_load(get_console_fd_or_die(), buffer, len);
330
331         return EXIT_SUCCESS;
332 }
333 #endif
334
335 #if ENABLE_SETFONT
336
337 /*
338 kbd-1.12:
339
340 setfont [-O font+umap.orig] [-o font.orig] [-om cmap.orig]
341 [-ou umap.orig] [-N] [font.new ...] [-m cmap] [-u umap] [-C console]
342 [-hNN] [-v] [-V]
343
344 -h NN  Override font height
345 -o file
346        Save previous font in file
347 -O file
348        Save previous font and Unicode map in file
349 -om file
350        Store console map in file
351 -ou file
352        Save previous Unicode map in file
353 -m file
354        Load console map or Unicode console map from file
355 -u file
356        Load Unicode table describing the font from file
357        Example:
358        # cp866
359        0x00-0x7f       idem
360        #
361        0x80    U+0410  # CYRILLIC CAPITAL LETTER A
362        0x81    U+0411  # CYRILLIC CAPITAL LETTER BE
363        0x82    U+0412  # CYRILLIC CAPITAL LETTER VE
364 -C console
365        Set the font for the indicated console
366 -v     Verbose
367 -V     Version
368 */
369
370 #if ENABLE_FEATURE_SETFONT_TEXTUAL_MAP
371 static int ctoi(char *s)
372 {
373         if (s[0] == '\'' && s[1] != '\0' && s[2] == '\'' && s[3] == '\0')
374                 return s[1];
375         // U+ means 0x
376         if (s[0] == 'U' && s[1] == '+') {
377                 s[0] = '0';
378                 s[1] = 'x';
379         }
380         if (!isdigit(s[0]))
381                 return -1;
382         return xstrtoul(s, 0);
383 }
384 #endif
385
386 int setfont_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
387 int setfont_main(int argc UNUSED_PARAM, char **argv)
388 {
389         size_t len;
390         unsigned opts;
391         int fd;
392         unsigned char *buffer;
393         char *mapfilename;
394         const char *tty_name = CURRENT_TTY;
395
396         opt_complementary = "=1";
397         opts = getopt32(argv, "m:C:", &mapfilename, &tty_name);
398         argv += optind;
399
400         fd = xopen_nonblocking(tty_name);
401
402         if (sizeof(CONFIG_DEFAULT_SETFONT_DIR) > 1) { // if not ""
403                 if (*argv[0] != '/') {
404                         // goto default fonts location. don't die if doesn't exist
405                         chdir(CONFIG_DEFAULT_SETFONT_DIR "/consolefonts");
406                 }
407         }
408         // load font
409         len = 32*1024; // can't be larger
410         buffer = xmalloc_open_zipped_read_close(*argv, &len);
411         if (!buffer)
412                 bb_simple_perror_msg_and_die(*argv);
413         do_load(fd, buffer, len);
414
415         // load the screen map, if any
416         if (opts & 1) { // -m
417                 unsigned mode = PIO_SCRNMAP;
418                 void *map;
419
420                 if (sizeof(CONFIG_DEFAULT_SETFONT_DIR) > 1) { // if not ""
421                         if (mapfilename[0] != '/') {
422                                 // goto default keymaps location
423                                 chdir(CONFIG_DEFAULT_SETFONT_DIR "/consoletrans");
424                         }
425                 }
426                 // fetch keymap
427                 map = xmalloc_open_zipped_read_close(mapfilename, &len);
428                 if (!map)
429                         bb_simple_perror_msg_and_die(mapfilename);
430                 // file size is 256 or 512 bytes? -> assume binary map
431                 if (len == E_TABSZ || len == 2*E_TABSZ) {
432                         if (len == 2*E_TABSZ)
433                                 mode = PIO_UNISCRNMAP;
434                 }
435 #if ENABLE_FEATURE_SETFONT_TEXTUAL_MAP
436                 // assume textual Unicode console maps:
437                 // 0x00 U+0000  #  NULL (NUL)
438                 // 0x01 U+0001  #  START OF HEADING (SOH)
439                 // 0x02 U+0002  #  START OF TEXT (STX)
440                 // 0x03 U+0003  #  END OF TEXT (ETX)
441                 else {
442                         int i;
443                         char *token[2];
444                         parser_t *parser;
445
446                         if (ENABLE_FEATURE_CLEAN_UP)
447                                 free(map);
448                         map = xmalloc(E_TABSZ * sizeof(unsigned short));
449
450 #define unicodes ((unsigned short *)map)
451                         // fill vanilla map
452                         for (i = 0; i < E_TABSZ; i++)
453                                 unicodes[i] = 0xf000 + i;
454
455                         parser = config_open(mapfilename);
456                         while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL | PARSE_MIN_DIE)) {
457                                 // parse code/value pair
458                                 int a = ctoi(token[0]);
459                                 int b = ctoi(token[1]);
460                                 if (a < 0 || a >= E_TABSZ
461                                  || b < 0 || b > 65535
462                                 ) {
463                                         bb_error_msg_and_die("map format");
464                                 }
465                                 // patch map
466                                 unicodes[a] = b;
467                                 // unicode character is met?
468                                 if (b > 255)
469                                         mode = PIO_UNISCRNMAP;
470                         }
471                         if (ENABLE_FEATURE_CLEAN_UP)
472                                 config_close(parser);
473
474                         if (mode != PIO_UNISCRNMAP) {
475 #define asciis ((unsigned char *)map)
476                                 for (i = 0; i < E_TABSZ; i++)
477                                         asciis[i] = unicodes[i];
478 #undef asciis
479                         }
480 #undef unicodes
481                 }
482 #endif // ENABLE_FEATURE_SETFONT_TEXTUAL_MAP
483
484                 // do set screen map
485                 xioctl(fd, mode, map);
486
487                 if (ENABLE_FEATURE_CLEAN_UP)
488                         free(map);
489         }
490
491         return EXIT_SUCCESS;
492 }
493 #endif