Wed, 31 Dec 2014 06:09:35 +0100
Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.
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/. */
6 // data implementation
8 #include "nsDataChannel.h"
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"
18 using namespace mozilla;
20 nsresult
21 nsDataChannel::OpenContentStream(bool async, nsIInputStream **result,
22 nsIChannel** channel)
23 {
24 NS_ENSURE_TRUE(URI(), NS_ERROR_NOT_INITIALIZED);
26 nsresult rv;
28 nsAutoCString spec;
29 rv = URI()->GetAsciiSpec(spec);
30 if (NS_FAILED(rv)) return rv;
32 nsCString contentType, contentCharset, dataBuffer, hashRef;
33 bool lBase64;
34 rv = nsDataHandler::ParseURI(spec, contentType, contentCharset,
35 lBase64, dataBuffer, hashRef);
37 NS_UnescapeURL(dataBuffer);
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 }
46 nsCOMPtr<nsIInputStream> bufInStream;
47 nsCOMPtr<nsIOutputStream> bufOutStream;
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;
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);
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;
82 SetContentType(contentType);
83 SetContentCharset(contentCharset);
84 mContentLength = contentLen;
86 NS_ADDREF(*result = bufInStream);
88 return NS_OK;
89 }