* roottypes.cs: Rename from tree.cs.
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / Mime.cs
1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
8 //
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 //
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 //
20 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
21 //
22 // Authors:
23 //
24 //  Alexander Olk       xenomorph2@onlinehome.de
25 //
26
27 using System;
28 using System.IO;
29 using System.Collections;
30 using System.Collections.Specialized;
31 using System.Text.RegularExpressions;
32 using System.Text;
33
34 // Usage:
35 // - for files:
36 //   string mimeType = Mime.GetMimeTypeForFile( string filename );
37 // - for byte array:
38 //   string mimeType = Mime.GetMimeTypeForData( byte[] data );
39 // - for string (maybe an email):
40 //   string mimeType = Mime.GetMimeTypeForString( string input );
41
42 // - get alias for mime type:
43 //   string alias = Mime.GetMimeAlias( string mimeType );
44 // - get subclass for mime type:
45 //   string subtype = Mime.GetMimeSubClass( string mimeType );
46 // - get all available mime types:
47 //   string[] available = Mime.AvailableMimeTypes;
48
49 // TODO:
50 // - optimize even more :)
51 // - async callback ?!?
52 // - freedesktop org file extensions can have regular expressions also, resolve them too
53 // - sort match collections by magic priority ( higher = first ) ?
54
55 // internal test:
56 // looking up the mime types 20 times for 2757 files in /usr/lib without caching (mime_file_cache)
57 // old version: Time: 00:00:32.3791220
58 // new version: Time: 00:00:16.9991810
59
60 namespace System.Windows.Forms
61 {
62         internal class Mime
63         {
64                 public static Mime Instance = new Mime();
65                 
66                 private string current_file_name;
67                 private string global_result = octet_stream;
68                 
69                 private FileStream file_stream;
70                 
71                 private byte[] buffer = null;
72                 
73                 private const string octet_stream = "application/octet-stream";
74                 private const string text_plain = "text/plain";
75                 private const string zero_file = "application/x-zerosize";
76                 
77                 private StringDictionary mime_file_cache = new StringDictionary();
78                 
79                 private const int mime_file_cache_max_size = 3000;
80                 
81                 private string search_string;
82                 
83                 private static object lock_object = new Object();
84                 
85 //              private int platform = (int) Environment.OSVersion.Platform;
86                 
87                 private bool is_zero_file = false;
88                 
89                 private int bytes_read = 0;
90                 
91                 public static NameValueCollection Aliases;
92                 public static NameValueCollection SubClasses;
93                 
94                 public static NameValueCollection GlobalPatternsShort;
95                 public static NameValueCollection GlobalPatternsLong;
96                 public static NameValueCollection GlobalLiterals;
97                 public static NameValueCollection GlobalSufPref;
98                 
99                 public static ArrayList Matches80Plus;
100                 public static ArrayList MatchesBelow80;
101                 
102                 private Mime( )
103                 {
104 #if NET_2_0
105                         Aliases = new NameValueCollection (StringComparer.CurrentCultureIgnoreCase);
106                         SubClasses = new NameValueCollection (StringComparer.CurrentCultureIgnoreCase);
107                         GlobalPatternsShort = new NameValueCollection (StringComparer.CurrentCultureIgnoreCase);
108                         GlobalPatternsLong = new NameValueCollection (StringComparer.CurrentCultureIgnoreCase);
109                         GlobalLiterals = new NameValueCollection (StringComparer.CurrentCultureIgnoreCase);
110                         GlobalSufPref = new NameValueCollection (StringComparer.CurrentCultureIgnoreCase);
111 #else
112                         Aliases = new NameValueCollection (new CaseInsensitiveHashCodeProvider (), new Comparer (System.Globalization.CultureInfo.CurrentUICulture));
113                         SubClasses = new NameValueCollection (new CaseInsensitiveHashCodeProvider (), new Comparer (System.Globalization.CultureInfo.CurrentUICulture));
114                         GlobalPatternsShort = new NameValueCollection (new CaseInsensitiveHashCodeProvider (), new Comparer (System.Globalization.CultureInfo.CurrentUICulture));
115                         GlobalPatternsLong = new NameValueCollection (new CaseInsensitiveHashCodeProvider (), new Comparer (System.Globalization.CultureInfo.CurrentUICulture));
116                         GlobalLiterals = new NameValueCollection (new CaseInsensitiveHashCodeProvider (), new Comparer (System.Globalization.CultureInfo.CurrentUICulture));
117                         GlobalSufPref = new NameValueCollection (new CaseInsensitiveHashCodeProvider (), new Comparer (System.Globalization.CultureInfo.CurrentUICulture));
118 #endif
119                         
120                         Matches80Plus = new ArrayList ();
121                         MatchesBelow80 = new ArrayList ();
122                         
123                         FDOMimeConfigReader fmcr = new FDOMimeConfigReader ();
124                         int buffer_length = fmcr.Init ();
125                         
126                         if (buffer_length != -1) {
127                                 buffer = new byte[ buffer_length ];
128                         }
129                 }
130                 
131                 public static string GetMimeTypeForFile( string filename )
132                 {
133                         lock ( lock_object )
134                         {
135                                 Instance.StartByFileName( filename );
136                         }
137                         
138                         return Instance.global_result;
139                 }
140                 
141                 // not tested
142                 public static string GetMimeTypeForData( byte[] data )
143                 {
144                         lock ( lock_object )
145                         {
146                                 Instance.StartDataLookup( data );
147                         }
148                         
149                         return Instance.global_result;
150                 }
151                 
152                 public static string GetMimeTypeForString( string input )
153                 {
154                         lock ( lock_object )
155                         {
156                                 Instance.StartStringLookup( input );
157                         }
158                         
159                         return Instance.global_result;
160                 }
161                 
162                 public static string GetMimeAlias( string mimetype )
163                 {
164                         return Aliases[ mimetype ];
165                 }
166                 
167                 public static string GetMimeSubClass( string mimetype )
168                 {
169                         return SubClasses[ mimetype ];
170                 }
171                 
172                 private void StartByFileName( string filename )
173                 {
174                         if ( mime_file_cache.ContainsKey( filename ) )
175                         {
176                                 global_result = mime_file_cache[ filename ];
177                                 return;
178                         }
179                         
180                         current_file_name = filename;
181                         is_zero_file = false;
182                         
183 //                      if ( !CheckForInode( ) )
184 //                      {
185                         global_result = octet_stream;
186                         
187                         GoByFileName( );
188 //                      }
189                         
190                         mime_file_cache.Add( current_file_name, global_result );
191                         
192                         if (mime_file_cache.Count > mime_file_cache_max_size) {
193                                 IEnumerator enumerator = mime_file_cache.GetEnumerator ();
194                                 
195                                 int counter = mime_file_cache_max_size - 1000;
196                                 
197                                 while (enumerator.MoveNext ()) {
198                                         mime_file_cache.Remove (enumerator.Current.ToString ());
199                                         counter--;
200                                         
201                                         if (counter == 0)
202                                                 break;
203                                 }
204                         }
205                 }
206                 
207                 private void StartDataLookup( byte[] data )
208                 {
209                         global_result = octet_stream;
210                         
211                         System.Array.Clear( buffer, 0, buffer.Length );
212                         
213                         if ( data.Length > buffer.Length )
214                         {
215                                 System.Array.Copy( data, buffer, buffer.Length );
216                         }
217                         else
218                         {
219                                 System.Array.Copy( data, buffer, data.Length );
220                         }
221                         
222                         if ( CheckMatch80Plus( ) )
223                                 return;
224                         
225                         if ( CheckMatchBelow80( ) )
226                                 return;
227                         
228                         CheckForBinaryOrText( );
229                 }
230                 
231                 private void StartStringLookup( string input )
232                 {
233                         global_result = text_plain;
234                         
235                         search_string = input;
236                         
237                         if ( CheckForContentTypeString( ) )
238                                 return;
239                 }
240                 
241 //              private bool CheckForInode( )
242 //              {
243 //                      if ( ( platform == 4 ) || ( platform == 128 ) )
244 //                      {
245 //#if __MonoCS__
246 //                              try
247 //                              {
248 //                                      // *nix platform
249 //                                      Mono.Unix.UnixFileInfo ufi = new Mono.Unix.UnixFileInfo( current_file_name );
250 //
251 //                                      if ( ufi.IsFile )
252 //                                      {
253 //                                              return false;
254 //                                      }
255 //                                      else
256 //                                      if ( ufi.IsDirectory )
257 //                                      {
258 //                                              global_result = "inode/directory";
259 //                                              return true;
260 //                                      }
261 //                                      else
262 //                                      if ( ufi.IsBlockDevice )
263 //                                      {
264 //                                              global_result = "inode/blockdevice";
265 //                                              return true;
266 //                                      }
267 //                                      else
268 //                                      if ( ufi.IsSocket )
269 //                                      {
270 //                                              global_result = "inode/socket";
271 //                                              return true;
272 //                                      }
273 //                                      else
274 //                                      if ( ufi.IsSymbolicLink )
275 //                                      {
276 //                                              global_result = "inode/symlink";
277 //                                              return true;
278 //                                      }
279 //                                      else
280 //                                      if ( ufi.IsCharacterDevice )
281 //                                      {
282 //                                              global_result = "inode/chardevice";
283 //                                              return true;
284 //                                      }
285 //                                      else
286 //                                      if ( ufi.IsFIFO )
287 //                                      {
288 //                                              global_result = "inode/fifo";
289 //                                              return true;
290 //                                      }
291 //                              } catch( Exception e )
292 //                              {
293 //                                      return false;
294 //                              }
295 //#endif
296 //                      }
297 //                      else
298 //                      {
299 //                              // TODO!!!!
300 //                              // windows platform
301 //                      }
302 //                      
303 //                      return false;
304 //              }
305                 
306                 private void GoByFileName( )
307                 {
308                         // check if we can open the file
309                         if ( !OpenFile( ) )
310                         {
311                                 // couldn't open the file, check globals only
312                                 CheckGlobalPatterns( );
313                                 
314                                 return;
315                         }
316                         
317                         if ( !is_zero_file )
318                         {
319                                 // check for matches with a priority >= 80
320                                 if ( CheckMatch80Plus( ) )
321                                         return;
322                         }
323                         
324                         // check global patterns, aka file extensions...
325                         // this should be done for zero size files also,
326                         // for example zero size file trash.ccc~ should return
327                         // application/x-trash instead of application/x-zerosize
328                         if ( CheckGlobalPatterns( ) )
329                                 return;
330                         
331                         // if file size is zero, no other checks are needed
332                         if ( is_zero_file )
333                                 return;
334                         
335                         // ok, still nothing matches then try matches with a priority < 80
336                         if ( CheckMatchBelow80( ) )
337                                 return;
338                         
339                         // wow, still nothing... return application/octet-stream for binary data, or text/plain for textual data
340                         CheckForBinaryOrText( );
341                 }
342                 
343                 private bool CheckMatch80Plus( )
344                 {
345                         foreach ( Match match in Matches80Plus )
346                         {
347                                 if ( TestMatch( match ) )
348                                 {
349                                         global_result = match.MimeType;
350                                         
351                                         return true;
352                                 }
353                         }
354                         
355                         return false;
356                 }
357                 
358                 // this little helper method gives us a real speed improvement
359                 private bool FastEndsWidth(string input, string value)
360                 {
361                         if (value.Length > input.Length)
362                                 return false;
363                         
364                         int z = input.Length - 1;
365                         
366                         for (int i = value.Length - 1; i > -1; i--) {
367                                 if (value[i] != input[z])
368                                         return false;
369                                 
370                                 z--;
371                         }
372                         
373                         return true;
374                 }
375                 
376                 private bool FastStartsWith(string input, string value)
377                 {
378                         if (value.Length > input.Length)
379                                 return false;
380                         
381                         for (int i = 0; i < value.Length; i++)
382                                 if (value[i] != input[i])
383                                         return false;
384                         
385                         return true;
386                 }
387                 
388                 // start always with index = 0
389                 private int FastIndexOf(string input, char value)
390                 {
391                         if (input.Length == 0)
392                                 return -1;
393                         
394                         for (int i = 0; i < input.Length; i++)
395                                 if (input[i] == value)
396                                         return i;
397                         
398                         return -1;
399                 }
400                 
401                 private int FastIndexOf(string input, string value)
402                 {
403                         if (input.Length == 0)
404                                 return -1;
405                         
406                         for (int i = 0; i < input.Length - value.Length; i++) {
407                                 if (input[i] == value[0]) {
408                                         int counter = 0;
409                                         for (int z = 1; z < value.Length; z++) {
410                                                 if (input[i+z] != value[z])
411                                                         break;
412                                                 
413                                                 counter++;
414                                         }
415                                         if (counter == value.Length -1) {
416                                                 return i;
417                                         }
418                                 }
419                         }
420                         
421                         return -1;
422                 }
423                 
424                 private void CheckGlobalResult( )
425                 {
426                         int comma_index = FastIndexOf(global_result, ',');
427                         
428                         if ( comma_index != -1 )
429                         {
430                                 global_result = global_result.Substring( 0, comma_index );
431                         }
432                 }
433                 
434                 private bool CheckGlobalPatterns( )
435                 {
436                         string filename = Path.GetFileName( current_file_name );
437                         
438                         // first check for literals
439                         for ( int i = 0; i < GlobalLiterals.Count; i++ )
440                         {
441                                 string key = GlobalLiterals.GetKey(i);
442                                 
443                                 // no regex char
444                                 if ( FastIndexOf(key, '[' ) == -1 )
445                                 {
446                                         if (FastIndexOf(filename, key) != -1)
447                                         {
448                                                 global_result = GlobalLiterals[i];
449                                                 CheckGlobalResult( );
450                                                 return true;
451                                         }
452                                 }
453                                 else // regex it ;)
454                                 {
455                                         if ( Regex.IsMatch( filename, key ) )
456                                         {
457                                                 global_result = GlobalLiterals[ i ];
458                                                 CheckGlobalResult( );
459                                                 return true;
460                                         }
461                                 }
462                         }
463                         
464                         if ( FastIndexOf(filename, '.' ) != -1 )
465                         {
466                                 // check for double extension like .tar.gz
467                                 for ( int i = 0; i < GlobalPatternsLong.Count; i++ )
468                                 {
469                                         string key = GlobalPatternsLong.GetKey( i );
470                                         
471                                         if (FastEndsWidth (filename, key))
472                                         {
473                                                 global_result = GlobalPatternsLong[ i ];
474                                                 CheckGlobalResult( );
475                                                 return true;
476                                         }
477                                         else
478                                         {
479                                                 if ( FastEndsWidth (filename.ToLower( ), key ) )
480                                                 {
481                                                         global_result = GlobalPatternsLong[ i ];
482                                                         CheckGlobalResult( );
483                                                         return true;
484                                                 }
485                                         }
486                                 }
487                                 
488                                 // check normal extensions...
489                                 string extension = Path.GetExtension( current_file_name );
490                                 
491                                 if ( extension.Length != 0 )
492                                 {
493                                         global_result = GlobalPatternsShort[ extension ];
494                                         
495                                         if ( global_result != null )
496                                         {
497                                                 CheckGlobalResult( );
498                                                 return true;
499                                         }
500                                         
501                                         global_result = GlobalPatternsShort[ extension.ToLower( ) ];
502                                         
503                                         if ( global_result != null )
504                                         {
505                                                 CheckGlobalResult( );
506                                                 return true;
507                                         }
508                                 }
509                         }
510                         
511                         // finally check if a prefix or suffix matches
512                         for ( int i = 0; i < GlobalSufPref.Count; i++ )
513                         {
514                                 string key = GlobalSufPref.GetKey( i );
515                                 
516                                 if ( key[0] == '*' )
517                                 {
518                                         if (FastEndsWidth(filename, key.Replace( "*", "" )))
519                                         {
520                                                 global_result = GlobalSufPref[ i ];
521                                                 CheckGlobalResult( );
522                                                 return true;
523                                         }
524                                 }
525                                 else
526                                 {
527                                         if ( FastStartsWith(filename, key.Replace( "*", "" ) ) )
528                                         {
529                                                 global_result = GlobalSufPref[ i ];
530                                                 CheckGlobalResult( );
531                                                 return true;
532                                         }
533                                 }
534                         }
535                         
536                         return false;
537                 }
538                 
539                 private bool CheckMatchBelow80( )
540                 {
541                         foreach ( Match match in MatchesBelow80 )
542                         {
543                                 if ( TestMatch( match ) )
544                                 {
545                                         global_result = match.MimeType;
546                                         
547                                         return true;
548                                 }
549                         }
550                         
551                         return false;
552                 }
553                 
554                 private void CheckForBinaryOrText( )
555                 {
556                         // check the first 32 bytes
557                         
558                         for ( int i = 0; i < 32; i++ )
559                         {
560                                 char c = System.Convert.ToChar( buffer[ i ] );
561                                 
562                                 if ( c != '\t' &&  c != '\n' && c != '\r' && c != 12 && c < 32 )
563                                 {
564                                         global_result = octet_stream;
565                                         return;
566                                 }
567                         }
568                         
569                         global_result = text_plain;
570                 }
571                 
572                 private bool TestMatch (Match match)
573                 {
574                         foreach (Matchlet matchlet in match.Matchlets)
575                                 if (TestMatchlet (matchlet))
576                                         return true;
577                         
578                         return false;
579                 }
580                 
581                 private bool TestMatchlet( Matchlet matchlet )
582                 {
583                         //  using a simple brute force search algorithm
584                         // compare each (masked) value from the buffer with the (masked) value from the matchlet
585                         
586                         // no need to check if the offset + the bytevalue length exceed the # bytes read
587                         if (matchlet.Offset + matchlet.ByteValue.Length > bytes_read)
588                                 return false;
589                         
590                         for ( int offset_counter = 0; offset_counter < matchlet.OffsetLength; offset_counter++ )
591                         {
592                                 if (matchlet.Offset + offset_counter + matchlet.ByteValue.Length > bytes_read)
593                                         return false;
594                                 
595                                 if ( matchlet.Mask == null )
596                                 {
597                                         if ( buffer[ matchlet.Offset + offset_counter ] == matchlet.ByteValue[ 0 ] )
598                                         {
599                                                 if ( matchlet.ByteValue.Length == 1 )
600                                                 {
601                                                         if ( matchlet.Matchlets.Count > 0 )
602                                                         {
603                                                                 foreach ( Matchlet sub_matchlet in matchlet.Matchlets )
604                                                                 {
605                                                                         if ( TestMatchlet( sub_matchlet ) )
606                                                                                 return true;
607                                                                 }
608                                                         }
609                                                         else
610                                                                 return true;
611                                                 }
612                                                 
613                                                 int minus = 0;
614                                                 // check if the last matchlet byte value is the same as the byte value in the buffer...
615                                                 if (matchlet.ByteValue.Length > 2) {
616                                                         if (buffer[ matchlet.Offset + offset_counter + matchlet.ByteValue.Length - 1 ] != matchlet.ByteValue[ matchlet.ByteValue.Length - 1 ])
617                                                                 return false;
618                                                         
619                                                         minus = 1;
620                                                 }
621                                                 
622                                                 for ( int i = 1; i < matchlet.ByteValue.Length - minus; i++ )
623                                                 {
624                                                         if ( buffer[ matchlet.Offset + offset_counter + i ] != matchlet.ByteValue[ i ] )
625                                                                 return false;
626                                                 }
627                                                 
628                                                 if ( matchlet.Matchlets.Count > 0 )
629                                                 {
630                                                         foreach ( Matchlet sub_matchlets in matchlet.Matchlets )
631                                                         {
632                                                                 if ( TestMatchlet( sub_matchlets ) )
633                                                                         return true;
634                                                         }
635                                                 }
636                                                 else
637                                                         return true;
638                                         }
639                                 }
640                                 else // with mask ( it's the same as above, only AND the byte with the corresponding mask byte
641                                 {
642                                         if ( ( buffer[ matchlet.Offset + offset_counter ] & matchlet.Mask[ 0 ] )  ==
643                                             ( matchlet.ByteValue[ 0 ] & matchlet.Mask[ 0 ] ) )
644                                         {
645                                                 if ( matchlet.ByteValue.Length == 1 )
646                                                 {
647                                                         if ( matchlet.Matchlets.Count > 0 )
648                                                         {
649                                                                 foreach ( Matchlet sub_matchlets in matchlet.Matchlets )
650                                                                 {
651                                                                         if ( TestMatchlet( sub_matchlets ) )
652                                                                                 return true;
653                                                                 }
654                                                         }
655                                                         else
656                                                                 return true;
657                                                 }
658                                                 
659                                                 int minus = 0;
660                                                 // check if the last matchlet byte value is the same as the byte value in the buffer...
661                                                 if (matchlet.ByteValue.Length > 2) {
662                                                         
663                                                         if ((buffer[ matchlet.Offset + offset_counter + matchlet.ByteValue.Length - 1 ] & matchlet.Mask[ matchlet.ByteValue.Length - 1 ])
664                                                             != (matchlet.ByteValue[ matchlet.ByteValue.Length - 1 ] & matchlet.Mask[ matchlet.ByteValue.Length - 1 ]))
665                                                                 return false;
666                                                         
667                                                         minus = 1;
668                                                 }
669                                                 
670                                                 for ( int i = 1; i < matchlet.ByteValue.Length - minus; i++ )
671                                                 {
672                                                         if ( ( buffer[ matchlet.Offset + offset_counter + i ]  & matchlet.Mask[ i ] ) !=
673                                                             ( matchlet.ByteValue[ i ] & matchlet.Mask[ i ] ) )
674                                                                 return false;
675                                                 }
676                                                 
677                                                 if ( matchlet.Matchlets.Count > 0 )
678                                                 {
679                                                         foreach ( Matchlet sub_matchlets in matchlet.Matchlets )
680                                                         {
681                                                                 if ( TestMatchlet( sub_matchlets ) )
682                                                                         return true;
683                                                         }
684                                                 }
685                                                 else
686                                                         return true;
687                                         }
688                                 }
689                         }
690                         
691                         return false;
692                 }
693                 
694                 private bool OpenFile( )
695                 {
696                         try
697                         {
698                                 file_stream = new FileStream( current_file_name, FileMode.Open, FileAccess.Read ); // FileShare ??? use BinaryReader ???
699                                 
700                                 if ( file_stream.Length == 0 )
701                                 {
702                                         global_result = zero_file;
703                                         is_zero_file = true;
704                                 }
705                                 else
706                                 {
707                                         bytes_read = file_stream.Read( buffer, 0, buffer.Length );
708                                         
709                                         // do not clear the whole buffer everytime; clear only what's needed
710                                         if (bytes_read < buffer.Length) {
711                                                 System.Array.Clear( buffer, bytes_read, buffer.Length - bytes_read );
712                                         }
713                                 }
714                                 
715                                 file_stream.Close( );
716                         }
717                         catch (Exception)
718                         {
719                                 return false;
720                         }
721                         
722                         return true;
723                 }
724                 
725                 private bool CheckForContentTypeString( )
726                 {
727                         int index = search_string.IndexOf( "Content-type:" );
728                         
729                         if ( index != -1 )
730                         {
731                                 index += 13; // Length of string "Content-type:"
732                                 
733                                 global_result = "";
734                                 
735                                 while ( search_string[ index ] != ';' )
736                                 {
737                                         global_result += search_string[ index++ ];
738                                 }
739                                 
740                                 global_result.Trim( );
741                                 
742                                 return true;
743                         }
744                         
745                         // convert string to byte array
746                         byte[] string_byte = ( new ASCIIEncoding( ) ).GetBytes( search_string );
747                         
748                         System.Array.Clear( buffer, 0, buffer.Length );
749                         
750                         if ( string_byte.Length > buffer.Length )
751                         {
752                                 System.Array.Copy( string_byte, buffer, buffer.Length );
753                         }
754                         else
755                         {
756                                 System.Array.Copy( string_byte, buffer, string_byte.Length );
757                         }
758                         
759                         if ( CheckMatch80Plus( ) )
760                                 return true;
761                         
762                         if ( CheckMatchBelow80( ) )
763                                 return true;
764                         
765                         return false;
766                 }
767         }
768         
769         internal class FDOMimeConfigReader {
770                 bool fdo_mime_available = false;
771                 StringCollection shared_mime_paths = new StringCollection ();
772                 BinaryReader br;
773                 
774                 int max_offset_and_range = 0;
775                 
776                 public int Init ()
777                 {
778                         CheckFDOMimePaths ();
779                         
780                         if (!fdo_mime_available)
781                                 return -1;
782                         
783                         ReadMagicData ();
784                         
785                         ReadGlobsData ();
786                         
787                         ReadSubclasses ();
788                         
789                         ReadAliases ();
790                         
791                         shared_mime_paths = null;
792                         br = null;
793                         
794                         return max_offset_and_range;
795                 }
796                 
797                 private void CheckFDOMimePaths ()
798                 {
799                         if (Directory.Exists ("/usr/share/mime"))
800                                 shared_mime_paths.Add ("/usr/share/mime/");
801                         else
802                         if (Directory.Exists ("/usr/local/share/mime"))
803                                 shared_mime_paths.Add ("/usr/local/share/mime/");
804                         
805                         if (Directory.Exists (System.Environment.GetFolderPath (Environment.SpecialFolder.Personal) + "/.local/share/mime"))
806                                 shared_mime_paths.Add (System.Environment.GetFolderPath (Environment.SpecialFolder.Personal) + "/.local/share/mime/");
807                         
808                         if (shared_mime_paths.Count == 0)
809                                 return;
810                         
811                         fdo_mime_available = true;
812                 }
813                 
814                 private void ReadMagicData ()
815                 {
816                         foreach (string path in shared_mime_paths) {
817                                 if (!File.Exists (path + "/magic"))
818                                         continue;
819                                 
820                                 try {
821                                         FileStream fs = File.OpenRead (path + "/magic");
822                                         br = new BinaryReader (fs);
823                                         
824                                         if (CheckMagicHeader ()) {
825                                                 MakeMatches ();
826                                         }
827                                         
828                                         br.Close ();
829                                         fs.Close ();
830                                 } catch (Exception ) {
831                                 }
832                         }
833                 }
834                 
835                 private void MakeMatches ()
836                 {
837                         Matchlet[] matchlets = new Matchlet [30];
838                         
839                         while (br.PeekChar () != -1) {
840                                 int priority = -1;
841                                 string mime_type = ReadPriorityAndMimeType (ref priority);
842                                 
843                                 if (mime_type != null) {
844                                         Match match = new Match ();
845                                         match.Priority = priority;
846                                         match.MimeType = mime_type;
847                                         
848                                         while (true) {
849                                                 int indent = 0;
850                                                 // indent
851                                                 char c;
852                                                 if (br.PeekChar () != '>') {
853                                                         string indent_string = "";
854                                                         while (true) {
855                                                                 if (br.PeekChar () == '>')
856                                                                         break;
857                                                                 
858                                                                 c = br.ReadChar ();
859                                                                 indent_string += c;
860                                                         }
861                                                         indent = Convert.ToInt32 (indent_string);
862                                                 }
863                                                 
864                                                 int offset = 0;
865                                                 
866                                                 // offset
867                                                 if (br.PeekChar () == '>') {
868                                                         br.ReadChar ();
869                                                         offset = ReadValue ();
870                                                 }
871                                                 
872                                                 int value_length = 0;
873                                                 byte[] value = null;
874                                                 // value length and value
875                                                 if (br.PeekChar () == '=') {
876                                                         br.ReadChar ();
877                                                         
878                                                         // read 2 bytes value length (always big endian)
879                                                         byte first = br.ReadByte ();
880                                                         byte second = br.ReadByte ();
881                                                         
882                                                         value_length = first * 256 + second;
883                                                         
884                                                         value = br.ReadBytes (value_length);
885                                                 }
886                                                 
887                                                 // mask
888                                                 byte[] mask = null;
889                                                 
890                                                 if (br.PeekChar () == '&') {
891                                                         br.ReadChar ();
892                                                         
893                                                         mask = br.ReadBytes (value_length);
894                                                 }
895                                                 
896                                                 // word_size
897                                                 int word_size = 1;
898                                                 if (br.PeekChar () == '~') {
899                                                         br.ReadChar ();
900                                                         
901                                                         c = br.ReadChar ();
902                                                         
903                                                         word_size = Convert.ToInt32 (c - 0x30);
904                                                         
905                                                         // data is stored in big endian format. 
906                                                         if (word_size > 1 && System.BitConverter.IsLittleEndian) {
907                                                                 //convert the value and, if available, the mask data to little endian
908                                                                 if (word_size == 2) {
909                                                                         if (value != null) {
910                                                                                 for (int i = 0; i < value.Length; i += 2) {
911                                                                                         byte one = value [i];
912                                                                                         byte two = value [i + 1];
913                                                                                         value [i] = two;
914                                                                                         value [i + 1] = one;
915                                                                                 }
916                                                                         }
917                                                                         if (mask != null) {
918                                                                                 for (int i = 0; i < mask.Length; i += 2) {
919                                                                                         byte one = mask [i];
920                                                                                         byte two = mask [i + 1];
921                                                                                         mask [i] = two;
922                                                                                         mask [i + 1] = one;
923                                                                                 }
924                                                                         }
925                                                                 } else if (word_size == 4) {
926                                                                         if (value != null) {
927                                                                                 for (int i = 0; i < value.Length; i += 4) {
928                                                                                         byte one = value [i];
929                                                                                         byte two = value [i + 1];
930                                                                                         byte three = value [i + 2];
931                                                                                         byte four = value [i + 3];
932                                                                                         value [i] = four;
933                                                                                         value [i + 1] = three;
934                                                                                         value [i + 2] = two;
935                                                                                         value [i + 3] = one;
936                                                                                 }
937                                                                         }
938                                                                         if (mask != null) {
939                                                                                 for (int i = 0; i < mask.Length; i += 4) {
940                                                                                         byte one = mask [i];
941                                                                                         byte two = mask [i + 1];
942                                                                                         byte three = mask [i + 2];
943                                                                                         byte four = mask [i + 3];
944                                                                                         mask [i] = four;
945                                                                                         mask [i + 1] = three;
946                                                                                         mask [i + 2] = two;
947                                                                                         mask [i + 3] = one;
948                                                                                         
949                                                                                 }
950                                                                         }
951                                                                 }
952                                                         }
953                                                 }
954                                                 
955                                                 // range length
956                                                 int range_length = 1;
957                                                 if (br.PeekChar () == '+') {
958                                                         br.ReadChar ();
959                                                         range_length = ReadValue ();
960                                                 }
961                                                 
962                                                 // read \n
963                                                 br.ReadChar ();
964                                                 
965                                                 // create the matchlet
966                                                 matchlets [indent] = new Matchlet ();
967                                                 matchlets [indent].Offset = offset;
968                                                 matchlets [indent].OffsetLength = range_length;
969                                                 matchlets [indent].ByteValue = value;
970                                                 if (mask != null)
971                                                         matchlets [indent].Mask = mask;
972                                                 
973                                                 if (indent == 0) {
974                                                         match.Matchlets.Add (matchlets [indent]);
975                                                 } else {
976                                                         matchlets [indent - 1].Matchlets.Add (matchlets [indent]);
977                                                 }
978                                                 
979                                                 if (max_offset_and_range < matchlets [indent].Offset + matchlets [indent].OffsetLength + matchlets [indent].ByteValue.Length + 1)
980                                                         max_offset_and_range = matchlets [indent].Offset + matchlets [indent].OffsetLength + matchlets [indent].ByteValue.Length  + 1;
981                                                 
982                                                 // if '[' move to next mime type
983                                                 if (br.PeekChar () == '[')
984                                                         break;
985                                         }
986                                         
987                                         if (priority < 80)
988                                                 Mime.MatchesBelow80.Add (match);
989                                         else
990                                                 Mime.Matches80Plus.Add (match);
991                                 }
992                         }
993                 }
994                 
995                 private void ReadGlobsData ()
996                 {
997                         foreach (string path in shared_mime_paths) {
998                                 if (!File.Exists (path + "/globs"))
999                                         continue;
1000                                 
1001                                 try {
1002                                         StreamReader sr = new StreamReader (path + "/globs");
1003                                         
1004                                         while (sr.Peek () != -1) {
1005                                                 string line = sr.ReadLine ().Trim ();
1006                                                 
1007                                                 if (line.StartsWith ("#"))
1008                                                         continue;
1009                                                 
1010                                                 string[] split = line.Split (new char [] {':'});
1011                                                 
1012                                                 if (split [1].IndexOf ('*') > -1 && split [1].IndexOf ('.') == -1) {
1013                                                         Mime.GlobalSufPref.Add (split [1], split [0]);
1014                                                 } else if (split [1]. IndexOf ('*') == -1) {
1015                                                         Mime.GlobalLiterals.Add (split [1], split [0]);
1016                                                 } else {
1017                                                         string[] split2 = split [1].Split (new char [] {'.'});
1018                                                         
1019                                                         if (split2.Length > 2) {
1020                                                                 // more than one dot
1021                                                                 Mime.GlobalPatternsLong.Add (split [1].Remove(0, 1), split [0]);
1022                                                         } else {
1023                                                                 // normal
1024                                                                 Mime.GlobalPatternsShort.Add (split [1].Remove(0, 1), split [0]);
1025                                                         }
1026                                                 }
1027                                         }
1028                                         
1029                                         sr.Close ();
1030                                 } catch (Exception ) {
1031                                 }
1032                         }
1033                 }
1034                 
1035                 private void ReadSubclasses ()
1036                 {
1037                         foreach (string path in shared_mime_paths) {
1038                                 if (!File.Exists (path + "/subclasses"))
1039                                         continue;
1040                                 
1041                                 try {
1042                                         StreamReader sr = new StreamReader (path + "/subclasses");
1043                                         
1044                                         while (sr.Peek () != -1) {
1045                                                 string line = sr.ReadLine ().Trim ();
1046                                                 
1047                                                 if (line.StartsWith ("#"))
1048                                                         continue;
1049                                                 
1050                                                 string[] split = line.Split (new char [] {' '});
1051                                                 
1052                                                 Mime.SubClasses.Add (split [0], split [1]);
1053                                         }
1054                                         
1055                                         sr.Close ();
1056                                 } catch (Exception ) {
1057                                 }
1058                         }
1059                 }
1060                 
1061                 private void ReadAliases ()
1062                 {
1063                         foreach (string path in shared_mime_paths) {
1064                                 if (!File.Exists (path + "/aliases"))
1065                                         continue;
1066                                 
1067                                 try {
1068                                         StreamReader sr = new StreamReader (path + "/aliases");
1069                                         
1070                                         while (sr.Peek () != -1) {
1071                                                 string line = sr.ReadLine ().Trim ();
1072                                                 
1073                                                 if (line.StartsWith ("#"))
1074                                                         continue;
1075                                                 
1076                                                 string[] split = line.Split (new char [] {' '});
1077                                                 
1078                                                 Mime.Aliases.Add (split [0], split [1]);
1079                                         }
1080                                         
1081                                         sr.Close ();
1082                                 } catch (Exception ) {
1083                                 }
1084                         }
1085                 }
1086                 
1087                 private int ReadValue ()
1088                 {
1089                         string result_string = "";
1090                         int result = 0;
1091                         char c;
1092                         
1093                         while (true) {
1094                                 if (br.PeekChar () == '=' || br.PeekChar () == '\n')
1095                                         break;
1096                                 
1097                                 c = br.ReadChar ();
1098                                 result_string += c;
1099                         }
1100                         
1101                         result = Convert.ToInt32 (result_string);
1102                         
1103                         return result;
1104                 }
1105                 
1106                 private string ReadPriorityAndMimeType (ref int priority)
1107                 {
1108                         if (br.ReadChar () == '[') {
1109                                 string priority_string = "";
1110                                 while (true) {
1111                                         char c = br.ReadChar ();
1112                                         if (c == ':')
1113                                                 break;
1114                                         priority_string += c;
1115                                 }
1116                                 
1117                                 priority = System.Convert.ToInt32 (priority_string);
1118                                 
1119                                 string mime_type_result = "";
1120                                 while (true) {
1121                                         char c = br.ReadChar ();
1122                                         if (c == ']')
1123                                                 break;
1124                                         
1125                                         mime_type_result += c;
1126                                 }
1127                                 
1128                                 if (br.ReadChar () == '\n')
1129                                         return mime_type_result;
1130                         }
1131                         return null;
1132                 }
1133                 
1134                 private bool CheckMagicHeader ()
1135                 {
1136                         char[] chars = br.ReadChars (10);
1137                         string magic_header = new String (chars);
1138                         
1139                         if (magic_header != "MIME-Magic")
1140                                 return false;
1141                         
1142                         if (br.ReadByte () != 0)
1143                                 return false;
1144                         if (br.ReadChar () != '\n')
1145                                 return false;
1146                         
1147                         return true;
1148                 }
1149         }
1150         
1151         internal class Match {
1152                 string mimeType;
1153                 int priority;
1154                 ArrayList matchlets = new ArrayList();
1155                 
1156                 public string MimeType {
1157                         set {
1158                                 mimeType = value;
1159                         }
1160                         
1161                         get {
1162                                 return mimeType;
1163                         }
1164                 }
1165                 
1166                 public int Priority {
1167                         set {
1168                                 priority = value;
1169                         }
1170                         
1171                         get {
1172                                 return priority;
1173                         }
1174                 }
1175                 
1176                 public ArrayList Matchlets {
1177                         get {
1178                                 return matchlets;
1179                         }
1180                 }
1181         }
1182         
1183         internal class Matchlet {
1184                 byte[] byteValue;
1185                 byte[] mask = null;
1186                 
1187                 int offset;
1188                 int offsetLength;
1189                 int wordSize = 1;
1190                 
1191                 ArrayList matchlets = new ArrayList ();
1192                 
1193                 public byte[] ByteValue {
1194                         set {
1195                                 byteValue = value;
1196                         }
1197                         
1198                         get {
1199                                 return byteValue;
1200                         }
1201                 }
1202                 
1203                 public byte[] Mask {
1204                         set {
1205                                 mask = value;
1206                         }
1207                         
1208                         get {
1209                                 return mask;
1210                         }
1211                 }
1212                 
1213                 public int Offset {
1214                         set {
1215                                 offset = value;
1216                         }
1217                         
1218                         get {
1219                                 return offset;
1220                         }
1221                 }
1222                 
1223                 public int OffsetLength {
1224                         set {
1225                                 offsetLength = value;
1226                         }
1227                         
1228                         get {
1229                                 return offsetLength;
1230                         }
1231                 }
1232                 
1233                 public int WordSize {
1234                         set {
1235                                 wordSize = value;
1236                         }
1237                         
1238                         get {
1239                                 return wordSize;
1240                         }
1241                 }
1242                 
1243                 public ArrayList Matchlets {
1244                         get {
1245                                 return matchlets;
1246                         }
1247                 }
1248         }
1249 }
1250