Split gcontenttype.c
[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  * g_content_type_get_icon:
398  * @type: a content type string
399  *
400  * Gets the icon for a content type.
401  *
402  * Returns: (transfer full): #GIcon corresponding to the content type. Free the returned
403  *     object with g_object_unref()
404  */
405 GIcon *
406 g_content_type_get_icon (const gchar *type)
407 {
408   char *mimetype_icon, *generic_mimetype_icon, *q;
409   char *xdg_mimetype_icon, *legacy_mimetype_icon;
410   char *xdg_mimetype_generic_icon;
411   char *icon_names[5];
412   int n = 0;
413   const char *p;
414   GIcon *themed_icon;
415
416   g_return_val_if_fail (type != NULL, NULL);
417
418   G_LOCK (gio_xdgmime);
419   xdg_mimetype_icon = g_strdup (xdg_mime_get_icon (type));
420   xdg_mimetype_generic_icon = g_strdup (xdg_mime_get_generic_icon (type));
421   G_UNLOCK (gio_xdgmime);
422
423   mimetype_icon = g_strdup (type);
424
425   while ((q = strchr (mimetype_icon, '/')) != NULL)
426     *q = '-';
427
428   p = strchr (type, '/');
429   if (p == NULL)
430     p = type + strlen (type);
431
432   /* Not all icons have migrated to the new icon theme spec, look for old names too */
433   legacy_mimetype_icon = g_strconcat ("gnome-mime-", mimetype_icon, NULL);
434
435   generic_mimetype_icon = g_malloc (p - type + strlen ("-x-generic") + 1);
436   memcpy (generic_mimetype_icon, type, p - type);
437   memcpy (generic_mimetype_icon + (p - type), "-x-generic", strlen ("-x-generic"));
438   generic_mimetype_icon[(p - type) + strlen ("-x-generic")] = 0;
439
440   if (xdg_mimetype_icon)
441     icon_names[n++] = xdg_mimetype_icon;
442
443   icon_names[n++] = mimetype_icon;
444   icon_names[n++] = legacy_mimetype_icon;
445
446   if (xdg_mimetype_generic_icon)
447     icon_names[n++] = xdg_mimetype_generic_icon;
448
449   icon_names[n++] = generic_mimetype_icon;
450
451   themed_icon = g_themed_icon_new_from_names (icon_names, n);
452
453   g_free (xdg_mimetype_icon);
454   g_free (xdg_mimetype_generic_icon);
455   g_free (mimetype_icon);
456   g_free (legacy_mimetype_icon);
457   g_free (generic_mimetype_icon);
458
459   return themed_icon;
460 }
461
462 /**
463  * g_content_type_can_be_executable:
464  * @type: a content type string
465  *
466  * Checks if a content type can be executable. Note that for instance
467  * things like text files can be executables (i.e. scripts and batch files).
468  *
469  * Returns: %TRUE if the file type corresponds to a type that
470  *     can be executable, %FALSE otherwise.
471  */
472 gboolean
473 g_content_type_can_be_executable (const gchar *type)
474 {
475   g_return_val_if_fail (type != NULL, FALSE);
476
477   if (g_content_type_is_a (type, "application/x-executable")  ||
478       g_content_type_is_a (type, "text/plain"))
479     return TRUE;
480
481   return FALSE;
482 }
483
484 static gboolean
485 looks_like_text (const guchar *data, gsize data_size)
486 {
487   gsize i;
488   char c;
489
490   for (i = 0; i < data_size; i++)
491     {
492       c = data[i];
493
494       if (g_ascii_iscntrl (c) &&
495           !g_ascii_isspace (c) &&
496           c != '\b')
497         return FALSE;
498     }
499   return TRUE;
500 }
501
502 /**
503  * g_content_type_from_mime_type:
504  * @mime_type: a mime type string
505  *
506  * Tries to find a content type based on the mime type name.
507  *
508  * Returns: (allow-none): Newly allocated string with content type
509  *     or %NULL. Free with g_free()
510  *
511  * Since: 2.18
512  **/
513 gchar *
514 g_content_type_from_mime_type (const gchar *mime_type)
515 {
516   char *umime;
517
518   g_return_val_if_fail (mime_type != NULL, NULL);
519
520   G_LOCK (gio_xdgmime);
521   /* mime type and content type are same on unixes */
522   umime = g_strdup (xdg_mime_unalias_mime_type (mime_type));
523   G_UNLOCK (gio_xdgmime);
524
525   return umime;
526 }
527
528 /**
529  * g_content_type_guess:
530  * @filename: (allow-none): a string, or %NULL
531  * @data: (allow-none) (array length=data_size): a stream of data, or %NULL
532  * @data_size: the size of @data
533  * @result_uncertain: (allow-none) (out): return location for the certainty
534  *     of the result, or %NULL
535  *
536  * Guesses the content type based on example data. If the function is
537  * uncertain, @result_uncertain will be set to %TRUE. Either @filename
538  * or @data may be %NULL, in which case the guess will be based solely
539  * on the other argument.
540  *
541  * Returns: a string indicating a guessed content type for the
542  *     given data. Free with g_free()
543  */
544 gchar *
545 g_content_type_guess (const gchar  *filename,
546                       const guchar *data,
547                       gsize         data_size,
548                       gboolean     *result_uncertain)
549 {
550   char *basename;
551   const char *name_mimetypes[10], *sniffed_mimetype;
552   char *mimetype;
553   int i;
554   int n_name_mimetypes;
555   int sniffed_prio;
556
557   sniffed_prio = 0;
558   n_name_mimetypes = 0;
559   sniffed_mimetype = XDG_MIME_TYPE_UNKNOWN;
560
561   if (result_uncertain)
562     *result_uncertain = FALSE;
563
564   /* our test suite and potentially other code used -1 in the past, which is
565    * not documented and not allowed; guard against that */
566   g_return_val_if_fail (data_size != (gsize) -1, g_strdup (XDG_MIME_TYPE_UNKNOWN));
567
568   G_LOCK (gio_xdgmime);
569
570   if (filename)
571     {
572       i = strlen (filename);
573       if (filename[i - 1] == '/')
574         {
575           name_mimetypes[0] = "inode/directory";
576           name_mimetypes[1] = NULL;
577           n_name_mimetypes = 1;
578           if (result_uncertain)
579             *result_uncertain = TRUE;
580         }
581       else
582         {
583           basename = g_path_get_basename (filename);
584           n_name_mimetypes = xdg_mime_get_mime_types_from_file_name (basename, name_mimetypes, 10);
585           g_free (basename);
586         }
587     }
588
589   /* Got an extension match, and no conflicts. This is it. */
590   if (n_name_mimetypes == 1)
591     {
592       G_UNLOCK (gio_xdgmime);
593       return g_strdup (name_mimetypes[0]);
594     }
595
596   if (data)
597     {
598       sniffed_mimetype = xdg_mime_get_mime_type_for_data (data, data_size, &sniffed_prio);
599       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
600           data &&
601           looks_like_text (data, data_size))
602         sniffed_mimetype = "text/plain";
603
604       /* For security reasons we don't ever want to sniff desktop files
605        * where we know the filename and it doesn't have a .desktop extension.
606        * This is because desktop files allow executing any application and
607        * we don't want to make it possible to hide them looking like something
608        * else.
609        */
610       if (filename != NULL &&
611           strcmp (sniffed_mimetype, "application/x-desktop") == 0)
612         sniffed_mimetype = "text/plain";
613     }
614
615   if (n_name_mimetypes == 0)
616     {
617       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
618           result_uncertain)
619         *result_uncertain = TRUE;
620
621       mimetype = g_strdup (sniffed_mimetype);
622     }
623   else
624     {
625       mimetype = NULL;
626       if (sniffed_mimetype != XDG_MIME_TYPE_UNKNOWN)
627         {
628           if (sniffed_prio >= 80) /* High priority sniffing match, use that */
629             mimetype = g_strdup (sniffed_mimetype);
630           else
631             {
632               /* There are conflicts between the name matches and we
633                * have a sniffed type, use that as a tie breaker.
634                */
635               for (i = 0; i < n_name_mimetypes; i++)
636                 {
637                   if ( xdg_mime_mime_type_subclass (name_mimetypes[i], sniffed_mimetype))
638                     {
639                       /* This nametype match is derived from (or the same as)
640                        * the sniffed type). This is probably it.
641                        */
642                       mimetype = g_strdup (name_mimetypes[i]);
643                       break;
644                     }
645                 }
646             }
647         }
648
649       if (mimetype == NULL)
650         {
651           /* Conflicts, and sniffed type was no help or not there.
652            * Guess on the first one
653            */
654           mimetype = g_strdup (name_mimetypes[0]);
655           if (result_uncertain)
656             *result_uncertain = TRUE;
657         }
658     }
659
660   G_UNLOCK (gio_xdgmime);
661
662   return mimetype;
663 }
664
665 static void
666 enumerate_mimetypes_subdir (const char *dir,
667                             const char *prefix,
668                             GHashTable *mimetypes)
669 {
670   DIR *d;
671   struct dirent *ent;
672   char *mimetype;
673
674   d = opendir (dir);
675   if (d)
676     {
677       while ((ent = readdir (d)) != NULL)
678         {
679           if (g_str_has_suffix (ent->d_name, ".xml"))
680             {
681               mimetype = g_strdup_printf ("%s/%.*s", prefix, (int) strlen (ent->d_name) - 4, ent->d_name);
682               g_hash_table_replace (mimetypes, mimetype, NULL);
683             }
684         }
685       closedir (d);
686     }
687 }
688
689 static void
690 enumerate_mimetypes_dir (const char *dir,
691                          GHashTable *mimetypes)
692 {
693   DIR *d;
694   struct dirent *ent;
695   char *mimedir;
696   char *name;
697
698   mimedir = g_build_filename (dir, "mime", NULL);
699
700   d = opendir (mimedir);
701   if (d)
702     {
703       while ((ent = readdir (d)) != NULL)
704         {
705           if (strcmp (ent->d_name, "packages") != 0)
706             {
707               name = g_build_filename (mimedir, ent->d_name, NULL);
708               if (g_file_test (name, G_FILE_TEST_IS_DIR))
709                 enumerate_mimetypes_subdir (name, ent->d_name, mimetypes);
710               g_free (name);
711             }
712         }
713       closedir (d);
714     }
715
716   g_free (mimedir);
717 }
718
719 /**
720  * g_content_types_get_registered:
721  *
722  * Gets a list of strings containing all the registered content types
723  * known to the system. The list and its data should be freed using
724  * <programlisting>
725  * g_list_free_full (list, g_free);
726  * </programlisting>
727  *
728  * Returns: (element-type utf8) (transfer full): #GList of the registered content types
729  */
730 GList *
731 g_content_types_get_registered (void)
732 {
733   const char * const* dirs;
734   GHashTable *mimetypes;
735   GHashTableIter iter;
736   gpointer key;
737   int i;
738   GList *l;
739
740   mimetypes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
741
742   enumerate_mimetypes_dir (g_get_user_data_dir (), mimetypes);
743   dirs = g_get_system_data_dirs ();
744
745   for (i = 0; dirs[i] != NULL; i++)
746     enumerate_mimetypes_dir (dirs[i], mimetypes);
747
748   l = NULL;
749   g_hash_table_iter_init (&iter, mimetypes);
750   while (g_hash_table_iter_next (&iter, &key, NULL))
751     {
752       l = g_list_prepend (l, key);
753       g_hash_table_iter_steal (&iter);
754     }
755
756   g_hash_table_destroy (mimetypes);
757
758   return l;
759 }
760
761
762 /* tree magic data */
763 static GList *tree_matches = NULL;
764 static gboolean need_reload = FALSE;
765
766 G_LOCK_DEFINE_STATIC (gio_treemagic);
767
768 typedef struct
769 {
770   gchar *path;
771   GFileType type;
772   guint match_case : 1;
773   guint executable : 1;
774   guint non_empty  : 1;
775   guint on_disc    : 1;
776   gchar *mimetype;
777   GList *matches;
778 } TreeMatchlet;
779
780 typedef struct
781 {
782   gchar *contenttype;
783   gint priority;
784   GList *matches;
785 } TreeMatch;
786
787
788 static void
789 tree_matchlet_free (TreeMatchlet *matchlet)
790 {
791   g_list_free_full (matchlet->matches, (GDestroyNotify) tree_matchlet_free);
792   g_free (matchlet->path);
793   g_free (matchlet->mimetype);
794   g_slice_free (TreeMatchlet, matchlet);
795 }
796
797 static void
798 tree_match_free (TreeMatch *match)
799 {
800   g_list_free_full (match->matches, (GDestroyNotify) tree_matchlet_free);
801   g_free (match->contenttype);
802   g_slice_free (TreeMatch, match);
803 }
804
805 static TreeMatch *
806 parse_header (gchar *line)
807 {
808   gint len;
809   gchar *s;
810   TreeMatch *match;
811
812   len = strlen (line);
813
814   if (line[0] != '[' || line[len - 1] != ']')
815     return NULL;
816
817   line[len - 1] = 0;
818   s = strchr (line, ':');
819
820   match = g_slice_new0 (TreeMatch);
821   match->priority = atoi (line + 1);
822   match->contenttype = g_strdup (s + 1);
823
824   return match;
825 }
826
827 static TreeMatchlet *
828 parse_match_line (gchar *line,
829                   gint  *depth)
830 {
831   gchar *s, *p;
832   TreeMatchlet *matchlet;
833   gchar **parts;
834   gint i;
835
836   matchlet = g_slice_new0 (TreeMatchlet);
837
838   if (line[0] == '>')
839     {
840       *depth = 0;
841       s = line;
842     }
843   else
844     {
845       *depth = atoi (line);
846       s = strchr (line, '>');
847     }
848   s += 2;
849   p = strchr (s, '"');
850   *p = 0;
851
852   matchlet->path = g_strdup (s);
853   s = p + 1;
854   parts = g_strsplit (s, ",", 0);
855   if (strcmp (parts[0], "=file") == 0)
856     matchlet->type = G_FILE_TYPE_REGULAR;
857   else if (strcmp (parts[0], "=directory") == 0)
858     matchlet->type = G_FILE_TYPE_DIRECTORY;
859   else if (strcmp (parts[0], "=link") == 0)
860     matchlet->type = G_FILE_TYPE_SYMBOLIC_LINK;
861   else
862     matchlet->type = G_FILE_TYPE_UNKNOWN;
863   for (i = 1; parts[i]; i++)
864     {
865       if (strcmp (parts[i], "executable") == 0)
866         matchlet->executable = 1;
867       else if (strcmp (parts[i], "match-case") == 0)
868         matchlet->match_case = 1;
869       else if (strcmp (parts[i], "non-empty") == 0)
870         matchlet->non_empty = 1;
871       else if (strcmp (parts[i], "on-disc") == 0)
872         matchlet->on_disc = 1;
873       else
874         matchlet->mimetype = g_strdup (parts[i]);
875     }
876
877   g_strfreev (parts);
878
879   return matchlet;
880 }
881
882 static gint
883 cmp_match (gconstpointer a, gconstpointer b)
884 {
885   const TreeMatch *aa = (const TreeMatch *)a;
886   const TreeMatch *bb = (const TreeMatch *)b;
887
888   return bb->priority - aa->priority;
889 }
890
891 static void
892 insert_match (TreeMatch *match)
893 {
894   tree_matches = g_list_insert_sorted (tree_matches, match, cmp_match);
895 }
896
897 static void
898 insert_matchlet (TreeMatch    *match,
899                  TreeMatchlet *matchlet,
900                  gint          depth)
901 {
902   if (depth == 0)
903     match->matches = g_list_append (match->matches, matchlet);
904   else
905     {
906       GList *last;
907       TreeMatchlet *m;
908
909       last = g_list_last (match->matches);
910       if (!last)
911         {
912           tree_matchlet_free (matchlet);
913           g_warning ("can't insert tree matchlet at depth %d", depth);
914           return;
915         }
916
917       m = (TreeMatchlet *) last->data;
918       while (--depth > 0)
919         {
920           last = g_list_last (m->matches);
921           if (!last)
922             {
923               tree_matchlet_free (matchlet);
924               g_warning ("can't insert tree matchlet at depth %d", depth);
925               return;
926             }
927
928           m = (TreeMatchlet *) last->data;
929         }
930       m->matches = g_list_append (m->matches, matchlet);
931     }
932 }
933
934 static void
935 read_tree_magic_from_directory (const gchar *prefix)
936 {
937   gchar *filename;
938   gchar *text;
939   gsize len;
940   gchar **lines;
941   gint i;
942   TreeMatch *match;
943   TreeMatchlet *matchlet;
944   gint depth;
945
946   filename = g_build_filename (prefix, "mime", "treemagic", NULL);
947
948   if (g_file_get_contents (filename, &text, &len, NULL))
949     {
950       if (strcmp (text, "MIME-TreeMagic") == 0)
951         {
952           lines = g_strsplit (text + strlen ("MIME-TreeMagic") + 2, "\n", 0);
953           match = NULL;
954           for (i = 0; lines[i] && lines[i][0]; i++)
955             {
956               if (lines[i][0] == '[')
957                 {
958                   match = parse_header (lines[i]);
959                   insert_match (match);
960                 }
961               else
962                 {
963                   matchlet = parse_match_line (lines[i], &depth);
964                   insert_matchlet (match, matchlet, depth);
965                 }
966             }
967
968           g_strfreev (lines);
969         }
970       else
971         g_warning ("%s: header not found, skipping\n", filename);
972
973       g_free (text);
974     }
975
976   g_free (filename);
977 }
978
979
980 static void
981 xdg_mime_reload (void *user_data)
982 {
983   need_reload = TRUE;
984 }
985
986 static void
987 tree_magic_shutdown (void)
988 {
989   g_list_free_full (tree_matches, (GDestroyNotify) tree_match_free);
990   tree_matches = NULL;
991 }
992
993 static void
994 tree_magic_init (void)
995 {
996   static gboolean initialized = FALSE;
997   const gchar *dir;
998   const gchar * const * dirs;
999   int i;
1000
1001   if (!initialized)
1002     {
1003       initialized = TRUE;
1004
1005       xdg_mime_register_reload_callback (xdg_mime_reload, NULL, NULL);
1006       need_reload = TRUE;
1007     }
1008
1009   if (need_reload)
1010     {
1011       need_reload = FALSE;
1012
1013       tree_magic_shutdown ();
1014
1015       dir = g_get_user_data_dir ();
1016       read_tree_magic_from_directory (dir);
1017       dirs = g_get_system_data_dirs ();
1018       for (i = 0; dirs[i]; i++)
1019         read_tree_magic_from_directory (dirs[i]);
1020     }
1021 }
1022
1023 /* a filtering enumerator */
1024
1025 typedef struct
1026 {
1027   gchar *path;
1028   gint depth;
1029   gboolean ignore_case;
1030   gchar **components;
1031   gchar **case_components;
1032   GFileEnumerator **enumerators;
1033   GFile **children;
1034 } Enumerator;
1035
1036 static gboolean
1037 component_match (Enumerator  *e,
1038                  gint         depth,
1039                  const gchar *name)
1040 {
1041   gchar *case_folded, *key;
1042   gboolean found;
1043
1044   if (strcmp (name, e->components[depth]) == 0)
1045     return TRUE;
1046
1047   if (!e->ignore_case)
1048     return FALSE;
1049
1050   case_folded = g_utf8_casefold (name, -1);
1051   key = g_utf8_collate_key (case_folded, -1);
1052
1053   found = strcmp (key, e->case_components[depth]) == 0;
1054
1055   g_free (case_folded);
1056   g_free (key);
1057
1058   return found;
1059 }
1060
1061 static GFile *
1062 next_match_recurse (Enumerator *e,
1063                     gint        depth)
1064 {
1065   GFile *file;
1066   GFileInfo *info;
1067   const gchar *name;
1068
1069   while (TRUE)
1070     {
1071       if (e->enumerators[depth] == NULL)
1072         {
1073           if (depth > 0)
1074             {
1075               file = next_match_recurse (e, depth - 1);
1076               if (file)
1077                 {
1078                   e->children[depth] = file;
1079                   e->enumerators[depth] = g_file_enumerate_children (file,
1080                                                                      G_FILE_ATTRIBUTE_STANDARD_NAME,
1081                                                                      G_FILE_QUERY_INFO_NONE,
1082                                                                      NULL,
1083                                                                      NULL);
1084                 }
1085             }
1086           if (e->enumerators[depth] == NULL)
1087             return NULL;
1088         }
1089
1090       while ((info = g_file_enumerator_next_file (e->enumerators[depth], NULL, NULL)))
1091         {
1092           name = g_file_info_get_name (info);
1093           if (component_match (e, depth, name))
1094             {
1095               file = g_file_get_child (e->children[depth], name);
1096               g_object_unref (info);
1097               return file;
1098             }
1099           g_object_unref (info);
1100         }
1101
1102       g_object_unref (e->enumerators[depth]);
1103       e->enumerators[depth] = NULL;
1104       g_object_unref (e->children[depth]);
1105       e->children[depth] = NULL;
1106     }
1107 }
1108
1109 static GFile *
1110 enumerator_next (Enumerator *e)
1111 {
1112   return next_match_recurse (e, e->depth - 1);
1113 }
1114
1115 static Enumerator *
1116 enumerator_new (GFile      *root,
1117                 const char *path,
1118                 gboolean    ignore_case)
1119 {
1120   Enumerator *e;
1121   gint i;
1122   gchar *case_folded;
1123
1124   e = g_new0 (Enumerator, 1);
1125   e->path = g_strdup (path);
1126   e->ignore_case = ignore_case;
1127
1128   e->components = g_strsplit (e->path, G_DIR_SEPARATOR_S, -1);
1129   e->depth = g_strv_length (e->components);
1130   if (e->ignore_case)
1131     {
1132       e->case_components = g_new0 (char *, e->depth + 1);
1133       for (i = 0; e->components[i]; i++)
1134         {
1135           case_folded = g_utf8_casefold (e->components[i], -1);
1136           e->case_components[i] = g_utf8_collate_key (case_folded, -1);
1137           g_free (case_folded);
1138         }
1139     }
1140
1141   e->children = g_new0 (GFile *, e->depth);
1142   e->children[0] = g_object_ref (root);
1143   e->enumerators = g_new0 (GFileEnumerator *, e->depth);
1144   e->enumerators[0] = g_file_enumerate_children (root,
1145                                                  G_FILE_ATTRIBUTE_STANDARD_NAME,
1146                                                  G_FILE_QUERY_INFO_NONE,
1147                                                  NULL,
1148                                                  NULL);
1149
1150   return e;
1151 }
1152
1153 static void
1154 enumerator_free (Enumerator *e)
1155 {
1156   gint i;
1157
1158   for (i = 0; i < e->depth; i++)
1159     {
1160       if (e->enumerators[i])
1161         g_object_unref (e->enumerators[i]);
1162       if (e->children[i])
1163         g_object_unref (e->children[i]);
1164     }
1165
1166   g_free (e->enumerators);
1167   g_free (e->children);
1168   g_strfreev (e->components);
1169   if (e->case_components)
1170     g_strfreev (e->case_components);
1171   g_free (e->path);
1172   g_free (e);
1173 }
1174
1175 static gboolean
1176 matchlet_match (TreeMatchlet *matchlet,
1177                 GFile        *root)
1178 {
1179   GFile *file;
1180   GFileInfo *info;
1181   gboolean result;
1182   const gchar *attrs;
1183   Enumerator *e;
1184   GList *l;
1185
1186   e = enumerator_new (root, matchlet->path, !matchlet->match_case);
1187
1188   do
1189     {
1190       file = enumerator_next (e);
1191       if (!file)
1192         {
1193           enumerator_free (e);
1194           return FALSE;
1195         }
1196
1197       if (matchlet->mimetype)
1198         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1199                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE ","
1200                 G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE;
1201       else
1202         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1203                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE;
1204       info = g_file_query_info (file,
1205                                 attrs,
1206                                 G_FILE_QUERY_INFO_NONE,
1207                                 NULL,
1208                                 NULL);
1209       if (info)
1210         {
1211           result = TRUE;
1212
1213           if (matchlet->type != G_FILE_TYPE_UNKNOWN &&
1214               g_file_info_get_file_type (info) != matchlet->type)
1215             result = FALSE;
1216
1217           if (matchlet->executable &&
1218               !g_file_info_get_attribute_boolean (info, G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE))
1219             result = FALSE;
1220         }
1221       else
1222         result = FALSE;
1223
1224       if (result && matchlet->non_empty)
1225         {
1226           GFileEnumerator *child_enum;
1227           GFileInfo *child_info;
1228
1229           child_enum = g_file_enumerate_children (file,
1230                                                   G_FILE_ATTRIBUTE_STANDARD_NAME,
1231                                                   G_FILE_QUERY_INFO_NONE,
1232                                                   NULL,
1233                                                   NULL);
1234
1235           if (child_enum)
1236             {
1237               child_info = g_file_enumerator_next_file (child_enum, NULL, NULL);
1238               if (child_info)
1239                 g_object_unref (child_info);
1240               else
1241                 result = FALSE;
1242               g_object_unref (child_enum);
1243             }
1244           else
1245             result = FALSE;
1246         }
1247
1248       if (result && matchlet->mimetype)
1249         {
1250           if (strcmp (matchlet->mimetype, g_file_info_get_content_type (info)) != 0)
1251             result = FALSE;
1252         }
1253
1254       g_object_unref (info);
1255       g_object_unref (file);
1256     }
1257   while (!result);
1258
1259   enumerator_free (e);
1260
1261   if (!matchlet->matches)
1262     return TRUE;
1263
1264   for (l = matchlet->matches; l; l = l->next)
1265     {
1266       TreeMatchlet *submatchlet;
1267
1268       submatchlet = l->data;
1269       if (matchlet_match (submatchlet, root))
1270         return TRUE;
1271     }
1272
1273   return FALSE;
1274 }
1275
1276 static void
1277 match_match (TreeMatch    *match,
1278              GFile        *root,
1279              GPtrArray    *types)
1280 {
1281   GList *l;
1282
1283   for (l = match->matches; l; l = l->next)
1284     {
1285       TreeMatchlet *matchlet = l->data;
1286       if (matchlet_match (matchlet, root))
1287         {
1288           g_ptr_array_add (types, g_strdup (match->contenttype));
1289           break;
1290         }
1291     }
1292 }
1293
1294 /**
1295  * g_content_type_guess_for_tree:
1296  * @root: the root of the tree to guess a type for
1297  *
1298  * Tries to guess the type of the tree with root @root, by
1299  * looking at the files it contains. The result is an array
1300  * of content types, with the best guess coming first.
1301  *
1302  * The types returned all have the form x-content/foo, e.g.
1303  * x-content/audio-cdda (for audio CDs) or x-content/image-dcf
1304  * (for a camera memory card). See the <ulink url="http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec">shared-mime-info</ulink>
1305  * specification for more on x-content types.
1306  *
1307  * This function is useful in the implementation of
1308  * g_mount_guess_content_type().
1309  *
1310  * Returns: (transfer full) (array zero-terminated=1): an %NULL-terminated
1311  *     array of zero or more content types. Free with g_strfreev()
1312  *
1313  * Since: 2.18
1314  */
1315 gchar **
1316 g_content_type_guess_for_tree (GFile *root)
1317 {
1318   GPtrArray *types;
1319   GList *l;
1320
1321   types = g_ptr_array_new ();
1322
1323   G_LOCK (gio_treemagic);
1324
1325   tree_magic_init ();
1326   for (l = tree_matches; l; l = l->next)
1327     {
1328       TreeMatch *match = l->data;
1329       match_match (match, root, types);
1330     }
1331
1332   G_UNLOCK (gio_treemagic);
1333
1334   g_ptr_array_add (types, NULL);
1335
1336   return (gchar **)g_ptr_array_free (types, FALSE);
1337 }