forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDimeDelimitedInputStream.java
More file actions
565 lines (486 loc) · 19.2 KB
/
Copy pathDimeDelimitedInputStream.java
File metadata and controls
565 lines (486 loc) · 19.2 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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/* Took the basic code from Axis 1.2 and modified to fit into the cloud code base */
package com.cloud.bridge.io;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.log4j.Logger;
/**
* This class takes the input stream and turns it multiple streams.
DIME version 0 format
<pre>
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ---
| VERSION |B|E|C| TYPE_T| OPT_T | OPTIONS_LENGTH | A
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ID_LENGTH | TYPE_LENGTH | Always present 12 bytes
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ even on chunked data.
| DATA_LENGTH | V
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ---
| /
/ OPTIONS + PADDING /
/ (absent for version 0) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| /
/ ID + PADDING /
/ |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| /
/ TYPE + PADDING /
/ |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| /
/ DATA + PADDING /
/ |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
</pre>
* This implementation of input stream does not support marking operations.
*
* Incoming data is DIME encoded when its MIME type is "application/dime".
* Then use this class to pull out 2 streams:
* (1) The first stream is the SOAP request,
* (2) The second stream is a chunked attachment (e.g., a file to store)
*
* The DIME format is defined at this reference:
* http://msdn.microsoft.com/en-us/library/aa480488.aspx
*
* @author Rick Rineholt
*/
public class DimeDelimitedInputStream extends FilterInputStream {
protected final static Logger logger = Logger.getLogger(DimeDelimitedInputStream.class);
InputStream is = null; //The source input stream.
boolean closed = true; //The stream has been closed.
boolean theEnd = false; //There are no more streams left.
boolean moreChunks = false; //More chunks are a coming!
boolean MB = false; //Message begin flag
boolean ME = false; //Message end flag
String type = null; //
String id = null; //
String tnf = null; //DIME type format
long recordLength = 0L; //length of the current record.
long bytesRead = 0L; //How many bytes of the current record have been read.
int dataPadLength = 0; //How many pad bytes there are.
protected int streamNo = 0;
protected IOException streamInError = null;
private static byte[] trash = new byte[4];
protected static int streamCount = 0; //number of streams produced.
protected static synchronized int newStreamNo() {
logger.debug("streamNo " + (streamCount + 1));
return ++streamCount;
}
/**
* There can be multiple streams in a DIME encoding. For example, the first
* stream can be a SOAP message, and the second stream a binary attachment (e.g.,
* a file). During reading after an EOF is returned, this function should be
* called to see if there is another stream following the last.
*
* @return the dime delimited stream, null if there are no more streams
* @throws IOException if there was an error loading the data for the next stream
*/
public synchronized DimeDelimitedInputStream getNextStream() throws IOException {
if (null != streamInError)
throw streamInError;
if (theEnd)
return null;
//Each Stream must be read in succession
if (bytesRead < recordLength || moreChunks)
throw new RuntimeException("attach.dimeReadFullyError");
dataPadLength -= readPad(dataPadLength);
//Create an new dime stream that comes after this one.
return new DimeDelimitedInputStream(this.is);
}
/**
* Create a new dime stream.
*
* @param is the <code>InputStream</code> to wrap
* @throws IOException if anything goes wrong
*/
public DimeDelimitedInputStream(InputStream is) throws IOException {
super(null);
streamNo = newStreamNo();
closed = false;
this.is = is;
readHeader(false);
}
/**
* Make sure to skip the pad which appear in several parts of a DIME message.
* @param size
* @return
* @throws IOException
*/
private final int readPad(int size) throws IOException {
if (0 == size)
return 0;
int read = readFromStream(trash, 0, size);
if (size != read) {
streamInError = new IOException("attach.dimeNotPaddedCorrectly");
throw streamInError;
}
return read;
}
private final int readFromStream(byte[] b) throws IOException {
return readFromStream(b, 0, b.length);
}
private final int readFromStream(byte[] b, int start, int length) throws IOException {
int br = 0;
int brTotal = 0;
if (length == 0)
return 0;
do {
try {
br = is.read(b, brTotal + start, length - brTotal);
} catch (IOException e) {
streamInError = e;
throw e;
}
if (br > 0)
brTotal += br;
} while (br > -1 && brTotal < length);
return br > -1 ? brTotal : br;
}
/**
* Get the id for this stream part.
* @return the id;
*/
public String getContentId() {
return id;
}
public String getDimeTypeNameFormat() {
return tnf;
}
/**
* Get the type, as read from the header.
* @return the type of this dime
*/
public String getType() {
return type;
}
/**
* Read from the DIME stream.
*
* @param b is the array to read into.
* @param off is the offset
* @return the number of bytes read. -1 if endof stream
* @throws IOException if data could not be read from the stream
*/
public synchronized int read(byte[] b, int off, int len) throws IOException {
if (closed) {
dataPadLength -= readPad(dataPadLength);
throw new IOException("streamClosed");
}
return _read(b, off, len);
}
protected int _read(byte[] b, int off, int len) throws IOException {
int totalbytesread = 0;
int bytes2read = 0;
if (len < 0)
throw new IllegalArgumentException("attach.readLengthError" + len);
if (off < 0)
throw new IllegalArgumentException("attach.readOffsetError" + off);
if (b == null)
throw new IllegalArgumentException("attach.readArrayNullError");
if (b.length < off + len)
throw new IllegalArgumentException("attach.readArraySizeError " + b.length + " " + len + " " + off);
if (null != streamInError)
throw streamInError;
if (0 == len)
return 0; //quick.
// odd case no data to read -- give back 0 next time -1;
if (recordLength == 0 && bytesRead == 0 && !moreChunks) {
++bytesRead;
if (ME)
finalClose();
return 0;
}
if (bytesRead >= recordLength && !moreChunks) {
dataPadLength -= readPad(dataPadLength);
if (ME)
finalClose();
return -1;
}
do {
if (bytesRead >= recordLength && moreChunks)
readHeader(true);
bytes2read = (int)Math.min(recordLength - bytesRead, (long)len - totalbytesread);
try {
bytes2read = is.read(b, off + totalbytesread, bytes2read);
} catch (IOException e) {
streamInError = e;
throw e;
}
if (0 < bytes2read) {
totalbytesread += bytes2read;
bytesRead += bytes2read;
}
} while (bytes2read > -1 && totalbytesread < len && (bytesRead < recordLength || moreChunks));
if (0 > bytes2read) {
if (moreChunks) {
streamInError = new IOException("attach.DimeStreamError0");
throw streamInError;
}
if (bytesRead < recordLength) {
streamInError = new IOException("attach.DimeStreamError1 " + (recordLength - bytesRead));
throw streamInError;
}
if (!ME) {
streamInError = new IOException("attach.DimeStreamError0");
throw streamInError;
}
//in theory the last chunk of data should also have been padded, but lets be tolerant of that.
dataPadLength = 0;
} else if (bytesRead >= recordLength) {
//get rid of pading.
try {
dataPadLength -= readPad(dataPadLength);
} catch (IOException e) {
//in theory the last chunk of data should also have been padded, but lets be tolerant of that.
if (!ME)
throw e;
else {
dataPadLength = 0;
streamInError = null;
}
}
}
if (bytesRead >= recordLength && ME)
finalClose();
return totalbytesread >= 0 ? totalbytesread : -1;
}
/**
* The DIME header is read into local class data fields and are not
* passed as part of the stream data.
*
* @param isChunk
* @throws IOException
*/
protected void readHeader(boolean isChunk) throws IOException {
bytesRead = 0; //How many bytes of the record have been read.
if (isChunk) {
if (!moreChunks)
throw new RuntimeException("attach.DimeStreamError2");
dataPadLength -= readPad(dataPadLength); //Just in case it was left over.
}
byte[] header = new byte[12];
if (header.length != readFromStream(header)) {
streamInError = new IOException("attach.DimeStreamError3 " + header.length);
throw streamInError;
}
//VERSION
byte version = (byte)((header[0] >>> 3) & 0x1f);
if (version > 1) {
streamInError = new IOException("attach.DimeStreamError4 " + version);
throw streamInError;
}
//B, E, C
MB = 0 != (0x4 & header[0]);
ME = 0 != (0x2 & header[0]);
moreChunks = 0 != (0x1 & header[0]);
//TYPE_T
if (!isChunk) {
switch (((header[1] >>> 4) & (byte)0x0f)) {
case 0x00:
tnf = "UNCHANGED";
break;
case 0x01:
tnf = "MIME";
break;
case 0x02:
tnf = "URI";
break;
default:
tnf = "UNKNOWN";
break;
}
}
//OPTIONS_LENGTH
int oneButLastByte = (((int)header[2]) << 8) & 0xff00;
int lastByte = (int)header[3] & 0xff;
int optionsLength = oneButLastByte | lastByte;
//ID_LENGTH
oneButLastByte = ((((int)header[4]) << 8) & 0xff00);
lastByte = ((int)header[5]) & 0xff;
int idLength = oneButLastByte | lastByte;
//TYPE_LENGTH
oneButLastByte = ((((int)header[6]) << 8) & 0xff00);
lastByte = ((int)header[7]) & 0xff;
int typeLength = oneButLastByte | lastByte;
//DATA_LENGTH
recordLength =
((((long)header[8]) << 24) & 0xff000000L) | ((((long)header[9]) << 16) & 0xff0000L) | ((((long)header[10]) << 8) & 0xff00L) | ((long)header[11] & 0xffL);
//OPTIONS + PADDING
if (0 != optionsLength) {
byte[] optBytes = new byte[optionsLength];
if (optionsLength != readFromStream(optBytes)) {
streamInError = new IOException("attach.DimeStreamError5 " + optionsLength);
throw streamInError;
}
optBytes = null; // throw it away, don't know anything about options.
int pad = (int)((4L - (optionsLength & 0x3L)) & 0x03L);
if (pad != readFromStream(header, 0, pad)) {
streamInError = new IOException("attach.DimeStreamError7");
throw streamInError;
}
}
// ID + PADDING
if (0 < idLength) {
byte[] idBytes = new byte[idLength];
if (idLength != readFromStream(idBytes)) {
streamInError = new IOException("attach.DimeStreamError8");
throw streamInError;
}
if (idLength != 0 && !isChunk)
id = new String(idBytes);
int pad = (int)((4L - (idLength & 0x3L)) & 0x03L);
if (pad != readFromStream(header, 0, pad)) {
streamInError = new IOException("attach.DimeStreamError9");
throw streamInError;
}
}
//TYPE + PADDING
if (0 < typeLength) {
byte[] typeBytes = new byte[typeLength];
if (typeLength != readFromStream(typeBytes)) {
streamInError = new IOException("attach.DimeStreamError10");
throw streamInError;
}
if (typeLength != 0 && !isChunk)
type = new String(typeBytes);
int pad = (int)((4L - (typeLength & 0x3L)) & 0x03L);
if (pad != readFromStream(header, 0, pad)) {
streamInError = new IOException("attach.DimeStreamError11");
throw streamInError;
}
}
logger.debug("MB:" + MB + ", ME:" + ME + ", CF:" + moreChunks + "Option length:" + optionsLength + ", ID length:" + idLength + ", typeLength:" + typeLength +
", TYPE_T:" + tnf);
logger.debug("id:\"" + id + "\"");
logger.debug("type:\"" + type + "\"");
logger.debug("recordlength:\"" + recordLength + "\"");
dataPadLength = (int)((4L - (recordLength & 0x3L)) & 0x03L);
}
/**
* Read from the delimited stream.
*
* @param b is the array to read into. Read as much as possible
* into the size of this array.
* @return the number of bytes read. -1 if endof stream
* @throws IOException if data could not be read from the stream
*/
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
// fixme: this seems a bit inefficient
/**
* Read from the boundary delimited stream.
*
* @return the byte read, or -1 if endof stream
* @throws IOException if there was an error reading the data
*/
public int read() throws IOException {
byte[] b = new byte[1];
int read = read(b, 0, 1);
if (read < 0)
return -1; // fixme: should we also check for read != 1?
return (b[0] & 0xff); // convert byte value to a positive int
}
/**
* Closes the stream.
* This will take care of flushing any remaining data to the stream.
* Multiple calls to this method will result in the stream being closed once
* and then all subsequent calls being ignored.
*
* @throws IOException if the stream could not be closed
*/
public void close() throws IOException {
synchronized (this) {
if (closed)
return;
closed = true; //mark it closed.
}
logger.debug("bStreamClosed " + streamNo);
if (bytesRead < recordLength || moreChunks) {
//We need get this off the stream. Easy way to flush through the stream;
byte[] readrest = new byte[1024 * 16];
int bread = 0;
do {
bread = _read(readrest, 0, readrest.length); //should also close the original stream.
} while (bread > -1);
}
dataPadLength -= readPad(dataPadLength);
}
/**
* Skip n bytes of data in the DIME stream, while reading and processing
* any headers in the current stream.
*
* @param n - number of data bytes to skip
* @return number of bytes actually skipped
* @throws IOException
*/
public long skip(long n) throws IOException {
long bytesSkipped = 0;
long bytes2Read = 0;
byte[] dumpbytes = new byte[1024];
while (n > 0) {
bytes2Read = (n > 1024 ? 1024 : n);
bytes2Read = _read(dumpbytes, 0, (int)bytes2Read);
n -= bytes2Read;
bytesSkipped += bytes2Read;
}
return bytesSkipped;
}
/**
* Mark the stream. This is not supported.
*/
public void mark(int readlimit) { //do nothing
}
public void reset() throws IOException {
streamInError = new IOException("attach.bounday.mns");
throw streamInError;
}
public boolean markSupported() {
return false;
}
public synchronized int available() throws IOException {
if (null != streamInError)
throw streamInError;
int chunkAvail = (int)Math.min((long)Integer.MAX_VALUE, recordLength - bytesRead);
int streamAvail = 0;
try {
streamAvail = is.available();
} catch (IOException e) {
streamInError = e;
throw e;
}
if (chunkAvail == 0 && moreChunks && (12 + dataPadLength) <= streamAvail) {
dataPadLength -= readPad(dataPadLength);
readHeader(true);
return available();
}
return Math.min(streamAvail, chunkAvail);
}
protected void finalClose() throws IOException {
try {
theEnd = true;
if (null != is)
is.close();
} finally {
is = null;
}
}
}