|
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ |
|
2 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 // data implementation |
|
7 |
|
8 #include "nsDataChannel.h" |
|
9 |
|
10 #include "mozilla/Base64.h" |
|
11 #include "nsIOService.h" |
|
12 #include "nsDataHandler.h" |
|
13 #include "nsIPipe.h" |
|
14 #include "nsIInputStream.h" |
|
15 #include "nsIOutputStream.h" |
|
16 #include "nsEscape.h" |
|
17 |
|
18 using namespace mozilla; |
|
19 |
|
20 nsresult |
|
21 nsDataChannel::OpenContentStream(bool async, nsIInputStream **result, |
|
22 nsIChannel** channel) |
|
23 { |
|
24 NS_ENSURE_TRUE(URI(), NS_ERROR_NOT_INITIALIZED); |
|
25 |
|
26 nsresult rv; |
|
27 |
|
28 nsAutoCString spec; |
|
29 rv = URI()->GetAsciiSpec(spec); |
|
30 if (NS_FAILED(rv)) return rv; |
|
31 |
|
32 nsCString contentType, contentCharset, dataBuffer, hashRef; |
|
33 bool lBase64; |
|
34 rv = nsDataHandler::ParseURI(spec, contentType, contentCharset, |
|
35 lBase64, dataBuffer, hashRef); |
|
36 |
|
37 NS_UnescapeURL(dataBuffer); |
|
38 |
|
39 if (lBase64) { |
|
40 // Don't allow spaces in base64-encoded content. This is only |
|
41 // relevant for escaped spaces; other spaces are stripped in |
|
42 // NewURI. |
|
43 dataBuffer.StripWhitespace(); |
|
44 } |
|
45 |
|
46 nsCOMPtr<nsIInputStream> bufInStream; |
|
47 nsCOMPtr<nsIOutputStream> bufOutStream; |
|
48 |
|
49 // create an unbounded pipe. |
|
50 rv = NS_NewPipe(getter_AddRefs(bufInStream), |
|
51 getter_AddRefs(bufOutStream), |
|
52 nsIOService::gDefaultSegmentSize, |
|
53 UINT32_MAX, |
|
54 async, true); |
|
55 if (NS_FAILED(rv)) |
|
56 return rv; |
|
57 |
|
58 uint32_t contentLen; |
|
59 if (lBase64) { |
|
60 const uint32_t dataLen = dataBuffer.Length(); |
|
61 int32_t resultLen = 0; |
|
62 if (dataLen >= 1 && dataBuffer[dataLen-1] == '=') { |
|
63 if (dataLen >= 2 && dataBuffer[dataLen-2] == '=') |
|
64 resultLen = dataLen-2; |
|
65 else |
|
66 resultLen = dataLen-1; |
|
67 } else { |
|
68 resultLen = dataLen; |
|
69 } |
|
70 resultLen = ((resultLen * 3) / 4); |
|
71 |
|
72 nsAutoCString decodedData; |
|
73 rv = Base64Decode(dataBuffer, decodedData); |
|
74 NS_ENSURE_SUCCESS(rv, rv); |
|
75 rv = bufOutStream->Write(decodedData.get(), resultLen, &contentLen); |
|
76 } else { |
|
77 rv = bufOutStream->Write(dataBuffer.get(), dataBuffer.Length(), &contentLen); |
|
78 } |
|
79 if (NS_FAILED(rv)) |
|
80 return rv; |
|
81 |
|
82 SetContentType(contentType); |
|
83 SetContentCharset(contentCharset); |
|
84 mContentLength = contentLen; |
|
85 |
|
86 NS_ADDREF(*result = bufInStream); |
|
87 |
|
88 return NS_OK; |
|
89 } |