source: libcaca/trunk/cucul/import.c @ 1236

Last change on this file since 1236 was 1236, checked in by Sam Hocevar, 16 years ago
  • Fix a buffer overflow in the import format autodetection code.
  • Property svn:keywords set to Id
File size: 15.4 KB
Line 
1/*
2 *  libcucul      Canvas for ultrafast compositing of Unicode letters
3 *  Copyright (c) 2002-2006 Sam Hocevar <sam@zoy.org>
4 *                All Rights Reserved
5 *
6 *  $Id: import.c 1236 2006-10-26 08:47:39Z sam $
7 *
8 *  This library is free software; you can redistribute it and/or
9 *  modify it under the terms of the Do What The Fuck You Want To
10 *  Public License, Version 2, as published by Sam Hocevar. See
11 *  http://sam.zoy.org/wtfpl/COPYING for more details.
12 */
13
14/*
15 *  This file contains various import functions.
16 */
17
18#include "config.h"
19#include "common.h"
20
21#if !defined(__KERNEL__)
22#   if defined(HAVE_ERRNO_H)
23#       include <errno.h>
24#   endif
25#   include <stdio.h>
26#   include <stdlib.h>
27#   include <string.h>
28#endif
29
30#include "cucul.h"
31#include "cucul_internals.h"
32
33/* ANSI Graphic Rendition Combination Mode */
34struct ansi_grcm
35{
36    uint8_t fg, bg;   /* ANSI-context fg/bg */
37    uint8_t efg, ebg; /* Effective (libcucul) fg/bg */
38    uint8_t bold, negative, concealed;
39};
40
41static cucul_canvas_t *import_caca(void const *, unsigned int);
42static cucul_canvas_t *import_text(void const *, unsigned int);
43static cucul_canvas_t *import_ansi(void const *, unsigned int, int);
44
45static void ansi_parse_grcm(cucul_canvas_t *, struct ansi_grcm *,
46                            unsigned int, unsigned int const *);
47
48/** \brief Import a buffer into a canvas
49 *
50 *  Import a libcucul buffer as returned by cucul_load_memory()
51 *  or cucul_load_file() into an internal libcucul canvas.
52 *
53 *  Valid values for \c format are:
54 *  - \c "": attempt to autodetect the file format.
55 *  - \c "text": import ASCII text files.
56 *  - \c "ansi": import ANSI files.
57 *  - \c "utf8": import UTF-8 files with ANSI colour codes.
58 *  - \c "caca": import native libcaca files.
59 *
60 *  If an error occurs, NULL is returned and \b errno is set accordingly:
61 *  - \c ENOMEM Not enough memory to allocate canvas.
62 *  - \c EINVAL Invalid format requested.
63 *
64 *  \param buffer A \e libcucul buffer containing the data to be loaded
65 *         into a canvas.
66 *  \param format A string describing the input format.
67 *  \return A libcucul canvas, or NULL in case of error.
68 */
69cucul_canvas_t * cucul_import_canvas(cucul_buffer_t *buffer, char const *format)
70{
71    char const *buf = (char const*)buffer->data;
72
73    if(!strcasecmp("caca", format))
74        return import_caca(buffer->data, buffer->size);
75    if(!strcasecmp("utf8", format))
76        return import_ansi(buffer->data, buffer->size, 1);
77    if(!strcasecmp("text", format))
78        return import_text(buffer->data, buffer->size);
79    if(!strcasecmp("ansi", format))
80        return import_ansi(buffer->data, buffer->size, 0);
81
82    /* Autodetection */
83    if(!strcasecmp("", format))
84    {
85        unsigned int i;
86
87        /* If 4 first letters are CACA */
88        if(buffer->size >= 4 &&
89           buf[0] == 'C' && buf[1] == 'A' && buf[2] == 'C' && buf[3] != 'A')
90            return import_caca(buffer->data, buffer->size);
91
92        /* If we find ESC[ argv, we guess it's an ANSI file */
93        for(i = 0; i + 1 < buffer->size; i++)
94            if((buf[i] == 0x1b) && (buf[i + 1] == '['))
95                return import_ansi(buffer->data, buffer->size, 0);
96
97        /* Otherwise, import it as text */
98        return import_text(buffer->data, buffer->size);
99    }
100
101#if defined(HAVE_ERRNO_H)
102    errno = EINVAL;
103#endif
104    return NULL;
105}
106
107/** \brief Get available import formats
108 *
109 *  Return a list of available import formats. The list is a NULL-terminated
110 *  array of strings, interleaving a string containing the internal value for
111 *  the import format, to be used with cucul_import_canvas(), and a string
112 *  containing the natural language description for that import format.
113 *
114 *  This function never fails.
115 *
116 *  \return An array of strings.
117 */
118char const * const * cucul_get_import_list(void)
119{
120    static char const * const list[] =
121        {
122            "", "autodetect",
123            "text", "plain text",
124            "caca", "native libcaca format",
125            "ansi", "ANSI coloured text",
126            NULL, NULL
127        };
128
129    return list;
130}
131
132/*
133 * XXX: the following functions are local.
134 */
135
136static cucul_canvas_t *import_caca(void const *data, unsigned int size)
137{
138    cucul_canvas_t *cv;
139    uint8_t const *buf = (uint8_t const *)data;
140    unsigned int width, height, n;
141
142    if(size < 16)
143        goto invalid_caca;
144
145    if(buf[0] != 'C' || buf[1] != 'A' || buf[2] != 'C' || buf[3] != 'A')
146        goto invalid_caca;
147
148    if(buf[4] != 'C' || buf[5] != 'A' || buf[6] != 'N' || buf[7] != 'V')
149        goto invalid_caca;
150
151    width = ((uint32_t)buf[8] << 24) | ((uint32_t)buf[9] << 16)
152        | ((uint32_t)buf[10] << 8) | (uint32_t)buf[11];
153    height = ((uint32_t)buf[12] << 24) | ((uint32_t)buf[13] << 16)
154        | ((uint32_t)buf[14] << 8) | (uint32_t)buf[15];
155
156    if(size != 16 + width * height * 8)
157        goto invalid_caca;
158
159    cv = cucul_create_canvas(width, height);
160
161    if(!cv)
162    {
163#if defined(HAVE_ERRNO_H)
164        errno = ENOMEM;
165#endif
166        return NULL;
167    }
168
169    for(n = height * width; n--; )
170    {
171        cv->chars[n] = ((uint32_t)buf[16 + 0 + 8 * n] << 24)
172            | ((uint32_t)buf[16 + 1 + 8 * n] << 16)
173            | ((uint32_t)buf[16 + 2 + 8 * n] << 8)
174            | (uint32_t)buf[16 + 3 + 8 * n];
175        cv->attr[n] = ((uint32_t)buf[16 + 4 + 8 * n] << 24)
176            | ((uint32_t)buf[16 + 5 + 8 * n] << 16)
177            | ((uint32_t)buf[16 + 6 + 8 * n] << 8)
178            | (uint32_t)buf[16 + 7 + 8 * n];
179    }
180
181    return cv;
182
183invalid_caca:
184#if defined(HAVE_ERRNO_H)
185    errno = EINVAL;
186#endif
187    return NULL;
188}
189
190static cucul_canvas_t *import_text(void const *data, unsigned int size)
191{
192    cucul_canvas_t *cv;
193    char const *text = (char const *)data;
194    unsigned int width = 0, height = 0, x = 0, y = 0, i;
195
196    cv = cucul_create_canvas(width, height);
197    if(!cv)
198    {
199#if defined(HAVE_ERRNO_H)
200        errno = ENOMEM;
201#endif
202        return NULL;
203    }
204
205    cucul_set_color(cv, CUCUL_COLOR_DEFAULT, CUCUL_COLOR_TRANSPARENT);
206
207    for(i = 0; i < size; i++)
208    {
209        unsigned char ch = *text++;
210
211        if(ch == '\r')
212            continue;
213
214        if(ch == '\n')
215        {
216            x = 0;
217            y++;
218            continue;
219        }
220
221        if(x >= width || y >= height)
222        {
223            if(x >= width)
224                width = x + 1;
225
226            if(y >= height)
227                height = y + 1;
228
229            cucul_set_canvas_size(cv, width, height);
230        }
231
232        cucul_putchar(cv, x, y, ch);
233        x++;
234    }
235
236    return cv;
237}
238
239static cucul_canvas_t *import_ansi(void const *data, unsigned int size,
240                                   int utf8)
241{
242    struct ansi_grcm grcm;
243    unsigned char const *buffer = (unsigned char const*)data;
244    cucul_canvas_t *cv;
245    unsigned int i, j, skip, dummy = 0;
246    unsigned int width = 0, height = 0, wch = 1;
247    unsigned long int ch;
248    int x = 0, y = 0, save_x = 0, save_y = 0;
249
250    cv = cucul_create_canvas(width, height);
251    if(!cv)
252    {
253#if defined(HAVE_ERRNO_H)
254        errno = ENOMEM;
255#endif
256        return NULL;
257    }
258
259    ansi_parse_grcm(cv, &grcm, 1, &dummy);
260
261    for(i = 0; i < size; i += skip)
262    {
263        skip = 1;
264
265        /* Wrap long lines */
266        if((unsigned int)x >= 80)
267        {
268            x = 0;
269            y++;
270        }
271
272        if(buffer[i] == '\x1a' && size - i >= 8
273           && !memcmp(buffer + i + 1, "SAUCE00", 7))
274            break; /* End before SAUCE data */
275
276        if(buffer[i] == '\r')
277            continue; /* DOS sucks */
278
279        if(buffer[i] == '\n')
280        {
281            x = 0;
282            y++;
283            continue;
284        }
285
286        /* Interpret escape commands, as per Standard ECMA-48 "Control
287         * Functions for Coded Character Sets", 5.4. Control sequences. */
288        if(buffer[i] == '\x1b' && buffer[i + 1] == '[')
289        {
290            unsigned int argc = 0, argv[101];
291            unsigned int param, inter, final;
292
293        /* Compute offsets to parameter bytes, intermediate bytes and
294         * to the final byte. Only the final byte is mandatory, there
295         * can be zero of the others.
296         * 0  param=2             inter                 final           final+1
297         * +-----+------------------+---------------------+-----------------+
298         * | CSI | parameter bytes  | intermediate bytes  |   final byte    |
299         * |     |   0x30 - 0x3f    |    0x20 - 0x2f      |   0x40 - 0x7e   |
300         * | ^[[ | 0123456789:;<=>? | SPC !"#$%&'()*+,-./ | azAZ@[\]^_`{|}~ |
301         * +-----+------------------+---------------------+-----------------+
302         */
303            param = 2;
304
305            for(inter = param; i + inter < size; inter++)
306                if(buffer[i + inter] < 0x30 || buffer[i + inter] > 0x3f)
307                    break;
308
309            for(final = inter; i + final < size; final++)
310                if(buffer[i + final] < 0x20 || buffer[i + final] > 0x2f)
311                    break;
312
313            if(buffer[i + final] < 0x40 || buffer[i + final] > 0x7e)
314                break; /* Invalid Final Byte */
315
316            skip += final;
317
318            /* Sanity checks */
319            if(param < inter && buffer[i + param] >= 0x3c)
320            {
321                fprintf(stderr, "private sequence \"^[[%.*s\"\n",
322                        final - param + 1, buffer + i + param);
323                continue; /* Private sequence, skip it entirely */
324            }
325
326            if(final - param > 100)
327                continue; /* Suspiciously long sequence, skip it */
328
329            /* Parse parameter bytes as per ECMA-48 5.4.2: Parameter string
330             * format */
331            if(param < inter)
332            {
333                argv[0] = 0;
334                for(j = param; j < inter; j++)
335                {
336                    if(buffer[i + j] == ';')
337                        argv[++argc] = 0;
338                    else if(buffer[i + j] >= '0' && buffer[i + j] <= '9')
339                        argv[argc] = 10 * argv[argc] + (buffer[i + j] - '0');
340                }
341                argc++;
342            }
343
344            /* Interpret final byte. The code representations are given in
345             * ECMA-48 5.4: Control sequences, and the code definitions are
346             * given in ECMA-48 8.3: Definition of control functions. */
347            switch(buffer[i + final])
348            {
349            case 'f': /* CUP - Cursor Position */
350            case 'H': /* HVP - Character And Line Position */
351                x = (argc > 1 && argv[1] > 0) ? argv[1] - 1 : 0;
352                y = (argc > 0 && argv[0] > 0) ? argv[0] - 1 : 0;
353                break;
354            case 'A': /* CUU - Cursor Up */
355                y -= argc ? argv[0] : 1;
356                if(y < 0)
357                    y = 0;
358                break;
359            case 'B': /* CUD - Cursor Down */
360                y += argc ? argv[0] : 1;
361                break;
362            case 'C': /* CUF - Cursor Right */
363                x += argc ? argv[0] : 1;
364                break;
365            case 'D': /* CUB - Cursor Left */
366                x -= argc ? argv[0] : 1;
367                if(x < 0)
368                    x = 0;
369                break;
370            case 's': /* Private (save cursor position) */
371                save_x = x;
372                save_y = y;
373                break;
374            case 'u': /* Private (reload cursor position) */
375                x = save_x;
376                y = save_y;
377                break;
378            case 'J': /* ED - Erase In Page */
379                if(argv[0] == 2)
380                    x = y = 0;
381                break;
382            case 'K': /* EL - Erase In Line */
383                if(width < 80)
384                    cucul_set_color(cv, CUCUL_COLOR_DEFAULT,
385                                        CUCUL_COLOR_TRANSPARENT);
386                    cucul_set_canvas_size(cv, width = 80, height);
387                for(j = x; j < 80; j++)
388                    cucul_putchar(cv, j, y, ' ');
389                x = 80;
390                break;
391            case 'm': /* SGR - Select Graphic Rendition */
392                ansi_parse_grcm(cv, &grcm, argc, argv);
393                break;
394            default:
395                fprintf(stderr, "unknown command %c\n", buffer[i + final]);
396                break;
397            }
398
399            continue;
400        }
401
402        /* Get the character we’re going to paste */
403        if(utf8)
404        {
405            unsigned int bytes;
406            ch = cucul_utf8_to_utf32((char const *)(buffer + i), &bytes);
407            wch = cucul_utf32_is_fullwidth(ch) ? 2 : 1;
408            skip += bytes - 1;
409        }
410        else
411        {
412            ch = cucul_cp437_to_utf32(buffer[i]);
413        }
414
415        /* Make sure the canvas is big enough. */
416        if((unsigned int)x + wch > width)
417        {
418            cucul_set_color(cv, CUCUL_COLOR_DEFAULT, CUCUL_COLOR_TRANSPARENT);
419            cucul_set_canvas_size(cv, width = x + wch, height);
420        }
421
422        if((unsigned int)y >= height)
423        {
424            cucul_set_color(cv, CUCUL_COLOR_DEFAULT, CUCUL_COLOR_TRANSPARENT);
425            cucul_set_canvas_size(cv, width, height = y + 1);
426        }
427
428        /* Now paste our character */
429        cucul_set_color(cv, grcm.efg, grcm.ebg);
430        cucul_putchar(cv, x, y, ch);
431        x += wch;
432    }
433
434    return cv;
435}
436
437/* XXX : ANSI loader helper */
438
439static void ansi_parse_grcm(cucul_canvas_t *cv, struct ansi_grcm *g,
440                            unsigned int argc, unsigned int const *argv)
441{
442    static uint8_t const ansi2cucul[] =
443    {
444        CUCUL_COLOR_BLACK, CUCUL_COLOR_RED,
445        CUCUL_COLOR_GREEN, CUCUL_COLOR_BROWN,
446        CUCUL_COLOR_BLUE, CUCUL_COLOR_MAGENTA,
447        CUCUL_COLOR_CYAN, CUCUL_COLOR_LIGHTGRAY
448    };
449
450    unsigned int j;
451
452    for(j = 0; j < argc; j++)
453    {
454        /* Defined in ECMA-48 8.3.117: SGR - SELECT GRAPHIC RENDITION */
455        if(argv[j] >= 30 && argv[j] <= 37)
456            g->fg = ansi2cucul[argv[j] - 30];
457        else if(argv[j] >= 40 && argv[j] <= 47)
458            g->bg = ansi2cucul[argv[j] - 40];
459        else if(argv[j] >= 90 && argv[j] <= 97)
460            g->fg = ansi2cucul[argv[j] - 90] + 8;
461        else if(argv[j] >= 100 && argv[j] <= 107)
462            g->bg = ansi2cucul[argv[j] - 100] + 8;
463        else switch(argv[j])
464        {
465        case 0: /* default rendition */
466            g->fg = CUCUL_COLOR_DEFAULT;
467            g->bg = CUCUL_COLOR_TRANSPARENT;
468            g->bold = g->negative = g->concealed = 0;
469            break;
470        case 1: /* bold or increased intensity */
471            g->bold = 1;
472            break;
473        case 4: /* singly underlined */
474            break;
475        case 5: /* slowly blinking (less then 150 per minute) */
476            break;
477        case 7: /* negative image */
478            g->negative = 1;
479            break;
480        case 8: /* concealed characters */
481            g->concealed = 1;
482            break;
483        case 22: /* normal colour or normal intensity (neither bold nor faint) */
484            g->bold = 0;
485            break;
486        case 28: /* revealed characters */
487            g->concealed = 0;
488            break;
489        case 39: /* default display colour (implementation-defined) */
490            g->fg = CUCUL_COLOR_DEFAULT;
491            break;
492        case 49: /* default background colour (implementation-defined) */
493            g->bg = CUCUL_COLOR_TRANSPARENT;
494            break;
495        default:
496            fprintf(stderr, "unknown sgr %i\n", argv[j]);
497            break;
498        }
499    }
500
501    if(g->concealed)
502    {
503        g->efg = g->ebg = CUCUL_COLOR_TRANSPARENT;
504    }
505    else
506    {
507        g->efg = g->negative ? g->bg : g->fg;
508        g->ebg = g->negative ? g->fg : g->bg;
509
510        if(g->bold)
511        {
512            if(g->efg < 8)
513                g->efg += 8;
514            else if(g->efg == CUCUL_COLOR_DEFAULT)
515                g->efg = CUCUL_COLOR_WHITE;
516        }
517    }
518}
519
Note: See TracBrowser for help on using the repository browser.