registry: fix lseek() return code handling
[platform/upstream/gstreamer.git] / 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., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, 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/gsturi.h>
60 #include <gst/gstinfo.h>
61 #include <gst/gstenumtypes.h>
62 #include <gst/gstpadtemplate.h>
63
64 #include <gst/gstregistrychunks.h>
65 #include <gst/gstregistrybinary.h>
66
67 #include <glib/gstdio.h>        /* for g_stat(), g_mapped_file(), ... */
68
69 #include "glib-compat-private.h"
70
71
72 #define GST_CAT_DEFAULT GST_CAT_REGISTRY
73
74 /* reading macros */
75 #define unpack_element(inptr, outptr, element, endptr, error_label) G_STMT_START{ \
76   if (inptr + sizeof(element) >= endptr) \
77     goto error_label; \
78   outptr = (element *) inptr; \
79   inptr += sizeof (element); \
80 }G_STMT_END
81
82 #define ALIGNMENT            (sizeof (void *))
83 #define alignment(_address)  (gsize)_address%ALIGNMENT
84 #define align(_ptr)          _ptr += (( alignment(_ptr) == 0) ? 0 : ALIGNMENT-alignment(_ptr))
85
86 /* Registry saving */
87
88 #ifdef G_OS_WIN32
89 /* On win32, we can't use g_mkstmp(), because of cross-DLL file I/O problems.
90  * So, we just create the entire binary registry in memory, then write it out
91  * with g_file_set_contents(), which creates a temporary file internally
92  */
93
94 typedef struct BinaryRegistryCache
95 {
96   const char *location;
97   guint8 *mem;
98   gssize len;
99 } BinaryRegistryCache;
100
101 static BinaryRegistryCache *
102 gst_registry_binary_cache_init (GstRegistry * registry, const char *location)
103 {
104   BinaryRegistryCache *cache = g_slice_new0 (BinaryRegistryCache);
105   cache->location = location;
106   return cache;
107 }
108
109 static int
110 gst_registry_binary_cache_write (BinaryRegistryCache * cache,
111     unsigned long offset, const void *data, int length)
112 {
113   cache->len = MAX (offset + length, cache->len);
114   cache->mem = g_realloc (cache->mem, cache->len);
115
116   memcpy (cache->mem + offset, data, length);
117
118   return length;
119 }
120
121 static gboolean
122 gst_registry_binary_cache_finish (BinaryRegistryCache * cache, gboolean success)
123 {
124   gboolean ret = TRUE;
125   GError *error = NULL;
126   if (!g_file_set_contents (cache->location, (const gchar *) cache->mem,
127           cache->len, &error)) {
128     /* Probably the directory didn't exist; create it */
129     gchar *dir;
130     dir = g_path_get_dirname (cache->location);
131     g_mkdir_with_parents (dir, 0777);
132     g_free (dir);
133
134     g_error_free (error);
135     error = NULL;
136
137     if (!g_file_set_contents (cache->location, (const gchar *) cache->mem,
138             cache->len, &error)) {
139       /* Probably the directory didn't exist; create it */
140       gchar *dir;
141       dir = g_path_get_dirname (cache->location);
142       g_mkdir_with_parents (dir, 0777);
143       g_free (dir);
144
145       g_error_free (error);
146       error = NULL;
147
148       if (!g_file_set_contents (cache->location, (const gchar *) cache->mem,
149               cache->len, &error)) {
150         GST_ERROR ("Failed to write to cache file: %s", error->message);
151         g_error_free (error);
152         ret = FALSE;
153       }
154     }
155   }
156
157   g_free (cache->mem);
158   g_slice_free (BinaryRegistryCache, cache);
159   return ret;
160 }
161
162 #else
163 typedef struct BinaryRegistryCache
164 {
165   const char *location;
166   char *tmp_location;
167   unsigned long currentoffset;
168   int cache_fd;
169 } BinaryRegistryCache;
170
171 static BinaryRegistryCache *
172 gst_registry_binary_cache_init (GstRegistry * registry, const char *location)
173 {
174   BinaryRegistryCache *cache = g_slice_new0 (BinaryRegistryCache);
175
176   cache->location = location;
177   cache->tmp_location = g_strconcat (location, ".tmpXXXXXX", NULL);
178   cache->cache_fd = g_mkstemp (cache->tmp_location);
179   if (cache->cache_fd == -1) {
180     int ret;
181     GStatBuf statbuf;
182     gchar *dir;
183
184     /* oops, I bet the directory doesn't exist */
185     dir = g_path_get_dirname (location);
186     g_mkdir_with_parents (dir, 0777);
187
188     ret = g_stat (dir, &statbuf);
189     if (ret != -1 && (statbuf.st_mode & 0700) != 0700) {
190       g_chmod (dir, 0700);
191     }
192
193     g_free (dir);
194
195     /* the previous g_mkstemp call overwrote the XXXXXX placeholder ... */
196     g_free (cache->tmp_location);
197     cache->tmp_location = g_strconcat (location, ".tmpXXXXXX", NULL);
198     cache->cache_fd = g_mkstemp (cache->tmp_location);
199
200     if (cache->cache_fd == -1) {
201       GST_DEBUG ("g_mkstemp() failed: %s", g_strerror (errno));
202       g_free (cache->tmp_location);
203       g_slice_free (BinaryRegistryCache, cache);
204       return NULL;
205     }
206
207     ret = g_stat (cache->tmp_location, &statbuf);
208     if (ret != -1 && (statbuf.st_mode & 0600) != 0600) {
209       g_chmod (cache->tmp_location, 0600);
210     }
211   }
212
213   return cache;
214 }
215
216 static int
217 gst_registry_binary_cache_write (BinaryRegistryCache * cache,
218     unsigned long offset, const void *data, int length)
219 {
220   long written;
221   if (offset != cache->currentoffset) {
222     if (lseek (cache->cache_fd, offset, SEEK_SET) < 0) {
223       GST_ERROR ("Seeking to new offset failed: %s", g_strerror (errno));
224       return -1;
225     }
226     GST_LOG ("Seeked from offset %lu to %lu", offset, cache->currentoffset);
227     cache->currentoffset = offset;
228   }
229
230   written = write (cache->cache_fd, data, length);
231   if (written != length) {
232     GST_ERROR ("Failed to write to cache file");
233   }
234   cache->currentoffset += written;
235
236   return written;
237 }
238
239 static gboolean
240 gst_registry_binary_cache_finish (BinaryRegistryCache * cache, gboolean success)
241 {
242   /* only fsync if we're actually going to use and rename the file below */
243   if (success && fsync (cache->cache_fd) < 0)
244     goto fsync_failed;
245
246   if (close (cache->cache_fd) < 0)
247     goto close_failed;
248
249   if (!success)
250     goto fail_after_close;
251
252   /* Only do the rename if we wrote the entire file successfully */
253   if (g_rename (cache->tmp_location, cache->location) < 0) {
254     GST_ERROR ("g_rename() failed: %s", g_strerror (errno));
255     goto rename_failed;
256   }
257
258   g_free (cache->tmp_location);
259   g_slice_free (BinaryRegistryCache, cache);
260   GST_INFO ("Wrote binary registry cache");
261   return TRUE;
262
263 /* ERRORS */
264 fail_after_close:
265   {
266     g_unlink (cache->tmp_location);
267     g_free (cache->tmp_location);
268     g_slice_free (BinaryRegistryCache, cache);
269     return FALSE;
270   }
271 fsync_failed:
272   {
273     GST_ERROR ("fsync() failed: %s", g_strerror (errno));
274     goto fail_after_close;
275   }
276 close_failed:
277   {
278     GST_ERROR ("close() failed: %s", g_strerror (errno));
279     goto fail_after_close;
280   }
281 rename_failed:
282   {
283     GST_ERROR ("g_rename() failed: %s", g_strerror (errno));
284     goto fail_after_close;
285   }
286 }
287 #endif
288
289 /*
290  * gst_registry_binary_write_chunk:
291  *
292  * Write from a memory location to the registry cache file
293  *
294  * Returns: %TRUE for success
295  */
296 inline static gboolean
297 gst_registry_binary_write_chunk (BinaryRegistryCache * cache,
298     GstRegistryChunk * chunk, unsigned long *file_position)
299 {
300   gchar padder[ALIGNMENT] = { 0, };
301   int padsize = 0;
302
303   /* Padding to insert the struct that requiere word alignment */
304   if ((chunk->align) && (alignment (*file_position) != 0)) {
305     padsize = ALIGNMENT - alignment (*file_position);
306     if (gst_registry_binary_cache_write (cache, *file_position,
307             padder, padsize) != padsize) {
308       GST_ERROR ("Failed to write binary registry padder");
309       return FALSE;
310     }
311     *file_position += padsize;
312   }
313
314   if (gst_registry_binary_cache_write (cache, *file_position,
315           chunk->data, chunk->size) != chunk->size) {
316     GST_ERROR ("Failed to write binary registry element");
317     return FALSE;
318   }
319
320   *file_position += chunk->size;
321
322   return TRUE;
323 }
324
325
326 /*
327  * gst_registry_binary_initialize_magic:
328  *
329  * Initialize the GstBinaryRegistryMagic, setting both our magic number and
330  * gstreamer major/minor version
331  */
332 inline static gboolean
333 gst_registry_binary_initialize_magic (GstBinaryRegistryMagic * m)
334 {
335   memset (m, 0, sizeof (GstBinaryRegistryMagic));
336
337   if (!strncpy (m->magic, GST_MAGIC_BINARY_REGISTRY_STR,
338           GST_MAGIC_BINARY_REGISTRY_LEN)
339       || !strncpy (m->version, GST_MAGIC_BINARY_VERSION_STR,
340           GST_MAGIC_BINARY_VERSION_LEN)) {
341     GST_ERROR ("Failed to write magic to the registry magic structure");
342     return FALSE;
343   }
344
345   return TRUE;
346 }
347
348 /**
349  * gst_registry_binary_write_cache:
350  * @registry: a #GstRegistry
351  * @location: a filename
352  *
353  * Write the @registry to a cache to file at given @location.
354  *
355  * Returns: %TRUE on success.
356  */
357 gboolean
358 gst_registry_binary_write_cache (GstRegistry * registry, const char *location)
359 {
360   GList *walk;
361   GstBinaryRegistryMagic magic;
362   GList *to_write = NULL;
363   unsigned long file_position = 0;
364   BinaryRegistryCache *cache;
365
366   GST_INFO ("Building binary registry cache image");
367
368   g_return_val_if_fail (GST_IS_REGISTRY (registry), FALSE);
369
370   if (!gst_registry_binary_initialize_magic (&magic))
371     goto fail;
372
373   /* iterate trough the list of plugins and fit them into binary structures */
374   for (walk = registry->plugins; walk; walk = g_list_next (walk)) {
375     GstPlugin *plugin = GST_PLUGIN (walk->data);
376
377     if (!plugin->filename)
378       continue;
379
380     if (plugin->flags & GST_PLUGIN_FLAG_CACHED) {
381       GStatBuf statbuf;
382
383       if (g_stat (plugin->filename, &statbuf) < 0 ||
384           plugin->file_mtime != statbuf.st_mtime ||
385           plugin->file_size != statbuf.st_size)
386         continue;
387     }
388
389     if (!_priv_gst_registry_chunks_save_plugin (&to_write, registry, plugin)) {
390       GST_ERROR ("Can't write binary plugin information for \"%s\"",
391           plugin->filename);
392     }
393   }
394
395   _priv_gst_registry_chunks_save_global_header (&to_write, registry,
396       priv_gst_plugin_loading_get_whitelist_hash ());
397
398   GST_INFO ("Writing binary registry cache");
399
400   cache = gst_registry_binary_cache_init (registry, location);
401   if (!cache)
402     goto fail_free_list;
403
404   /* write magic */
405   if (gst_registry_binary_cache_write (cache, file_position,
406           &magic, sizeof (GstBinaryRegistryMagic)) !=
407       sizeof (GstBinaryRegistryMagic)) {
408     GST_ERROR ("Failed to write binary registry magic");
409     goto fail_free_list;
410   }
411   file_position += sizeof (GstBinaryRegistryMagic);
412
413   /* write out data chunks */
414   for (walk = to_write; walk; walk = g_list_next (walk)) {
415     GstRegistryChunk *cur = walk->data;
416     gboolean res;
417
418     res = gst_registry_binary_write_chunk (cache, cur, &file_position);
419
420     _priv_gst_registry_chunk_free (cur);
421     walk->data = NULL;
422     if (!res)
423       goto fail_free_list;
424   }
425   g_list_free (to_write);
426
427   if (!gst_registry_binary_cache_finish (cache, TRUE))
428     return FALSE;
429
430   return TRUE;
431
432   /* Errors */
433 fail_free_list:
434   {
435     for (walk = to_write; walk; walk = g_list_next (walk)) {
436       GstRegistryChunk *cur = walk->data;
437
438       if (cur)
439         _priv_gst_registry_chunk_free (cur);
440     }
441     g_list_free (to_write);
442
443     if (cache)
444       (void) gst_registry_binary_cache_finish (cache, FALSE);
445     /* fall through */
446   }
447 fail:
448   {
449     return FALSE;
450   }
451 }
452
453
454 /* Registry loading */
455
456 /*
457  * gst_registry_binary_check_magic:
458  *
459  * Check GstBinaryRegistryMagic validity.
460  * Return < 0 if something is wrong, -2 means
461  * that just the version of the registry is out of
462  * date, -1 is a general failure.
463  */
464 static gint
465 gst_registry_binary_check_magic (gchar ** in, gsize size)
466 {
467   GstBinaryRegistryMagic *m;
468
469   align (*in);
470   GST_DEBUG ("Reading/casting for GstBinaryRegistryMagic at address %p", *in);
471   unpack_element (*in, m, GstBinaryRegistryMagic, (*in + size), fail);
472
473   if (strncmp (m->magic, GST_MAGIC_BINARY_REGISTRY_STR,
474           GST_MAGIC_BINARY_REGISTRY_LEN) != 0) {
475     GST_WARNING
476         ("Binary registry magic is different : %02x%02x%02x%02x != %02x%02x%02x%02x",
477         GST_MAGIC_BINARY_REGISTRY_STR[0] & 0xff,
478         GST_MAGIC_BINARY_REGISTRY_STR[1] & 0xff,
479         GST_MAGIC_BINARY_REGISTRY_STR[2] & 0xff,
480         GST_MAGIC_BINARY_REGISTRY_STR[3] & 0xff, m->magic[0] & 0xff,
481         m->magic[1] & 0xff, m->magic[2] & 0xff, m->magic[3] & 0xff);
482     return -1;
483   }
484   if (strncmp (m->version, GST_MAGIC_BINARY_VERSION_STR,
485           GST_MAGIC_BINARY_VERSION_LEN)) {
486     GST_WARNING ("Binary registry magic version is different : %s != %s",
487         GST_MAGIC_BINARY_VERSION_STR, m->version);
488     return -2;
489   }
490
491   return 0;
492
493 fail:
494   GST_WARNING ("Not enough data for binary registry magic structure");
495   return -1;
496 }
497
498 /**
499  * gst_registry_binary_read_cache:
500  * @registry: a #GstRegistry
501  * @location: a filename
502  *
503  * Read the contents of the binary cache file at @location into @registry.
504  *
505  * Returns: %TRUE on success.
506  */
507 gboolean
508 gst_registry_binary_read_cache (GstRegistry * registry, const char *location)
509 {
510   GMappedFile *mapped = NULL;
511   gchar *contents = NULL;
512   gchar *in = NULL;
513   gsize size;
514   GError *err = NULL;
515   gboolean res = FALSE;
516   guint32 filter_env_hash = 0;
517   gint check_magic_result;
518 #ifndef GST_DISABLE_GST_DEBUG
519   GTimer *timer = NULL;
520   gdouble seconds;
521 #endif
522
523   /* make sure these types exist */
524   GST_TYPE_ELEMENT_FACTORY;
525   GST_TYPE_TYPE_FIND_FACTORY;
526   GST_TYPE_INDEX_FACTORY;
527
528 #ifndef GST_DISABLE_GST_DEBUG
529   timer = g_timer_new ();
530 #endif
531
532   mapped = g_mapped_file_new (location, FALSE, &err);
533   if (G_UNLIKELY (err != NULL)) {
534     GST_INFO ("Unable to mmap file %s : %s", location, err->message);
535     g_error_free (err);
536     err = NULL;
537   }
538
539   if (mapped == NULL) {
540     /* Error mmap-ing the cache, try a plain memory read */
541
542     g_file_get_contents (location, &contents, &size, &err);
543     if (err != NULL) {
544       GST_INFO ("Unable to read file %s : %s", location, err->message);
545 #ifndef GST_DISABLE_GST_DEBUG
546       g_timer_destroy (timer);
547 #endif
548       g_error_free (err);
549       return FALSE;
550     }
551   } else {
552     /* This can't fail if g_mapped_file_new() succeeded */
553     contents = g_mapped_file_get_contents (mapped);
554     size = g_mapped_file_get_length (mapped);
555   }
556
557   /* in is a cursor pointer, we initialize it with the begin of registry and is updated on each read */
558   in = contents;
559   GST_DEBUG ("File data at address %p", in);
560   if (G_UNLIKELY (size < sizeof (GstBinaryRegistryMagic))) {
561     GST_ERROR ("No or broken registry header for file at %s", location);
562     goto Error;
563   }
564
565   /* check if header is valid */
566   if (G_UNLIKELY ((check_magic_result =
567               gst_registry_binary_check_magic (&in, size)) < 0)) {
568
569     if (check_magic_result == -1)
570       GST_ERROR
571           ("Binary registry type not recognized (invalid magic) for file at %s",
572           location);
573     goto Error;
574   }
575
576   if (!_priv_gst_registry_chunks_load_global_header (registry, &in,
577           contents + size, &filter_env_hash)) {
578     GST_ERROR ("Couldn't read global header chunk");
579     goto Error;
580   }
581
582   if (filter_env_hash != priv_gst_plugin_loading_get_whitelist_hash ()) {
583     GST_INFO_OBJECT (registry, "Plugin loading filter environment changed, "
584         "ignoring plugin cache to force update with new filter environment");
585     goto done;
586   }
587
588   /* check if there are plugins in the file */
589   if (G_UNLIKELY (!(((gsize) in + sizeof (GstRegistryChunkPluginElement)) <
590               (gsize) contents + size))) {
591     GST_INFO ("No binary plugins structure to read");
592     /* empty file, this is not an error */
593   } else {
594     gchar *end = contents + size;
595     /* read as long as we still have space for a GstRegistryChunkPluginElement */
596     for (;
597         ((gsize) in + sizeof (GstRegistryChunkPluginElement)) <
598         (gsize) contents + size;) {
599       GST_DEBUG ("reading binary registry %" G_GSIZE_FORMAT "(%x)/%"
600           G_GSIZE_FORMAT, (gsize) in - (gsize) contents,
601           (guint) ((gsize) in - (gsize) contents), size);
602       if (!_priv_gst_registry_chunks_load_plugin (registry, &in, end, NULL)) {
603         GST_ERROR ("Problem while reading binary registry %s", location);
604         goto Error;
605       }
606     }
607   }
608
609 done:
610
611 #ifndef GST_DISABLE_GST_DEBUG
612   g_timer_stop (timer);
613   seconds = g_timer_elapsed (timer, NULL);
614 #endif
615
616   GST_INFO ("loaded %s in %lf seconds", location, seconds);
617
618   res = TRUE;
619   /* TODO: once we re-use the pointers to registry contents, return here */
620
621 Error:
622 #ifndef GST_DISABLE_GST_DEBUG
623   g_timer_destroy (timer);
624 #endif
625   if (mapped) {
626     g_mapped_file_unref (mapped);
627   } else {
628     g_free (contents);
629   }
630   return res;
631 }
632
633 #ifndef GST_REMOVE_DEPRECATED
634 #ifdef GST_DISABLE_DEPRECATED
635 gboolean
636 gst_registry_xml_read_cache (GstRegistry * registry, const char *location);
637 #endif
638 /* FIXME 0.11: these symbols are here for backwards compatibility and should
639  * be removed or made private */
640 gboolean
641 gst_registry_xml_read_cache (GstRegistry * registry, const char *location)
642 {
643   return FALSE;
644 }
645
646 #ifdef GST_DISABLE_DEPRECATED
647 gboolean
648 gst_registry_xml_write_cache (GstRegistry * registry, const char *location);
649 #endif
650 gboolean
651 gst_registry_xml_write_cache (GstRegistry * registry, const char *location)
652 {
653   return FALSE;
654 }
655 #endif /* GST_REMOVE_DEPRECATED */