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