Clarify that Privoxy is licensed under GPLv2 or later
[privoxy.git] / deanimate.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/deanimate.c,v $
4  *
5  * Purpose     :  Declares functions to manipulate binary images on the
6  *                fly.  High-level functions include:
7  *                  - Deanimation of GIF images
8  *
9  * Copyright   :  Written by and Copyright (C) 2001 - 2004, 2006 by the
10  *                Privoxy team. https://www.privoxy.org/
11  *
12  *                Based on the GIF file format specification (see
13  *                http://tronche.com/computer-graphics/gif/gif89a.html)
14  *                and ideas from the Image::DeAnim Perl module by
15  *                Ken MacFarlane, <ksm+cpan@universal.dca.net>
16  *
17  *                This program is free software; you can redistribute it
18  *                and/or modify it under the terms of the GNU General
19  *                Public License as published by the Free Software
20  *                Foundation; either version 2 of the License, or (at
21  *                your option) any later version.
22  *
23  *                This program is distributed in the hope that it will
24  *                be useful, but WITHOUT ANY WARRANTY; without even the
25  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
26  *                PARTICULAR PURPOSE.  See the GNU General Public
27  *                License for more details.
28  *
29  *                The GNU General Public License should be included with
30  *                this file.  If not, you can view it at
31  *                http://www.gnu.org/copyleft/gpl.html
32  *                or write to the Free Software Foundation, Inc., 59
33  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
34  *
35  **********************************************************************/
36
37
38 #include "config.h"
39
40 #include <string.h>
41 #include <fcntl.h>
42
43 #include "project.h"
44 #include "errlog.h"
45 #include "deanimate.h"
46 #include "miscutil.h"
47
48 /*********************************************************************
49  *
50  * Function    :  buf_free
51  *
52  * Description :  Safely frees a struct binbuffer
53  *
54  * Parameters  :
55  *          1  :  buf = Pointer to the binbuffer to be freed
56  *
57  * Returns     :  N/A
58  *
59  *********************************************************************/
60 void buf_free(struct binbuffer *buf)
61 {
62    if (buf == NULL) return;
63
64    if (buf->buffer != NULL)
65    {
66       free(buf->buffer);
67    }
68
69    free(buf);
70
71 }
72
73
74 /*********************************************************************
75  *
76  * Function    :  buf_extend
77  *
78  * Description :  Ensure that a given binbuffer can hold a given amount
79  *                of bytes, by reallocating its buffer if necessary.
80  *                Allocate new mem in chunks of 1024 bytes, so we don't
81  *                have to realloc() too often.
82  *
83  * Parameters  :
84  *          1  :  buf = Pointer to the binbuffer
85  *          2  :  length = Desired minimum size
86  *
87  *
88  * Returns     :  0 on success, 1 on failure.
89  *
90  *********************************************************************/
91 static int buf_extend(struct binbuffer *buf, size_t length)
92 {
93    char *newbuf;
94
95    if (buf->offset + length > buf->size)
96    {
97       buf->size = ((buf->size + length + (size_t)1023) & ~(size_t)1023);
98       newbuf = (char *)realloc(buf->buffer, buf->size);
99
100       if (newbuf == NULL)
101       {
102          freez(buf->buffer);
103          return 1;
104       }
105       else
106       {
107          buf->buffer = newbuf;
108          return 0;
109       }
110    }
111    return 0;
112
113 }
114
115
116 /*********************************************************************
117  *
118  * Function    :  buf_copy
119  *
120  * Description :  Safely copies a given amount of bytes from one
121  *                struct binbuffer to another, advancing the
122  *                offsets appropriately.
123  *
124  * Parameters  :
125  *          1  :  src = Pointer to the source binbuffer
126  *          2  :  dst = Pointer to the destination binbuffer
127  *          3  :  length = Number of bytes to be copied
128  *
129  * Returns     :  0 on success, 1 on failure.
130  *
131  *********************************************************************/
132 static int buf_copy(struct binbuffer *src, struct binbuffer *dst, size_t length)
133 {
134
135    /*
136     * Sanity check: Can't copy more data than we have
137     */
138    if (src->offset + length > src->size)
139    {
140       return 1;
141    }
142
143    /*
144     * Ensure that dst can hold the new data
145     */
146    if (buf_extend(dst, length))
147    {
148       return 1;
149    }
150
151    /*
152     * Now that it's safe, memcpy() the desired amount of
153     * data from src to dst and adjust the offsets
154     */
155    memcpy(dst->buffer + dst->offset, src->buffer + src->offset, length);
156    src->offset += length;
157    dst->offset += length;
158
159    return 0;
160
161 }
162
163
164 /*********************************************************************
165  *
166  * Function    :  buf_getbyte
167  *
168  * Description :  Safely gets a byte from a given binbuffer at a
169  *                given offset
170  *
171  * Parameters  :
172  *          1  :  src = Pointer to the source binbuffer
173  *          2  :  offset = Offset to the desired byte
174  *
175  * Returns     :  The byte on success, or 0 on failure
176  *
177  *********************************************************************/
178 static unsigned char buf_getbyte(const struct binbuffer *src, size_t offset)
179 {
180    if (src->offset + offset < src->size)
181    {
182       return (unsigned char)*(src->buffer + src->offset + offset);
183    }
184    else
185    {
186       return '\0';
187    }
188
189 }
190
191
192 /*********************************************************************
193  *
194  * Function    :  gif_skip_data_block
195  *
196  * Description :  Safely advances the offset of a given struct binbuffer
197  *                that contains a GIF image and whose offset is
198  *                positioned at the start of a data block, behind
199  *                that block.
200  *
201  * Parameters  :
202  *          1  :  buf = Pointer to the binbuffer
203  *
204  * Returns     :  0 on success, or 1 on failure
205  *
206  *********************************************************************/
207 static int gif_skip_data_block(struct binbuffer *buf)
208 {
209    unsigned char c;
210
211    /*
212     * Data blocks are sequences of chunks, which are headed
213     * by a one-byte length field, with the last chunk having
214     * zero length.
215     */
216    while((c = buf_getbyte(buf, 0)) != '\0')
217    {
218       buf->offset += (size_t)c + 1;
219       if (buf->offset >= buf->size - 1)
220       {
221          return 1;
222       }
223    }
224    buf->offset++;
225
226    return 0;
227
228 }
229
230
231 /*********************************************************************
232  *
233  * Function    :  gif_extract_image
234  *
235  * Description :  Safely extracts an image data block from a given
236  *                struct binbuffer that contains a GIF image and whose
237  *                offset is positioned at the start of a data block
238  *                into a given destination binbuffer.
239  *
240  * Parameters  :
241  *          1  :  src = Pointer to the source binbuffer
242  *          2  :  dst = Pointer to the destination binbuffer
243  *
244  * Returns     :  0 on success, or 1 on failure
245  *
246  *********************************************************************/
247 static int gif_extract_image(struct binbuffer *src, struct binbuffer *dst)
248 {
249    unsigned char c;
250
251    /*
252     * Remember the colormap flag and copy the image head
253     */
254    c = buf_getbyte(src, 9);
255    if (buf_copy(src, dst, 10))
256    {
257       return 1;
258    }
259
260    /*
261     * If the image has a local colormap, copy it.
262     */
263    if (c & 0x80)
264    {
265       int map_length = 3 * (1 << ((c & 0x07) + 1));
266       if (map_length <= 0)
267       {
268          log_error(LOG_LEVEL_DEANIMATE,
269             "colormap length = %d (%c)?", map_length, c);
270          return 1;
271       }
272       if (buf_copy(src, dst, (size_t)map_length))
273       {
274          return 1;
275       }
276    }
277    if (buf_copy(src, dst, 1)) return 1;
278
279    /*
280     * Copy the image chunk by chunk.
281     */
282    while((c = buf_getbyte(src, 0)) != '\0')
283    {
284       if (buf_copy(src, dst, 1 + (size_t) c)) return 1;
285    }
286    if (buf_copy(src, dst, 1)) return 1;
287
288    /*
289     * Trim and rewind the dst buffer
290     */
291    if (NULL == (dst->buffer = (char *)realloc(dst->buffer, dst->offset))) return 1;
292    dst->size = dst->offset;
293    dst->offset = 0;
294
295    return(0);
296
297 }
298
299 /*********************************************************************
300  *
301  * Function    :  gif_deanimate
302  *
303  * Description :  Deanimate a given GIF image, i.e. given a GIF with
304  *                an (optional) image block and an arbitrary number
305  *                of image extension blocks, produce an output GIF with
306  *                only one image block that contains the last image
307  *                (extension) block of the original.
308  *                Also strip Comments, Application extensions, etc.
309  *
310  * Parameters  :
311  *          1  :  src = Pointer to the source binbuffer
312  *          2  :  dst = Pointer to the destination binbuffer
313  *          3  :  get_first_image = Flag: If set, get the first image
314  *                                        If unset (default), get the last
315  *
316  * Returns     :  0 on success, or 1 on failure
317  *
318  *********************************************************************/
319 int gif_deanimate(struct binbuffer *src, struct binbuffer *dst, int get_first_image)
320 {
321    unsigned char c;
322    struct binbuffer *image;
323
324    if (NULL == src || NULL == dst)
325    {
326       return 1;
327    }
328
329    c = buf_getbyte(src, 10);
330
331    /*
332     * Check & copy GIF header
333     */
334    if (strncmp(src->buffer, "GIF89a", 6) && strncmp(src->buffer, "GIF87a", 6))
335    {
336       return 1;
337    }
338    else
339    {
340       if (buf_copy(src, dst, 13))
341       {
342          return 1;
343       }
344    }
345
346    /*
347     * Look for global colormap and  copy if found.
348     */
349    if (c & 0x80)
350    {
351       int map_length = 3 * (1 << ((c & 0x07) + 1));
352       if (map_length <= 0)
353       {
354          log_error(LOG_LEVEL_DEANIMATE,
355             "colormap length = %d (%c)?", map_length, c);
356          return 1;
357       }
358       if (buf_copy(src, dst, (size_t)map_length))
359       {
360          return 1;
361       }
362    }
363
364    /*
365     * Reserve a buffer for the current image block
366     */
367    image = zalloc_or_die(sizeof(*image));
368
369    /*
370     * Parse the GIF block by block and copy the relevant
371     * parts to dst
372     */
373    while(src->offset < src->size)
374    {
375       switch(buf_getbyte(src, 0))
376       {
377          /*
378           *  End-of-GIF Marker: Append current image and return
379           */
380       case 0x3b:
381          goto write;
382
383          /*
384           * Image block: Extract to current image buffer.
385           */
386       case 0x2c:
387          image->offset = 0;
388          if (gif_extract_image(src, image)) goto failed;
389          if (get_first_image) goto write;
390          continue;
391
392          /*
393           * Extension block: Look at next byte and decide
394           */
395       case 0x21:
396          switch (buf_getbyte(src, 1))
397          {
398             /*
399              * Image extension: Copy extension  header and image
400              *                  to the current image buffer
401              */
402          case 0xf9:
403             image->offset = 0;
404             if (buf_copy(src, image, 8) || buf_getbyte(src, 0) != 0x2c) goto failed;
405             if (gif_extract_image(src, image)) goto failed;
406             if (get_first_image) goto write;
407             continue;
408
409             /*
410              * Application extension: Skip
411              */
412          case 0xff:
413             if ((src->offset += 14) >= src->size || gif_skip_data_block(src)) goto failed;
414             continue;
415
416             /*
417              * Comment extension: Skip
418              */
419          case 0xfe:
420             if ((src->offset += 2) >= src->size || gif_skip_data_block(src)) goto failed;
421             continue;
422
423             /*
424              * Plain text extension: Skip
425              */
426          case 0x01:
427             if ((src->offset += 15) >= src->size || gif_skip_data_block(src)) goto failed;
428             continue;
429
430             /*
431              * Ooops, what type of extension is that?
432              */
433          default:
434             goto failed;
435
436          }
437
438          /*
439           * Ooops, what type of block is that?
440           */
441       default:
442          goto failed;
443
444       }
445    } /* -END- while src */
446
447    /*
448     * Either we got here by goto, or because the GIF is
449     * bogus and EOF was reached before an end-of-gif marker
450     * was found.
451     */
452
453 failed:
454    buf_free(image);
455    return 1;
456
457    /*
458     * Append the current image to dst and return
459     */
460
461 write:
462    if (buf_copy(image, dst, image->size)) goto failed;
463    if (buf_extend(dst, 1)) goto failed;
464    *(dst->buffer + dst->offset++) = 0x3b;
465    buf_free(image);
466    return 0;
467
468 }
469
470
471 /*
472   Local Variables:
473   tab-width: 3
474   end:
475 */