Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / gst / gstpluginloader.c
1 /* GStreamer
2  * Copyright (C) 2008 Jan Schmidt <jan.schmidt@sun.com>
3  *
4  * gstpluginloader.c: GstPluginLoader helper for loading plugin files
5  * out of process.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include <gst/gst_private.h>
28
29 #ifndef G_OS_WIN32
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #else
36 #define fsync(fd) _commit(fd)
37 #include <io.h>
38 #endif
39
40 #include <errno.h>
41
42 #include <gst/gstconfig.h>
43
44 #include <gst/gstpoll.h>
45 #include <gst/gstutils.h>
46
47 #include <gst/gstpluginloader.h>
48 #include <gst/gstregistrychunks.h>
49 #include <gst/gstregistrybinary.h>
50
51 /* IMPORTANT: Bump the version number if the plugin loader packet protocol
52  * changes. Changes in the binary registry format itself are handled by
53  * bumping the GST_MAGIC_BINARY_VERSION_STR
54  */
55 static const guint32 loader_protocol_version = 3;
56
57 #define GST_CAT_DEFAULT GST_CAT_PLUGIN_LOADING
58
59 static GstPluginLoader *plugin_loader_new (GstRegistry * registry);
60 static gboolean plugin_loader_free (GstPluginLoader * loader);
61 static gboolean plugin_loader_load (GstPluginLoader * loader,
62     const gchar * filename, off_t file_size, time_t file_mtime);
63
64 /* functions used in GstRegistry scanning */
65 const GstPluginLoaderFuncs _priv_gst_plugin_loader_funcs = {
66   plugin_loader_new, plugin_loader_free, plugin_loader_load
67 };
68
69 typedef struct _PendingPluginEntry
70 {
71   /* sequence number */
72   guint32 tag;
73   gchar *filename;
74   off_t file_size;
75   time_t file_mtime;
76 } PendingPluginEntry;
77
78 struct _GstPluginLoader
79 {
80   GstRegistry *registry;
81   GstPoll *fdset;
82
83   gboolean child_running;
84   GPid child_pid;
85   GstPollFD fd_w;
86   GstPollFD fd_r;
87
88   gboolean is_child;
89   gboolean got_plugin_details;
90
91   /* Transmit buffer */
92   guint8 *tx_buf;
93   guint tx_buf_size;
94   guint tx_buf_write;
95   guint tx_buf_read;
96
97   /* next sequence number (for PendingPluginEntry) */
98   guint32 next_tag;
99
100   guint8 *rx_buf;
101   guint rx_buf_size;
102   gboolean rx_done;
103   gboolean rx_got_sync;
104
105   /* Head and tail of the pending plugins list. List of
106      PendingPluginEntry structs */
107   GList *pending_plugins;
108   GList *pending_plugins_tail;
109 };
110
111 #define PACKET_EXIT 1
112 #define PACKET_LOAD_PLUGIN 2
113 #define PACKET_SYNC 3
114 #define PACKET_PLUGIN_DETAILS 4
115 #define PACKET_VERSION 5
116
117 #define BUF_INIT_SIZE 512
118 #define BUF_GROW_EXTRA 512
119 #define BUF_MAX_SIZE (32 * 1024 * 1024)
120
121 #define HEADER_SIZE 12
122 /* 4 magic hex bytes to mark each packet */
123 #define HEADER_MAGIC 0xbefec0ae
124 #define ALIGNMENT   (sizeof (void *))
125
126 static gboolean gst_plugin_loader_spawn (GstPluginLoader * loader);
127 static void put_packet (GstPluginLoader * loader, guint type, guint32 tag,
128     const guint8 * payload, guint32 payload_len);
129 static gboolean exchange_packets (GstPluginLoader * l);
130 static gboolean plugin_loader_replay_pending (GstPluginLoader * l);
131 static gboolean plugin_loader_load_and_sync (GstPluginLoader * l,
132     PendingPluginEntry * entry);
133 static void plugin_loader_create_blacklist_plugin (GstPluginLoader * l,
134     PendingPluginEntry * entry);
135 static void plugin_loader_cleanup_child (GstPluginLoader * loader);
136 static gboolean plugin_loader_sync_with_child (GstPluginLoader * l);
137
138 static GstPluginLoader *
139 plugin_loader_new (GstRegistry * registry)
140 {
141   GstPluginLoader *l = g_slice_new0 (GstPluginLoader);
142
143   if (registry)
144     l->registry = gst_object_ref (registry);
145   l->fdset = gst_poll_new (FALSE);
146   gst_poll_fd_init (&l->fd_w);
147   gst_poll_fd_init (&l->fd_r);
148
149   l->tx_buf_size = BUF_INIT_SIZE;
150   l->tx_buf = g_malloc (BUF_INIT_SIZE);
151
152   l->next_tag = 0;
153
154   l->rx_buf_size = BUF_INIT_SIZE;
155   l->rx_buf = g_malloc (BUF_INIT_SIZE);
156
157   return l;
158 }
159
160 static gboolean
161 plugin_loader_free (GstPluginLoader * loader)
162 {
163   GList *cur;
164   gboolean got_plugin_details;
165
166   fsync (loader->fd_w.fd);
167
168   if (loader->child_running) {
169     put_packet (loader, PACKET_EXIT, 0, NULL, 0);
170
171     /* Swap packets with the child until it exits cleanly */
172     while (!loader->rx_done) {
173       if (exchange_packets (loader) || loader->rx_done)
174         continue;
175
176       if (!plugin_loader_replay_pending (loader))
177         break;
178       put_packet (loader, PACKET_EXIT, 0, NULL, 0);
179     }
180
181     plugin_loader_cleanup_child (loader);
182   } else {
183     close (loader->fd_w.fd);
184     close (loader->fd_r.fd);
185   }
186
187   gst_poll_free (loader->fdset);
188
189   g_free (loader->rx_buf);
190   g_free (loader->tx_buf);
191
192   if (loader->registry)
193     gst_object_unref (loader->registry);
194
195   got_plugin_details = loader->got_plugin_details;
196
197   /* Free any pending plugin entries */
198   cur = loader->pending_plugins;
199   while (cur) {
200     PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data);
201     g_free (entry->filename);
202     g_slice_free (PendingPluginEntry, entry);
203
204     cur = g_list_delete_link (cur, cur);
205   }
206
207   g_slice_free (GstPluginLoader, loader);
208
209   return got_plugin_details;
210 }
211
212 static gboolean
213 plugin_loader_load (GstPluginLoader * loader, const gchar * filename,
214     off_t file_size, time_t file_mtime)
215 {
216   gint len;
217   PendingPluginEntry *entry;
218
219   if (!gst_plugin_loader_spawn (loader))
220     return FALSE;
221
222   /* Send a packet to the child requesting that it load the given file */
223   GST_LOG_OBJECT (loader->registry,
224       "Sending file %s to child. tag %u", filename, loader->next_tag);
225
226   entry = g_slice_new (PendingPluginEntry);
227   entry->tag = loader->next_tag++;
228   entry->filename = g_strdup (filename);
229   entry->file_size = file_size;
230   entry->file_mtime = file_mtime;
231   loader->pending_plugins_tail =
232       g_list_append (loader->pending_plugins_tail, entry);
233
234   if (loader->pending_plugins == NULL)
235     loader->pending_plugins = loader->pending_plugins_tail;
236   else
237     loader->pending_plugins_tail = g_list_next (loader->pending_plugins_tail);
238
239   len = strlen (filename);
240   put_packet (loader, PACKET_LOAD_PLUGIN, entry->tag,
241       (guint8 *) filename, len + 1);
242
243   if (!exchange_packets (loader)) {
244     if (!plugin_loader_replay_pending (loader))
245       return FALSE;
246   }
247
248   return TRUE;
249 }
250
251 static gboolean
252 plugin_loader_replay_pending (GstPluginLoader * l)
253 {
254   GList *cur, *next;
255
256 restart:
257   if (!gst_plugin_loader_spawn (l))
258     return FALSE;
259
260   /* Load each plugin one by one synchronously until we find the
261    * crashing one */
262   while ((cur = l->pending_plugins)) {
263     PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data);
264
265     if (!plugin_loader_load_and_sync (l, entry)) {
266       /* Create dummy plugin entry to block re-scanning this file */
267       GST_ERROR ("Plugin file %s failed to load. Blacklisting",
268           entry->filename);
269       plugin_loader_create_blacklist_plugin (l, entry);
270       l->got_plugin_details = TRUE;
271       /* Now remove this crashy plugin from the head of the list */
272       l->pending_plugins = g_list_delete_link (cur, cur);
273       g_free (entry->filename);
274       g_slice_free (PendingPluginEntry, entry);
275       if (l->pending_plugins == NULL)
276         l->pending_plugins_tail = NULL;
277       if (!gst_plugin_loader_spawn (l))
278         return FALSE;
279       break;
280     }
281   }
282
283   /* We exited after finding the crashing one. If there's any more pending,
284    * dispatch them post-haste, but don't wait */
285   for (cur = l->pending_plugins; cur != NULL; cur = next) {
286     PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data);
287
288     next = g_list_next (cur);
289
290     put_packet (l, PACKET_LOAD_PLUGIN, entry->tag,
291         (guint8 *) entry->filename, strlen (entry->filename) + 1);
292
293     /* This might invalidate cur, which is why we grabbed 'next' above */
294     if (!exchange_packets (l))
295       goto restart;
296   }
297
298   return TRUE;
299 }
300
301 static gboolean
302 plugin_loader_sync_with_child (GstPluginLoader * l)
303 {
304   put_packet (l, PACKET_SYNC, 0, NULL, 0);
305
306   l->rx_got_sync = FALSE;
307   while (!l->rx_got_sync) {
308     if (!exchange_packets (l))
309       return FALSE;
310   }
311   return TRUE;
312 }
313
314 static gboolean
315 plugin_loader_load_and_sync (GstPluginLoader * l, PendingPluginEntry * entry)
316 {
317   gint len;
318
319   GST_DEBUG_OBJECT (l->registry, "Synchronously loading plugin file %s",
320       entry->filename);
321
322   len = strlen (entry->filename);
323   put_packet (l, PACKET_LOAD_PLUGIN, entry->tag,
324       (guint8 *) entry->filename, len + 1);
325
326   return plugin_loader_sync_with_child (l);
327 }
328
329 static void
330 plugin_loader_create_blacklist_plugin (GstPluginLoader * l,
331     PendingPluginEntry * entry)
332 {
333   GstPlugin *plugin = g_object_newv (GST_TYPE_PLUGIN, 0, NULL);
334
335   plugin->filename = g_strdup (entry->filename);
336   plugin->file_mtime = entry->file_mtime;
337   plugin->file_size = entry->file_size;
338   plugin->flags |= GST_PLUGIN_FLAG_BLACKLISTED;
339
340   plugin->basename = g_path_get_basename (plugin->filename);
341   plugin->desc.name = g_intern_string (plugin->basename);
342   plugin->desc.description = "Plugin for blacklisted file";
343   plugin->desc.version = "0.0.0";
344   plugin->desc.license = "BLACKLIST";
345   plugin->desc.source = plugin->desc.license;
346   plugin->desc.package = plugin->desc.license;
347   plugin->desc.origin = plugin->desc.license;
348
349   GST_DEBUG ("Adding blacklist plugin '%s'", plugin->desc.name);
350   gst_registry_add_plugin (l->registry, plugin);
351 }
352
353 static gboolean
354 gst_plugin_loader_try_helper (GstPluginLoader * loader, gchar * location)
355 {
356 #ifdef __APPLE__
357 #if defined(__x86_64__)
358   char *argv[] = { (char *) "/usr/bin/arch", (char *) "-x86_64",
359     location, (char *) "-l", NULL
360   };
361 #elif defined(__i386__)
362   char *argv[] = { (char *) "/usr/bin/arch", (char *) "-i386",
363     location, (char *) "-l", NULL
364   };
365 #elif defined(__ppc__)
366   char *argv[] = { (char *) "/usr/bin/arch", (char *) "-ppc",
367     location, (char *) "-l", NULL
368   };
369 #elif defined(__ppc64__)
370   char *argv[] = { (char *) "/usr/bin/arch", (char *) "-ppc64",
371     location, (char *) "-l", NULL
372   };
373 #endif
374 #else /* ! __APPLE__ */
375   char *argv[] = { location, (char *) "-l", NULL };
376 #endif
377
378
379 #ifdef __APPLE__
380   GST_LOG ("Trying to spawn gst-plugin-scanner helper at %s with arch %s",
381       location, argv[1]);
382 #else
383   GST_LOG ("Trying to spawn gst-plugin-scanner helper at %s", location);
384 #endif
385
386   if (!g_spawn_async_with_pipes (NULL, argv, NULL,
387           G_SPAWN_DO_NOT_REAP_CHILD /* | G_SPAWN_STDERR_TO_DEV_NULL */ ,
388           NULL, NULL, &loader->child_pid, &loader->fd_w.fd, &loader->fd_r.fd,
389           NULL, NULL))
390     return FALSE;
391
392   gst_poll_add_fd (loader->fdset, &loader->fd_w);
393   gst_poll_add_fd (loader->fdset, &loader->fd_r);
394
395   gst_poll_fd_ctl_read (loader->fdset, &loader->fd_r, TRUE);
396
397   loader->tx_buf_write = loader->tx_buf_read = 0;
398
399   put_packet (loader, PACKET_VERSION, 0, NULL, 0);
400   if (!plugin_loader_sync_with_child (loader))
401     return FALSE;
402
403   loader->child_running = TRUE;
404
405   return TRUE;
406 }
407
408 static gboolean
409 gst_plugin_loader_spawn (GstPluginLoader * loader)
410 {
411   const gchar *env;
412   char *helper_bin;
413   gboolean res = FALSE;
414
415   if (loader->child_running)
416     return TRUE;
417
418   /* Find the gst-plugin-scanner: first try the env-var if it is set,
419    * otherwise use the installed version */
420   env = g_getenv ("GST_PLUGIN_SCANNER");
421
422   if (env != NULL && *env != '\0') {
423     GST_LOG ("Trying GST_PLUGIN_SCANNER env var: %s", env);
424     helper_bin = g_strdup (env);
425     res = gst_plugin_loader_try_helper (loader, helper_bin);
426     g_free (helper_bin);
427   }
428
429   if (!res) {
430     GST_LOG ("Trying installed plugin scanner");
431     helper_bin = g_strdup (GST_PLUGIN_SCANNER_INSTALLED);
432     res = gst_plugin_loader_try_helper (loader, helper_bin);
433     g_free (helper_bin);
434
435     if (!res) {
436       GST_INFO ("No gst-plugin-scanner available, or not working");
437     }
438   }
439
440   return loader->child_running;
441 }
442
443 static void
444 plugin_loader_cleanup_child (GstPluginLoader * l)
445 {
446   if (!l->child_running || l->is_child)
447     return;
448
449   gst_poll_remove_fd (l->fdset, &l->fd_w);
450   gst_poll_remove_fd (l->fdset, &l->fd_r);
451
452   close (l->fd_w.fd);
453   close (l->fd_r.fd);
454
455 #ifndef G_OS_WIN32
456   GST_LOG ("waiting for child process to exit");
457   waitpid (l->child_pid, NULL, 0);
458 #else
459   g_warning ("FIXME: Implement child process shutdown for Win32");
460 #endif
461   g_spawn_close_pid (l->child_pid);
462
463   l->child_running = FALSE;
464 }
465
466 gboolean
467 _gst_plugin_loader_client_run (void)
468 {
469   GstPluginLoader *l;
470
471   l = plugin_loader_new (NULL);
472   if (l == NULL)
473     return FALSE;
474
475   /* On entry, the inward pipe is STDIN, and outward is STDOUT.
476    * Dup those somewhere better so that plugins printing things
477    * won't interfere with anything */
478 #ifndef G_OS_WIN32
479   {
480     int dup_fd;
481
482     dup_fd = dup (0);           /* STDIN */
483     if (dup_fd == -1) {
484       GST_ERROR ("Failed to start. Could no dup STDIN, errno %d", errno);
485       return FALSE;
486     }
487     l->fd_r.fd = dup_fd;
488     close (0);
489
490     dup_fd = dup (1);           /* STDOUT */
491     if (dup_fd == -1) {
492       GST_ERROR ("Failed to start. Could no dup STDOUT, errno %d", errno);
493       return FALSE;
494     }
495     l->fd_w.fd = dup_fd;
496     close (1);
497
498     /* Dup stderr down to stdout so things that plugins print are visible,
499      * but don't care if it fails */
500     dup2 (2, 1);
501   }
502 #else
503   /* FIXME: Use DuplicateHandle and friends on win32 */
504   l->fd_w.fd = 1;               /* STDOUT */
505   l->fd_r.fd = 0;               /* STDIN */
506 #endif
507
508   gst_poll_add_fd (l->fdset, &l->fd_w);
509   gst_poll_add_fd (l->fdset, &l->fd_r);
510   gst_poll_fd_ctl_read (l->fdset, &l->fd_r, TRUE);
511
512   l->is_child = TRUE;
513
514   GST_DEBUG ("Plugin scanner child running. Waiting for instructions");
515
516   /* Loop, listening for incoming packets on the fd and writing responses */
517   while (!l->rx_done && exchange_packets (l));
518
519   plugin_loader_free (l);
520
521   return TRUE;
522 }
523
524 static void
525 put_packet (GstPluginLoader * l, guint type, guint32 tag,
526     const guint8 * payload, guint32 payload_len)
527 {
528   guint8 *out;
529   guint len = payload_len + HEADER_SIZE;
530
531   if (l->tx_buf_write + len >= l->tx_buf_size) {
532     GST_LOG ("Expanding tx buf from %d to %d for packet of size %d",
533         l->tx_buf_size, l->tx_buf_write + len + BUF_GROW_EXTRA, len);
534     l->tx_buf_size = l->tx_buf_write + len + BUF_GROW_EXTRA;
535     l->tx_buf = g_realloc (l->tx_buf, l->tx_buf_size);
536   }
537
538   out = l->tx_buf + l->tx_buf_write;
539
540   /* one byte packet type */
541   out[0] = type;
542   /* 3 byte packet tag number */
543   GST_WRITE_UINT24_BE (out + 1, tag);
544   /* 4 bytes packet length */
545   GST_WRITE_UINT32_BE (out + 4, payload_len);
546   /* payload */
547   memcpy (out + HEADER_SIZE, payload, payload_len);
548   /* Write magic into the header */
549   GST_WRITE_UINT32_BE (out + 8, HEADER_MAGIC);
550
551   l->tx_buf_write += len;
552   gst_poll_fd_ctl_write (l->fdset, &l->fd_w, TRUE);
553 }
554
555 static void
556 put_chunk (GstPluginLoader * l, GstRegistryChunk * chunk, guint * pos)
557 {
558   guint padsize = 0;
559   guint len;
560   guint8 *out;
561
562   /* Might need to align the chunk */
563   if (chunk->align && ((*pos) % ALIGNMENT) != 0)
564     padsize = ALIGNMENT - ((*pos) % ALIGNMENT);
565
566   len = padsize + chunk->size;
567
568   if (G_UNLIKELY (l->tx_buf_write + len >= l->tx_buf_size)) {
569     guint new_size = MAX (l->tx_buf_write + len,
570         l->tx_buf_size + l->tx_buf_size / 4) + BUF_GROW_EXTRA;
571     GST_LOG ("Expanding tx buf from %d to %d for chunk of size %d",
572         l->tx_buf_size, new_size, chunk->size);
573     l->tx_buf_size = new_size;
574     l->tx_buf = g_realloc (l->tx_buf, l->tx_buf_size);
575   }
576
577   out = l->tx_buf + l->tx_buf_write;
578   /* Clear the padding */
579   if (padsize)
580     memset (out, 0, padsize);
581   memcpy (out + padsize, chunk->data, chunk->size);
582
583   l->tx_buf_write += len;
584   *pos += len;
585
586   gst_poll_fd_ctl_write (l->fdset, &l->fd_w, TRUE);
587 };
588
589 static gboolean
590 write_one (GstPluginLoader * l)
591 {
592   guint8 *out;
593   guint32 to_write, magic;
594   int res;
595
596   if (l->tx_buf_read + HEADER_SIZE > l->tx_buf_write)
597     return FALSE;
598
599   out = l->tx_buf + l->tx_buf_read;
600
601   magic = GST_READ_UINT32_BE (out + 8);
602   if (magic != HEADER_MAGIC) {
603     GST_ERROR ("Packet magic number is missing. Memory corruption detected");
604     goto fail_and_cleanup;
605   }
606
607   to_write = GST_READ_UINT32_BE (out + 4) + HEADER_SIZE;
608   /* Check that the magic is intact, and the size is sensible */
609   if (to_write > l->tx_buf_size) {
610     GST_ERROR ("Indicated packet size is too large. Corruption detected");
611     goto fail_and_cleanup;
612   }
613
614   l->tx_buf_read += to_write;
615
616   GST_LOG ("Writing packet of size %d bytes to fd %d", to_write, l->fd_w.fd);
617
618   do {
619     res = write (l->fd_w.fd, out, to_write);
620     if (G_UNLIKELY (res < 0)) {
621       if (errno == EAGAIN || errno == EINTR)
622         continue;
623       /* Failed to write -> child died */
624       goto fail_and_cleanup;
625     }
626     to_write -= res;
627     out += res;
628   } while (to_write > 0);
629
630   if (l->tx_buf_read == l->tx_buf_write) {
631     gst_poll_fd_ctl_write (l->fdset, &l->fd_w, FALSE);
632     l->tx_buf_read = l->tx_buf_write = 0;
633   }
634
635   return TRUE;
636
637 fail_and_cleanup:
638   plugin_loader_cleanup_child (l);
639   return FALSE;
640 }
641
642 static gboolean
643 do_plugin_load (GstPluginLoader * l, const gchar * filename, guint tag)
644 {
645   GstPlugin *newplugin;
646   GList *chunks = NULL;
647
648   GST_DEBUG ("Plugin scanner loading file %s. tag %u", filename, tag);
649
650 #if 0                           /* Test code - crash based on filename */
651   if (strstr (filename, "coreelements") == NULL) {
652     g_printerr ("Crashing on file %s\n", filename);
653     g_printerr ("%d", *(gint *) (NULL));
654   }
655 #endif
656
657   newplugin = gst_plugin_load_file ((gchar *) filename, NULL);
658   if (newplugin) {
659     guint hdr_pos;
660     guint offset;
661
662     /* Now serialise the plugin details and send */
663     if (!_priv_gst_registry_chunks_save_plugin (&chunks,
664             gst_registry_get_default (), newplugin))
665       goto fail;
666
667     /* Store where the header is, write an empty one, then write
668      * all the payload chunks, then fix up the header size */
669     hdr_pos = l->tx_buf_write;
670     offset = HEADER_SIZE;
671     put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0);
672
673     if (chunks) {
674       GList *walk;
675       for (walk = chunks; walk; walk = g_list_next (walk)) {
676         GstRegistryChunk *cur = walk->data;
677         put_chunk (l, cur, &offset);
678
679         _priv_gst_registry_chunk_free (cur);
680       }
681
682       g_list_free (chunks);
683
684       /* Store the size of the written payload */
685       GST_WRITE_UINT32_BE (l->tx_buf + hdr_pos + 4, offset - HEADER_SIZE);
686     }
687 #if 0                           /* Test code - corrupt the tx buffer based on filename */
688     if (strstr (filename, "sink") != NULL) {
689       int fd, res;
690       g_printerr ("Corrupting tx buf on file %s\n", filename);
691       fd = open ("/dev/urandom", O_RDONLY);
692       res = read (fd, l->tx_buf, l->tx_buf_size);
693       close (fd);
694     }
695 #endif
696
697     gst_object_unref (newplugin);
698   } else {
699     put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0);
700   }
701
702   return TRUE;
703 fail:
704   put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0);
705   if (chunks) {
706     GList *walk;
707     for (walk = chunks; walk; walk = g_list_next (walk)) {
708       GstRegistryChunk *cur = walk->data;
709
710       _priv_gst_registry_chunk_free (cur);
711     }
712
713     g_list_free (chunks);
714   }
715
716   return FALSE;
717 }
718
719 static gboolean
720 check_protocol_version (GstPluginLoader * l, guint8 * payload,
721     guint payload_len)
722 {
723   guint32 got_version;
724   guint8 *binary_reg_ver;
725
726   if (payload_len < sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN)
727     return FALSE;
728
729   got_version = GST_READ_UINT32_BE (payload);
730   GST_LOG ("Got VERSION %u from child. Ours is %u", got_version,
731       loader_protocol_version);
732   if (got_version != loader_protocol_version)
733     return FALSE;
734
735   binary_reg_ver = payload + sizeof (guint32);
736   if (strcmp ((gchar *) binary_reg_ver, GST_MAGIC_BINARY_VERSION_STR)) {
737     GST_LOG ("Binary chunk format of child is different. Ours: %s, child %s\n",
738         GST_MAGIC_BINARY_VERSION_STR, binary_reg_ver);
739     return FALSE;
740   }
741
742   return TRUE;
743 };
744
745 static gboolean
746 handle_rx_packet (GstPluginLoader * l,
747     guint pack_type, guint32 tag, guint8 * payload, guint payload_len)
748 {
749   gboolean res = TRUE;
750
751   switch (pack_type) {
752     case PACKET_EXIT:
753       gst_poll_fd_ctl_read (l->fdset, &l->fd_r, FALSE);
754       if (l->is_child) {
755         /* Respond */
756         put_packet (l, PACKET_EXIT, 0, NULL, 0);
757       }
758       l->rx_done = TRUE;
759       return TRUE;
760     case PACKET_LOAD_PLUGIN:{
761       if (!l->is_child)
762         return TRUE;
763
764       /* Payload is the filename to load */
765       res = do_plugin_load (l, (gchar *) payload, tag);
766
767       break;
768     }
769     case PACKET_PLUGIN_DETAILS:{
770       gchar *tmp = (gchar *) payload;
771       PendingPluginEntry *entry = NULL;
772       GList *cur;
773
774       GST_DEBUG_OBJECT (l->registry,
775           "Received plugin details from child w/ tag %u. %d bytes info",
776           tag, payload_len);
777
778       /* Assume that tagged details come back in the order
779        * we requested, and delete anything before (but not
780        * including) this one */
781       cur = l->pending_plugins;
782       while (cur) {
783         PendingPluginEntry *e = (PendingPluginEntry *) (cur->data);
784
785         if (e->tag > tag)
786           break;
787
788         if (e->tag == tag) {
789           entry = e;
790           break;
791         } else {
792           cur = g_list_delete_link (cur, cur);
793           g_free (e->filename);
794           g_slice_free (PendingPluginEntry, e);
795         }
796       }
797
798       l->pending_plugins = cur;
799       if (cur == NULL)
800         l->pending_plugins_tail = NULL;
801
802       if (payload_len > 0) {
803         GstPlugin *newplugin = NULL;
804         if (!_priv_gst_registry_chunks_load_plugin (l->registry, &tmp,
805                 tmp + payload_len, &newplugin)) {
806           /* Got garbage from the child, so fail and trigger replay of plugins */
807           GST_ERROR_OBJECT (l->registry,
808               "Problems loading plugin details with tag %u from scanner", tag);
809           return FALSE;
810         }
811
812         newplugin->flags &= ~GST_PLUGIN_FLAG_CACHED;
813         GST_LOG_OBJECT (l->registry,
814             "marking plugin %p as registered as %s", newplugin,
815             newplugin->filename);
816         newplugin->registered = TRUE;
817
818         /* We got a set of plugin details - remember it for later */
819         l->got_plugin_details = TRUE;
820       } else if (entry != NULL) {
821         /* Create a blacklist entry for this file to prevent scanning every time */
822         plugin_loader_create_blacklist_plugin (l, entry);
823         l->got_plugin_details = TRUE;
824       }
825
826       if (entry != NULL) {
827         g_free (entry->filename);
828         g_slice_free (PendingPluginEntry, entry);
829       }
830
831       /* Remove the plugin entry we just loaded */
832       cur = l->pending_plugins;
833       if (cur != NULL)
834         cur = g_list_delete_link (cur, cur);
835       l->pending_plugins = cur;
836       if (cur == NULL)
837         l->pending_plugins_tail = NULL;
838
839       break;
840     }
841     case PACKET_SYNC:
842       if (l->is_child) {
843         /* Respond with our reply - also a sync */
844         put_packet (l, PACKET_SYNC, tag, NULL, 0);
845         GST_LOG ("Got SYNC in child - replying");
846       } else
847         l->rx_got_sync = TRUE;
848       break;
849     case PACKET_VERSION:
850       if (l->is_child) {
851         /* Respond with our reply - a version packet, with the version */
852         const gint version_len =
853             sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN;
854         guint8 version_info[sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN];
855         memset (version_info, 0, version_len);
856         GST_WRITE_UINT32_BE (version_info, loader_protocol_version);
857         memcpy (version_info + sizeof (guint32), GST_MAGIC_BINARY_VERSION_STR,
858             strlen (GST_MAGIC_BINARY_VERSION_STR));
859         put_packet (l, PACKET_VERSION, tag, version_info, version_len);
860         GST_LOG ("Got VERSION in child - replying %u", loader_protocol_version);
861       } else {
862         res = check_protocol_version (l, payload, payload_len);
863       }
864       break;
865     default:
866       return FALSE;             /* Invalid packet -> something is wrong */
867   }
868
869   return res;
870 }
871
872 static gboolean
873 read_one (GstPluginLoader * l)
874 {
875   guint64 magic;
876   guint32 to_read, packet_len, tag;
877   guint8 *in;
878   gint res;
879
880   to_read = HEADER_SIZE;
881   in = l->rx_buf;
882   do {
883     res = read (l->fd_r.fd, in, to_read);
884     if (G_UNLIKELY (res < 0)) {
885       if (errno == EAGAIN || errno == EINTR)
886         continue;
887       GST_LOG ("Failed reading packet header");
888       return FALSE;
889     }
890     to_read -= res;
891     in += res;
892   } while (to_read > 0);
893
894   magic = GST_READ_UINT32_BE (l->rx_buf + 8);
895   if (magic != HEADER_MAGIC) {
896     GST_WARNING
897         ("Invalid packet (bad magic number) received from plugin scanner subprocess");
898     return FALSE;
899   }
900
901   packet_len = GST_READ_UINT32_BE (l->rx_buf + 4);
902   if (packet_len + HEADER_SIZE > BUF_MAX_SIZE) {
903     GST_WARNING
904         ("Received excessively large packet for plugin scanner subprocess");
905     return FALSE;
906   }
907   tag = GST_READ_UINT24_BE (l->rx_buf + 1);
908
909   if (packet_len > 0) {
910     if (packet_len + HEADER_SIZE >= l->rx_buf_size) {
911       GST_LOG ("Expanding rx buf from %d to %d",
912           l->rx_buf_size, packet_len + HEADER_SIZE + BUF_GROW_EXTRA);
913       l->rx_buf_size = packet_len + HEADER_SIZE + BUF_GROW_EXTRA;
914       l->rx_buf = g_realloc (l->rx_buf, l->rx_buf_size);
915     }
916
917     in = l->rx_buf + HEADER_SIZE;
918     to_read = packet_len;
919     do {
920       res = read (l->fd_r.fd, in, to_read);
921       if (G_UNLIKELY (res < 0)) {
922         if (errno == EAGAIN || errno == EINTR)
923           continue;
924         GST_ERROR ("Packet payload read failed");
925         return FALSE;
926       }
927       to_read -= res;
928       in += res;
929     } while (to_read > 0);
930   } else {
931     GST_LOG ("No payload to read for 0 length packet type %d tag %u",
932         l->rx_buf[0], tag);
933   }
934
935   return handle_rx_packet (l, l->rx_buf[0], tag,
936       l->rx_buf + HEADER_SIZE, packet_len);
937 }
938
939 static gboolean
940 exchange_packets (GstPluginLoader * l)
941 {
942   gint res;
943
944   /* Wait for activity on our FDs */
945   do {
946     do {
947       res = gst_poll_wait (l->fdset, GST_SECOND);
948     } while (res == -1 && (errno == EINTR || errno == EAGAIN));
949
950     if (res < 0)
951       return FALSE;
952
953     GST_LOG ("Poll res = %d. %d bytes pending for write", res,
954         l->tx_buf_write - l->tx_buf_read);
955
956     if (!l->rx_done) {
957       if (gst_poll_fd_has_error (l->fdset, &l->fd_r) ||
958           gst_poll_fd_has_closed (l->fdset, &l->fd_r)) {
959         GST_LOG ("read fd %d closed/errored", l->fd_r.fd);
960         goto fail_and_cleanup;
961       }
962
963       if (gst_poll_fd_can_read (l->fdset, &l->fd_r)) {
964         if (!read_one (l))
965           goto fail_and_cleanup;
966       }
967     }
968
969     if (l->tx_buf_read < l->tx_buf_write) {
970       if (gst_poll_fd_has_error (l->fdset, &l->fd_w) ||
971           gst_poll_fd_has_closed (l->fdset, &l->fd_r)) {
972         GST_ERROR ("write fd %d closed/errored", l->fd_w.fd);
973         goto fail_and_cleanup;
974       }
975       if (gst_poll_fd_can_write (l->fdset, &l->fd_w)) {
976         if (!write_one (l))
977           goto fail_and_cleanup;
978       }
979     }
980   } while (l->tx_buf_read < l->tx_buf_write);
981
982   return TRUE;
983 fail_and_cleanup:
984   plugin_loader_cleanup_child (l);
985   return FALSE;
986 }