File: CWMIMEUtility.m

package info (click to toggle)
pantomime 1.4.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,288 kB
  • sloc: objc: 22,039; makefile: 11; sh: 4
file content (961 lines) | stat: -rw-r--r-- 22,961 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
/*
**  CWMIMEUtility.m
**
**  Copyright (c) 2001-2007 Ludovic Marcotte
**  Copyright (C) 2014-2018 Riccardo Mottola
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**          Riccardo Mottola <rm@gnu.org>
**          Sebastian Reitenbach
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**  
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
**  Lesser General Public License for more details.
**  
** You should have received a copy of the GNU General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#import <Pantomime/CWMIMEUtility.h>

#import <Pantomime/CWConstants.h>
#import <Pantomime/CWMessage.h>
#import <Pantomime/CWMIMEMultipart.h>
#import <Pantomime/NSString+Extensions.h>
#import <Pantomime/NSData+Extensions.h>
#import <Pantomime/CWPart.h>
#import <Pantomime/CWMD5.h>
#import <Pantomime/CWUUFile.h>

#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSBundle.h>
#import <Foundation/NSCharacterSet.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSHost.h>
#import <Foundation/NSScanner.h>
#import <Foundation/NSValue.h>

#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

//
// C functions
//
char ent(char **ref);
char *striphtml(char *s, int encoding);
NSString *unique_id();

static const char *hexDigit = "0123456789ABCDEF";
static unsigned seed_count = 1;

@implementation CWMIMEUtility

//
// See RFC2047.
// It supports:
// 
// Abcd =?ISO-8859-1?Q?=E8fgh?=
// =?iso-8859-1?Q?ab=E7de?= =?iso-8859-1?Q?_?= =?iso-8859-1?Q?oo=F4oo?=
// Abd =?ISO-8859-1?Q?=E8?= fghijklmn
//
//
+ (NSString *) decodeHeader: (NSData *) theData
		    charset: (NSString *) theCharset
{
  NSMutableString *aMutableString;
  NSData *charset, *encoded_text;
  NSString *aString;
  
  NSUInteger i, length, start, i_charset, i_encoding, end; 
  const char *bytes;
 
  BOOL ignore_span;
  char encoding;

  // We first verify for a nil value
  if (theData == nil || (length = [theData length]) == 0)
    {
      return @"";
    }
  
  // We check for the ISO-2022-JP announcer sequence
  if ([theData hasCPrefix: "\e$B"])
    {
      return AUTORELEASE([[NSString alloc] initWithData: theData  encoding: NSISO2022JPStringEncoding]);
    }

  bytes = [theData bytes];
  
  aMutableString = [[NSMutableString alloc] initWithCapacity: length];
  
  start = i = 0;
  ignore_span = NO;
  
  while (i < (length - 1))
    {
      if (bytes[i] != '=' || bytes[i+1] != '?')
	{
	  if (bytes[i] > 32)
	    {
	      ignore_span = NO;
	    }
	  
	  i++;
	  continue;
	}
      
      if (i != start && !ignore_span)
	{
	  aString = nil;

	  if (theCharset)
	    {  
	      aString = [NSString stringWithData: [NSData dataWithBytes: bytes+start  length: i-start]
				  charset: [theCharset dataUsingEncoding: NSASCIIStringEncoding]];
	      RETAIN(aString);
	    }
	  
	  if (!aString)
	    {
	      aString = [[NSString alloc] initWithCString: bytes+start  length: i-start];
	    }

	  [aMutableString appendString: aString];
	  DESTROY(aString);
	}
      
      start = i;
      
      // skip the =? and one character (or it isn't valid)
      i += 3; 
      while (i < length && bytes[i] != '?') 
	{
	  i++;
	}
      
      if ( i == length) 
	{
	  break;
	}
      
      i_charset = i;
      
      // encoding is a single character
      if (i+2 >= length)
	{
	  break;
	}
      
      encoding = bytes[i+1];
      
      if (bytes[i+2] != '?')
	{
	  break;
	}
      
      i += 3;
      i_encoding = i;
      
      while (i <length && bytes[i] != '?')
	{
	  i++;
	}
      
      if (i+1 >= length)
	{
	  break;
	}
      
      if (bytes[i+1] != '=')
	{
	  break;
	}

      end = i;
      i += 2;
      
      if (theCharset)
	{
	  charset = [theCharset dataUsingEncoding: NSASCIIStringEncoding];
	}
      else
	{
          NSRange charsetRange;
          charsetRange = NSMakeRange(start+2,i_charset-start-2);
	  charset = [theData subdataWithRange: charsetRange];
	}
      
      encoded_text = [theData subdataWithRange: NSMakeRange(i_encoding,end-i_encoding)];
      
      if (encoding == 'q' || encoding == 'Q')
	{
	  aString = [NSString stringWithData: [encoded_text decodeQuotedPrintableInHeader: YES]
			      charset: charset];
	}
      else if (encoding == 'b' || encoding== 'B')
	{
          NSData *decodedData;
        
          decodedData = [encoded_text decodeBase64];
	  aString = [NSString stringWithData: decodedData
			      charset: charset];
	}
      else
	{
	  continue;
	}

      if (aString)
	{
          [aMutableString appendString: aString];
        }
      aString = nil;
      start = i;
      ignore_span = YES;
    }
  
  // always append end of string, even if there was a space
  i = length;
  if (i > start)
    {
      aString = nil;

      if (theCharset)
      	{  
	  aString = [NSString stringWithData: [NSData dataWithBytes: bytes+start  length: i-start]
			      charset: [theCharset dataUsingEncoding: NSASCIIStringEncoding]];
	  RETAIN(aString);
      	}
      
      if (!aString)
	{
	  aString = [[NSString alloc] initWithCString: bytes+start  length: i-start];
      	}
      
      [aMutableString appendString: aString];
      DESTROY(aString);
    }
  
  return AUTORELEASE(aMutableString);
}


//
//
//
+ (NSData *) globallyUniqueBoundary
{
  NSMutableData *aMutableData;
  
  aMutableData = [[NSMutableData alloc] init];
  [aMutableData appendBytes: "=_"  length: 2];
  [aMutableData appendCFormat: @"%@", unique_id()];

  return AUTORELEASE(aMutableData);
}


//
// Instead of using [[NSHost currentHost] name],
// we use gethostname(). This is due to the fact
// that NSHost's -name method will block for a good
// amount of time if DNS resolutions can't be made.
//
+ (NSData *) globallyUniqueID
{
  NSMutableData *aMutableData;
  char s[65];
  
 
  aMutableData = [[NSMutableData alloc] init];
  [aMutableData appendCFormat: @"%@", unique_id()];
 
  memset(s, 0, sizeof(s));
  gethostname(s, sizeof(s)-1);
  [aMutableData appendCFormat: @"@%s", s];

  return AUTORELEASE(aMutableData);
}


//
// FIXME: Should we really use NSUTF8StringEncoding in base64?
//
+ (NSData *) encodeHeader: (NSString *) theText
		  charset: (NSString *) theCharset
		 encoding: (PantomimeEncoding) theEncoding
{
  NSData *aData;
  
  // Initial verification
  if (!theText || [theText length] == 0)
    {
      return [NSData data];
    }
  
  aData = [theText dataUsingEncoding: [NSString encodingForCharset:
						  [theCharset dataUsingEncoding: NSASCIIStringEncoding]]];
  
  if (theEncoding == PantomimeEncodingQuotedPrintable)
    {
      return [aData encodeQuotedPrintableWithLineLength: 0  inHeader: YES];
    }
  else if (theEncoding == PantomimeEncodingBase64)
    {
      return [aData encodeBase64WithLineLength: 0];
    }
  //
  // FIXME: What should we do here, should we just return the 'aData' w/o 
  //        encoding it or should we generate an exception?
  else
    {
      return aData; 
    }
}


//
// The format returned is for example:
//
// =?ISO-8859-1?B?....?=
// 
// This format is known as an encoded-word defined in RFC2047.
// If the word doesn't need to be encoded, it's just returned as is.
//
// FIXME: We should verify that the length doesn't exceed 75 chars.
//
#warning remove/combine or leave and document
+ (NSData *) encodeWordUsingBase64: (NSString *) theWord
		      prefixLength: (int) thePrefixLength
{
  // Initial verification
  if (!theWord || [theWord length] == 0)
    {
      return [NSData data];
    }
  else if ([theWord is7bitSafe])
    {
      return [theWord dataUsingEncoding: NSASCIIStringEncoding];
    }
  else
    {
      NSMutableData *aMutableData;
      NSString *aCharset;

      aMutableData = [[NSMutableData alloc] init];
      aCharset = [theWord charset];

      [aMutableData appendCFormat: @"=?%@?b?", aCharset];
      [aMutableData appendData: [CWMIMEUtility encodeHeader: theWord
					       charset: aCharset
					       encoding: PantomimeEncodingBase64]];
      [aMutableData appendCString: "?="];

      return AUTORELEASE(aMutableData);
    }

  // Never reached.
  return nil;
}


//
// The format returned is for example:
//
// =?ISO-8859-1?Q?=E8fgh?=
//
// This format is known as an encoded-word defined in RFC2047.
// If the word doesn't need to be encoded, it's just returned as it.
//
// The string returned will NOT be more than 75 characters long
// for each folded part of the original string.
//
#warning remove/combine or leave and document
+ (NSData *) encodeWordUsingQuotedPrintable: (NSString *) theWord
			       prefixLength: (NSUInteger) thePrefixLength
{  
  NSMutableString *aMutableString;
  NSMutableArray *aMutableArray;
  NSString *aCharset, *aString;
  NSMutableData *aMutableData;
  NSScanner *aScanner;
  
  NSUInteger i, count;
  NSUInteger previousLocation, currentLocation;
  BOOL mustUseEncoding;

  if (!theWord || [theWord length] == 0 )
    {
      return [NSData data];
    } 

  // If it's not an ASCII string, we must use the encoding!
  mustUseEncoding = ![theWord is7bitSafe];
  
  aCharset = nil;
  
  if (mustUseEncoding)
    {
      aCharset = [theWord charset];
    }
  
  aMutableString = [[NSMutableString alloc] init];
  
  aMutableArray = [[NSMutableArray alloc] init];
  AUTORELEASE(aMutableArray);
  
  // We initialize our scanner with the content of our word
  aScanner = [[NSScanner alloc] initWithString: theWord];
  
  previousLocation = 0;
  
  while ([aScanner scanUpToCharactersFromSet: [NSCharacterSet whitespaceCharacterSet]  intoString: NULL])
    {
      NSUInteger length;
      
      currentLocation = [aScanner scanLocation]; 
	  
      // aString contains the substring WITH the spaces present BEFORE the word and AFTER the last aString.
      // 
      // For example, the result of "this is a test" will be
      //
      // aString = "this"
      // aString = " is"
      // aString = " a"
      // aString = " test"
      //
      aString = [theWord substringWithRange: NSMakeRange(previousLocation, currentLocation - previousLocation)];

      if (mustUseEncoding)
	{
	  // Our 'initial' length contains =?iso-8859-x?q? and ?=
	  length = 18;
	  length += [[CWMIMEUtility encodeHeader: [NSString stringWithFormat: @"%@%@", aMutableString, aString]
				    charset: aCharset
				    encoding: PantomimeEncodingQuotedPrintable] length];
	}
      else
	{
	  length = [aMutableString length] + [aString length];
	}

      // If we are on the first line, we must consider the prefix length.
      // For example, the prefix length might be the length of the string "Subject: "
      if ([aMutableArray count] == 0)
	{
	  length += thePrefixLength;
	}

      if (length > 75)
	{
	  [aMutableArray addObject: aMutableString];

	  RELEASE(aMutableString);
	  aMutableString = [[NSMutableString alloc] init];
	}
      
      [aMutableString appendString: aString];
      previousLocation = currentLocation;
    }
  
  // We add our last string to the array.
  [aMutableArray addObject: aMutableString];
  RELEASE(aMutableString);
  
  RELEASE(aScanner);
      
  aMutableData = [[NSMutableData alloc] init];
  
  count = [aMutableArray count];
  for (i = 0; i < count; i++)
    {
      aString = [aMutableArray objectAtIndex: i];

      // We must append a space (' ') before each folded line.
      if (i > 0)
	{
	  [aMutableData appendCString: " "];
	}
	  
      if (mustUseEncoding)
	{
	  [aMutableData appendCFormat: @"=?%@?q?", aCharset];
	  [aMutableData appendData: [CWMIMEUtility encodeHeader: aString
						   charset: aCharset
						   encoding: PantomimeEncodingQuotedPrintable] ];
	  [aMutableData appendCString: "?="];
	}
      else
	{
	  [aMutableData appendData: [aString dataUsingEncoding: NSASCIIStringEncoding]];
	}
      
      // We if it is our last string, we must NOT append the \n
      if (!(i == (count-1)))
	{
	  [aMutableData appendCString: "\n"];
	}
    }

  return AUTORELEASE(aMutableData);
}
  

//
//
//
+ (CWMessage *) compositeMessageContentFromRawSource: (NSData *) theData
{
  return AUTORELEASE([[CWMessage alloc] initWithData: theData]);
}


//
// FIXME: whitespace after boundary markers
// 
+ (CWMIMEMultipart *) compositeMultipartContentFromRawSource: (NSData *) theData
						    boundary: (NSData *) theBoundary
{
  CWMIMEMultipart *aMimeMultipart;
  
  NSMutableData *aMutableData;
  NSArray *allParts;
  NSRange aRange;
  NSUInteger i, count;
  
  aMimeMultipart = [[CWMIMEMultipart alloc] init];

  aMutableData = [[NSMutableData alloc] init];
  [aMutableData appendBytes: "--"  length: 2];
  [aMutableData appendData: theBoundary];

  // We first skip everything before the first boundary
  aRange = [theData rangeOfData: aMutableData];
   
  if (aRange.length && aRange.location)
    {
      theData = [theData subdataFromIndex: (aRange.location + aRange.length)];
    }
  
  [aMutableData setLength: 0];
  [aMutableData appendBytes: "\n--"  length: 3];
  [aMutableData appendData: theBoundary];
  
  // Add terminating 0 so we can use it as a C string below
  [aMutableData appendBytes: "\0" length: 1];

  // We split this mime body part into multiple parts since we have various representations
  // of the actual body part.
  allParts = [theData componentsSeparatedByCString: [aMutableData bytes]];
  count = [allParts count];
  RELEASE(aMutableData);

  for (i = 0; i < count; i++)
    {
      CWPart *aPart;
      NSData *aData;

      aData = [allParts objectAtIndex: i];
      
      if (aData && [aData length] > 0)
	{
	  // This is the last part. Ignore everything past the end marker
	  if ([aData hasCPrefix: "--\n"] ||
	      ([aData length] == 2 && [aData hasCPrefix: "--"]))
	    {
	      break;
	    }
	  
	  // We then skip the first character since it's a \n (the one at the end of the boundary)
	  if ([aData hasCPrefix: "\n"])
	    {
	      aData = [aData subdataFromIndex: 1];
	    }
	
	  aPart = [[CWPart alloc] initWithData: aData];
	  [aPart setSize: [aData length]];
	  [aMimeMultipart addPart: aPart];
	  RELEASE(aPart);
	}
    }

  return AUTORELEASE(aMimeMultipart);
}


//
//
// 
+ (id) discreteContentFromRawSource: (NSData *) theData
			   encoding: (PantomimeEncoding) theEncoding
{
  if (theEncoding == PantomimeEncodingQuotedPrintable)
    {
      return [theData decodeQuotedPrintableInHeader: NO];
    }
  else if (theEncoding == PantomimeEncodingBase64)
    {
      return [[theData dataByRemovingLineFeedCharacters] decodeBase64];
    }
  
  return theData;
}


//
//
//
+ (void) setContentFromRawSource: (NSData *) theData
                          inPart: (CWPart *) thePart
{
  NSAutoreleasePool *pool;
 
  // We create a temporary autorelease pool since this method can be
  // memory consuming on our default autorelease pool.
  pool = [[NSAutoreleasePool alloc] init];

  //
  // Composite types (message/multipart).
  //
  if ([thePart isMIMEType: @"message"  subType: @"rfc822"])
    {
      NSData *aData;

      aData = theData;

      // We verify the Content-Transfer-Encoding, this part could be base64 encoded.
      if ([thePart contentTransferEncoding] == PantomimeEncodingBase64)
	{
	  NSMutableData *aMutableData;

	  aData = [[theData dataByRemovingLineFeedCharacters] decodeBase64];
	  
	  aMutableData = [NSMutableData dataWithData: aData];
	  [aMutableData replaceCRLFWithLF];
	  aData = aMutableData;
	}

      [thePart setContent: [CWMIMEUtility compositeMessageContentFromRawSource: aData]];
    }
  else if ([thePart isMIMEType: @"multipart"  subType: @"*"])
    {
      [thePart setContent: [CWMIMEUtility compositeMultipartContentFromRawSource: theData
					  boundary: [thePart boundary]]];
    }
  // 
  // Discrete types (text/application/audio/image/video) or any "unsupported Content-Type:s"
  //
  // text/*
  // image/*
  // application/*
  // audio/*
  // video/*
  //
  // We also treat those composite type as discrete types:
  //
#warning test extensively those
  // message/delivery-status
  // message/disposition-notification
  //
  else
    {
      [thePart setContent: [CWMIMEUtility discreteContentFromRawSource: theData
					  encoding: [thePart contentTransferEncoding]]];
    }
  
  RELEASE(pool);
}


//
//
//
+ (NSData *) plainTextContentFromPart: (CWPart *) thePart
{
  NSData *aContent;

  aContent = (NSData *)[thePart content];

  //
  // If it's a text/html part, we must remove all the formatting codes and 
  // keep only the 'real' text contained in that part. We should do the
  // same for text/rtf or text/enriched parts.
  //
  if ([thePart isMIMEType: @"text"  subType: @"html"])
    {
      char *buf, *bytes;
 
      buf = (char *)malloc(([aContent length]+1)*sizeof(char));
      memset(buf, 0, [aContent length]+1);
      memcpy(buf, [aContent bytes], [aContent length]);

      bytes = striphtml(buf, [NSString encodingForPart: thePart]);
      free(buf);

      aContent = [NSData dataWithBytesNoCopy: bytes  length: strlen(bytes)  freeWhenDone: YES];
    }
  
  return aContent;
}

@end


//
// This C function has been written by Abhijit Menon-Sen <ams@wiw.org>
// This code is in the public domain.
//
char *striphtml(char *s, int encoding)
{
  char c, *t, *text;

  if ((t = text = malloc(strlen(s)+1)) == NULL)
    {
      return NULL;
    }

  while ((c = *s++))
    {
      if (c == '<')
        {
          /*
           * Ignore everything to the end of this tag or sgml comment.
           */
          if (s[0] == '!' && s[1] == '-' && s[2] == '-')
            {
              s += 3;
              while ((c = *s++))
                {
                  if (c == '-' && s[0] == '-' && s[1] == '>')
                    {
                      s += 2;
                      break;
                    }
                }
            }
          else
            {
              while ((c = *s++))
                {
                  if (c == '>')
                    {
                      break;
                    }
                }
            }
        }
      else if (c == '&')
        {
	  NSString *aString;

	  c = ent(&s);
	  aString = AUTORELEASE([[NSString alloc] initWithBytes: &c  length: 1  encoding: NSISOLatin1StringEncoding]);

	  if ([aString length])
	    {
	      NSData *aData;

	      aData = [aString dataUsingEncoding: encoding];
	      
	      if (aData)
		{
		  char *bytes;
		  NSUInteger len;
		  
		  bytes = (char *)[aData bytes];
		  len = [aData length];
		  
		  while (len--)
		    {
		      *t++ = *bytes;
		      bytes++;
		    }
		}
	    }
	}
      else
        {
          *t++ = c;
        }
    }

  *t = '\0';

  return text;
}


