]> git.sesse.net Git - vlc/blob - modules/stream_filter/decomp.c
decomp: fix leak on error and clean up a little
[vlc] / modules / stream_filter / decomp.c
1 /*****************************************************************************
2  * decomp.c : Decompression module for vlc
3  *****************************************************************************
4  * Copyright © 2008-2009 Rémi Denis-Courmont
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation; either version 2.1 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19  *****************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 # include "config.h"
23 #endif
24
25 #include <vlc_common.h>
26 #include <vlc_plugin.h>
27 #include <vlc_stream.h>
28 #include <vlc_network.h>
29 #include <vlc_fs.h>
30 #include <assert.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #ifndef _POSIX_SPAWN
34 # define _POSIX_SPAWN (-1)
35 #endif
36 #include <fcntl.h>
37 #if (_POSIX_SPAWN >= 0)
38 # include <spawn.h>
39 #endif
40 #include <sys/wait.h>
41 #include <sys/ioctl.h>
42 #if defined (__linux__) && defined (HAVE_VMSPLICE)
43 # include <sys/uio.h>
44 # include <sys/mman.h>
45 #else
46 # undef HAVE_VMSPLICE
47 #endif
48
49 static int  OpenGzip (vlc_object_t *);
50 static int  OpenBzip2 (vlc_object_t *);
51 static int  OpenXZ (vlc_object_t *);
52 static void Close (vlc_object_t *);
53
54 vlc_module_begin ()
55     set_category (CAT_INPUT)
56     set_subcategory (SUBCAT_INPUT_STREAM_FILTER)
57     set_capability ("stream_filter", 20)
58
59     set_description (N_("LZMA decompression"))
60     set_callbacks (OpenXZ, Close)
61
62     add_submodule ()
63     set_description (N_("Burrows-Wheeler decompression"))
64     set_callbacks (OpenBzip2, Close)
65     /* TODO: access shortnames for stream_UrlNew() */
66
67     add_submodule ()
68     set_description (N_("gzip decompression"))
69     set_callbacks (OpenGzip, Close)
70 vlc_module_end ()
71
72 struct stream_sys_t
73 {
74     /* Thread data */
75     int          write_fd;
76
77     /* Caller data */
78     vlc_thread_t thread;
79     pid_t        pid;
80
81     uint64_t     offset;
82     block_t      *peeked;
83
84     int          read_fd;
85     bool         can_pace;
86 };
87
88 extern char **environ;
89
90 static const size_t bufsize = 65536;
91 #ifdef HAVE_VMSPLICE
92 static void cleanup_mmap (void *addr)
93 {
94     munmap (addr, bufsize);
95 }
96 #endif
97
98 static void *Thread (void *data)
99 {
100     stream_t *stream = data;
101     stream_sys_t *p_sys = stream->p_sys;
102 #ifdef HAVE_VMSPLICE
103     const ssize_t page_mask = sysconf (_SC_PAGE_SIZE) - 1;
104 #endif
105     int fd = p_sys->write_fd;
106     bool error = false;
107
108     do
109     {
110         ssize_t len;
111         int canc = vlc_savecancel ();
112 #ifdef HAVE_VMSPLICE
113         unsigned char *buf = mmap (NULL, bufsize, PROT_READ|PROT_WRITE,
114                                    MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
115         if (unlikely(buf == MAP_FAILED))
116             break;
117         vlc_cleanup_push (cleanup_mmap, buf);
118 #else
119         unsigned char *buf = malloc (bufsize);
120         if (unlikely(buf == NULL))
121             break;
122         vlc_cleanup_push (free, buf);
123 #endif
124
125         len = stream_Read (stream->p_source, buf, bufsize);
126         vlc_restorecancel (canc);
127         error = len <= 0;
128
129         for (ssize_t i = 0, j; i < len; i += j)
130         {
131 #ifdef HAVE_VMSPLICE
132             if ((len - i) <= page_mask) /* incomplete last page */
133                 j = write (fd, buf + i, len - i);
134             else
135             {
136                 struct iovec iov = { buf + i, (len - i) & ~page_mask, };
137                 j = vmsplice (fd, &iov, 1, SPLICE_F_GIFT);
138             }
139             if (j == -1 && errno == ENOSYS) /* vmsplice() not supported */
140 #endif
141             j = write (fd, buf + i, len - i);
142             if (j <= 0)
143             {
144                 if (j == 0)
145                     errno = EPIPE;
146                 msg_Err (stream, "cannot write data (%m)");
147                 error = true;
148                 break;
149             }
150         }
151         vlc_cleanup_run (); /* free (buf) */
152     }
153     while (!error);
154
155     msg_Dbg (stream, "compressed stream at EOF");
156     /* Let child process know about EOF */
157     p_sys->write_fd = -1;
158     close (fd);
159     return NULL;
160 }
161
162
163 static int Peek (stream_t *, const uint8_t **, unsigned int);
164
165 #define MIN_BLOCK (1 << 10)
166 #define MAX_BLOCK (1 << 20)
167 /**
168  * Reads decompressed from the decompression program
169  * @return -1 for EAGAIN, 0 for EOF, byte count otherwise.
170  */
171 static int Read (stream_t *stream, void *buf, unsigned int buflen)
172 {
173     stream_sys_t *p_sys = stream->p_sys;
174     block_t *peeked;
175     ssize_t length;
176
177     if (buf == NULL) /* caller skips data, get big enough peek buffer */
178         buflen = Peek (stream, &(const uint8_t *){ NULL }, buflen);
179
180     if ((peeked = p_sys->peeked) != NULL)
181     {   /* dequeue peeked data */
182         length = (buflen > peeked->i_buffer) ? peeked->i_buffer : buflen;
183         if (buf != NULL)
184         {
185             memcpy (buf, peeked->p_buffer, length);
186             buf = ((char *)buf) + length;
187         }
188         buflen -= length;
189         peeked->p_buffer += length;
190         peeked->i_buffer -= length;
191         if (peeked->i_buffer == 0)
192         {
193             block_Release (peeked);
194             p_sys->peeked = NULL;
195         }
196         p_sys->offset += length;
197
198         if (buflen > 0)
199             length += Read (stream, ((char *)buf) + length, buflen - length);
200         return length;
201     }
202     assert ((buf != NULL) || (buflen == 0));
203
204     length = net_Read (stream, p_sys->read_fd, NULL, buf, buflen, false);
205     if (length < 0)
206         return 0;
207     p_sys->offset += length;
208     return length;
209 }
210
211 /**
212  *
213  */
214 static int Peek (stream_t *stream, const uint8_t **pbuf, unsigned int len)
215 {
216     stream_sys_t *p_sys = stream->p_sys;
217     block_t *peeked = p_sys->peeked;
218     size_t curlen = 0;
219     int fd = p_sys->read_fd;
220
221     if (peeked == NULL)
222         peeked = block_Alloc (len);
223     else if ((curlen = peeked->i_buffer) < len)
224         peeked = block_Realloc (peeked, 0, len);
225
226     if ((p_sys->peeked = peeked) == NULL)
227         return 0;
228
229     if (curlen < len)
230     {
231         ssize_t val = net_Read (stream, fd, NULL, peeked->p_buffer + curlen,
232                                 len - curlen, true);
233         if (val >= 0)
234         {
235             curlen += val;
236             peeked->i_buffer = curlen;
237         }
238     }
239     *pbuf = peeked->p_buffer;
240     return curlen;
241 }
242
243 /**
244  *
245  */
246 static int Control (stream_t *stream, int query, va_list args)
247 {
248     stream_sys_t *p_sys = stream->p_sys;
249
250     switch (query)
251     {
252         case STREAM_CAN_SEEK:
253         case STREAM_CAN_FASTSEEK:
254         case STREAM_CAN_PAUSE: /* TODO: support pause */
255             *(va_arg (args, bool *)) = false;
256             break;
257         case STREAM_CAN_CONTROL_PACE:
258             *(va_arg (args, bool *)) = p_sys->can_pace;
259             break;
260         case STREAM_GET_POSITION:
261             *(va_arg (args, uint64_t *)) = p_sys->offset;
262             break;
263         case STREAM_GET_SIZE:
264             *(va_arg (args, uint64_t *)) = 0;
265             break;
266         default:
267             return VLC_EGENERIC;
268     }
269     return VLC_SUCCESS;
270 }
271
272 /**
273  * Pipe data through an external executable.
274  * @param stream the stream filter object.
275  * @param path path to the executable.
276  */
277 static int Open (stream_t *stream, const char *path)
278 {
279     stream_sys_t *p_sys = stream->p_sys = malloc (sizeof (*p_sys));
280     if (p_sys == NULL)
281         return VLC_ENOMEM;
282
283     stream->pf_read = Read;
284     stream->pf_peek = Peek;
285     stream->pf_control = Control;
286
287     p_sys->pid = -1;
288     p_sys->offset = 0;
289     p_sys->peeked = NULL;
290     stream_Control (stream->p_source, STREAM_CAN_CONTROL_PACE,
291                     &p_sys->can_pace);
292
293     /* I am not a big fan of the pyramid style, but I cannot think of anything
294      * better here. There are too many failure cases. */
295     int ret = VLC_EGENERIC;
296     int comp[2];
297
298     /* We use two pipes rather than one stream socket pair, so that we can
299      * use vmsplice() on Linux. */
300     if (vlc_pipe (comp) == 0)
301     {
302         p_sys->write_fd = comp[1];
303
304         int uncomp[2];
305         if (vlc_pipe (uncomp) == 0)
306         {
307             p_sys->read_fd = uncomp[0];
308
309 #if (_POSIX_SPAWN >= 0)
310             posix_spawn_file_actions_t actions;
311             if (posix_spawn_file_actions_init (&actions) == 0)
312             {
313                 char *const argv[] = { (char *)path, NULL };
314
315                 if (!posix_spawn_file_actions_adddup2 (&actions, comp[0], 0)
316                  && !posix_spawn_file_actions_adddup2 (&actions, uncomp[1], 1)
317                  && !posix_spawnp (&p_sys->pid, path, &actions, NULL, argv,
318                                    environ))
319                 {
320                     if (vlc_clone (&p_sys->thread, Thread, stream,
321                                    VLC_THREAD_PRIORITY_INPUT) == 0)
322                         ret = VLC_SUCCESS;
323                 }
324                 else
325                 {
326                     msg_Err (stream, "Cannot execute %s", path);
327                     p_sys->pid = -1;
328                 }
329                 posix_spawn_file_actions_destroy (&actions);
330             }
331 #else /* _POSIX_SPAWN */
332             switch (p_sys->pid = fork ())
333             {
334                 case -1:
335                     msg_Err (stream, "Cannot fork (%m)");
336                     break;
337                 case 0:
338                     dup2 (comp[0], 0);
339                     dup2 (uncomp[1], 1);
340                     execlp (path, path, (char *)NULL);
341                     exit (1); /* if we get, execlp() failed! */
342                 default:
343                     if (vlc_clone (&p_sys->thread, Thread, stream,
344                                    VLC_THREAD_PRIORITY_INPUT) == 0)
345                         ret = VLC_SUCCESS;
346             }
347 #endif /* _POSIX_SPAWN < 0 */
348             close (uncomp[1]);
349             if (ret != VLC_SUCCESS)
350                 close (uncomp[0]);
351         }
352         close (comp[0]);
353         if (ret != VLC_SUCCESS)
354             close (comp[1]);
355     }
356
357     if (ret == VLC_SUCCESS)
358         return VLC_SUCCESS;
359
360     if (p_sys->pid != -1)
361         while (waitpid (p_sys->pid, &(int){ 0 }, 0) == -1);
362     free (p_sys);
363     return ret;
364 }
365
366
367 /**
368  * Releases allocate resources.
369  */
370 static void Close (vlc_object_t *obj)
371 {
372     stream_t *stream = (stream_t *)obj;
373     stream_sys_t *p_sys = stream->p_sys;
374     int status;
375
376     vlc_cancel (p_sys->thread);
377     close (p_sys->read_fd);
378     vlc_join (p_sys->thread, NULL);
379     if (p_sys->write_fd != -1)
380         /* Killed before EOF? */
381         close (p_sys->write_fd);
382
383     msg_Dbg (obj, "waiting for PID %u", (unsigned)p_sys->pid);
384     while (waitpid (p_sys->pid, &status, 0) == -1);
385     msg_Dbg (obj, "exit status %d", status);
386
387     if (p_sys->peeked)
388         block_Release (p_sys->peeked);
389     free (p_sys);
390 }
391
392
393 /**
394  * Detects gzip file format
395  */
396 static int OpenGzip (vlc_object_t *obj)
397 {
398     stream_t      *stream = (stream_t *)obj;
399     const uint8_t *peek;
400
401     if (stream_Peek (stream->p_source, &peek, 3) < 3)
402         return VLC_EGENERIC;
403
404     if (memcmp (peek, "\x1f\x8b\x08", 3))
405         return VLC_EGENERIC;
406
407     msg_Dbg (obj, "detected gzip compressed stream");
408     return Open (stream, "zcat");
409 }
410
411
412 /**
413  * Detects bzip2 file format
414  */
415 static int OpenBzip2 (vlc_object_t *obj)
416 {
417     stream_t      *stream = (stream_t *)obj;
418     const uint8_t *peek;
419
420     /* (Try to) parse the bzip2 header */
421     if (stream_Peek (stream->p_source, &peek, 10) < 10)
422         return VLC_EGENERIC;
423
424     if (memcmp (peek, "BZh", 3) || (peek[3] < '1') || (peek[3] > '9')
425      || memcmp (peek + 4, "\x31\x41\x59\x26\x53\x59", 6))
426         return VLC_EGENERIC;
427
428     msg_Dbg (obj, "detected bzip2 compressed stream");
429     return Open (stream, "bzcat");
430 }
431
432 /**
433  * Detects xz file format
434  */
435 static int OpenXZ (vlc_object_t *obj)
436 {
437     stream_t      *stream = (stream_t *)obj;
438     const uint8_t *peek;
439
440     /* (Try to) parse the xz stream header */
441     if (stream_Peek (stream->p_source, &peek, 8) < 8)
442         return VLC_EGENERIC;
443
444     if (memcmp (peek, "\xfd\x37\x7a\x58\x5a", 6))
445         return VLC_EGENERIC;
446
447     msg_Dbg (obj, "detected xz compressed stream");
448     return Open (stream, "xzcat");
449 }