comments: add a few comments to the sparsely documented plugin loader
[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       if (l->pending_plugins == NULL)
274         l->pending_plugins_tail = NULL;
275       if (!gst_plugin_loader_spawn (l))
276         return FALSE;
277       break;
278     }
279   }
280
281   /* We exited after finding the crashing one. If there's any more pending,
282    * dispatch them post-haste, but don't wait */
283   for (cur = l->pending_plugins; cur != NULL; cur = next) {
284     PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data);
285
286     next = g_list_next (cur);
287
288     put_packet (l, PACKET_LOAD_PLUGIN, entry->tag,
289         (guint8 *) entry->filename, strlen (entry->filename) + 1);
290
291     /* This might invalidate cur, which is why we grabbed 'next' above */
292     if (!exchange_packets (l))
293       goto restart;
294   }
295
296   return TRUE;
297 }
298
299 static gboolean
300 plugin_loader_sync_with_child (GstPluginLoader * l)
301 {
302   put_packet (l, PACKET_SYNC, 0, NULL, 0);
303
304   l->rx_got_sync = FALSE;
305   while (!l->rx_got_sync) {
306     if (!exchange_packets (l))
307       return FALSE;
308   }
309   return TRUE;
310 }
311
312 static gboolean
313 plugin_loader_load_and_sync (GstPluginLoader * l, PendingPluginEntry * entry)
314 {
315   gint len;
316
317   GST_DEBUG_OBJECT (l->registry, "Synchronously loading plugin file %s",
318       entry->filename);
319
320   len = strlen (entry->filename);
321   put_packet (l, PACKET_LOAD_PLUGIN, entry->tag,
322       (guint8 *) entry->filename, len + 1);
323
324   return plugin_loader_sync_with_child (l);
325 }
326
327 static void
328 plugin_loader_create_blacklist_plugin (GstPluginLoader * l,
329     PendingPluginEntry * entry)
330 {
331   GstPlugin *plugin = g_object_newv (GST_TYPE_PLUGIN, 0, NULL);
332
333   plugin->filename = g_strdup (entry->filename);
334   plugin->file_mtime = entry->file_mtime;
335   plugin->file_size = entry->file_size;
336   plugin->flags |= GST_PLUGIN_FLAG_BLACKLISTED;
337
338   plugin->basename = g_path_get_basename (plugin->filename);
339   plugin->desc.name = g_intern_string (plugin->basename);
340   plugin->desc.description = g_strdup_printf ("Plugin for blacklisted file");
341   plugin->desc.version = g_intern_string ("0.0.0");
342   plugin->desc.license = g_intern_string ("BLACKLIST");
343   plugin->desc.source = plugin->desc.license;
344   plugin->desc.package = plugin->desc.license;
345   plugin->desc.origin = plugin->desc.license;
346
347   GST_DEBUG ("Adding blacklist plugin '%s'", plugin->desc.name);
348   gst_registry_add_plugin (l->registry, plugin);
349 }
350
351 static gboolean
352 gst_plugin_loader_try_helper (GstPluginLoader * loader, gchar * location)
353 {
354   char *argv[] = { location, (char *) "-l", NULL };
355
356   GST_LOG ("Trying to spawn gst-plugin-scanner helper at %s", location);
357   if (!g_spawn_async_with_pipes (NULL, argv, NULL,
358           G_SPAWN_DO_NOT_REAP_CHILD /* | G_SPAWN_STDERR_TO_DEV_NULL */ ,
359           NULL, NULL, &loader->child_pid, &loader->fd_w.fd, &loader->fd_r.fd,
360           NULL, NULL))
361     return FALSE;
362
363   gst_poll_add_fd (loader->fdset, &loader->fd_w);
364   gst_poll_add_fd (loader->fdset, &loader->fd_r);
365
366   gst_poll_fd_ctl_read (loader->fdset, &loader->fd_r, TRUE);
367
368   loader->tx_buf_write = loader->tx_buf_read = 0;
369
370   put_packet (loader, PACKET_VERSION, 0, NULL, 0);
371   if (!plugin_loader_sync_with_child (loader))
372     return FALSE;
373
374   loader->child_running = TRUE;
375
376   return TRUE;
377 }
378
379 static gboolean
380 gst_plugin_loader_spawn (GstPluginLoader * loader)
381 {
382   const gchar *env;
383   char *helper_bin;
384   gboolean res = FALSE;
385
386   if (loader->child_running)
387     return TRUE;
388
389   /* Find the gst-plugin-scanner: first try the env-var if it is set,
390    * otherwise use the installed version */
391   env = g_getenv ("GST_PLUGIN_SCANNER");
392
393   if (env != NULL && *env != '\0') {
394     GST_LOG ("Trying GST_PLUGIN_SCANNER env var: %s", env);
395     helper_bin = g_strdup (env);
396     res = gst_plugin_loader_try_helper (loader, helper_bin);
397     g_free (helper_bin);
398   }
399
400   if (!res) {
401     GST_LOG ("Trying installed plugin scanner");
402     helper_bin = g_strdup (GST_PLUGIN_SCANNER_INSTALLED);
403     res = gst_plugin_loader_try_helper (loader, helper_bin);
404     g_free (helper_bin);
405
406     if (!res) {
407       GST_INFO ("No gst-plugin-scanner available, or not working");
408     }
409   }
410
411   return loader->child_running;
412 }
413
414 static void
415 plugin_loader_cleanup_child (GstPluginLoader * l)
416 {
417   if (!l->child_running || l->is_child)
418     return;
419
420   gst_poll_remove_fd (l->fdset, &l->fd_w);
421   gst_poll_remove_fd (l->fdset, &l->fd_r);
422
423   close (l->fd_w.fd);
424   close (l->fd_r.fd);
425
426 #ifndef G_OS_WIN32
427   GST_LOG ("waiting for child process to exit");
428   waitpid (l->child_pid, NULL, 0);
429 #else
430   g_warning ("FIXME: Implement child process shutdown for Win32");
431 #endif
432   g_spawn_close_pid (l->child_pid);
433
434   l->child_running = FALSE;
435 }
436
437 gboolean
438 _gst_plugin_loader_client_run (void)
439 {
440   GstPluginLoader *l;
441
442   l = plugin_loader_new (NULL);
443   if (l == NULL)
444     return FALSE;
445
446   /* On entry, the inward pipe is STDIN, and outward is STDOUT.
447    * Dup those somewhere better so that plugins printing things
448    * won't interfere with anything */
449 #ifndef G_OS_WIN32
450   {
451     int dup_fd;
452
453     dup_fd = dup (0);           /* STDIN */
454     if (dup_fd == -1) {
455       GST_ERROR ("Failed to start. Could no dup STDIN, errno %d", errno);
456       return FALSE;
457     }
458     l->fd_r.fd = dup_fd;
459     close (0);
460
461     dup_fd = dup (1);           /* STDOUT */
462     if (dup_fd == -1) {
463       GST_ERROR ("Failed to start. Could no dup STDOUT, errno %d", errno);
464       return FALSE;
465     }
466     l->fd_w.fd = dup_fd;
467     close (1);
468
469     /* Dup stderr down to stdout so things that plugins print are visible,
470      * but don't care if it fails */
471     dup2 (2, 1);
472   }
473 #else
474   /* FIXME: Use DuplicateHandle and friends on win32 */
475   l->fd_w.fd = 1;               /* STDOUT */
476   l->fd_r.fd = 0;               /* STDIN */
477 #endif
478
479   gst_poll_add_fd (l->fdset, &l->fd_w);
480   gst_poll_add_fd (l->fdset, &l->fd_r);
481   gst_poll_fd_ctl_read (l->fdset, &l->fd_r, TRUE);
482
483   l->is_child = TRUE;
484
485   GST_DEBUG ("Plugin scanner child running. Waiting for instructions");
486
487   /* Loop, listening for incoming packets on the fd and writing responses */
488   while (!l->rx_done && exchange_packets (l));
489
490   plugin_loader_free (l);
491
492   return TRUE;
493 }
494
495 static void
496 put_packet (GstPluginLoader * l, guint type, guint32 tag,
497     const guint8 * payload, guint32 payload_len)
498 {
499   guint8 *out;
500   guint len = payload_len + HEADER_SIZE;
501
502   if (l->tx_buf_write + len >= l->tx_buf_size) {
503     GST_LOG ("Expanding tx buf from %d to %d for packet of size %d",
504         l->tx_buf_size, l->tx_buf_write + len + BUF_GROW_EXTRA, len);
505     l->tx_buf_size = l->tx_buf_write + len + BUF_GROW_EXTRA;
506     l->tx_buf = g_realloc (l->tx_buf, l->tx_buf_size);
507   }
508
509   out = l->tx_buf + l->tx_buf_write;
510
511   /* one byte packet type */
512   out[0] = type;
513   /* 3 byte packet tag number */
514   GST_WRITE_UINT24_BE (out + 1, tag);
515   /* 4 bytes packet length */
516   GST_WRITE_UINT32_BE (out + 4, payload_len);
517   /* payload */
518   memcpy (out + HEADER_SIZE, payload, payload_len);
519   /* Write magic into the header */
520   GST_WRITE_UINT32_BE (out + 8, HEADER_MAGIC);
521
522   l->tx_buf_write += len;
523   gst_poll_fd_ctl_write (l->fdset, &l->fd_w, TRUE);
524 }
525
526 static void
527 put_chunk (GstPluginLoader * l, GstRegistryChunk * chunk, guint * pos)
528 {
529   guint padsize = 0;
530   guint len;
531   guint8 *out;
532
533   /* Might need to align the chunk */
534   if (chunk->align && ((*pos) % ALIGNMENT) != 0)
535     padsize = ALIGNMENT - ((*pos) % ALIGNMENT);
536
537   len = padsize + chunk->size;
538
539   if (G_UNLIKELY (l->tx_buf_write + len >= l->tx_buf_size)) {
540     guint new_size = MAX (l->tx_buf_write + len,
541         l->tx_buf_size + l->tx_buf_size / 4) + BUF_GROW_EXTRA;
542     GST_LOG ("Expanding tx buf from %d to %d for chunk of size %d",
543         l->tx_buf_size, new_size, chunk->size);
544     l->tx_buf_size = new_size;
545     l->tx_buf = g_realloc (l->tx_buf, l->tx_buf_size);
546   }
547
548   out = l->tx_buf + l->tx_buf_write;
549   /* Clear the padding */
550   if (padsize)
551     memset (out, 0, padsize);
552   memcpy (out + padsize, chunk->data, chunk->size);
553
554   l->tx_buf_write += len;
555   *pos += len;
556
557   gst_poll_fd_ctl_write (l->fdset, &l->fd_w, TRUE);
558 };
559
560 static gboolean
561 write_one (GstPluginLoader * l)
562 {
563   guint8 *out;
564   guint32 to_write, magic;
565   int res;
566
567   if (l->tx_buf_read + HEADER_SIZE > l->tx_buf_write)
568     return FALSE;
569
570   out = l->tx_buf + l->tx_buf_read;
571
572   magic = GST_READ_UINT32_BE (out + 8);
573   if (magic != HEADER_MAGIC) {
574     GST_ERROR ("Packet magic number is missing. Memory corruption detected");
575     goto fail_and_cleanup;
576   }
577
578   to_write = GST_READ_UINT32_BE (out + 4) + HEADER_SIZE;
579   /* Check that the magic is intact, and the size is sensible */
580   if (to_write > l->tx_buf_size) {
581     GST_ERROR ("Indicated packet size is too large. Corruption detected");
582     goto fail_and_cleanup;
583   }
584
585   l->tx_buf_read += to_write;
586
587   GST_LOG ("Writing packet of size %d bytes to fd %d", to_write, l->fd_w.fd);
588
589   do {
590     res = write (l->fd_w.fd, out, to_write);
591     if (G_UNLIKELY (res < 0)) {
592       if (errno == EAGAIN || errno == EINTR)
593         continue;
594       /* Failed to write -> child died */
595       goto fail_and_cleanup;
596     }
597     to_write -= res;
598     out += res;
599   } while (to_write > 0);
600
601   if (l->tx_buf_read == l->tx_buf_write) {
602     gst_poll_fd_ctl_write (l->fdset, &l->fd_w, FALSE);
603     l->tx_buf_read = l->tx_buf_write = 0;
604   }
605
606   return TRUE;
607
608 fail_and_cleanup:
609   plugin_loader_cleanup_child (l);
610   return FALSE;
611 }
612
613 static gboolean
614 do_plugin_load (GstPluginLoader * l, const gchar * filename, guint tag)
615 {
616   GstPlugin *newplugin;
617   GList *chunks = NULL;
618
619   GST_DEBUG ("Plugin scanner loading file %s. tag %u", filename, tag);
620
621 #if 0                           /* Test code - crash based on filename */
622   if (strstr (filename, "coreelements") == NULL) {
623     g_printerr ("Crashing on file %s\n", filename);
624     g_printerr ("%d", *(gint *) (NULL));
625   }
626 #endif
627
628   newplugin = gst_plugin_load_file ((gchar *) filename, NULL);
629   if (newplugin) {
630     guint hdr_pos;
631     guint offset;
632
633     /* Now serialise the plugin details and send */
634     if (!_priv_gst_registry_chunks_save_plugin (&chunks,
635             gst_registry_get_default (), newplugin))
636       goto fail;
637
638     /* Store where the header is, write an empty one, then write
639      * all the payload chunks, then fix up the header size */
640     hdr_pos = l->tx_buf_write;
641     offset = HEADER_SIZE;
642     put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0);
643
644     if (chunks) {
645       GList *walk;
646       for (walk = chunks; walk; walk = g_list_next (walk)) {
647         GstRegistryChunk *cur = walk->data;
648         put_chunk (l, cur, &offset);
649
650         _priv_gst_registry_chunk_free (cur);
651       }
652
653       g_list_free (chunks);
654
655       /* Store the size of the written payload */
656       GST_WRITE_UINT32_BE (l->tx_buf + hdr_pos + 4, offset - HEADER_SIZE);
657     }
658 #if 0                           /* Test code - corrupt the tx buffer based on filename */
659     if (strstr (filename, "sink") != NULL) {
660       int fd, res;
661       g_printerr ("Corrupting tx buf on file %s\n", filename);
662       fd = open ("/dev/urandom", O_RDONLY);
663       res = read (fd, l->tx_buf, l->tx_buf_size);
664       close (fd);
665     }
666 #endif
667
668     gst_object_unref (newplugin);
669   } else {
670     put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0);
671   }
672
673   return TRUE;
674 fail:
675   put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0);
676   if (chunks) {
677     GList *walk;
678     for (walk = chunks; walk; walk = g_list_next (walk)) {
679       GstRegistryChunk *cur = walk->data;
680
681       _priv_gst_registry_chunk_free (cur);
682     }
683
684     g_list_free (chunks);
685   }
686
687   return FALSE;
688 }
689
690 static gboolean
691 check_protocol_version (GstPluginLoader * l, guint8 * payload,
692     guint payload_len)
693 {
694   guint32 got_version;
695   guint8 *binary_reg_ver;
696
697   if (payload_len < sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN)
698     return FALSE;
699
700   got_version = GST_READ_UINT32_BE (payload);
701   GST_LOG ("Got VERSION %u from child. Ours is %u", got_version,
702       loader_protocol_version);
703   if (got_version != loader_protocol_version)
704     return FALSE;
705
706   binary_reg_ver = payload + sizeof (guint32);
707   if (strcmp ((gchar *) binary_reg_ver, GST_MAGIC_BINARY_VERSION_STR)) {
708     GST_LOG ("Binary chunk format of child is different. Ours: %s, child %s\n",
709         GST_MAGIC_BINARY_VERSION_STR, binary_reg_ver);
710     return FALSE;
711   }
712
713   return TRUE;
714 };
715
716 static gboolean
717 handle_rx_packet (GstPluginLoader * l,
718     guint pack_type, guint32 tag, guint8 * payload, guint payload_len)
719 {
720   gboolean res = TRUE;
721
722   switch (pack_type) {
723     case PACKET_EXIT:
724       gst_poll_fd_ctl_read (l->fdset, &l->fd_r, FALSE);
725       if (l->is_child) {
726         /* Respond, then we keep looping until the parent closes the fd */
727         put_packet (l, PACKET_EXIT, 0, NULL, 0);
728       } else {
729         l->rx_done = TRUE;      /* All done reading from child */
730       }
731       return TRUE;
732     case PACKET_LOAD_PLUGIN:{
733       if (!l->is_child)
734         return TRUE;
735
736       /* Payload is the filename to load */
737       res = do_plugin_load (l, (gchar *) payload, tag);
738
739       break;
740     }
741     case PACKET_PLUGIN_DETAILS:{
742       gchar *tmp = (gchar *) payload;
743       PendingPluginEntry *entry = NULL;
744       GList *cur;
745
746       GST_DEBUG_OBJECT (l->registry,
747           "Received plugin details from child w/ tag %u. %d bytes info",
748           tag, payload_len);
749
750       /* Assume that tagged details come back in the order
751        * we requested, and delete anything before (but not
752        * including) this one */
753       cur = l->pending_plugins;
754       while (cur) {
755         PendingPluginEntry *e = (PendingPluginEntry *) (cur->data);
756
757         if (e->tag > tag)
758           break;
759
760         if (e->tag == tag) {
761           entry = e;
762           break;
763         } else {
764           cur = g_list_delete_link (cur, cur);
765           g_free (e->filename);
766           g_slice_free (PendingPluginEntry, e);
767         }
768       }
769
770       l->pending_plugins = cur;
771       if (cur == NULL)
772         l->pending_plugins_tail = NULL;
773
774       if (payload_len > 0) {
775         GstPlugin *newplugin = NULL;
776         if (!_priv_gst_registry_chunks_load_plugin (l->registry, &tmp,
777                 tmp + payload_len, &newplugin)) {
778           /* Got garbage from the child, so fail and trigger replay of plugins */
779           GST_ERROR_OBJECT (l->registry,
780               "Problems loading plugin details with tag %u from scanner", tag);
781           return FALSE;
782         }
783
784         newplugin->flags &= ~GST_PLUGIN_FLAG_CACHED;
785         GST_LOG_OBJECT (l->registry,
786             "marking plugin %p as registered as %s", newplugin,
787             newplugin->filename);
788         newplugin->registered = TRUE;
789
790         /* We got a set of plugin details - remember it for later */
791         l->got_plugin_details = TRUE;
792       } else if (entry != NULL) {
793         /* Create a blacklist entry for this file to prevent scanning every time */
794         plugin_loader_create_blacklist_plugin (l, entry);
795         l->got_plugin_details = TRUE;
796       }
797
798       if (entry != NULL) {
799         g_free (entry->filename);
800         g_slice_free (PendingPluginEntry, entry);
801       }
802
803       /* Remove the plugin entry we just loaded */
804       cur = l->pending_plugins;
805       if (cur != NULL)
806         cur = g_list_delete_link (cur, cur);
807       l->pending_plugins = cur;
808       if (cur == NULL)
809         l->pending_plugins_tail = NULL;
810
811       break;
812     }
813     case PACKET_SYNC:
814       if (l->is_child) {
815         /* Respond with our reply - also a sync */
816         put_packet (l, PACKET_SYNC, tag, NULL, 0);
817         GST_LOG ("Got SYNC in child - replying");
818       } else
819         l->rx_got_sync = TRUE;
820       break;
821     case PACKET_VERSION:
822       if (l->is_child) {
823         /* Respond with our reply - a version packet, with the version */
824         const gint version_len =
825             sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN;
826         guint8 version_info[sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN];
827         memset (version_info, 0, version_len);
828         GST_WRITE_UINT32_BE (version_info, loader_protocol_version);
829         memcpy (version_info + sizeof (guint32), GST_MAGIC_BINARY_VERSION_STR,
830             strlen (GST_MAGIC_BINARY_VERSION_STR));
831         put_packet (l, PACKET_VERSION, tag, version_info, version_len);
832         GST_LOG ("Got VERSION in child - replying %u", loader_protocol_version);
833       } else {
834         res = check_protocol_version (l, payload, payload_len);
835       }
836       break;
837     default:
838       return FALSE;             /* Invalid packet -> something is wrong */
839   }
840
841   return res;
842 }
843
844 static gboolean
845 read_one (GstPluginLoader * l)
846 {
847   guint64 magic;
848   guint32 to_read, packet_len, tag;
849   guint8 *in;
850   gint res;
851
852   to_read = HEADER_SIZE;
853   in = l->rx_buf;
854   do {
855     res = read (l->fd_r.fd, in, to_read);
856     if (G_UNLIKELY (res < 0)) {
857       if (errno == EAGAIN || errno == EINTR)
858         continue;
859       GST_LOG ("Failed reading packet header");
860       return FALSE;
861     }
862     to_read -= res;
863     in += res;
864   } while (to_read > 0);
865
866   magic = GST_READ_UINT32_BE (l->rx_buf + 8);
867   if (magic != HEADER_MAGIC) {
868     GST_WARNING
869         ("Invalid packet (bad magic number) received from plugin scanner subprocess");
870     return FALSE;
871   }
872
873   packet_len = GST_READ_UINT32_BE (l->rx_buf + 4);
874   if (packet_len + HEADER_SIZE > BUF_MAX_SIZE) {
875     GST_WARNING
876         ("Received excessively large packet for plugin scanner subprocess");
877     return FALSE;
878   }
879   tag = GST_READ_UINT24_BE (l->rx_buf + 1);
880
881   if (packet_len > 0) {
882     if (packet_len + HEADER_SIZE >= l->rx_buf_size) {
883       GST_LOG ("Expanding rx buf from %d to %d",
884           l->rx_buf_size, packet_len + HEADER_SIZE + BUF_GROW_EXTRA);
885       l->rx_buf_size = packet_len + HEADER_SIZE + BUF_GROW_EXTRA;
886       l->rx_buf = g_realloc (l->rx_buf, l->rx_buf_size);
887     }
888
889     in = l->rx_buf + HEADER_SIZE;
890     to_read = packet_len;
891     do {
892       res = read (l->fd_r.fd, in, to_read);
893       if (G_UNLIKELY (res < 0)) {
894         if (errno == EAGAIN || errno == EINTR)
895           continue;
896         GST_ERROR ("Packet payload read failed");
897         return FALSE;
898       }
899       to_read -= res;
900       in += res;
901     } while (to_read > 0);
902   } else {
903     GST_LOG ("No payload to read for 0 length packet type %d tag %u",
904         l->rx_buf[0], tag);
905   }
906
907   return handle_rx_packet (l, l->rx_buf[0], tag,
908       l->rx_buf + HEADER_SIZE, packet_len);
909 }
910
911 static gboolean
912 exchange_packets (GstPluginLoader * l)
913 {
914   gint res;
915
916   /* Wait for activity on our FDs */
917   do {
918     do {
919       res = gst_poll_wait (l->fdset, GST_SECOND);
920     } while (res == -1 && (errno == EINTR || errno == EAGAIN));
921
922     if (res < 0)
923       return FALSE;
924
925     GST_LOG ("Poll res = %d. %d bytes pending for write", res,
926         l->tx_buf_write - l->tx_buf_read);
927
928     if (!l->rx_done) {
929       if (gst_poll_fd_has_error (l->fdset, &l->fd_r) ||
930           gst_poll_fd_has_closed (l->fdset, &l->fd_r)) {
931         GST_LOG ("read fd %d closed/errored", l->fd_r.fd);
932         goto fail_and_cleanup;
933       }
934
935       if (gst_poll_fd_can_read (l->fdset, &l->fd_r)) {
936         if (!read_one (l))
937           goto fail_and_cleanup;
938       }
939     }
940
941     if (l->tx_buf_read < l->tx_buf_write) {
942       if (gst_poll_fd_has_error (l->fdset, &l->fd_w) ||
943           gst_poll_fd_has_closed (l->fdset, &l->fd_r)) {
944         GST_ERROR ("write fd %d closed/errored", l->fd_w.fd);
945         goto fail_and_cleanup;
946       }
947       if (gst_poll_fd_can_write (l->fdset, &l->fd_w)) {
948         if (!write_one (l))
949           goto fail_and_cleanup;
950       }
951     }
952   } while (l->tx_buf_read < l->tx_buf_write);
953
954   return TRUE;
955 fail_and_cleanup:
956   plugin_loader_cleanup_child (l);
957   return FALSE;
958 }