registrybinary: registry file mode via GST_REGISTRY_MODE
[platform/upstream/gstreamer.git] / subprojects / gstreamer / gst / gstregistrybinary.c
1 /* GStreamer
2  * Copyright (C) 2006 Josep Torra <josep@fluendo.com>
3  *               2006 Mathieu Garcia <matthieu@fluendo.com>
4  *               2006,2007 Stefan Kost <ensonic@users.sf.net>
5  *               2008 Sebastian Dröge <slomo@circular-chaos.org>
6  *
7  * gstregistrybinary.c: GstRegistryBinary object, support routines
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /* FIXME:
26  * - keep registry binary blob and reference strings
27  *   - don't free/unmmap contents when leaving gst_registry_binary_read_cache()
28  *     - free at gst_deinit() / _priv_gst_registry_cleanup() ?
29  *   - GstPlugin:
30  *     - GST_PLUGIN_FLAG_CONST
31  *   - GstPluginFeature, GstIndexFactory, GstElementFactory
32  *     - needs Flags (GST_PLUGIN_FEATURE_FLAG_CONST)
33  *     - can we turn loaded into flag?
34  * - why do we collect a list of binary chunks and not write immediately
35  *   - because we need to process subchunks, before we can set e.g. nr_of_items
36  *     in parent chunk
37  */
38
39 #ifdef HAVE_CONFIG_H
40 #  include "config.h"
41 #endif
42
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46
47 #include <errno.h>
48 #include <stdio.h>
49
50 #if defined (_MSC_VER) && _MSC_VER >= 1400
51 #include <io.h>
52 #endif
53
54 #include <gst/gst_private.h>
55 #include <gst/gstconfig.h>
56 #include <gst/gstelement.h>
57 #include <gst/gsttypefind.h>
58 #include <gst/gsttypefindfactory.h>
59 #include <gst/gstdeviceproviderfactory.h>
60 #include <gst/gstdynamictypefactory.h>
61 #include <gst/gsturi.h>
62 #include <gst/gstinfo.h>
63 #include <gst/gstenumtypes.h>
64 #include <gst/gstpadtemplate.h>
65
66 #include <gst/gstregistrychunks.h>
67 #include <gst/gstregistrybinary.h>
68
69 #include <glib/gstdio.h>        /* for g_stat(), g_mapped_file(), ... */
70
71 #include "glib-compat-private.h"
72
73
74 #define GST_CAT_DEFAULT GST_CAT_REGISTRY
75
76 /* reading macros */
77 #define unpack_element(inptr, outptr, element, endptr, error_label) G_STMT_START{ \
78   if (inptr + sizeof(element) >= endptr) \
79     goto error_label; \
80   outptr = (element *) inptr; \
81   inptr += sizeof (element); \
82 }G_STMT_END
83
84 #define ALIGNMENT            (sizeof (void *))
85 #define alignment(_address)  (gsize)_address%ALIGNMENT
86 #define align(_ptr)          _ptr += (( alignment(_ptr) == 0) ? 0 : ALIGNMENT-alignment(_ptr))
87
88 /* Registry saving */
89
90 #ifdef G_OS_WIN32
91 /* On win32, we can't use g_mkstmp(), because of cross-DLL file I/O problems.
92  * So, we just create the entire binary registry in memory, then write it out
93  * with g_file_set_contents(), which creates a temporary file internally
94  */
95
96 typedef struct BinaryRegistryCache
97 {
98   const char *location;
99   guint8 *mem;
100   gssize len;
101 } BinaryRegistryCache;
102
103 static BinaryRegistryCache *
104 gst_registry_binary_cache_init (GstRegistry * registry, const char *location)
105 {
106   BinaryRegistryCache *cache = g_slice_new0 (BinaryRegistryCache);
107   cache->location = location;
108   return cache;
109 }
110
111 static int
112 gst_registry_binary_cache_write (BinaryRegistryCache * cache,
113     unsigned long offset, const void *data, int length)
114 {
115   cache->len = MAX (offset + length, cache->len);
116   cache->mem = g_realloc (cache->mem, cache->len);
117
118   memcpy (cache->mem + offset, data, length);
119
120   return length;
121 }
122
123 static gboolean
124 gst_registry_binary_cache_finish (BinaryRegistryCache * cache, gboolean success)
125 {
126   gboolean ret = TRUE;
127   GError *error = NULL;
128   if (!g_file_set_contents (cache->location, (const gchar *) cache->mem,
129           cache->len, &error)) {
130     /* Probably the directory didn't exist; create it */
131     gchar *dir;
132     dir = g_path_get_dirname (cache->location);
133     g_mkdir_with_parents (dir, 0777);
134     g_free (dir);
135
136     g_error_free (error);
137     error = NULL;
138
139     if (!g_file_set_contents (cache->location, (const gchar *) cache->mem,
140             cache->len, &error)) {
141       /* Probably the directory didn't exist; create it */
142       gchar *dir;
143       dir = g_path_get_dirname (cache->location);
144       g_mkdir_with_parents (dir, 0777);
145       g_free (dir);
146
147       g_error_free (error);
148       error = NULL;
149
150       if (!g_file_set_contents (cache->location, (const gchar *) cache->mem,
151               cache->len, &error)) {
152         GST_ERROR ("Failed to write to cache file: %s", error->message);
153         g_error_free (error);
154         ret = FALSE;
155       }
156     }
157   }
158
159   g_free (cache->mem);
160   g_slice_free (BinaryRegistryCache, cache);
161   return ret;
162 }
163
164 #else
165 typedef struct BinaryRegistryCache
166 {
167   const char *location;
168   char *tmp_location;
169   unsigned long currentoffset;
170   FILE *cache_file;
171 } BinaryRegistryCache;
172
173 static BinaryRegistryCache *
174 gst_registry_binary_cache_init (GstRegistry * registry, const char *location)
175 {
176   BinaryRegistryCache *cache = g_slice_new0 (BinaryRegistryCache);
177   int fd;
178
179   cache->location = location;
180   cache->tmp_location = g_strconcat (location, ".tmpXXXXXX", NULL);
181   fd = g_mkstemp (cache->tmp_location);
182   if (fd == -1) {
183     int ret;
184     GStatBuf statbuf;
185     gchar *dir;
186
187     /* oops, I bet the directory doesn't exist */
188     dir = g_path_get_dirname (location);
189     g_mkdir_with_parents (dir, 0777);
190
191     ret = g_stat (dir, &statbuf);
192     if (ret != -1 && (statbuf.st_mode & 0700) != 0700) {
193       g_chmod (dir, 0700);
194     }
195
196     g_free (dir);
197
198     /* the previous g_mkstemp call overwrote the XXXXXX placeholder ... */
199     g_free (cache->tmp_location);
200     cache->tmp_location = g_strconcat (location, ".tmpXXXXXX", NULL);
201     fd = g_mkstemp (cache->tmp_location);
202
203     if (fd == -1) {
204       GST_DEBUG ("g_mkstemp() failed: %s", g_strerror (errno));
205       g_free (cache->tmp_location);
206       g_slice_free (BinaryRegistryCache, cache);
207       return NULL;
208     }
209
210     ret = g_stat (cache->tmp_location, &statbuf);
211     if (ret != -1 && (statbuf.st_mode & 0600) != 0600) {
212       g_chmod (cache->tmp_location, 0600);
213     }
214   }
215
216   cache->cache_file = fdopen (fd, "w");
217   if (!cache->cache_file) {
218     GST_DEBUG ("fdopen() failed: %s", g_strerror (errno));
219     close (fd);
220     g_free (cache->tmp_location);
221     g_slice_free (BinaryRegistryCache, cache);
222     return NULL;
223   }
224
225   return cache;
226 }
227
228 static int
229 gst_registry_binary_cache_write (BinaryRegistryCache * cache,
230     unsigned long offset, const void *data, int length)
231 {
232   long written;
233   if (offset != cache->currentoffset) {
234     if (fseek (cache->cache_file, offset, SEEK_SET) < 0) {
235       GST_ERROR ("Seeking to new offset failed: %s", g_strerror (errno));
236       return -1;
237     }
238     GST_LOG ("Seeked from offset %lu to %lu", offset, cache->currentoffset);
239     cache->currentoffset = offset;
240   }
241
242   written = fwrite (data, 1, length, cache->cache_file);
243   if (written != length) {
244     GST_ERROR ("Failed to write to cache file");
245   }
246   cache->currentoffset += written;
247
248   return written;
249 }
250
251 static gboolean
252 gst_registry_binary_cache_finish (BinaryRegistryCache * cache, gboolean success)
253 {
254   gint fclose_ret;
255   const gchar *registry_mode;
256
257   if (success) {
258     /* flush the file and make sure the OS's buffer has been written to disk */
259     gint fflush_ret, fsync_ret;
260     int file_fd;
261
262     file_fd = fileno (cache->cache_file);
263
264     do {
265       fflush_ret = fflush (cache->cache_file);
266     } while (fflush_ret && errno == EINTR);
267     if (fflush_ret)
268       goto fflush_failed;
269
270     do {
271       fsync_ret = fsync (file_fd);
272     } while (fsync_ret < 0 && errno == EINTR);
273     if (fsync_ret < 0)
274       goto fsync_failed;
275   }
276
277   /* close the file, even when unsuccessful, so not to leak a file descriptor.
278    * We must not retry fclose() on EINTR as POSIX states:
279    *   After the call to fclose(), any use of stream results in undefined
280    *   behavior.
281    * We ensure above with fflush() and fsync() that everything is written out
282    * so chances of running into EINTR are very low. Nonetheless assume that
283    * the file can't be safely renamed, we'll just try again on the next
284    * opportunity. */
285   fclose_ret = fclose (cache->cache_file);
286   if (fclose_ret)
287     goto fclose_failed;
288
289   if (!success)
290     goto fail_after_fclose;
291
292   /* Only do the rename if we wrote the entire file successfully */
293   if (g_rename (cache->tmp_location, cache->location) < 0)
294     goto rename_failed;
295
296   /* Change mode of registry if set in environment */
297   registry_mode = g_getenv ("GST_REGISTRY_MODE");
298   if (registry_mode) {
299     gchar *endptr;
300     gint64 mode;
301
302     /* Expect numeric mode as one to four octal digits */
303     mode = g_ascii_strtoll (registry_mode, &endptr, 8);
304     if (mode > G_MAXINT || *endptr != '\0')
305       GST_ERROR ("GST_REGISTRY_MODE not an integer value");
306     else if (g_chmod (cache->location, mode) < 0)
307       GST_ERROR ("g_chmod failed: %s", g_strerror (errno));
308     else
309       GST_INFO ("Changed mode of registry cache to %s", registry_mode);
310   }
311
312   g_free (cache->tmp_location);
313   g_slice_free (BinaryRegistryCache, cache);
314   GST_INFO ("Wrote binary registry cache");
315   return TRUE;
316
317 /* ERRORS */
318 fail_before_fclose:
319   {
320     fclose (cache->cache_file);
321   }
322   /* fall through */
323 fail_after_fclose:
324   {
325     g_unlink (cache->tmp_location);
326     g_free (cache->tmp_location);
327     g_slice_free (BinaryRegistryCache, cache);
328     return FALSE;
329   }
330 fflush_failed:
331   {
332     GST_ERROR ("fflush() failed: %s", g_strerror (errno));
333     goto fail_before_fclose;
334   }
335 fsync_failed:
336   {
337     GST_ERROR ("fsync() failed: %s", g_strerror (errno));
338     goto fail_before_fclose;
339   }
340 fclose_failed:
341   {
342     GST_ERROR ("fclose() failed: %s", g_strerror (errno));
343     goto fail_after_fclose;
344   }
345 rename_failed:
346   {
347     GST_ERROR ("g_rename() failed: %s", g_strerror (errno));
348     goto fail_after_fclose;
349   }
350 }
351 #endif
352
353 /*
354  * gst_registry_binary_write_chunk:
355  *
356  * Write from a memory location to the registry cache file
357  *
358  * Returns: %TRUE for success
359  */
360 inline static gboolean
361 gst_registry_binary_write_chunk (BinaryRegistryCache * cache,
362     GstRegistryChunk * chunk, unsigned long *file_position)
363 {
364   gchar padder[ALIGNMENT] = { 0, };
365   int padsize = 0;
366
367   /* Padding to insert the struct that require word alignment */
368   if ((chunk->align) && (alignment (*file_position) != 0)) {
369     padsize = ALIGNMENT - alignment (*file_position);
370     if (gst_registry_binary_cache_write (cache, *file_position,
371             padder, padsize) != padsize) {
372       GST_ERROR ("Failed to write binary registry padder");
373       return FALSE;
374     }
375     *file_position += padsize;
376   }
377
378   if (gst_registry_binary_cache_write (cache, *file_position,
379           chunk->data, chunk->size) != chunk->size) {
380     GST_ERROR ("Failed to write binary registry element");
381     return FALSE;
382   }
383
384   *file_position += chunk->size;
385
386   return TRUE;
387 }
388
389
390 /*
391  * gst_registry_binary_initialize_magic:
392  *
393  * Initialize the GstBinaryRegistryMagic, setting both our magic number and
394  * gstreamer major/minor version
395  */
396 inline static gboolean
397 gst_registry_binary_initialize_magic (GstBinaryRegistryMagic * m)
398 {
399   memset (m, 0, sizeof (GstBinaryRegistryMagic));
400
401   if (!memcpy (m->magic, GST_MAGIC_BINARY_REGISTRY_STR,
402           GST_MAGIC_BINARY_REGISTRY_LEN)
403       || !strncpy (m->version, GST_MAGIC_BINARY_VERSION_STR,
404           GST_MAGIC_BINARY_VERSION_LEN)) {
405     GST_ERROR ("Failed to write magic to the registry magic structure");
406     return FALSE;
407   }
408
409   return TRUE;
410 }
411
412 /**
413  * gst_registry_binary_write_cache:
414  * @registry: a #GstRegistry
415  * @location: a filename
416  *
417  * Write the @registry to a cache to file at given @location.
418  *
419  * Returns: %TRUE on success.
420  */
421 gboolean
422 priv_gst_registry_binary_write_cache (GstRegistry * registry, GList * plugins,
423     const char *location)
424 {
425   GList *walk;
426   GstBinaryRegistryMagic magic;
427   GList *to_write = NULL;
428   unsigned long file_position = 0;
429   BinaryRegistryCache *cache;
430
431   GST_INFO ("Building binary registry cache image");
432
433   g_return_val_if_fail (GST_IS_REGISTRY (registry), FALSE);
434
435   if (!gst_registry_binary_initialize_magic (&magic))
436     goto fail;
437
438   /* iterate trough the list of plugins and fit them into binary structures */
439   for (walk = plugins; walk != NULL; walk = walk->next) {
440     GstPlugin *plugin = GST_PLUGIN (walk->data);
441
442     if (!plugin->filename)
443       continue;
444
445     if (GST_OBJECT_FLAG_IS_SET (plugin, GST_PLUGIN_FLAG_CACHED)) {
446       GStatBuf statbuf;
447
448       if (g_stat (plugin->filename, &statbuf) < 0 ||
449           plugin->file_mtime != statbuf.st_mtime ||
450           plugin->file_size != statbuf.st_size)
451         continue;
452     }
453
454     if (!_priv_gst_registry_chunks_save_plugin (&to_write, registry, plugin)) {
455       GST_ERROR ("Can't write binary plugin information for \"%s\"",
456           plugin->filename);
457     }
458   }
459
460   _priv_gst_registry_chunks_save_global_header (&to_write, registry,
461       priv_gst_plugin_loading_get_whitelist_hash ());
462
463   GST_INFO ("Writing binary registry cache");
464
465   cache = gst_registry_binary_cache_init (registry, location);
466   if (!cache)
467     goto fail_free_list;
468
469   /* write magic */
470   if (gst_registry_binary_cache_write (cache, file_position,
471           &magic, sizeof (GstBinaryRegistryMagic)) !=
472       sizeof (GstBinaryRegistryMagic)) {
473     GST_ERROR ("Failed to write binary registry magic");
474     goto fail_free_list;
475   }
476   file_position += sizeof (GstBinaryRegistryMagic);
477
478   /* write out data chunks */
479   for (walk = to_write; walk; walk = g_list_next (walk)) {
480     GstRegistryChunk *cur = walk->data;
481     gboolean res;
482
483     res = gst_registry_binary_write_chunk (cache, cur, &file_position);
484
485     _priv_gst_registry_chunk_free (cur);
486     walk->data = NULL;
487     if (!res)
488       goto fail_free_list;
489   }
490   g_list_free (to_write);
491
492   if (!gst_registry_binary_cache_finish (cache, TRUE))
493     return FALSE;
494
495   return TRUE;
496
497   /* Errors */
498 fail_free_list:
499   {
500     for (walk = to_write; walk; walk = g_list_next (walk)) {
501       GstRegistryChunk *cur = walk->data;
502
503       if (cur)
504         _priv_gst_registry_chunk_free (cur);
505     }
506     g_list_free (to_write);
507
508     if (cache)
509       (void) gst_registry_binary_cache_finish (cache, FALSE);
510     /* fall through */
511   }
512 fail:
513   {
514     return FALSE;
515   }
516 }
517
518
519 /* Registry loading */
520
521 /*
522  * gst_registry_binary_check_magic:
523  *
524  * Check GstBinaryRegistryMagic validity.
525  * Return < 0 if something is wrong, -2 means
526  * that just the version of the registry is out of
527  * date, -1 is a general failure.
528  */
529 static gint
530 gst_registry_binary_check_magic (gchar ** in, gsize size)
531 {
532   GstBinaryRegistryMagic *m;
533
534   align (*in);
535   GST_DEBUG ("Reading/casting for GstBinaryRegistryMagic at address %p", *in);
536   unpack_element (*in, m, GstBinaryRegistryMagic, (*in + size), fail);
537
538   if (strncmp (m->magic, GST_MAGIC_BINARY_REGISTRY_STR,
539           GST_MAGIC_BINARY_REGISTRY_LEN) != 0) {
540     GST_WARNING
541         ("Binary registry magic is different : %02x%02x%02x%02x != %02x%02x%02x%02x",
542         GST_MAGIC_BINARY_REGISTRY_STR[0] & 0xff,
543         GST_MAGIC_BINARY_REGISTRY_STR[1] & 0xff,
544         GST_MAGIC_BINARY_REGISTRY_STR[2] & 0xff,
545         GST_MAGIC_BINARY_REGISTRY_STR[3] & 0xff, m->magic[0] & 0xff,
546         m->magic[1] & 0xff, m->magic[2] & 0xff, m->magic[3] & 0xff);
547     return -1;
548   }
549   if (strncmp (m->version, GST_MAGIC_BINARY_VERSION_STR,
550           GST_MAGIC_BINARY_VERSION_LEN)) {
551     GST_WARNING ("Binary registry magic version is different : %s != %s",
552         GST_MAGIC_BINARY_VERSION_STR, m->version);
553     return -2;
554   }
555
556   return 0;
557
558 fail:
559   GST_WARNING ("Not enough data for binary registry magic structure");
560   return -1;
561 }
562
563 /**
564  * gst_registry_binary_read_cache:
565  * @registry: a #GstRegistry
566  * @location: a filename
567  *
568  * Read the contents of the binary cache file at @location into @registry.
569  *
570  * Returns: %TRUE on success.
571  */
572 gboolean
573 priv_gst_registry_binary_read_cache (GstRegistry * registry,
574     const char *location)
575 {
576   GMappedFile *mapped = NULL;
577   gchar *contents = NULL;
578   gchar *in = NULL;
579   gsize size;
580   GError *err = NULL;
581   gboolean res = FALSE;
582   guint32 filter_env_hash = 0;
583   gint check_magic_result;
584 #ifndef GST_DISABLE_GST_DEBUG
585   GTimer *timer = NULL;
586   gdouble seconds;
587 #endif
588
589   /* make sure these types exist */
590   GST_TYPE_ELEMENT_FACTORY;
591   GST_TYPE_TYPE_FIND_FACTORY;
592   GST_TYPE_DEVICE_PROVIDER_FACTORY;
593   GST_TYPE_DYNAMIC_TYPE_FACTORY;
594
595 #ifndef GST_DISABLE_GST_DEBUG
596   timer = g_timer_new ();
597 #endif
598
599   mapped = g_mapped_file_new (location, FALSE, &err);
600   if (G_UNLIKELY (err != NULL)) {
601     GST_INFO ("Unable to mmap file %s : %s", location, err->message);
602     g_error_free (err);
603     err = NULL;
604   }
605
606   if (mapped == NULL) {
607     /* Error mmap-ing the cache, try a plain memory read */
608
609     g_file_get_contents (location, &contents, &size, &err);
610     if (err != NULL) {
611       GST_INFO ("Unable to read file %s : %s", location, err->message);
612 #ifndef GST_DISABLE_GST_DEBUG
613       g_timer_destroy (timer);
614 #endif
615       g_error_free (err);
616       return FALSE;
617     }
618   } else {
619     /* This can't fail if g_mapped_file_new() succeeded */
620     contents = g_mapped_file_get_contents (mapped);
621     size = g_mapped_file_get_length (mapped);
622   }
623
624   /* in is a cursor pointer, we initialize it with the begin of registry and is updated on each read */
625   in = contents;
626   GST_DEBUG ("File data at address %p", in);
627   if (G_UNLIKELY (size < sizeof (GstBinaryRegistryMagic))) {
628     GST_ERROR ("No or broken registry header for file at %s", location);
629     goto Error;
630   }
631
632   /* check if header is valid */
633   if (G_UNLIKELY ((check_magic_result =
634               gst_registry_binary_check_magic (&in, size)) < 0)) {
635
636     if (check_magic_result == -1)
637       GST_ERROR
638           ("Binary registry type not recognized (invalid magic) for file at %s",
639           location);
640     goto Error;
641   }
642
643   if (!_priv_gst_registry_chunks_load_global_header (registry, &in,
644           contents + size, &filter_env_hash)) {
645     GST_ERROR ("Couldn't read global header chunk");
646     goto Error;
647   }
648
649   if (filter_env_hash != priv_gst_plugin_loading_get_whitelist_hash ()) {
650     GST_INFO_OBJECT (registry, "Plugin loading filter environment changed, "
651         "ignoring plugin cache to force update with new filter environment");
652     goto done;
653   }
654
655   /* check if there are plugins in the file */
656   if (G_UNLIKELY (!(((gsize) in + sizeof (GstRegistryChunkPluginElement)) <
657               (gsize) contents + size))) {
658     GST_INFO ("No binary plugins structure to read");
659     /* empty file, this is not an error */
660   } else {
661     gchar *end = contents + size;
662     /* read as long as we still have space for a GstRegistryChunkPluginElement */
663     for (;
664         ((gsize) in + sizeof (GstRegistryChunkPluginElement)) <
665         (gsize) contents + size;) {
666       GST_DEBUG ("reading binary registry %" G_GSIZE_FORMAT "(%x)/%"
667           G_GSIZE_FORMAT, (gsize) in - (gsize) contents,
668           (guint) ((gsize) in - (gsize) contents), size);
669       if (!_priv_gst_registry_chunks_load_plugin (registry, &in, end, NULL)) {
670         GST_ERROR ("Problem while reading binary registry %s", location);
671         goto Error;
672       }
673     }
674   }
675
676 done:
677
678 #ifndef GST_DISABLE_GST_DEBUG
679   g_timer_stop (timer);
680   seconds = g_timer_elapsed (timer, NULL);
681 #endif
682
683   GST_INFO ("loaded %s in %lf seconds", location, seconds);
684
685   res = TRUE;
686   /* TODO: once we re-use the pointers to registry contents, return here */
687
688 Error:
689 #ifndef GST_DISABLE_GST_DEBUG
690   g_timer_destroy (timer);
691 #endif
692   if (mapped) {
693     g_mapped_file_unref (mapped);
694   } else {
695     g_free (contents);
696   }
697   return res;
698 }