//
// This C function has been written by Abhijit Menon-Sen <ams@wiw.org>
// This code is in the public domain.
//
char ent(char **ref)
{
  unsigned i;
  char c = ' ', *s = *ref, *t = s;
  
  struct {
    char *name;
    char chr;
  } refs[] = {
    { "lt"    , '<'       },
    { "gt"    , '>'       },
    { "amp"   , '&'       },
    { "quot"  , '"'       },
    { "nbsp"  , (char)160 },
    { "iexcl" , (char)161 },
    { "cent"  , (char)162 },
    { "pound" , (char)163 },
    { "curren", (char)164 },
    { "yen"   , (char)165 },
    { "brvbar", (char)166 },
    { "sect"  , (char)167 },
    { "uml"   , (char)168 },
    { "copy"  , (char)169 },
    { "ordf"  , (char)170 },
    { "laquo" , (char)171 },
    { "not"   , (char)172 },
    { "shy"   , (char)173 },
    { "reg"   , (char)174 },
    { "macr"  , (char)175 },
    { "deg"   , (char)176 },
    { "plusmn", (char)177 },
    { "sup2"  , (char)178 },
    { "sup3"  , (char)179 },
    { "acute" , (char)180 },
    { "micro" , (char)181 },
    { "para"  , (char)182 },
    { "middot", (char)183 },
    { "cedil" , (char)184 },
    { "sup1"  , (char)185 },
    { "ordm"  , (char)186 },
    { "raquo" , (char)187 },
    { "frac14", (char)188 },
    { "frac12", (char)189 },
    { "frac34", (char)190 },
    { "iquest", (char)191 },
    { "Agrave", (char)192 },
    { "Aacute", (char)193 },
    { "Acirc" , (char)194 },
    { "Atilde", (char)195 },
    { "Auml"  , (char)196 },
    { "Aring" , (char)197 },
    { "AElig" , (char)198 },
    { "Ccedil", (char)199 },
    { "Egrave", (char)200 },
    { "Eacute", (char)201 },
    { "Ecirc" , (char)202 },
    { "Euml"  , (char)203 },
    { "Igrave", (char)204 },
    { "Iacute", (char)205 },
    { "Icirc" , (char)206 },
    { "Iuml"  , (char)207 },
    { "ETH"   , (char)208 },
    { "Ntilde", (char)209 },
    { "Ograve", (char)210 },
    { "Oacute", (char)211 },
    { "Ocirc" , (char)212 },
    { "Otilde", (char)213 },
    { "Ouml"  , (char)214 },
    { "times" , (char)215 },
    { "Oslash", (char)216 },
    { "Ugrave", (char)217 },
    { "Uacute", (char)218 },
    { "Ucirc" , (char)219 },
    { "Uuml"  , (char)220 },
    { "Yacute", (char)221 },
    { "THORN" , (char)222 },
    { "szlig" , (char)223 },
    { "agrave", (char)224 },
    { "aacute", (char)225 },
    { "acirc" , (char)226 },
    { "atilde", (char)227 },
    { "auml"  , (char)228 },
    { "aring" , (char)229 },
    { "aelig" , (char)230 },
    { "ccedil", (char)231 },
    { "egrave", (char)232 },
    { "eacute", (char)233 },
    { "ecirc" , (char)234 },
    { "euml"  , (char)235 },
    { "igrave", (char)236 },
    { "iacute", (char)237 },
    { "icirc" , (char)238 },
    { "iuml"  , (char)239 },
    { "eth"   , (char)240 },
    { "ntilde", (char)241 },
    { "ograve", (char)242 },
    { "oacute", (char)243 },
    { "ocirc" , (char)244 },
    { "otilde", (char)245 },
    { "ouml"  , (char)246 },
    { "divide", (char)247 },
    { "oslash", (char)248 },
    { "ugrave", (char)249 },
    { "uacute", (char)250 },
    { "ucirc" , (char)251 },
    { "uuml"  , (char)252 },
    { "yacute", (char)253 },
    { "thorn" , (char)254 },
    { "yuml"  , (char)255 }
  };
  
  while (isalpha((int)(unsigned char)*s) || isdigit((int)(unsigned char)*s) || *s == '#')
    s++;
  
  for (i = 0; i < sizeof(refs)/sizeof(refs[0]); i++) {
    if (strncmp(refs[i].name, t, s-t) == 0) {
      c = refs[i].chr;
      break;
    }
  }
  
  if (*s == ';')
    s++;
  
  *ref = s;
  return c;
}


//
//
//
NSString *unique_id()
{
  NSMutableData *aMutableData;
  CWMD5 *aMD5;
  
  char random_data[9];
  time_t curtime;
  int i, pid;
  
  pid = getpid();
  time(&curtime);
  
  for (i = 0; i < 8; i++)
    {
      srand(seed_count++);
      random_data[i] = hexDigit[rand()&0xf];
    }
  random_data[8] = '\0';
  
  aMutableData = [[NSMutableData alloc] init];
  [aMutableData appendCFormat: @"%d.%ld%s", pid, (long)curtime, random_data];
  aMD5 = [[CWMD5 alloc] initWithData: aMutableData];
  RELEASE(aMutableData);
  AUTORELEASE(aMD5);
  
  [aMD5 computeDigest];
  
  return [aMD5 digestAsString];
}