mem-overflow: test malloc and realloc corner cases
[platform/upstream/glib.git] / gio / gcontenttype.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2
3 /* GIO - GLib Input, Output and Streaming Library
4  *
5  * Copyright (C) 2006-2007 Red Hat, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser 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  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public 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  * Author: Alexander Larsson <alexl@redhat.com>
23  */
24
25 #include "config.h"
26 #include <sys/types.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <stdio.h>
30 #include "gcontenttypeprivate.h"
31 #include "gthemedicon.h"
32 #include "gicon.h"
33 #include "gfile.h"
34 #include "gfileenumerator.h"
35 #include "gfileinfo.h"
36 #include "glibintl.h"
37
38
39 /**
40  * SECTION:gcontenttype
41  * @short_description: Platform-specific content typing
42  * @include: gio/gio.h
43  *
44  * A content type is a platform specific string that defines the type
45  * of a file. On UNIX it is a <ulink url="http://www.wikipedia.org/wiki/Internet_media_type">mime type</ulink> like "text/plain" or "image/png".
46  * On Win32 it is an extension string like ".doc", ".txt" or a perceived
47  * string like "audio". Such strings can be looked up in the registry at
48  * HKEY_CLASSES_ROOT.
49  **/
50
51 #include <dirent.h>
52
53 #define XDG_PREFIX _gio_xdg
54 #include "xdgmime/xdgmime.h"
55
56 /* We lock this mutex whenever we modify global state in this module.  */
57 G_LOCK_DEFINE_STATIC (gio_xdgmime);
58
59 gsize
60 _g_unix_content_type_get_sniff_len (void)
61 {
62   gsize size;
63
64   G_LOCK (gio_xdgmime);
65   size = xdg_mime_get_max_buffer_extents ();
66   G_UNLOCK (gio_xdgmime);
67
68   return size;
69 }
70
71 gchar *
72 _g_unix_content_type_unalias (const gchar *type)
73 {
74   gchar *res;
75
76   G_LOCK (gio_xdgmime);
77   res = g_strdup (xdg_mime_unalias_mime_type (type));
78   G_UNLOCK (gio_xdgmime);
79
80   return res;
81 }
82
83 gchar **
84 _g_unix_content_type_get_parents (const gchar *type)
85 {
86   const gchar *umime;
87   gchar **parents;
88   GPtrArray *array;
89   int i;
90
91   array = g_ptr_array_new ();
92
93   G_LOCK (gio_xdgmime);
94
95   umime = xdg_mime_unalias_mime_type (type);
96
97   g_ptr_array_add (array, g_strdup (umime));
98
99   parents = xdg_mime_list_mime_parents (umime);
100   for (i = 0; parents && parents[i] != NULL; i++)
101     g_ptr_array_add (array, g_strdup (parents[i]));
102
103   free (parents);
104
105   G_UNLOCK (gio_xdgmime);
106
107   g_ptr_array_add (array, NULL);
108
109   return (gchar **)g_ptr_array_free (array, FALSE);
110 }
111
112 /**
113  * g_content_type_equals:
114  * @type1: a content type string
115  * @type2: a content type string
116  *
117  * Compares two content types for equality.
118  *
119  * Returns: %TRUE if the two strings are identical or equivalent,
120  *     %FALSE otherwise.
121  */
122 gboolean
123 g_content_type_equals (const gchar *type1,
124                        const gchar *type2)
125 {
126   gboolean res;
127
128   g_return_val_if_fail (type1 != NULL, FALSE);
129   g_return_val_if_fail (type2 != NULL, FALSE);
130
131   G_LOCK (gio_xdgmime);
132   res = xdg_mime_mime_type_equal (type1, type2);
133   G_UNLOCK (gio_xdgmime);
134
135   return res;
136 }
137
138 /**
139  * g_content_type_is_a:
140  * @type: a content type string
141  * @supertype: a content type string
142  *
143  * Determines if @type is a subset of @supertype.
144  *
145  * Returns: %TRUE if @type is a kind of @supertype,
146  *     %FALSE otherwise.
147  */
148 gboolean
149 g_content_type_is_a (const gchar *type,
150                      const gchar *supertype)
151 {
152   gboolean res;
153
154   g_return_val_if_fail (type != NULL, FALSE);
155   g_return_val_if_fail (supertype != NULL, FALSE);
156
157   G_LOCK (gio_xdgmime);
158   res = xdg_mime_mime_type_subclass (type, supertype);
159   G_UNLOCK (gio_xdgmime);
160
161   return res;
162 }
163
164 /**
165  * g_content_type_is_unknown:
166  * @type: a content type string
167  *
168  * Checks if the content type is the generic "unknown" type.
169  * On UNIX this is the "application/octet-stream" mimetype,
170  * while on win32 it is "*".
171  *
172  * Returns: %TRUE if the type is the unknown type.
173  */
174 gboolean
175 g_content_type_is_unknown (const gchar *type)
176 {
177   g_return_val_if_fail (type != NULL, FALSE);
178
179   return strcmp (XDG_MIME_TYPE_UNKNOWN, type) == 0;
180 }
181
182
183 typedef enum {
184   MIME_TAG_TYPE_OTHER,
185   MIME_TAG_TYPE_COMMENT
186 } MimeTagType;
187
188 typedef struct {
189   int current_type;
190   int current_lang_level;
191   int comment_lang_level;
192   char *comment;
193 } MimeParser;
194
195
196 static int
197 language_level (const char *lang)
198 {
199   const char * const *lang_list;
200   int i;
201
202   /* The returned list is sorted from most desirable to least
203      desirable and always contains the default locale "C". */
204   lang_list = g_get_language_names ();
205
206   for (i = 0; lang_list[i]; i++)
207     if (strcmp (lang_list[i], lang) == 0)
208       return 1000-i;
209
210   return 0;
211 }
212
213 static void
214 mime_info_start_element (GMarkupParseContext  *context,
215                          const gchar          *element_name,
216                          const gchar         **attribute_names,
217                          const gchar         **attribute_values,
218                          gpointer              user_data,
219                          GError              **error)
220 {
221   int i;
222   const char *lang;
223   MimeParser *parser = user_data;
224
225   if (strcmp (element_name, "comment") == 0)
226     {
227       lang = "C";
228       for (i = 0; attribute_names[i]; i++)
229         if (strcmp (attribute_names[i], "xml:lang") == 0)
230           {
231             lang = attribute_values[i];
232             break;
233           }
234
235       parser->current_lang_level = language_level (lang);
236       parser->current_type = MIME_TAG_TYPE_COMMENT;
237     }
238   else
239     parser->current_type = MIME_TAG_TYPE_OTHER;
240 }
241
242 static void
243 mime_info_end_element (GMarkupParseContext  *context,
244                        const gchar          *element_name,
245                        gpointer              user_data,
246                        GError              **error)
247 {
248   MimeParser *parser = user_data;
249
250   parser->current_type = MIME_TAG_TYPE_OTHER;
251 }
252
253 static void
254 mime_info_text (GMarkupParseContext  *context,
255                 const gchar          *text,
256                 gsize                 text_len,
257                 gpointer              user_data,
258                 GError              **error)
259 {
260   MimeParser *parser = user_data;
261
262   if (parser->current_type == MIME_TAG_TYPE_COMMENT &&
263       parser->current_lang_level > parser->comment_lang_level)
264     {
265       g_free (parser->comment);
266       parser->comment = g_strndup (text, text_len);
267       parser->comment_lang_level = parser->current_lang_level;
268     }
269 }
270
271 static char *
272 load_comment_for_mime_helper (const char *dir,
273                               const char *basename)
274 {
275   GMarkupParseContext *context;
276   char *filename, *data;
277   gsize len;
278   gboolean res;
279   MimeParser parse_data = {0};
280   GMarkupParser parser = {
281     mime_info_start_element,
282     mime_info_end_element,
283     mime_info_text
284   };
285
286   filename = g_build_filename (dir, "mime", basename, NULL);
287
288   res = g_file_get_contents (filename,  &data,  &len,  NULL);
289   g_free (filename);
290   if (!res)
291     return NULL;
292
293   context = g_markup_parse_context_new   (&parser, 0, &parse_data, NULL);
294   res = g_markup_parse_context_parse (context, data, len, NULL);
295   g_free (data);
296   g_markup_parse_context_free (context);
297
298   if (!res)
299     return NULL;
300
301   return parse_data.comment;
302 }
303
304
305 static char *
306 load_comment_for_mime (const char *mimetype)
307 {
308   const char * const* dirs;
309   char *basename;
310   char *comment;
311   int i;
312
313   basename = g_strdup_printf ("%s.xml", mimetype);
314
315   comment = load_comment_for_mime_helper (g_get_user_data_dir (), basename);
316   if (comment)
317     {
318       g_free (basename);
319       return comment;
320     }
321
322   dirs = g_get_system_data_dirs ();
323
324   for (i = 0; dirs[i] != NULL; i++)
325     {
326       comment = load_comment_for_mime_helper (dirs[i], basename);
327       if (comment)
328         {
329           g_free (basename);
330           return comment;
331         }
332     }
333   g_free (basename);
334
335   return g_strdup_printf (_("%s type"), mimetype);
336 }
337
338 /**
339  * g_content_type_get_description:
340  * @type: a content type string
341  *
342  * Gets the human readable description of the content type.
343  *
344  * Returns: a short description of the content type @type. Free the
345  *     returned string with g_free()
346  */
347 gchar *
348 g_content_type_get_description (const gchar *type)
349 {
350   static GHashTable *type_comment_cache = NULL;
351   gchar *comment;
352
353   g_return_val_if_fail (type != NULL, NULL);
354
355   G_LOCK (gio_xdgmime);
356   type = xdg_mime_unalias_mime_type (type);
357
358   if (type_comment_cache == NULL)
359     type_comment_cache = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
360
361   comment = g_hash_table_lookup (type_comment_cache, type);
362   comment = g_strdup (comment);
363   G_UNLOCK (gio_xdgmime);
364
365   if (comment != NULL)
366     return comment;
367
368   comment = load_comment_for_mime (type);
369
370   G_LOCK (gio_xdgmime);
371   g_hash_table_insert (type_comment_cache,
372                        g_strdup (type),
373                        g_strdup (comment));
374   G_UNLOCK (gio_xdgmime);
375
376   return comment;
377 }
378
379 /**
380  * g_content_type_get_mime_type:
381  * @type: a content type string
382  *
383  * Gets the mime type for the content type, if one is registered.
384  *
385  * Returns: (allow-none): the registered mime type for the given @type,
386  *     or %NULL if unknown.
387  */
388 char *
389 g_content_type_get_mime_type (const char *type)
390 {
391   g_return_val_if_fail (type != NULL, NULL);
392
393   return g_strdup (type);
394 }
395
396
397 static GIcon *
398 g_content_type_get_icon_internal (const gchar *type,
399                                   gboolean     symbolic)
400 {
401   char *mimetype_icon;
402   char *generic_mimetype_icon = NULL;
403   char *q;
404   char *xdg_mimetype_icon = NULL;
405   char *legacy_mimetype_icon;
406   char *xdg_mimetype_generic_icon;
407   char *icon_names[5];
408   int n = 0;
409   GIcon *themed_icon;
410   const char *file_template;
411   const char  *xdg_icon;
412
413   g_return_val_if_fail (type != NULL, NULL);
414
415   if (symbolic)
416     {
417       file_template = "%s-symbolic";
418     }
419   else
420     {
421       file_template = "%s";
422     }
423
424   G_LOCK (gio_xdgmime);
425   xdg_icon = xdg_mime_get_icon (type);
426   G_UNLOCK (gio_xdgmime);
427   if (xdg_icon != NULL)
428     xdg_mimetype_icon = g_strdup_printf (file_template, xdg_icon);
429   xdg_mimetype_generic_icon = g_content_type_get_generic_icon_name (type);
430
431   mimetype_icon = g_strdup_printf (file_template, type);
432   if (xdg_mimetype_generic_icon)
433     generic_mimetype_icon = g_strdup_printf (file_template, xdg_mimetype_generic_icon);
434
435   while ((q = strchr (mimetype_icon, '/')) != NULL)
436     *q = '-';
437
438   /* Not all icons have migrated to the new icon theme spec, look for old names too */
439   legacy_mimetype_icon = g_strconcat ("gnome-mime-", mimetype_icon, NULL);
440
441   if (xdg_mimetype_icon)
442     icon_names[n++] = xdg_mimetype_icon;
443
444   icon_names[n++] = mimetype_icon;
445   icon_names[n++] = legacy_mimetype_icon;
446
447   if (generic_mimetype_icon)
448     icon_names[n++] = generic_mimetype_icon;
449
450   themed_icon = g_themed_icon_new_from_names (icon_names, n);
451
452   g_free (xdg_mimetype_icon);
453   g_free (xdg_mimetype_generic_icon);
454   g_free (mimetype_icon);
455   g_free (legacy_mimetype_icon);
456   g_free (generic_mimetype_icon);
457
458   return themed_icon;
459 }
460
461 /**
462  * g_content_type_get_icon:
463  * @type: a content type string
464  *
465  * Gets the icon for a content type.
466  *
467  * Returns: (transfer full): #GIcon corresponding to the content type. Free the returned
468  *     object with g_object_unref()
469  */
470 GIcon *
471 g_content_type_get_icon (const gchar *type)
472 {
473   return g_content_type_get_icon_internal (type, FALSE);
474 }
475
476 /**
477  * g_content_type_get_symbolic_icon:
478  * @type: a content type string
479  *
480  * Gets the symbolic icon for a content type.
481  *
482  * Returns: (transfer full): symbolic #GIcon corresponding to the content type.
483  *     Free the returned object with g_object_unref()
484  *
485  * Since: 2.34
486  */
487 GIcon *
488 g_content_type_get_symbolic_icon (const gchar *type)
489 {
490   return g_content_type_get_icon_internal (type, TRUE);
491 }
492
493 /**
494  * g_content_type_get_generic_icon_name:
495  * @type: a content type string
496  *
497  * Gets the generic icon name for a content type.
498  *
499  * See the <ulink url="http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec">shared-mime-info</ulink>
500  * specification for more on the generic icon name.
501  *
502  * Returns: (allow-none): the registered generic icon name for the given @type,
503  *     or %NULL if unknown. Free with g_free()
504  *
505  * Since: 2.34
506  */
507 gchar *
508 g_content_type_get_generic_icon_name (const gchar *type)
509 {
510   const gchar *xdg_icon_name;
511   gchar *icon_name;
512
513   G_LOCK (gio_xdgmime);
514   xdg_icon_name = xdg_mime_get_generic_icon (type);
515   G_UNLOCK (gio_xdgmime);
516
517   if (!xdg_icon_name)
518     {
519       const char *p;
520       const char *suffix = "-x-generic";
521
522       p = strchr (type, '/');
523       if (p == NULL)
524         p = type + strlen (type);
525
526       icon_name = g_malloc (p - type + strlen (suffix) + 1);
527       memcpy (icon_name, type, p - type);
528       memcpy (icon_name + (p - type), suffix, strlen (suffix));
529       icon_name[(p - type) + strlen (suffix)] = 0;
530     }
531   else
532     {
533       icon_name = g_strdup (xdg_icon_name);
534     }
535
536   return icon_name;
537 }
538
539 /**
540  * g_content_type_can_be_executable:
541  * @type: a content type string
542  *
543  * Checks if a content type can be executable. Note that for instance
544  * things like text files can be executables (i.e. scripts and batch files).
545  *
546  * Returns: %TRUE if the file type corresponds to a type that
547  *     can be executable, %FALSE otherwise.
548  */
549 gboolean
550 g_content_type_can_be_executable (const gchar *type)
551 {
552   g_return_val_if_fail (type != NULL, FALSE);
553
554   if (g_content_type_is_a (type, "application/x-executable")  ||
555       g_content_type_is_a (type, "text/plain"))
556     return TRUE;
557
558   return FALSE;
559 }
560
561 static gboolean
562 looks_like_text (const guchar *data, gsize data_size)
563 {
564   gsize i;
565   char c;
566
567   for (i = 0; i < data_size; i++)
568     {
569       c = data[i];
570
571       if (g_ascii_iscntrl (c) &&
572           !g_ascii_isspace (c) &&
573           c != '\b')
574         return FALSE;
575     }
576   return TRUE;
577 }
578
579 /**
580  * g_content_type_from_mime_type:
581  * @mime_type: a mime type string
582  *
583  * Tries to find a content type based on the mime type name.
584  *
585  * Returns: (allow-none): Newly allocated string with content type
586  *     or %NULL. Free with g_free()
587  *
588  * Since: 2.18
589  **/
590 gchar *
591 g_content_type_from_mime_type (const gchar *mime_type)
592 {
593   char *umime;
594
595   g_return_val_if_fail (mime_type != NULL, NULL);
596
597   G_LOCK (gio_xdgmime);
598   /* mime type and content type are same on unixes */
599   umime = g_strdup (xdg_mime_unalias_mime_type (mime_type));
600   G_UNLOCK (gio_xdgmime);
601
602   return umime;
603 }
604
605 /**
606  * g_content_type_guess:
607  * @filename: (allow-none): a string, or %NULL
608  * @data: (allow-none) (array length=data_size): a stream of data, or %NULL
609  * @data_size: the size of @data
610  * @result_uncertain: (allow-none) (out): return location for the certainty
611  *     of the result, or %NULL
612  *
613  * Guesses the content type based on example data. If the function is
614  * uncertain, @result_uncertain will be set to %TRUE. Either @filename
615  * or @data may be %NULL, in which case the guess will be based solely
616  * on the other argument.
617  *
618  * Returns: a string indicating a guessed content type for the
619  *     given data. Free with g_free()
620  */
621 gchar *
622 g_content_type_guess (const gchar  *filename,
623                       const guchar *data,
624                       gsize         data_size,
625                       gboolean     *result_uncertain)
626 {
627   char *basename;
628   const char *name_mimetypes[10], *sniffed_mimetype;
629   char *mimetype;
630   int i;
631   int n_name_mimetypes;
632   int sniffed_prio;
633
634   sniffed_prio = 0;
635   n_name_mimetypes = 0;
636   sniffed_mimetype = XDG_MIME_TYPE_UNKNOWN;
637
638   if (result_uncertain)
639     *result_uncertain = FALSE;
640
641   /* our test suite and potentially other code used -1 in the past, which is
642    * not documented and not allowed; guard against that */
643   g_return_val_if_fail (data_size != (gsize) -1, g_strdup (XDG_MIME_TYPE_UNKNOWN));
644
645   G_LOCK (gio_xdgmime);
646
647   if (filename)
648     {
649       i = strlen (filename);
650       if (filename[i - 1] == '/')
651         {
652           name_mimetypes[0] = "inode/directory";
653           name_mimetypes[1] = NULL;
654           n_name_mimetypes = 1;
655           if (result_uncertain)
656             *result_uncertain = TRUE;
657         }
658       else
659         {
660           basename = g_path_get_basename (filename);
661           n_name_mimetypes = xdg_mime_get_mime_types_from_file_name (basename, name_mimetypes, 10);
662           g_free (basename);
663         }
664     }
665
666   /* Got an extension match, and no conflicts. This is it. */
667   if (n_name_mimetypes == 1)
668     {
669       gchar *s = g_strdup (name_mimetypes[0]);
670       G_UNLOCK (gio_xdgmime);
671       return s;
672     }
673
674   if (data)
675     {
676       sniffed_mimetype = xdg_mime_get_mime_type_for_data (data, data_size, &sniffed_prio);
677       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
678           data &&
679           looks_like_text (data, data_size))
680         sniffed_mimetype = "text/plain";
681
682       /* For security reasons we don't ever want to sniff desktop files
683        * where we know the filename and it doesn't have a .desktop extension.
684        * This is because desktop files allow executing any application and
685        * we don't want to make it possible to hide them looking like something
686        * else.
687        */
688       if (filename != NULL &&
689           strcmp (sniffed_mimetype, "application/x-desktop") == 0)
690         sniffed_mimetype = "text/plain";
691     }
692
693   if (n_name_mimetypes == 0)
694     {
695       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
696           result_uncertain)
697         *result_uncertain = TRUE;
698
699       mimetype = g_strdup (sniffed_mimetype);
700     }
701   else
702     {
703       mimetype = NULL;
704       if (sniffed_mimetype != XDG_MIME_TYPE_UNKNOWN)
705         {
706           if (sniffed_prio >= 80) /* High priority sniffing match, use that */
707             mimetype = g_strdup (sniffed_mimetype);
708           else
709             {
710               /* There are conflicts between the name matches and we
711                * have a sniffed type, use that as a tie breaker.
712                */
713               for (i = 0; i < n_name_mimetypes; i++)
714                 {
715                   if ( xdg_mime_mime_type_subclass (name_mimetypes[i], sniffed_mimetype))
716                     {
717                       /* This nametype match is derived from (or the same as)
718                        * the sniffed type). This is probably it.
719                        */
720                       mimetype = g_strdup (name_mimetypes[i]);
721                       break;
722                     }
723                 }
724             }
725         }
726
727       if (mimetype == NULL)
728         {
729           /* Conflicts, and sniffed type was no help or not there.
730            * Guess on the first one
731            */
732           mimetype = g_strdup (name_mimetypes[0]);
733           if (result_uncertain)
734             *result_uncertain = TRUE;
735         }
736     }
737
738   G_UNLOCK (gio_xdgmime);
739
740   return mimetype;
741 }
742
743 static void
744 enumerate_mimetypes_subdir (const char *dir,
745                             const char *prefix,
746                             GHashTable *mimetypes)
747 {
748   DIR *d;
749   struct dirent *ent;
750   char *mimetype;
751
752   d = opendir (dir);
753   if (d)
754     {
755       while ((ent = readdir (d)) != NULL)
756         {
757           if (g_str_has_suffix (ent->d_name, ".xml"))
758             {
759               mimetype = g_strdup_printf ("%s/%.*s", prefix, (int) strlen (ent->d_name) - 4, ent->d_name);
760               g_hash_table_replace (mimetypes, mimetype, NULL);
761             }
762         }
763       closedir (d);
764     }
765 }
766
767 static void
768 enumerate_mimetypes_dir (const char *dir,
769                          GHashTable *mimetypes)
770 {
771   DIR *d;
772   struct dirent *ent;
773   char *mimedir;
774   char *name;
775
776   mimedir = g_build_filename (dir, "mime", NULL);
777
778   d = opendir (mimedir);
779   if (d)
780     {
781       while ((ent = readdir (d)) != NULL)
782         {
783           if (strcmp (ent->d_name, "packages") != 0)
784             {
785               name = g_build_filename (mimedir, ent->d_name, NULL);
786               if (g_file_test (name, G_FILE_TEST_IS_DIR))
787                 enumerate_mimetypes_subdir (name, ent->d_name, mimetypes);
788               g_free (name);
789             }
790         }
791       closedir (d);
792     }
793
794   g_free (mimedir);
795 }
796
797 /**
798  * g_content_types_get_registered:
799  *
800  * Gets a list of strings containing all the registered content types
801  * known to the system. The list and its data should be freed using
802  * <programlisting>
803  * g_list_free_full (list, g_free);
804  * </programlisting>
805  *
806  * Returns: (element-type utf8) (transfer full): #GList of the registered content types
807  */
808 GList *
809 g_content_types_get_registered (void)
810 {
811   const char * const* dirs;
812   GHashTable *mimetypes;
813   GHashTableIter iter;
814   gpointer key;
815   int i;
816   GList *l;
817
818   mimetypes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
819
820   enumerate_mimetypes_dir (g_get_user_data_dir (), mimetypes);
821   dirs = g_get_system_data_dirs ();
822
823   for (i = 0; dirs[i] != NULL; i++)
824     enumerate_mimetypes_dir (dirs[i], mimetypes);
825
826   l = NULL;
827   g_hash_table_iter_init (&iter, mimetypes);
828   while (g_hash_table_iter_next (&iter, &key, NULL))
829     {
830       l = g_list_prepend (l, key);
831       g_hash_table_iter_steal (&iter);
832     }
833
834   g_hash_table_destroy (mimetypes);
835
836   return l;
837 }
838
839
840 /* tree magic data */
841 static GList *tree_matches = NULL;
842 static gboolean need_reload = FALSE;
843
844 G_LOCK_DEFINE_STATIC (gio_treemagic);
845
846 typedef struct
847 {
848   gchar *path;
849   GFileType type;
850   guint match_case : 1;
851   guint executable : 1;
852   guint non_empty  : 1;
853   guint on_disc    : 1;
854   gchar *mimetype;
855   GList *matches;
856 } TreeMatchlet;
857
858 typedef struct
859 {
860   gchar *contenttype;
861   gint priority;
862   GList *matches;
863 } TreeMatch;
864
865
866 static void
867 tree_matchlet_free (TreeMatchlet *matchlet)
868 {
869   g_list_free_full (matchlet->matches, (GDestroyNotify) tree_matchlet_free);
870   g_free (matchlet->path);
871   g_free (matchlet->mimetype);
872   g_slice_free (TreeMatchlet, matchlet);
873 }
874
875 static void
876 tree_match_free (TreeMatch *match)
877 {
878   g_list_free_full (match->matches, (GDestroyNotify) tree_matchlet_free);
879   g_free (match->contenttype);
880   g_slice_free (TreeMatch, match);
881 }
882
883 static TreeMatch *
884 parse_header (gchar *line)
885 {
886   gint len;
887   gchar *s;
888   TreeMatch *match;
889
890   len = strlen (line);
891
892   if (line[0] != '[' || line[len - 1] != ']')
893     return NULL;
894
895   line[len - 1] = 0;
896   s = strchr (line, ':');
897
898   match = g_slice_new0 (TreeMatch);
899   match->priority = atoi (line + 1);
900   match->contenttype = g_strdup (s + 1);
901
902   return match;
903 }
904
905 static TreeMatchlet *
906 parse_match_line (gchar *line,
907                   gint  *depth)
908 {
909   gchar *s, *p;
910   TreeMatchlet *matchlet;
911   gchar **parts;
912   gint i;
913
914   matchlet = g_slice_new0 (TreeMatchlet);
915
916   if (line[0] == '>')
917     {
918       *depth = 0;
919       s = line;
920     }
921   else
922     {
923       *depth = atoi (line);
924       s = strchr (line, '>');
925     }
926   s += 2;
927   p = strchr (s, '"');
928   *p = 0;
929
930   matchlet->path = g_strdup (s);
931   s = p + 1;
932   parts = g_strsplit (s, ",", 0);
933   if (strcmp (parts[0], "=file") == 0)
934     matchlet->type = G_FILE_TYPE_REGULAR;
935   else if (strcmp (parts[0], "=directory") == 0)
936     matchlet->type = G_FILE_TYPE_DIRECTORY;
937   else if (strcmp (parts[0], "=link") == 0)
938     matchlet->type = G_FILE_TYPE_SYMBOLIC_LINK;
939   else
940     matchlet->type = G_FILE_TYPE_UNKNOWN;
941   for (i = 1; parts[i]; i++)
942     {
943       if (strcmp (parts[i], "executable") == 0)
944         matchlet->executable = 1;
945       else if (strcmp (parts[i], "match-case") == 0)
946         matchlet->match_case = 1;
947       else if (strcmp (parts[i], "non-empty") == 0)
948         matchlet->non_empty = 1;
949       else if (strcmp (parts[i], "on-disc") == 0)
950         matchlet->on_disc = 1;
951       else
952         matchlet->mimetype = g_strdup (parts[i]);
953     }
954
955   g_strfreev (parts);
956
957   return matchlet;
958 }
959
960 static gint
961 cmp_match (gconstpointer a, gconstpointer b)
962 {
963   const TreeMatch *aa = (const TreeMatch *)a;
964   const TreeMatch *bb = (const TreeMatch *)b;
965
966   return bb->priority - aa->priority;
967 }
968
969 static void
970 insert_match (TreeMatch *match)
971 {
972   tree_matches = g_list_insert_sorted (tree_matches, match, cmp_match);
973 }
974
975 static void
976 insert_matchlet (TreeMatch    *match,
977                  TreeMatchlet *matchlet,
978                  gint          depth)
979 {
980   if (depth == 0)
981     match->matches = g_list_append (match->matches, matchlet);
982   else
983     {
984       GList *last;
985       TreeMatchlet *m;
986
987       last = g_list_last (match->matches);
988       if (!last)
989         {
990           tree_matchlet_free (matchlet);
991           g_warning ("can't insert tree matchlet at depth %d", depth);
992           return;
993         }
994
995       m = (TreeMatchlet *) last->data;
996       while (--depth > 0)
997         {
998           last = g_list_last (m->matches);
999           if (!last)
1000             {
1001               tree_matchlet_free (matchlet);
1002               g_warning ("can't insert tree matchlet at depth %d", depth);
1003               return;
1004             }
1005
1006           m = (TreeMatchlet *) last->data;
1007         }
1008       m->matches = g_list_append (m->matches, matchlet);
1009     }
1010 }
1011
1012 static void
1013 read_tree_magic_from_directory (const gchar *prefix)
1014 {
1015   gchar *filename;
1016   gchar *text;
1017   gsize len;
1018   gchar **lines;
1019   gint i;
1020   TreeMatch *match;
1021   TreeMatchlet *matchlet;
1022   gint depth;
1023
1024   filename = g_build_filename (prefix, "mime", "treemagic", NULL);
1025
1026   if (g_file_get_contents (filename, &text, &len, NULL))
1027     {
1028       if (strcmp (text, "MIME-TreeMagic") == 0)
1029         {
1030           lines = g_strsplit (text + strlen ("MIME-TreeMagic") + 2, "\n", 0);
1031           match = NULL;
1032           for (i = 0; lines[i] && lines[i][0]; i++)
1033             {
1034               if (lines[i][0] == '[')
1035                 {
1036                   match = parse_header (lines[i]);
1037                   insert_match (match);
1038                 }
1039               else
1040                 {
1041                   matchlet = parse_match_line (lines[i], &depth);
1042                   insert_matchlet (match, matchlet, depth);
1043                 }
1044             }
1045
1046           g_strfreev (lines);
1047         }
1048       else
1049         g_warning ("%s: header not found, skipping\n", filename);
1050
1051       g_free (text);
1052     }
1053
1054   g_free (filename);
1055 }
1056
1057
1058 static void
1059 xdg_mime_reload (void *user_data)
1060 {
1061   need_reload = TRUE;
1062 }
1063
1064 static void
1065 tree_magic_shutdown (void)
1066 {
1067   g_list_free_full (tree_matches, (GDestroyNotify) tree_match_free);
1068   tree_matches = NULL;
1069 }
1070
1071 static void
1072 tree_magic_init (void)
1073 {
1074   static gboolean initialized = FALSE;
1075   const gchar *dir;
1076   const gchar * const * dirs;
1077   int i;
1078
1079   if (!initialized)
1080     {
1081       initialized = TRUE;
1082
1083       xdg_mime_register_reload_callback (xdg_mime_reload, NULL, NULL);
1084       need_reload = TRUE;
1085     }
1086
1087   if (need_reload)
1088     {
1089       need_reload = FALSE;
1090
1091       tree_magic_shutdown ();
1092
1093       dir = g_get_user_data_dir ();
1094       read_tree_magic_from_directory (dir);
1095       dirs = g_get_system_data_dirs ();
1096       for (i = 0; dirs[i]; i++)
1097         read_tree_magic_from_directory (dirs[i]);
1098     }
1099 }
1100
1101 /* a filtering enumerator */
1102
1103 typedef struct
1104 {
1105   gchar *path;
1106   gint depth;
1107   gboolean ignore_case;
1108   gchar **components;
1109   gchar **case_components;
1110   GFileEnumerator **enumerators;
1111   GFile **children;
1112 } Enumerator;
1113
1114 static gboolean
1115 component_match (Enumerator  *e,
1116                  gint         depth,
1117                  const gchar *name)
1118 {
1119   gchar *case_folded, *key;
1120   gboolean found;
1121
1122   if (strcmp (name, e->components[depth]) == 0)
1123     return TRUE;
1124
1125   if (!e->ignore_case)
1126     return FALSE;
1127
1128   case_folded = g_utf8_casefold (name, -1);
1129   key = g_utf8_collate_key (case_folded, -1);
1130
1131   found = strcmp (key, e->case_components[depth]) == 0;
1132
1133   g_free (case_folded);
1134   g_free (key);
1135
1136   return found;
1137 }
1138
1139 static GFile *
1140 next_match_recurse (Enumerator *e,
1141                     gint        depth)
1142 {
1143   GFile *file;
1144   GFileInfo *info;
1145   const gchar *name;
1146
1147   while (TRUE)
1148     {
1149       if (e->enumerators[depth] == NULL)
1150         {
1151           if (depth > 0)
1152             {
1153               file = next_match_recurse (e, depth - 1);
1154               if (file)
1155                 {
1156                   e->children[depth] = file;
1157                   e->enumerators[depth] = g_file_enumerate_children (file,
1158                                                                      G_FILE_ATTRIBUTE_STANDARD_NAME,
1159                                                                      G_FILE_QUERY_INFO_NONE,
1160                                                                      NULL,
1161                                                                      NULL);
1162                 }
1163             }
1164           if (e->enumerators[depth] == NULL)
1165             return NULL;
1166         }
1167
1168       while ((info = g_file_enumerator_next_file (e->enumerators[depth], NULL, NULL)))
1169         {
1170           name = g_file_info_get_name (info);
1171           if (component_match (e, depth, name))
1172             {
1173               file = g_file_get_child (e->children[depth], name);
1174               g_object_unref (info);
1175               return file;
1176             }
1177           g_object_unref (info);
1178         }
1179
1180       g_object_unref (e->enumerators[depth]);
1181       e->enumerators[depth] = NULL;
1182       g_object_unref (e->children[depth]);
1183       e->children[depth] = NULL;
1184     }
1185 }
1186
1187 static GFile *
1188 enumerator_next (Enumerator *e)
1189 {
1190   return next_match_recurse (e, e->depth - 1);
1191 }
1192
1193 static Enumerator *
1194 enumerator_new (GFile      *root,
1195                 const char *path,
1196                 gboolean    ignore_case)
1197 {
1198   Enumerator *e;
1199   gint i;
1200   gchar *case_folded;
1201
1202   e = g_new0 (Enumerator, 1);
1203   e->path = g_strdup (path);
1204   e->ignore_case = ignore_case;
1205
1206   e->components = g_strsplit (e->path, G_DIR_SEPARATOR_S, -1);
1207   e->depth = g_strv_length (e->components);
1208   if (e->ignore_case)
1209     {
1210       e->case_components = g_new0 (char *, e->depth + 1);
1211       for (i = 0; e->components[i]; i++)
1212         {
1213           case_folded = g_utf8_casefold (e->components[i], -1);
1214           e->case_components[i] = g_utf8_collate_key (case_folded, -1);
1215           g_free (case_folded);
1216         }
1217     }
1218
1219   e->children = g_new0 (GFile *, e->depth);
1220   e->children[0] = g_object_ref (root);
1221   e->enumerators = g_new0 (GFileEnumerator *, e->depth);
1222   e->enumerators[0] = g_file_enumerate_children (root,
1223                                                  G_FILE_ATTRIBUTE_STANDARD_NAME,
1224                                                  G_FILE_QUERY_INFO_NONE,
1225                                                  NULL,
1226                                                  NULL);
1227
1228   return e;
1229 }
1230
1231 static void
1232 enumerator_free (Enumerator *e)
1233 {
1234   gint i;
1235
1236   for (i = 0; i < e->depth; i++)
1237     {
1238       if (e->enumerators[i])
1239         g_object_unref (e->enumerators[i]);
1240       if (e->children[i])
1241         g_object_unref (e->children[i]);
1242     }
1243
1244   g_free (e->enumerators);
1245   g_free (e->children);
1246   g_strfreev (e->components);
1247   if (e->case_components)
1248     g_strfreev (e->case_components);
1249   g_free (e->path);
1250   g_free (e);
1251 }
1252
1253 static gboolean
1254 matchlet_match (TreeMatchlet *matchlet,
1255                 GFile        *root)
1256 {
1257   GFile *file;
1258   GFileInfo *info;
1259   gboolean result;
1260   const gchar *attrs;
1261   Enumerator *e;
1262   GList *l;
1263
1264   e = enumerator_new (root, matchlet->path, !matchlet->match_case);
1265
1266   do
1267     {
1268       file = enumerator_next (e);
1269       if (!file)
1270         {
1271           enumerator_free (e);
1272           return FALSE;
1273         }
1274
1275       if (matchlet->mimetype)
1276         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1277                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE ","
1278                 G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE;
1279       else
1280         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1281                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE;
1282       info = g_file_query_info (file,
1283                                 attrs,
1284                                 G_FILE_QUERY_INFO_NONE,
1285                                 NULL,
1286                                 NULL);
1287       if (info)
1288         {
1289           result = TRUE;
1290
1291           if (matchlet->type != G_FILE_TYPE_UNKNOWN &&
1292               g_file_info_get_file_type (info) != matchlet->type)
1293             result = FALSE;
1294
1295           if (matchlet->executable &&
1296               !g_file_info_get_attribute_boolean (info, G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE))
1297             result = FALSE;
1298         }
1299       else
1300         result = FALSE;
1301
1302       if (result && matchlet->non_empty)
1303         {
1304           GFileEnumerator *child_enum;
1305           GFileInfo *child_info;
1306
1307           child_enum = g_file_enumerate_children (file,
1308                                                   G_FILE_ATTRIBUTE_STANDARD_NAME,
1309                                                   G_FILE_QUERY_INFO_NONE,
1310                                                   NULL,
1311                                                   NULL);
1312
1313           if (child_enum)
1314             {
1315               child_info = g_file_enumerator_next_file (child_enum, NULL, NULL);
1316               if (child_info)
1317                 g_object_unref (child_info);
1318               else
1319                 result = FALSE;
1320               g_object_unref (child_enum);
1321             }
1322           else
1323             result = FALSE;
1324         }
1325
1326       if (result && matchlet->mimetype)
1327         {
1328           if (strcmp (matchlet->mimetype, g_file_info_get_content_type (info)) != 0)
1329             result = FALSE;
1330         }
1331
1332       g_object_unref (info);
1333       g_object_unref (file);
1334     }
1335   while (!result);
1336
1337   enumerator_free (e);
1338
1339   if (!matchlet->matches)
1340     return TRUE;
1341
1342   for (l = matchlet->matches; l; l = l->next)
1343     {
1344       TreeMatchlet *submatchlet;
1345
1346       submatchlet = l->data;
1347       if (matchlet_match (submatchlet, root))
1348         return TRUE;
1349     }
1350
1351   return FALSE;
1352 }
1353
1354 static void
1355 match_match (TreeMatch    *match,
1356              GFile        *root,
1357              GPtrArray    *types)
1358 {
1359   GList *l;
1360
1361   for (l = match->matches; l; l = l->next)
1362     {
1363       TreeMatchlet *matchlet = l->data;
1364       if (matchlet_match (matchlet, root))
1365         {
1366           g_ptr_array_add (types, g_strdup (match->contenttype));
1367           break;
1368         }
1369     }
1370 }
1371
1372 /**
1373  * g_content_type_guess_for_tree:
1374  * @root: the root of the tree to guess a type for
1375  *
1376  * Tries to guess the type of the tree with root @root, by
1377  * looking at the files it contains. The result is an array
1378  * of content types, with the best guess coming first.
1379  *
1380  * The types returned all have the form x-content/foo, e.g.
1381  * x-content/audio-cdda (for audio CDs) or x-content/image-dcf
1382  * (for a camera memory card). See the <ulink url="http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec">shared-mime-info</ulink>
1383  * specification for more on x-content types.
1384  *
1385  * This function is useful in the implementation of
1386  * g_mount_guess_content_type().
1387  *
1388  * Returns: (transfer full) (array zero-terminated=1): an %NULL-terminated
1389  *     array of zero or more content types. Free with g_strfreev()
1390  *
1391  * Since: 2.18
1392  */
1393 gchar **
1394 g_content_type_guess_for_tree (GFile *root)
1395 {
1396   GPtrArray *types;
1397   GList *l;
1398
1399   types = g_ptr_array_new ();
1400
1401   G_LOCK (gio_treemagic);
1402
1403   tree_magic_init ();
1404   for (l = tree_matches; l; l = l->next)
1405     {
1406       TreeMatch *match = l->data;
1407       match_match (match, root, types);
1408     }
1409
1410   G_UNLOCK (gio_treemagic);
1411
1412   g_ptr_array_add (types, NULL);
1413
1414   return (gchar **)g_ptr_array_free (types, FALSE);
1415 }