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