-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathCodecs.java
More file actions
1541 lines (1293 loc) · 46.9 KB
/
Codecs.java
File metadata and controls
1541 lines (1293 loc) · 46.9 KB
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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package HTTPClient;
import java.util.BitSet;
import java.util.Vector;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.EOFException;
import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLConnection;
/**
* This class collects various encoders and decoders.
*
* @version 0.3-3 06/05/2001
* @author Ronald Tschal�r
*/
public class Codecs
{
private static BitSet BoundChar;
private static BitSet EBCDICUnsafeChar;
private static byte[] Base64EncMap, Base64DecMap;
private static char[] UUEncMap;
private static byte[] UUDecMap;
private final static String ContDisp = "\r\nContent-Disposition: form-data; name=\"";
private final static String FileName = "\"; filename=\"";
private final static String ContType = "\r\nContent-Type: ";
private final static String Boundary = "\r\n----------ieoau._._+2_8_GoodLuck8.3-dskdfJwSJKl234324jfLdsjfdAuaoei-----";
// Class Initializer
static
{
// rfc-2046 & rfc-2045: (bcharsnospace & token)
// used for multipart codings
BoundChar = new BitSet(256);
for (int ch='0'; ch <= '9'; ch++) BoundChar.set(ch);
for (int ch='A'; ch <= 'Z'; ch++) BoundChar.set(ch);
for (int ch='a'; ch <= 'z'; ch++) BoundChar.set(ch);
BoundChar.set('+');
BoundChar.set('_');
BoundChar.set('-');
BoundChar.set('.');
// EBCDIC unsafe characters to be quoted in quoted-printable
// See first NOTE in section 6.7 of rfc-2045
EBCDICUnsafeChar = new BitSet(256);
EBCDICUnsafeChar.set('!');
EBCDICUnsafeChar.set('"');
EBCDICUnsafeChar.set('#');
EBCDICUnsafeChar.set('$');
EBCDICUnsafeChar.set('@');
EBCDICUnsafeChar.set('[');
EBCDICUnsafeChar.set('\\');
EBCDICUnsafeChar.set(']');
EBCDICUnsafeChar.set('^');
EBCDICUnsafeChar.set('`');
EBCDICUnsafeChar.set('{');
EBCDICUnsafeChar.set('|');
EBCDICUnsafeChar.set('}');
EBCDICUnsafeChar.set('~');
// rfc-2045: Base64 Alphabet
byte[] map = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F',
(byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L',
(byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R',
(byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X',
(byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f',
(byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l',
(byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r',
(byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x',
(byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' };
Base64EncMap = map;
Base64DecMap = new byte[128];
for (int idx=0; idx<Base64EncMap.length; idx++)
Base64DecMap[Base64EncMap[idx]] = (byte) idx;
// uuencode'ing maps
UUEncMap = new char[64];
for (int idx=0; idx<UUEncMap.length; idx++)
UUEncMap[idx] = (char) (idx + 0x20);
UUDecMap = new byte[128];
for (int idx=0; idx<UUEncMap.length; idx++)
UUDecMap[UUEncMap[idx]] = (byte) idx;
}
// Constructors
/**
* This class isn't meant to be instantiated.
*/
private Codecs() {}
// Methods
/**
* This method encodes the given string using the base64-encoding
* specified in RFC-2045 (Section 6.8). It's used for example in the
* "Basic" authorization scheme.
*
* @param str the string
* @return the base64-encoded <var>str</var>
*/
public final static String base64Encode(String str)
{
if (str == null) return null;
try
{ return new String(base64Encode(str.getBytes("8859_1")), "8859_1"); }
catch (UnsupportedEncodingException uee)
{ throw new Error(uee.toString()); }
}
/**
* This method encodes the given byte[] using the base64-encoding
* specified in RFC-2045 (Section 6.8).
*
* @param data the data
* @return the base64-encoded <var>data</var>
*/
public final static byte[] base64Encode(byte[] data)
{
if (data == null) return null;
int sidx, didx;
byte dest[] = new byte[((data.length+2)/3)*4];
// 3-byte to 4-byte conversion + 0-63 to ascii printable conversion
for (sidx=0, didx=0; sidx < data.length-2; sidx += 3)
{
dest[didx++] = Base64EncMap[(data[sidx] >>> 2) & 077];
dest[didx++] = Base64EncMap[(data[sidx+1] >>> 4) & 017 |
(data[sidx] << 4) & 077];
dest[didx++] = Base64EncMap[(data[sidx+2] >>> 6) & 003 |
(data[sidx+1] << 2) & 077];
dest[didx++] = Base64EncMap[data[sidx+2] & 077];
}
if (sidx < data.length)
{
dest[didx++] = Base64EncMap[(data[sidx] >>> 2) & 077];
if (sidx < data.length-1)
{
dest[didx++] = Base64EncMap[(data[sidx+1] >>> 4) & 017 |
(data[sidx] << 4) & 077];
dest[didx++] = Base64EncMap[(data[sidx+1] << 2) & 077];
}
else
dest[didx++] = Base64EncMap[(data[sidx] << 4) & 077];
}
// add padding
for ( ; didx < dest.length; didx++)
dest[didx] = (byte) '=';
return dest;
}
/**
* This method decodes the given string using the base64-encoding
* specified in RFC-2045 (Section 6.8).
*
* @param str the base64-encoded string.
* @return the decoded <var>str</var>.
*/
public final static String base64Decode(String str)
{
if (str == null) return null;
try
{ return new String(base64Decode(str.getBytes("8859_1")), "8859_1"); }
catch (UnsupportedEncodingException uee)
{ throw new Error(uee.toString()); }
}
/**
* This method decodes the given byte[] using the base64-encoding
* specified in RFC-2045 (Section 6.8).
*
* @param data the base64-encoded data.
* @return the decoded <var>data</var>.
*/
public final static byte[] base64Decode(byte[] data)
{
if (data == null) return null;
int tail = data.length;
while (data[tail-1] == '=') tail--;
byte dest[] = new byte[tail - data.length/4];
// ascii printable to 0-63 conversion
for (int idx = 0; idx <data.length; idx++)
data[idx] = Base64DecMap[data[idx]];
// 4-byte to 3-byte conversion
int sidx, didx;
for (sidx = 0, didx=0; didx < dest.length-2; sidx += 4, didx += 3)
{
dest[didx] = (byte) ( ((data[sidx] << 2) & 255) |
((data[sidx+1] >>> 4) & 003) );
dest[didx+1] = (byte) ( ((data[sidx+1] << 4) & 255) |
((data[sidx+2] >>> 2) & 017) );
dest[didx+2] = (byte) ( ((data[sidx+2] << 6) & 255) |
(data[sidx+3] & 077) );
}
if (didx < dest.length)
dest[didx] = (byte) ( ((data[sidx] << 2) & 255) |
((data[sidx+1] >>> 4) & 003) );
if (++didx < dest.length)
dest[didx] = (byte) ( ((data[sidx+1] << 4) & 255) |
((data[sidx+2] >>> 2) & 017) );
return dest;
}
/**
* This method encodes the given byte[] using the unix uuencode
* encding. The output is split into lines starting with the encoded
* number of encoded octets in the line and ending with a newline.
* No line is longer than 45 octets (60 characters), not including
* length and newline.
*
* <P><em>Note:</em> just the raw data is encoded; no 'begin' and 'end'
* lines are added as is done by the unix <code>uuencode</code> utility.
*
* @param data the data
* @return the uuencoded <var>data</var>
*/
public final static char[] uuencode(byte[] data)
{
if (data == null) return null;
if (data.length == 0) return new char[0];
int line_len = 45; // line length, in octets
int sidx, didx;
char nl[] = System.getProperty("line.separator", "\n").toCharArray(),
dest[] = new char[(data.length+2)/3*4 +
((data.length+line_len-1)/line_len)*(nl.length+1)];
// split into lines, adding line-length and line terminator
for (sidx=0, didx=0; sidx+line_len < data.length; )
{
// line length
dest[didx++] = UUEncMap[line_len];
// 3-byte to 4-byte conversion + 0-63 to ascii printable conversion
for (int end = sidx+line_len; sidx < end; sidx += 3)
{
dest[didx++] = UUEncMap[(data[sidx] >>> 2) & 077];
dest[didx++] = UUEncMap[(data[sidx+1] >>> 4) & 017 |
(data[sidx] << 4) & 077];
dest[didx++] = UUEncMap[(data[sidx+2] >>> 6) & 003 |
(data[sidx+1] << 2) & 077];
dest[didx++] = UUEncMap[data[sidx+2] & 077];
}
// line terminator
for (int idx=0; idx<nl.length; idx++) dest[didx++] = nl[idx];
}
// last line
// line length
dest[didx++] = UUEncMap[data.length-sidx];
// 3-byte to 4-byte conversion + 0-63 to ascii printable conversion
for (; sidx+2 < data.length; sidx += 3)
{
dest[didx++] = UUEncMap[(data[sidx] >>> 2) & 077];
dest[didx++] = UUEncMap[(data[sidx+1] >>> 4) & 017 |
(data[sidx] << 4) & 077];
dest[didx++] = UUEncMap[(data[sidx+2] >>> 6) & 003 |
(data[sidx+1] << 2) & 077];
dest[didx++] = UUEncMap[data[sidx+2] & 077];
}
if (sidx < data.length-1)
{
dest[didx++] = UUEncMap[(data[sidx] >>> 2) & 077];
dest[didx++] = UUEncMap[(data[sidx+1] >>> 4) & 017 |
(data[sidx] << 4) & 077];
dest[didx++] = UUEncMap[(data[sidx+1] << 2) & 077];
dest[didx++] = UUEncMap[0];
}
else if (sidx < data.length)
{
dest[didx++] = UUEncMap[(data[sidx] >>> 2) & 077];
dest[didx++] = UUEncMap[(data[sidx] << 4) & 077];
dest[didx++] = UUEncMap[0];
dest[didx++] = UUEncMap[0];
}
// line terminator
for (int idx=0; idx<nl.length; idx++) dest[didx++] = nl[idx];
// sanity check
if (didx != dest.length)
throw new Error("Calculated "+dest.length+" chars but wrote "+didx+" chars!");
return dest;
}
/**
* TBD! How to return file name and mode?
*
* @param rdr the reader from which to read and decode the data
* @exception ParseException if either the "begin" or "end" line are not
* found, or the "begin" is incorrect
* @exception IOException if the <var>rdr</var> throws an IOException
*/
private final static byte[] uudecode(BufferedReader rdr)
throws ParseException, IOException
{
String line, file_name;
int file_mode;
// search for beginning
while ((line = rdr.readLine()) != null && !line.startsWith("begin "))
;
if (line == null)
throw new ParseException("'begin' line not found");
// parse 'begin' line
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // throw away 'begin'
try // extract mode
{ file_mode = Integer.parseInt(tok.nextToken(), 8); }
catch (Exception e)
{ throw new ParseException("Invalid mode on line: " + line); }
try // extract name
{ file_name = tok.nextToken(); }
catch (java.util.NoSuchElementException e)
{ throw new ParseException("No file name found on line: " + line); }
// read and parse body
byte[] body = new byte[1000];
int off = 0;
while ((line = rdr.readLine()) != null && !line.equals("end"))
{
byte[] tmp = uudecode(line.toCharArray());
if (off + tmp.length > body.length)
body = Util.resizeArray(body, off+1000);
System.arraycopy(tmp, 0, body, off, tmp.length);
off += tmp.length;
}
if (line == null)
throw new ParseException("'end' line not found");
return Util.resizeArray(body, off);
}
/**
* This method decodes the given uuencoded char[].
*
* <P><em>Note:</em> just the actual data is decoded; any 'begin' and
* 'end' lines such as those generated by the unix <code>uuencode</code>
* utility must not be included.
*
* @param data the uuencode-encoded data.
* @return the decoded <var>data</var>.
*/
public final static byte[] uudecode(char[] data)
{
if (data == null) return null;
int sidx, didx;
byte dest[] = new byte[data.length/4*3];
for (sidx=0, didx=0; sidx < data.length; )
{
// get line length (in number of encoded octets)
int len = UUDecMap[data[sidx++]];
// ascii printable to 0-63 and 4-byte to 3-byte conversion
int end = didx+len;
for (; didx < end-2; sidx += 4)
{
byte A = UUDecMap[data[sidx]],
B = UUDecMap[data[sidx+1]],
C = UUDecMap[data[sidx+2]],
D = UUDecMap[data[sidx+3]];
dest[didx++] = (byte) ( ((A << 2) & 255) | ((B >>> 4) & 003) );
dest[didx++] = (byte) ( ((B << 4) & 255) | ((C >>> 2) & 017) );
dest[didx++] = (byte) ( ((C << 6) & 255) | (D & 077) );
}
if (didx < end)
{
byte A = UUDecMap[data[sidx]],
B = UUDecMap[data[sidx+1]];
dest[didx++] = (byte) ( ((A << 2) & 255) | ((B >>> 4) & 003) );
}
if (didx < end)
{
byte B = UUDecMap[data[sidx+1]],
C = UUDecMap[data[sidx+2]];
dest[didx++] = (byte) ( ((B << 4) & 255) | ((C >>> 2) & 017) );
}
// skip padding
while (sidx < data.length &&
data[sidx] != '\n' && data[sidx] != '\r')
sidx++;
// skip end of line
while (sidx < data.length &&
(data[sidx] == '\n' || data[sidx] == '\r'))
sidx++;
}
return Util.resizeArray(dest, didx);
}
/**
* This method does a quoted-printable encoding of the given string
* according to RFC-2045 (Section 6.7). <em>Note:</em> this assumes
* 8-bit characters.
*
* @param str the string
* @return the quoted-printable encoded string
*/
public final static String quotedPrintableEncode(String str)
{
if (str == null) return null;
char map[] =
{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'},
nl[] = System.getProperty("line.separator", "\n").toCharArray(),
res[] = new char[(int) (str.length()*1.5)],
src[] = str.toCharArray();
char ch;
int cnt = 0,
didx = 1,
last = 0,
slen = str.length();
for (int sidx=0; sidx < slen; sidx++)
{
ch = src[sidx];
if (ch == nl[0] && match(src, sidx, nl)) // Rule #4
{
if (res[didx-1] == ' ') // Rule #3
{
res[didx-1] = '=';
res[didx++] = '2';
res[didx++] = '0';
}
else if (res[didx-1] == '\t') // Rule #3
{
res[didx-1] = '=';
res[didx++] = '0';
res[didx++] = '9';
}
res[didx++] = '\r';
res[didx++] = '\n';
sidx += nl.length - 1;
cnt = didx;
}
else if (ch > 126 || (ch < 32 && ch != '\t') || ch == '=' ||
EBCDICUnsafeChar.get((int) ch))
{ // Rule #1, #2
res[didx++] = '=';
res[didx++] = map[(ch & 0xf0) >>> 4];
res[didx++] = map[ch & 0x0f];
}
else // Rule #1
{
res[didx++] = ch;
}
if (didx > cnt+70) // Rule #5
{
res[didx++] = '=';
res[didx++] = '\r';
res[didx++] = '\n';
cnt = didx;
}
if (didx > res.length-5)
res = Util.resizeArray(res, res.length+500);
}
return String.valueOf(res, 1, didx-1);
}
private final static boolean match(char[] str, int start, char[] arr)
{
if (str.length < start + arr.length) return false;
for (int idx=1; idx < arr.length; idx++)
if (str[start+idx] != arr[idx]) return false;
return true;
}
/**
* This method does a quoted-printable decoding of the given string
* according to RFC-2045 (Section 6.7). <em>Note:</em> this method
* expects the whole message in one chunk, not line by line.
*
* @param str the message
* @return the decoded message
* @exception ParseException If a '=' is not followed by a valid
* 2-digit hex number or '\r\n'.
*/
public final static String quotedPrintableDecode(String str)
throws ParseException
{
if (str == null) return null;
char res[] = new char[(int) (str.length()*1.1)],
src[] = str.toCharArray(),
nl[] = System.getProperty("line.separator", "\n").toCharArray();
int last = 0,
didx = 0,
slen = str.length();
for (int sidx=0; sidx<slen; )
{
char ch = src[sidx++];
if (ch == '=')
{
if (sidx >= slen-1)
throw new ParseException("Premature end of input detected");
if (src[sidx] == '\n' || src[sidx] == '\r')
{ // Rule #5
sidx++;
if (src[sidx-1] == '\r' &&
src[sidx] == '\n')
sidx++;
}
else // Rule #1
{
char repl;
int hi = Character.digit(src[sidx], 16),
lo = Character.digit(src[sidx+1], 16);
if ((hi | lo) < 0)
throw new ParseException(new String(src, sidx-1, 3) +
" is an invalid code");
else
{
repl = (char) (hi << 4 | lo);
sidx += 2;
}
res[didx++] = repl;
}
last = didx;
}
else if (ch == '\n' || ch == '\r') // Rule #4
{
if (ch == '\r' && sidx < slen && src[sidx] == '\n')
sidx++;
for (int idx=0; idx<nl.length; idx++)
res[last++] = nl[idx];
didx = last;
}
else // Rule #1, #2
{
res[didx++] = ch;
if (ch != ' ' && ch != '\t') // Rule #3
last = didx;
}
if (didx > res.length-nl.length-2)
res = Util.resizeArray(res, res.length+500);
}
return new String(res, 0, didx);
}
/**
* This method urlencodes the given string. This method is here for
* symmetry reasons and just calls java.net.URLEncoder.encode().
*
* @param str the string
* @return the url-encoded string
*/
public final static String URLEncode(String str)
{
if (str == null) return null;
try
{
return java.net.URLEncoder.encode(str, "UTF-8");
}
catch (java.io.UnsupportedEncodingException e)
{
return "";
}
}
/**
* This method decodes the given urlencoded string.
*
* @param str the url-encoded string
* @return the decoded string
* @exception ParseException If a '%' is not followed by a valid
* 2-digit hex number.
*/
public final static String URLDecode(String str) throws ParseException
{
if (str == null) return null;
char[] res = new char[str.length()];
int didx = 0;
for (int sidx=0; sidx<str.length(); sidx++)
{
char ch = str.charAt(sidx);
if (ch == '+')
res[didx++] = ' ';
else if (ch == '%')
{
try
{
res[didx++] = (char)
Integer.parseInt(str.substring(sidx+1,sidx+3), 16);
sidx += 2;
}
catch (NumberFormatException e)
{
throw new ParseException(str.substring(sidx,sidx+3) +
" is an invalid code");
}
}
else
res[didx++] = ch;
}
return String.valueOf(res, 0, didx);
}
/**
* This method decodes a multipart/form-data encoded string.
*
* @param data the form-data to decode.
* @param cont_type the content type header (must contain the
* boundary string).
* @param dir the directory to create the files in.
* @return an array of name/value pairs, one for each part;
* the name is the 'name' attribute given in the
* Content-Disposition header; the value is either
* the name of the file if a filename attribute was
* found, or the contents of the part.
* @exception IOException If any file operation fails.
* @exception ParseException If an error during parsing occurs.
* @see #mpFormDataDecode(byte[], java.lang.String, java.lang.String, HTTPClient.FilenameMangler)
*/
public final static NVPair[] mpFormDataDecode(byte[] data, String cont_type,
String dir)
throws IOException, ParseException
{
return mpFormDataDecode(data, cont_type, dir, null);
}
/**
* This method decodes a multipart/form-data encoded string. The boundary
* is parsed from the <var>cont_type</var> parameter, which must be of the
* form 'multipart/form-data; boundary=...'. Any encoded files are created
* in the directory specified by <var>dir</var> using the encoded filename.
*
* <P><em>Note:</em> Does not handle nested encodings (yet).
*
* <P>Examples: If you're receiving a multipart/form-data encoded response
* from a server you could use something like:
* <PRE>
* NVPair[] opts = Codecs.mpFormDataDecode(resp.getData(),
* resp.getHeader("Content-type"), ".");
* </PRE>
* If you're using this in a Servlet to decode the body of a request from
* a client you could use something like:
* <PRE>
* byte[] body = new byte[req.getContentLength()];
* new DataInputStream(req.getInputStream()).readFully(body);
* NVPair[] opts = Codecs.mpFormDataDecode(body, req.getContentType(),
* ".");
* </PRE>
* (where 'req' is the HttpServletRequest).
*
* <P>Assuming the data received looked something like:
* <PRE>
* -----------------------------114975832116442893661388290519
* Content-Disposition: form-data; name="option"
*
* doit
* -----------------------------114975832116442893661388290519
* Content-Disposition: form-data; name="comment"; filename="comment.txt"
*
* Gnus and Gnats are not Gnomes.
* -----------------------------114975832116442893661388290519--
* </PRE>
* you would get one file called <VAR>comment.txt</VAR> in the current
* directory, and opts would contain two elements: {"option", "doit"}
* and {"comment", "comment.txt"}
*
* @param data the form-data to decode.
* @param cont_type the content type header (must contain the
* boundary string).
* @param dir the directory to create the files in.
* @param mangler the filename mangler, or null if no mangling is
* to be done. This is invoked just before each
* file is created and written, thereby allowing
* you to control the names of the files.
* @return an array of name/value pairs, one for each part;
* the name is the 'name' attribute given in the
* Content-Disposition header; the value is either
* the name of the file if a filename attribute was
* found, or the contents of the part.
* @exception IOException If any file operation fails.
* @exception ParseException If an error during parsing occurs.
*/
public final static NVPair[] mpFormDataDecode(byte[] data, String cont_type,
String dir,
FilenameMangler mangler)
throws IOException, ParseException
{
// Find and extract boundary string
String bndstr = Util.getParameter("boundary", cont_type);
if (bndstr == null)
throw new ParseException("'boundary' parameter not found in Content-type: " + cont_type);
byte[] srtbndry = ( "--" + bndstr + "\r\n").getBytes("8859_1"),
boundary = ("\r\n--" + bndstr + "\r\n").getBytes("8859_1"),
endbndry = ("\r\n--" + bndstr + "--" ).getBytes("8859_1");
// setup search routines
int[] bs = Util.compile_search(srtbndry),
bc = Util.compile_search(boundary),
be = Util.compile_search(endbndry);
// let's start parsing the actual data
int start = Util.findStr(srtbndry, bs, data, 0, data.length);
if (start == -1) // didn't even find the start
throw new ParseException("Starting boundary not found: " +
new String(srtbndry, "8859_1"));
start += srtbndry.length;
NVPair[] res = new NVPair[10];
boolean done = false;
int idx;
for (idx=0; !done; idx++)
{
// find end of this part
int end = Util.findStr(boundary, bc, data, start, data.length);
if (end == -1) // must be the last part
{
end = Util.findStr(endbndry, be, data, start, data.length);
if (end == -1)
throw new ParseException("Ending boundary not found: " +
new String(endbndry, "8859_1"));
done = true;
}
// parse header(s)
String hdr, name=null, value, filename=null, cont_disp = null;
while (true)
{
int next = findEOL(data, start) + 2;
if (next-2 <= start) break; // empty line -> end of headers
hdr = new String(data, start, next-2-start, "8859_1");
start = next;
// handle line continuation
byte ch;
while (next < data.length-1 &&
((ch = data[next]) == ' ' || ch == '\t'))
{
next = findEOL(data, start) + 2;
hdr += new String(data, start, next-2-start, "8859_1");
start = next;
}
if (!hdr.regionMatches(true, 0, "Content-Disposition", 0, 19))
continue;
Vector<HttpHeaderElement> pcd =
Util.parseHeader(hdr.substring(hdr.indexOf(':')+1));
HttpHeaderElement elem = Util.getElement(pcd, "form-data");
if (elem == null)
throw new ParseException("Expected 'Content-Disposition: form-data' in line: "+hdr);
NVPair[] params = elem.getParams();
name = filename = null;
for (int pidx=0; pidx<params.length; pidx++)
{
if (params[pidx].getName().equalsIgnoreCase("name"))
name = params[pidx].getValue();
if (params[pidx].getName().equalsIgnoreCase("filename"))
filename = params[pidx].getValue();
}
if (name == null)
throw new ParseException("'name' parameter not found in header: "+hdr);
cont_disp = hdr;
}
start += 2;
if (start > end)
throw new ParseException("End of header not found at offset "+end);
if (cont_disp == null)
throw new ParseException("Missing 'Content-Disposition' header at offset "+start);
// handle data for this part
if (filename != null) // It's a file
{
if (mangler != null)
filename = mangler.mangleFilename(filename, name);
if (filename != null && filename.length() > 0)
{
File file = new File(dir, filename);
FileOutputStream out = new FileOutputStream(file);
out.write(data, start, end-start);
out.close();
}
value = filename;
}
else // It's simple data
{
value = new String(data, start, end-start, "8859_1");
}
if (idx >= res.length)
res = Util.resizeArray(res, idx+10);
res[idx] = new NVPair(name, value);
start = end + boundary.length;
}
return Util.resizeArray(res, idx);
}
/**
* Searches for the next CRLF in an array.
*
* @param arr the byte array to search.
* @param off the offset at which to start the search.
* @return the position of the CR or (arr.length-2) if not found
*/
private final static int findEOL(byte[] arr, int off)
{
while (off < arr.length-1 &&
!(arr[off++] == '\r' && arr[off] == '\n'));
return off-1;
}
/**
* This method encodes name/value pairs and files into a byte array
* using the multipart/form-data encoding.
*
* @param opts the simple form-data to encode (may be null);
* for each NVPair the name refers to the 'name'
* attribute to be used in the header of the part,
* and the value is contents of the part.
* @param files the files to encode (may be null); for each
* NVPair the name refers to the 'name' attribute
* to be used in the header of the part, and the
* value is the actual filename (the file will be
* read and it's contents put in the body of that
* part).
* @param ct_hdr this returns a new NVPair in the 0'th element
* which contains name = "Content-Type",
* value = "multipart/form-data; boundary=..."
* (the reason this parameter is an array is
* because a) that's the only way to simulate
* pass-by-reference and b) you need an array for
* the headers parameter to the Post() or Put()
* anyway).
* @return an encoded byte array containing all the opts
* and files.
* @exception IOException If any file operation fails.
* @see #mpFormDataEncode(HTTPClient.NVPair[], HTTPClient.NVPair[], HTTPClient.NVPair[], HTTPClient.FilenameMangler)
*/
public final static byte[] mpFormDataEncode(NVPair[] opts, NVPair[] files,
NVPair[] ct_hdr)
throws IOException
{
return mpFormDataEncode(opts, files, ct_hdr, null);
}
private static NVPair[] dummy = new NVPair[0];
/**
* This method encodes name/value pairs and files into a byte array
* using the multipart/form-data encoding. The boundary is returned
* as part of <var>ct_hdr</var>.
* <BR>Example:
* <PRE>
* NVPair[] opts = { new NVPair("option", "doit") };
* NVPair[] file = { new NVPair("comment", "comment.txt") };
* NVPair[] hdrs = new NVPair[1];
* byte[] data = Codecs.mpFormDataEncode(opts, file, hdrs);
* con.Post("/cgi-bin/handle-it", data, hdrs);
* </PRE>
* <VAR>data</VAR> will look something like the following:
* <PRE>
* -----------------------------114975832116442893661388290519
* Content-Disposition: form-data; name="option"
*
* doit
* -----------------------------114975832116442893661388290519
* Content-Disposition: form-data; name="comment"; filename="comment.txt"
* Content-Type: text/plain
*
* Gnus and Gnats are not Gnomes.
* -----------------------------114975832116442893661388290519--
* </PRE>
* where the "Gnus and Gnats ..." is the contents of the file
* <VAR>comment.txt</VAR> in the current directory.
*
* <P>If no elements are found in the parameters then a zero-length
* byte[] is returned and the content-type is set to
* <var>application/octet-string</var> (because a multipart must
* always have at least one part.
*
* <P>For files an attempt is made to discover the content-type, and if
* found a Content-Type header will be added to that part. The content type
* is retrieved using java.net.URLConnection.guessContentTypeFromName() -
* see java.net.URLConnection.setFileNameMap() for how to modify that map.
* Note that under JDK 1.1 by default the map seems to be empty. If you
* experience troubles getting the server to accept the data then make
* sure the fileNameMap is returning a content-type for each file (this
* may mean you'll have to set your own).
*
* @param opts the simple form-data to encode (may be null);
* for each NVPair the name refers to the 'name'
* attribute to be used in the header of the part,
* and the value is contents of the part.
* null elements in the array are ingored.
* @param files the files to encode (may be null); for each
* NVPair the name refers to the 'name' attribute
* to be used in the header of the part, and the
* value is the actual filename (the file will be
* read and it's contents put in the body of
* that part). null elements in the array
* are ingored.
* @param ct_hdr this returns a new NVPair in the 0'th element
* which contains name = "Content-Type",