Line data Source code
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 6 : nsDataChannel::OpenContentStream(bool async, nsIInputStream **result,
22 : nsIChannel** channel)
23 : {
24 6 : NS_ENSURE_TRUE(URI(), NS_ERROR_NOT_INITIALIZED);
25 :
26 : nsresult rv;
27 :
28 12 : nsAutoCString spec;
29 6 : rv = URI()->GetAsciiSpec(spec);
30 6 : if (NS_FAILED(rv)) return rv;
31 :
32 12 : nsCString contentType, contentCharset, dataBuffer;
33 : bool lBase64;
34 : rv = nsDataHandler::ParseURI(spec, contentType, &contentCharset,
35 6 : lBase64, &dataBuffer);
36 6 : if (NS_FAILED(rv))
37 0 : return rv;
38 :
39 6 : NS_UnescapeURL(dataBuffer);
40 :
41 6 : if (lBase64) {
42 : // Don't allow spaces in base64-encoded content. This is only
43 : // relevant for escaped spaces; other spaces are stripped in
44 : // NewURI.
45 0 : dataBuffer.StripWhitespace();
46 : }
47 :
48 12 : nsCOMPtr<nsIInputStream> bufInStream;
49 12 : nsCOMPtr<nsIOutputStream> bufOutStream;
50 :
51 : // create an unbounded pipe.
52 18 : rv = NS_NewPipe(getter_AddRefs(bufInStream),
53 12 : getter_AddRefs(bufOutStream),
54 : nsIOService::gDefaultSegmentSize,
55 : UINT32_MAX,
56 6 : async, true);
57 6 : if (NS_FAILED(rv))
58 0 : return rv;
59 :
60 : uint32_t contentLen;
61 6 : if (lBase64) {
62 0 : const uint32_t dataLen = dataBuffer.Length();
63 0 : int32_t resultLen = 0;
64 0 : if (dataLen >= 1 && dataBuffer[dataLen-1] == '=') {
65 0 : if (dataLen >= 2 && dataBuffer[dataLen-2] == '=')
66 0 : resultLen = dataLen-2;
67 : else
68 0 : resultLen = dataLen-1;
69 : } else {
70 0 : resultLen = dataLen;
71 : }
72 0 : resultLen = ((resultLen * 3) / 4);
73 :
74 0 : nsAutoCString decodedData;
75 0 : rv = Base64Decode(dataBuffer, decodedData);
76 0 : NS_ENSURE_SUCCESS(rv, rv);
77 0 : rv = bufOutStream->Write(decodedData.get(), resultLen, &contentLen);
78 : } else {
79 6 : rv = bufOutStream->Write(dataBuffer.get(), dataBuffer.Length(), &contentLen);
80 : }
81 6 : if (NS_FAILED(rv))
82 0 : return rv;
83 :
84 6 : SetContentType(contentType);
85 6 : SetContentCharset(contentCharset);
86 6 : mContentLength = contentLen;
87 :
88 6 : bufInStream.forget(result);
89 :
90 6 : return NS_OK;
91 : }
|