Debian Codegraph @

Framework/Pantomime/NSData+Extensions.m

raw
1 /*
2 ** NSData+Extensions.m
3 **
4 ** Copyright (c) 2001-2007 Ludovic Marcotte
5 ** Copyright (C) 2014-2022 Riccardo Mottola
6 **
7 ** Author: Ludovic Marcotte <[email protected]>
8 ** Riccardo Mottola <[email protected]>
9 **
10 ** This library is free software; you can redistribute it and/or
11 ** modify it under the terms of the GNU Lesser General Public
12 ** License as published by the Free Software Foundation; either
13 ** version 2.1 of the License, or (at your option) any later version.
14 **
15 ** This library is distributed in the hope that it will be useful,
16 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 ** Lesser General Public License for more details.
19 **
20 ** You should have received a copy of the GNU General Public License
21 ** along with this program. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #import <Pantomime/NSData+Extensions.h>
25
26 #import <Foundation/NSArray.h>
27 #import <Foundation/NSException.h>
28 #import <Foundation/NSString.h>
29
30 #import <Pantomime/CWConstants.h>
31
32 #include <stdlib.h>
33 #include <string.h>
34
35 //
36 // C functions and constants
37 //
38 int getValue(const unsigned char c);
39 void nb64ChunkFor3Characters(char *buf, const char *inBuf, unsigned numChars);
40
41 static const char basis_64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
42 static const char *hexDigit = "0123456789ABCDEF";
43
44
45
46 // TODO:
47 // add an NSData cluster member NSSubrangeData that retaind its parent and
48 // used its data. Would make almost all of these operations work without
49 // copying.
50 @implementation NSData (PantomimeExtensions)
51
52 //
53 // FIXME: this should ignore characters in the stream that aren't in
54 // the base64 alphabet (as per the spec). would remove need for
55 // ...removeLinefeeds... too
56 //
57 - (NSData *) decodeBase64
58 {
59 NSUInteger data_len;
60 NSUInteger i;
61 NSUInteger length;
62 NSUInteger pad;
63 unsigned rawIndex;
64 int block;
65 const unsigned char *bytes;
66 char *raw;
67
68 if ([self length] == 0)
69 {
70 return [NSData data];
71 }
72
73 data_len = [self length];
74 bytes = [self bytes];
75 pad = 0;
76
77 for (i = data_len - 1; bytes[i] == '='; i--)
78 {
79 pad++;
80 }
81
82 // This could happen for broken encoded base64 content such as the following example:
83 // ------=_NextPart_KO_X1098V29876N91O412QM815
84 // Content-Type: text/plain; charset=UTF-8
85 // Content-Disposition: attachment; filename="teste.txt"
86 // Content-Transfer-Encoding: base64
87 //
88 // ====
89 //
90 // we want to test (data_len * 6 / 8 - pad) < 0 but are using unisgned values, so we reverse it
91 if ((data_len * 6 / 8) < pad)
92 {
93 return [NSData data];
94 }
95
96 length = data_len * 6 / 8 - pad;
97
98 raw = (char *)malloc((size_t)length);
99 rawIndex = 0;
100
101 for (i = 0; i < data_len; i += 4)
102 {
103 NSUInteger j;
104
105 block = (getValue(bytes[i]) << 18) +
106 (getValue(bytes[i+1]) << 12) +
107 (getValue(bytes[i+2]) << 6) +
108 (getValue(bytes[i+3]));
109
110 for (j = 0; j < 3 && rawIndex+j < length; j++)
111 {
112 raw[rawIndex+j] = (char)((block >> (8 * (2 - j))) & 0xff);
113 }
114
115 rawIndex += 3;
116 }
117
118 return AUTORELEASE([[NSData alloc] initWithBytesNoCopy: raw length: length]);
119 }
120
121
122 //
123 //
124 //
125 - (NSData *) encodeBase64WithLineLength: (NSUInteger) theLength
126 {
127 const char *inBytes = [self bytes];
128 const char *inBytesPtr = inBytes;
129 NSUInteger inLength = [self length];
130 NSUInteger i;
131 char *outBytes;
132 char *outBytesPtr;
133
134 NSUInteger numWordsPerLine = theLength/4;
135 NSUInteger wordCounter = 0;
136
137 outBytes = malloc(sizeof(char)*(size_t)inLength*2);
138 outBytesPtr = outBytes;
139 // We memset 0 our buffer so with are sure to not have
140 // any garbage in it.
141 memset(outBytes, 0, sizeof(char)*(size_t)inLength*2);
142
143 for (i = 0; i < inLength; i += 3)
144 {
145 nb64ChunkFor3Characters(outBytesPtr, inBytesPtr, (unsigned)(inLength-i));
146 outBytesPtr += 4;
147 inBytesPtr += 3;
148
149 wordCounter++;
150
151 if (theLength && wordCounter == numWordsPerLine)
152 {
153 wordCounter = 0;
154 *outBytesPtr = '\n';
155 outBytesPtr++;
156 }
157 }
158
159 return AUTORELEASE([[NSData alloc] initWithBytesNoCopy: outBytes length: (NSUInteger)(outBytesPtr-outBytes)]);
160 }
161
162
163 //
164 //
165 //
166 - (NSData *) unfoldLines
167 {
168 NSMutableData *aMutableData;
169 NSUInteger i, length;
170
171 const unsigned char *b;
172
173 length = [self length];
174 b = [self bytes];
175
176 aMutableData = [[NSMutableData alloc] initWithCapacity: length];
177
178 [aMutableData appendBytes: b length: 1];
179 b++;
180
181 for (i = 1; i < length; i++,b++)
182 {
183 if (b[-1]=='\n' && (*b==' ' || *b=='\t'))
184 {
185 [aMutableData setLength: ([aMutableData length] - 1)];
186 }
187
188 [aMutableData appendBytes: b length: 1];
189 }
190
191 return AUTORELEASE(aMutableData);
192 }
193
194
195 //
196 //
197 //
198 - (NSData *) decodeQuotedPrintableInHeader: (BOOL) aBOOL
199 {
200 NSMutableData *result;
201
202 const unsigned char *bytes,*b;
203 unsigned char ch;
204 NSUInteger i,len;
205
206 len = [self length];
207 bytes = [self bytes];
208
209 result = [[NSMutableData alloc] initWithCapacity: len];
210
211 ch=0;
212 b=bytes;
213
214 for (i = 0; i < len; i++,b++)
215 {
216 if (b[0]=='=' && i+1<len && b[1]=='\n')
217 {
218 b++,i++;
219 continue;
220 }
221 else if (*b=='=' && i+1==len)
222 {
223 /* this is the last =, it is a soft-line-break at the end of the message */
224 continue;
225 }
226 else if (*b=='=' && i+2<len)
227 {
228 b++,i++;
229 if (*b>='A' && *b<='F')
230 {
231 ch=16*(*b-'A'+10);
232 }
233 else if (*b>='a' && *b<='f')
234 {
235 ch=16*(*b-'a'+10);
236 }
237 else if (*b>='0' && *b<='9')
238 {
239 ch=16*(*b-'0');
240 }
241 else
242 {
243 [result release];
244 [[NSException exceptionWithName:@"Pantomime Exception" reason:@"Hex data contained invalid char" userInfo:nil] raise];
245 return nil;
246 }
247
248 b++,i++;
249
250 if (*b>='A' && *b<='F')
251 {
252 ch+=*b-'A'+10;
253 }
254 else if (*b>='a' && *b<='f')
255 {
256 ch+=*b-'a'+10;
257 }
258 else if (*b>='0' && *b<='9')
259 {
260 ch+=*b-'0';
261 }
262 else
263 {
264 [result release];
265 [[NSException exceptionWithName:@"Pantomime Exception" reason:@"Hex data contained invalid char" userInfo:nil] raise];
266 return nil;
267 }
268
269 [result appendBytes: &ch length: 1];
270 }
271 else if (aBOOL && *b=='_')
272 {
273 ch=0x20;
274 [result appendBytes: &ch length: 1];
275 }
276 else
277 {
278 [result appendBytes: b length: 1];
279 }
280 }
281
282 return AUTORELEASE(result);
283 }
284
285
286 //
287 //
288 //
289 - (NSData *) encodeQuotedPrintableWithLineLength: (NSUInteger) theLength
290 inHeader: (BOOL) aBOOL
291 {
292 NSMutableData *aMutableData;
293 const unsigned char *b;
294 NSUInteger i, length, line;
295 char buf[4];
296
297 aMutableData = [[NSMutableData alloc] initWithCapacity: [self length]];
298 b = [self bytes];
299 length = [self length];
300
301 buf[3] = 0;
302 buf[0] = '=';
303 line = 0;
304
305 for (i = 0; i < length; i++, b++)
306 {
307 if (theLength && line >= theLength)
308 {
309 [aMutableData appendBytes: "=\n" length: 2];
310 line = 0;
311 }
312 // RFC says must encode space and tab right before end of line
313 if ( (*b == ' ' || *b == '\t') && i < length - 1 && b[1] == '\n')
314 {
315 buf[1] = hexDigit[(*b)>>4];
316 buf[2] = hexDigit[(*b)&15];
317 [aMutableData appendBytes: buf
318 length: 3];
319 line += 3;
320 }
321 // FIXME: really always pass \n through here?
322 else if (!aBOOL &&
323 (*b == '\n' || *b == ' ' || *b == '\t'
324 || (*b >= 33 && *b <= 60)
325 || (*b >= 62 && *b <= 126)))
326 {
327 [aMutableData appendBytes: b length: 1];
328 if (*b == '\n')
329 {
330 line = 0;
331 }
332 else
333 {
334 line++;
335 }
336 }
337 else if (aBOOL && ((*b >= 'a' && *b <= 'z') || (*b >= 'A' && *b <= 'Z')))
338 {
339 [aMutableData appendBytes: b length: 1];
340 if (*b == '\n')
341 {
342 line = 0;
343 }
344 else
345 {
346 line++;
347 }
348 }
349 else if (aBOOL && *b == ' ')
350 {
351 [aMutableData appendBytes: "_" length: 1];
352 }
353 else
354 {
355 buf[1] = hexDigit[(*b)>>4];
356 buf[2] = hexDigit[(*b)&15];
357 [aMutableData appendBytes: buf length: 3];
358 line += 3;
359 }
360 }
361
362 return AUTORELEASE(aMutableData);
363 }
364
365
366 //
367 //
368 //
369 - (NSRange) rangeOfData: (NSData *) theData
370 {
371 const char *b, *bytes, *str;
372 NSUInteger i, len, slen;
373
374 bytes = [self bytes];
375 len = [self length];
376
377 if (theData == nil || [theData length] == 0)
378 {
379 return NSMakeRange(NSNotFound,0);
380 }
381
382 slen = [theData length];
383 str = [theData bytes];
384
385 b = bytes;
386
387 // TODO: this could be optimized
388 i = 0;
389 b += i;
390 for (; i<= len-slen; i++, b++)
391 {
392 if (!memcmp(str,b,slen))
393 {
394 return NSMakeRange(i,slen);
395 }
396 }
397
398 return NSMakeRange(NSNotFound,0);
399 }
400
401
402 //
403 //
404 //
405 - (NSRange) rangeOfCString: (const char *) theCString
406 {
407 return [self rangeOfCString: theCString
408 options: 0
409 range: NSMakeRange(0,[self length])];
410 }
411
412
413 //
414 //
415 //
416 -(NSRange) rangeOfCString: (const char *) theCString
417 options: (NSUInteger) theOptions
418 {
419 return [self rangeOfCString: theCString
420 options: theOptions
421 range: NSMakeRange(0,[self length])];
422 }
423
424
425 //
426 //
427 //
428 -(NSRange) rangeOfCString: (const char *) theCString
429 options: (NSUInteger) theOptions
430 range: (NSRange) theRange
431 {
432 const char *b, *bytes;
433 NSUInteger i, len, slen;
434
435 if (!theCString)
436 {
437 return NSMakeRange(NSNotFound,0);
438 }
439 if (theRange.location == NSNotFound)
440 {
441 NSDebugLog(@"rangeOfCString: invalid range location");
442 return NSMakeRange(NSNotFound,0);
443 }
444
445 bytes = [self bytes];
446 len = [self length];
447 slen = (NSUInteger)strlen(theCString);
448
449 if (len < slen)
450 {
451 NSDebugLog(@"rangeOfCString: string too small to compare %@ to %s", self, theCString);
452 return NSMakeRange(NSNotFound,0);
453 }
454
455 b = bytes;
456
457 if (len > theRange.location + theRange.length)
458 {
459 len = theRange.location + theRange.length;
460 }
461
462 #warning this could be optimized
463 if (theOptions == NSCaseInsensitiveSearch)
464 {
465 i = theRange.location;
466 b += i;
467
468 for (; i <= len-slen; i++, b++)
469 {
470 if (!strncasecmp(theCString,b,slen))
471 {
472 return NSMakeRange(i,slen);
473 }
474 }
475 }
476 else
477 {
478 i = theRange.location;
479 b += i;
480
481 for (; i <= len-slen; i++, b++)
482 {
483 if (!memcmp(theCString,b,slen))
484 {
485 return NSMakeRange(i,slen);
486 }
487 }
488 }
489
490 return NSMakeRange(NSNotFound,0);
491 }
492
493
494 //
495 //
496 //
497 - (NSData *) subdataFromIndex: (NSUInteger) theIndex
498 {
499 if (theIndex > [self length])
500 return [NSData data];
501
502 return [self subdataWithRange: NSMakeRange(theIndex, [self length] - theIndex)];
503 }
504
505
506 //
507 //
508 //
509 - (NSData *) subdataToIndex: (NSUInteger) theIndex
510 {
511 return [self subdataWithRange: NSMakeRange(0, theIndex)];
512 }
513
514
515 //
516 //
517 //
518 - (NSData *) dataByTrimmingWhiteSpaces
519 {
520 const char *bytes;
521 NSUInteger i, len;
522 NSUInteger j;
523
524 bytes = [self bytes];
525 if (bytes == NULL)
526 return [NSData data];
527
528 len = [self length];
529 if (len == 0)
530 return [NSData data];
531
532 for (i = 0; i < len && (bytes[i] == ' ' || bytes[i] == '\t'); i++) ;
533
534 // We found only spaces, no need to search from the end
535 if (i == len)
536 return [NSData data];
537
538 for (j = len; j > 0 && (bytes[j-1] == ' ' || bytes[j-1] == '\t'); j--) ;
539
540 return [self subdataWithRange: NSMakeRange(i, j-i)];
541 }
542
543
544 //
545 //
546 //
547 - (NSData *) dataByRemovingLineFeedCharacters
548 {
549 NSMutableData *aMutableData;
550 const char *bytes;
551 NSUInteger i, j, len;
552 char *dest;
553
554 bytes = [self bytes];
555 len = [self length];
556
557 aMutableData = [[NSMutableData alloc] init];
558 [aMutableData setLength: len];
559
560 dest = [aMutableData mutableBytes];
561
562 for (i = j = 0; i < len; i++)
563 {
564 if (bytes[i] != '\n')
565 {
566 dest[j++] = bytes[i];
567 }
568 }
569
570 [aMutableData setLength: j];
571
572 return AUTORELEASE(aMutableData);
573 }
574
575
576 //
577 //
578 //
579 - (NSData *) dataFromQuotedData
580 {
581 const char *bytes;
582 NSUInteger len;
583
584 bytes = [self bytes];
585 len = [self length];
586
587 if (len < 2)
588 {
589 return AUTORELEASE(RETAIN(self));
590 }
591
592 if (bytes[0] == '"' && bytes[len-1] == '"')
593 {
594 return [self subdataWithRange: NSMakeRange(1, len-2)];
595 }
596
597 return AUTORELEASE(RETAIN(self));
598 }
599
600
601 //
602 //
603 //
604 - (NSData *) dataFromSemicolonTerminatedData
605 {
606 const char *bytes;
607 NSUInteger len;
608
609 bytes = [self bytes];
610 len = [self length];
611
612 if (len < 2)
613 {
614 return AUTORELEASE(RETAIN(self));
615 }
616
617 if (bytes[len-1] == ';')
618 {
619 return [self subdataToIndex: len-1];
620 }
621
622 return AUTORELEASE(RETAIN(self));
623 }
624
625 //
626 //
627 //
628 - (NSUInteger) indexOfCharacter: (unichar) theCharacter
629 {
630 const char *b;
631 NSUInteger i, len;
632
633 b = [self bytes];
634 len = [self length];
635
636 for ( i = 0; i < len; i++, b++)
637 if (*b == theCharacter)
638 {
639 return i;
640 }
641
642 return NSNotFound;
643 }
644
645
646 //
647 //
648 //
649 - (BOOL) hasCPrefix: (const char *) theCString
650 {
651 const char *bytes;
652 NSUInteger len, slen;
653
654 if (!theCString)
655 {
656 return NO;
657 }
658
659 bytes = [self bytes];
660 len = [self length];
661
662 slen = (NSUInteger)strlen(theCString);
663
664 if ( slen == 0 || slen > len)
665 {
666 return NO;
667 }
668
669 if (!strncmp(bytes,theCString,slen))
670 {
671 return YES;
672 }
673
674 return NO;
675 }
676
677
678 //
679 //
680 //
681 - (BOOL) hasCSuffix: (const char *) theCString
682 {
683 const char *bytes;
684 NSUInteger len, slen;
685
686 if (!theCString)
687 {
688 return NO;
689 }
690
691 bytes = [self bytes];
692 len = [self length];
693
694 slen = (NSUInteger)strlen(theCString);
695
696 if (slen == 0 || slen > len)
697 {
698 return NO;
699 }
700
701 if (!strncmp(&bytes[len-slen],theCString,slen))
702 {
703 return YES;
704 }
705
706 return NO;
707 }
708
709
710 //
711 //
712 //
713 - (BOOL) hasCaseInsensitiveCPrefix: (const char *) theCString
714 {
715 const char *bytes;
716 NSUInteger len, slen;
717
718 if (!theCString)
719 {
720 return NO;
721 }
722
723 bytes = [self bytes];
724 len = [self length];
725 slen = (NSUInteger)strlen(theCString);
726
727 if ( slen == 0 || slen > len)
728 {
729 return NO;
730 }
731
732 if ( !strncasecmp(bytes,theCString,slen) )
733 {
734 return YES;
735 }
736
737 return NO;
738 }
739
740
741 //
742 //
743 //
744 - (BOOL) hasCaseInsensitiveCSuffix: (const char *) theCString
745 {
746 const char *bytes;
747 NSUInteger len, slen;
748
749 if (!theCString)
750 {
751 return NO;
752 }
753
754 bytes = [self bytes];
755 len = [self length];
756 slen = (NSUInteger)strlen(theCString);
757
758 if (slen == 0 || slen > len)
759 {
760 return NO;
761 }
762
763 if (!strncasecmp(&bytes[len-slen],theCString,slen))
764 {
765 return YES;
766 }
767
768 return NO;
769 }
770
771
772 //
773 //
774 //
775 - (NSComparisonResult) caseInsensitiveCCompare: (const char *) theCString
776 {
777 NSUInteger slen, len, clen;
778 int i;
779 const char *bytes;
780
781 // Is this ok?
782 if (!theCString)
783 {
784 return NSOrderedDescending;
785 }
786
787 bytes = [self bytes];
788 len = [self length];
789 slen = (NSUInteger)strlen(theCString);
790
791 if (slen > len)
792 {
793 clen = len;
794 }
795 else
796 {
797 clen = slen;
798 }
799
800 i = strncasecmp(bytes,theCString,clen);
801
802 if (i < 0)
803 {
804 return NSOrderedAscending;
805 }
806
807 if (i > 0)
808 {
809 return NSOrderedDescending;
810 }
811
812 if (slen == len)
813 {
814 return NSOrderedSame;
815 }
816
817 if (slen < len)
818 {
819 return NSOrderedAscending;
820 }
821
822 return NSOrderedDescending;
823 }
824
825
826 //
827 //
828 //
829 - (NSArray *) componentsSeparatedByCString: (const char *) theCString
830 {
831 NSMutableArray *aMutableArray;
832 NSRange r1, r2;
833 NSUInteger len;
834
835 len = [self length];
836 if (len == 0)
837 return nil;
838
839 aMutableArray = [[NSMutableArray alloc] init];
840 r1 = NSMakeRange(0,len);
841
842 r2 = [self rangeOfCString: theCString
843 options: 0
844 range: r1];
845
846 while (r2.length)
847 {
848 [aMutableArray addObject: [self subdataWithRange: NSMakeRange(r1.location, r2.location - r1.location)]];
849 r1.location = r2.location + r2.length;
850 r1.length = len - r1.location;
851
852 r2 = [self rangeOfCString: theCString options: 0 range: r1];
853 }
854
855 [aMutableArray addObject: [self subdataWithRange: NSMakeRange(r1.location, len - r1.location)]];
856
857 return AUTORELEASE(aMutableArray);
858 }
859
860 //
861 //
862 //
863 - (NSString *) asciiString
864 {
865 return AUTORELEASE([[NSString alloc] initWithData: self encoding: NSASCIIStringEncoding]);
866 }
867
868
869 //
870 //
871 //
872 - (const char *) cString
873 {
874 NSMutableData *aMutableData;
875
876 aMutableData = [[NSMutableData alloc] init];
877 AUTORELEASE(aMutableData);
878
879 [aMutableData appendData: self];
880 [aMutableData appendBytes: "\0" length: 1];
881
882 return [aMutableData mutableBytes];
883 }
884
885
886 //
887 //
888 //
889 - (unichar) characterAtIndex: (NSUInteger) theIndex
890 {
891 const char *bytes;
892 NSUInteger len;
893 unichar ch;
894
895 len = [self length];
896
897 if (len == 0 || theIndex >= len)
898 {
899 [[NSException exceptionWithName: NSRangeException
900 reason: @"Index out of range."
901 userInfo: nil] raise];
902
903 return (unichar)0;
904 }
905
906 bytes = [self bytes];
907 ch = (unichar)bytes[theIndex];
908 return ch;
909 }
910
911
912 //
913 //
914 //
915 - (NSData *) unwrapWithLimit: (NSUInteger) theQuoteLimit
916 {
917 NSMutableData *aMutableData, *lines;
918 NSData *aLine;
919
920 NSUInteger i, len;
921 NSInteger quote_depth, line_quote_depth;
922 NSUInteger line_start;
923 BOOL is_flowed;
924
925 len = [self length];
926
927 aMutableData = [[NSMutableData alloc] init];//WithCapacity: len];
928 lines = [[NSMutableData alloc] init];
929 quote_depth = -1;
930
931 // We analyse the string until the last character
932 for (i = 0; i < len;)
933 {
934 // We analyse the quote depth of the current line
935 if ([self characterAtIndex: i] == '>')
936 {
937 for (line_quote_depth = 0; i < len && [self characterAtIndex: i] == '>'; i++)
938 {
939 line_quote_depth++;
940 }
941 }
942 else
943 {
944 line_quote_depth = 0;
945 }
946
947 // If the current quote depth is not defined, set it to quote depth of current line
948 if (quote_depth == -1)
949 {
950 quote_depth = line_quote_depth;
951 }
952
953 // We verify if the line has been space-stuffed
954 if (i < len && [self characterAtIndex: i] == ' ')
955 {
956 i++;
957 }
958 line_start = i;
959
960 // We look for the next line break
961 for (; i < len && [self characterAtIndex: i] != '\n'; i++);
962
963 // We get the actual content of the current line
964 aLine = [self subdataWithRange: NSMakeRange(line_start, i-line_start)];
965
966 // We verify if the line ends with a soft break
967 is_flowed = [aLine length] > 0 && [aLine characterAtIndex: [aLine length]-1] == ' ';
968
969 // We verify if the line is not just empty
970 if (is_flowed)
971 {
972 BOOL only_spaces;
973 NSUInteger k;
974
975 only_spaces = YES;
976 k = 0;
977 while (only_spaces && k < [aLine length]-1)
978 {
979 if ([aLine characterAtIndex:k] != ' ')
980 only_spaces = NO;
981 k++;
982 }
983
984 is_flowed = !only_spaces;
985 }
986
987 // We must handle usenet signature as a special case
988 if (is_flowed && [aLine caseInsensitiveCCompare: "-- "] == NSOrderedSame)
989 {
990 is_flowed = NO;
991 }
992
993 if (is_flowed && quote_depth == line_quote_depth)
994 {
995 // The current line is flowed;
996 // we append it to the buffer without quote characters
997 [lines appendData: aLine];
998 }
999 else if (is_flowed)
1000 {
1001 // The current line is flowed but has mis-matched quoting
1002
1003 // We first append the previous paragraph to the buffer with the necessary quote characters
1004 if (quote_depth > 0)
1005 {
1006 [lines replaceBytesInRange: NSMakeRange(0, [lines length])
1007 withBytes: [[lines quoteWithLevel: (NSUInteger)quote_depth wrappingLimit: theQuoteLimit] bytes]];
1008 }
1009
1010 [aMutableData appendData: lines];
1011 [aMutableData appendCString: "\n"];
1012
1013 // We initialize the current paragraph with the current line
1014 [lines replaceBytesInRange: NSMakeRange(0, [lines length]) withBytes: [aLine bytes]];
1015
1016 // We set the paragraph depth with the current line depth
1017 quote_depth = line_quote_depth;
1018 }
1019 else if (!is_flowed && quote_depth == line_quote_depth)
1020 {
1021 // The line is fixed, we append it.
1022 [lines appendData: aLine];
1023
1024 // We add the necessary quote characters in the paragraph
1025 if (quote_depth > 0)
1026 {
1027 NSData *d;
1028
1029 d = [lines quoteWithLevel: (NSUInteger)quote_depth wrappingLimit: theQuoteLimit];
1030 [lines replaceBytesInRange: NSMakeRange(0, [lines length])
1031 withBytes: [d bytes] length: [d length]];
1032 }
1033
1034 // We append the paragraph (if any)
1035 if ([lines length])
1036 {
1037 [aMutableData appendData: lines];
1038 }
1039 [aMutableData appendCString: "\n"];
1040
1041 // We empty the paragraph buffer
1042 [lines replaceBytesInRange: NSMakeRange(0,[lines length])
1043 withBytes: NULL
1044 length: 0];
1045
1046 // We reset the paragraph depth
1047 quote_depth = -1;
1048 }
1049 else
1050 {
1051 // The line is fixed but has mis-matched quoting
1052
1053 // We first append the previous paragraph (if any) to the buffer with the necessary quote characters
1054 if (quote_depth > 0)
1055 {
1056 [lines replaceBytesInRange: NSMakeRange(0, [lines length])
1057 withBytes: [[lines quoteWithLevel: (NSUInteger)quote_depth wrappingLimit: theQuoteLimit] bytes]];
1058 }
1059
1060 [aMutableData appendData: lines];
1061 [aMutableData appendCString: "\n"];
1062
1063 // We append the fixed line to the buffer with the necessary quote characters
1064 if (line_quote_depth > 0)
1065 {
1066 aLine = [aLine quoteWithLevel: (NSUInteger)line_quote_depth wrappingLimit: theQuoteLimit];
1067 }
1068
1069 [aMutableData appendData: aLine];
1070 [aMutableData appendCString: "\n"];
1071
1072 // We empty the paragraph buffer
1073 [lines replaceBytesInRange: NSMakeRange(0,[lines length])
1074 withBytes: NULL
1075 length: 0];
1076
1077 // We reset the paragraph depth
1078 quote_depth = -1;
1079 }
1080
1081 // The next iteration must starts after the line break
1082 i++;
1083 }
1084
1085 // We must handle flowed lines that don't have a fixed line break at the end of the message
1086 if ([lines length])
1087 {
1088 if (quote_depth > 0)
1089 {
1090 [lines replaceBytesInRange: NSMakeRange(0, [lines length])
1091 withBytes: [[lines quoteWithLevel: (NSUInteger)quote_depth wrappingLimit: theQuoteLimit] bytes]];
1092 }
1093
1094 [aMutableData appendData: lines];
1095 [aMutableData appendCString: "\n"];
1096 }
1097
1098 DESTROY(lines);
1099
1100 return AUTORELEASE(aMutableData);
1101 }
1102
1103
1104 //
1105 //
1106 //
1107 - (NSData *) wrapWithLimit: (NSUInteger) theLimit
1108 {
1109 NSMutableData *aMutableData;
1110 NSData *aLine, *part;
1111 NSArray *lines;
1112 NSUInteger i, j, k;
1113 NSUInteger split;
1114 NSUInteger depth;
1115
1116 // We first verify if the string is valid
1117 if ([self length] == 0)
1118 {
1119 return [NSData data];
1120 }
1121
1122 // We then verify if the limit is valid
1123 if (theLimit == 0 || theLimit > 998)
1124 {
1125 theLimit = 998;
1126 }
1127
1128 // We initialize our local variables
1129 aMutableData = [[NSMutableData alloc] init];//WithCapacity: [self length]];
1130 lines = [self componentsSeparatedByCString: "\n"];
1131
1132 // We analyse each line
1133 for (i = 0; i < [lines count]; i++)
1134 {
1135 aLine = [lines objectAtIndex: i];
1136
1137 // We compute the quote depth
1138 for (depth = 0; depth < [aLine length] && [aLine characterAtIndex: depth] == '>'; depth++);
1139 j = depth;
1140
1141 // We remove the leading whitespace if any
1142 if (depth && [aLine length] > j && [aLine characterAtIndex: j] == 32)
1143 {
1144 j++;
1145 }
1146
1147 aLine = [aLine subdataFromIndex: j];
1148
1149 // If the line is NOT the signature separator, we remove the trailing space(s)
1150 if ([aLine caseInsensitiveCCompare: "-- "] != NSOrderedSame)
1151 {
1152 for (j = [aLine length]; j > 0 && [aLine characterAtIndex: j-1] == 32; j--);
1153 if (depth && j < [aLine length])
1154 {
1155 // If line is quoted, we preserve a whitespace for the soft-break
1156 j++;
1157 }
1158 aLine = [aLine subdataToIndex: j];
1159 }
1160
1161 // If the line is the signature separator or if the line length with the
1162 // quote characters and the space-stuffing is lower than the limit,
1163 // we directly append the line to the buffer
1164 if ([aLine caseInsensitiveCCompare: "-- "] == NSOrderedSame || depth+1+[aLine length] <= theLimit)
1165 {
1166 // We add the quote characters
1167 for (j = 0; j < depth; j++)
1168 {
1169 [aMutableData appendCString: ">"];
1170 }
1171
1172 // We space-stuff the line if necessary. The conditions are:
1173 // - the line is quoted or
1174 // - the line starts with a quote character or
1175 // - the line starts with a whitespace or
1176 // - the line starts with the word From.
1177 if (depth ||
1178 ([aLine length] && ([aLine characterAtIndex: 0] == '>' || [aLine characterAtIndex: 0] == ' ' || [aLine hasCPrefix: "From"])))
1179 {
1180 [aMutableData appendCString: " "];
1181 }
1182
1183 // We append the line to the buffer
1184 [aMutableData appendData: aLine];
1185 [aMutableData appendCString: "\n"];
1186
1187 // We jump to the next line
1188 continue;
1189 }
1190
1191 // We look for the right place to split the line
1192 for (j = 0; j < [aLine length];)
1193 {
1194 // We verify if the line after character j has a length lower than the limit
1195 if ([aLine length] - j + depth + 1 < theLimit)
1196 {
1197 split = [aLine length];
1198 }
1199 // No it hasn't
1200 else
1201 {
1202 split = j;
1203
1204 // We search for the last whitespace before the limit
1205 for (k = j; k < [aLine length] && k - j + depth + 1 < theLimit; k++)
1206 {
1207 if ([aLine characterAtIndex: k] == 32)
1208 {
1209 split = k;
1210 }
1211 }
1212
1213 /*
1214 No good spot; include the entire next word. This isn't really
1215 optimal, but the alternative is to split the word, and that
1216 would be horribly ugly. Also, it'd mean that deeply quoted
1217 text might appear with one letter on each row, which is even
1218 uglier and means that the receiver won't be able to
1219 reconstruct the text.
1220
1221 A proper fix would be to have both parameters for a 'soft'
1222 line limit that we _try_ to break before, and a 'hard' line
1223 limit that specifies an actual hard limit of a protocol or
1224 something. In NNTP, the values would be 72 and 998
1225 respectively. This means that text quoted 70 levels (and yes,
1226 I have seen such posts) will appear with one unbroken word on
1227 each line (as long as the word is shorter than 928
1228 characters). This is still ugly, but:
1229
1230 a. invalid (protocol-wise) lines will never be generated
1231 (unless something's quoted >998 levels)
1232
1233 b. a MIME decoder that handles format=flowed will be able to
1234 reconstruct the text properly
1235
1236 (Additionally, it might turn out to be useful to have a lower
1237 limit on wrapping length, eg. 20. If the effective line
1238 length is shorter than this, wrap to quote-depth+soft-limit
1239 (so eg. text quoted 60 times would be wrapped at 60+72
1240 characters instead of 72). This wouldn't make any difference
1241 on flowed capable MIME decoders, but might turn out to look
1242 better when viewed with non-flowed handling programs.
1243 Hopefully, such deeply quoted text won't be common enough to
1244 be worth the trouble, so people with non-flowed capable
1245 software will simply have to live with the ugly posts in
1246 those cases.)
1247 */
1248 if (split == j)
1249 {
1250 // No whitespace found before the limit;
1251 // continue farther until a whitespace or the last character of the line
1252 for (; k < [aLine length] && [aLine characterAtIndex: k] != 32; k++);
1253 split = k;
1254 }
1255 }
1256
1257 // Since the line will be splitted, we must keep a whitespace for
1258 // the soft-line break
1259 if (split < [aLine length])
1260 {
1261 split++;
1262 }
1263
1264 // Retrieve splitted part of line
1265 part = [aLine subdataWithRange: NSMakeRange(j, split - j)];
1266
1267 // We add the quote characters
1268 for (k = 0; k < depth; k++)
1269 {
1270 [aMutableData appendCString: ">"];
1271 }
1272
1273 // We space-stuff the line if necesary.
1274 if (depth ||
1275 ([part length] && ([part characterAtIndex: 0] == '>' || [part characterAtIndex: 0] == ' ' || [part hasCPrefix: "From"])))
1276 {
1277 [aMutableData appendCString: " "];
1278 }
1279
1280 // Append line part to buffer
1281 [aMutableData appendData: part];
1282 [aMutableData appendCString: "\n"];
1283
1284 // Next iteration continues where current split occured
1285 j = split;
1286 }
1287
1288
1289 }
1290
1291 if (i > 0)
1292 {
1293 [aMutableData replaceBytesInRange: NSMakeRange([aMutableData length]-1, 1) withBytes: NULL length: 0];
1294 }
1295
1296 return AUTORELEASE(aMutableData);
1297 }
1298
1299 //
1300 //
1301 //
1302 - (NSData *) quoteWithLevel: (NSUInteger) theLevel
1303 wrappingLimit: (NSUInteger) theLimit
1304 {
1305 NSMutableData *aMutableData, *aQuotePrefix;
1306 NSData *aData, *aLine;
1307 NSArray *lines;
1308 BOOL isQuoted;
1309 NSUInteger i;
1310
1311 // We verify if the wrapping limit is smaller then the quote level
1312 if (theLevel > theLimit)
1313 {
1314 return [NSData data];
1315 }
1316
1317 aMutableData = [[NSMutableData alloc] initWithCapacity: [self length]];
1318 aQuotePrefix = [[NSMutableData alloc] initWithCapacity: theLevel];
1319
1320 // We wrap the string to the proper limit
1321 aData = [self wrapWithLimit: (theLimit - theLevel)];
1322 lines = [aData componentsSeparatedByCString: "\n"];
1323
1324 // We prepare the line prefix
1325 for (i = 0; i < theLevel; i++)
1326 {
1327 [aQuotePrefix appendCString: ">"];
1328 }
1329
1330 // We add the line prefix to each wrapped line
1331 for (i = 0; i < [lines count]; i++)
1332 {
1333 aLine = [lines objectAtIndex: i];
1334 isQuoted = ([aLine length] > 0 && [aLine characterAtIndex: 0] == '>');
1335
1336 [aMutableData appendData: aQuotePrefix];
1337 if (!isQuoted)
1338 {
1339 [aMutableData appendCString: " "];
1340 }
1341 [aMutableData appendData: aLine];
1342 [aMutableData appendCString: "\n"];
1343 }
1344
1345 if (i > 0)
1346 {
1347 [aMutableData replaceBytesInRange: NSMakeRange([aMutableData length]-1, 1) withBytes: NULL length: 0];
1348 }
1349
1350 RELEASE(aQuotePrefix);
1351
1352 return AUTORELEASE(aMutableData);
1353 }
1354
1355 @end
1356
1357
1358 //
1359 //
1360 //
1361 @implementation NSMutableData (PantomimeExtensions)
1362
1363 - (void) appendCFormat: (NSString *) theFormat, ...
1364 {
1365 NSString *aString;
1366 va_list args;
1367
1368 va_start(args, theFormat);
1369 aString = [[NSString alloc] initWithFormat: theFormat arguments: args];
1370 va_end(args);
1371
1372 // We allow lossy conversion to not lose any information / raise an exception
1373 [self appendData: [aString dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion: YES]];
1374
1375 RELEASE(aString);
1376 }
1377
1378
1379 //
1380 //
1381 //
1382 - (void) appendCString: (const char *) theCString
1383 {
1384 [self appendBytes: theCString length: strlen(theCString)];
1385 }
1386
1387
1388 //
1389 //
1390 //
1391 - (void) insertCString: (const char *) theCString
1392 atIndex: (NSUInteger) theIndex
1393 {
1394 NSUInteger s_length, length;
1395
1396 if (!theCString)
1397 {
1398 return;
1399 }
1400
1401 s_length = (NSUInteger)strlen(theCString);
1402
1403 if (s_length == 0)
1404 {
1405 return;
1406 }
1407
1408 length = [self length];
1409
1410 // We insert at the beginning of the data
1411 if (theIndex == 0)
1412 {
1413 NSMutableData *data;
1414
1415 data = [NSMutableData dataWithBytes: theCString length: s_length];
1416 [data appendData: self];
1417 [self setData: data];
1418 }
1419 // We insert at the end of the data
1420 else if (theIndex >= length)
1421 {
1422 [self appendCString: theCString];
1423 }
1424 // We insert somewhere in the middle
1425 else
1426 {
1427 NSMutableData *data;
1428
1429 data = [NSMutableData dataWithBytes: [self subdataWithRange: NSMakeRange(0, theIndex)] length: theIndex];
1430 [data appendCString: theCString];
1431 [data appendData: [self subdataWithRange: NSMakeRange(theIndex, length - theIndex)]];
1432 [self setData: data];
1433 }
1434 }
1435
1436
1437 //
1438 //
1439 //
1440 - (void) replaceCRLFWithLF
1441 {
1442 unsigned char *bytes, *bi, *bo;
1443 NSUInteger delta, i, length;
1444
1445 bytes = [self mutableBytes];
1446 length = [self length];
1447 bi = bo = bytes;
1448
1449 for (i = delta = 0; i < length; i++, bi++)
1450 {
1451 if (i+1 < length && bi[0] == '\r' && bi[1] == '\n')
1452 {
1453 i++;
1454 bi++;
1455 delta++;
1456 }
1457
1458 *bo = *bi;
1459 bo++;
1460 }
1461
1462 [self setLength: length-delta];
1463 }
1464
1465
1466 //
1467 //
1468 //
1469 - (NSMutableData *) replaceLFWithCRLF
1470 {
1471 NSMutableData *aMutableData;
1472 unsigned char *bytes, *bi, *bo;
1473 NSUInteger delta, i, length;
1474
1475 bi = bytes = [self mutableBytes];
1476 length = [self length];
1477 delta = 0;
1478
1479 if (bi[0] == '\n')
1480 {
1481 delta++;
1482 }
1483
1484 bi++;
1485
1486 for (i = 1; i < length; i++, bi++)
1487 {
1488 if ((bi[0] == '\n') && (bi[-1] != '\r'))
1489 {
1490 delta++;
1491 }
1492 }
1493
1494 bi = bytes;
1495 aMutableData = [[NSMutableData alloc] initWithLength: (length+delta)];
1496 bo = [aMutableData mutableBytes];
1497
1498 for (i = 0; i < length; i++, bi++, bo++)
1499 {
1500 if ((i+1 < length) && (bi[0] == '\r') && (bi[1] == '\n'))
1501 {
1502 *bo = *bi;
1503 bo++;
1504 bi++;
1505 i++;
1506 }
1507 else if (*bi == '\n')
1508 {
1509 *bo = '\r';
1510 bo++;
1511 }
1512
1513 *bo = *bi;
1514 }
1515
1516 return AUTORELEASE(aMutableData);
1517 }
1518
1519 @end
1520
1521
1522 //
1523 // C functions
1524 //
1525 int getValue(const unsigned char c)
1526 {
1527 if (c >= 'A' && c <= 'Z') return (c - 'A');
1528 if (c >= 'a' && c <= 'z') return (c - 'a' + 26);
1529 if (c >= '0' && c <= '9') return (c - '0' + 52);
1530 if (c == '+') return 62;
1531 if (c == '/') return 63;
1532 if (c == '=') return 0;
1533 return -1;
1534 }
1535
1536
1537 //
1538 //
1539 //
1540 void nb64ChunkFor3Characters(char *buf, const char *inBuf, unsigned theLength)
1541 {
1542 if (theLength >= 3)
1543 {
1544 buf[0] = basis_64[inBuf[0]>>2 & 0x3F];
1545 buf[1] = basis_64[(((inBuf[0] & 0x3)<< 4) | ((inBuf[1] & 0xF0) >> 4)) & 0x3F];
1546 buf[2] = basis_64[(((inBuf[1] & 0xF) << 2) | ((inBuf[2] & 0xC0) >>6)) & 0x3F];
1547 buf[3] = basis_64[inBuf[2] & 0x3F];
1548 }
1549 else if(theLength == 2)
1550 {
1551 buf[0] = basis_64[inBuf[0]>>2 & 0x3F];
1552 buf[1] = basis_64[(((inBuf[0] & 0x3)<< 4) | ((inBuf[1] & 0xF0) >> 4)) & 0x3F];
1553 buf[2] = basis_64[(((inBuf[1] & 0xF) << 2) | ((0 & 0xC0) >>6)) & 0x3F];
1554 buf[3] = '=';
1555 }
1556 else
1557 {
1558 buf[0] = basis_64[inBuf[0]>>2 & 0x3F];
1559 buf[1] = basis_64[(((inBuf[0] & 0x3)<< 4) | ((0 & 0xF0) >> 4)) & 0x3F];
1560 buf[2] = '=';
1561 buf[3] = '=';
1562 }
1563 }