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 : #include "nsBaseChannel.h"
7 : #include "nsIInputStream.h"
8 : #include "nsIRequest.h"
9 : #include "SimpleChannel.h"
10 :
11 : namespace mozilla {
12 : namespace net {
13 :
14 : // Like MOZ_TRY, but returns the unwrapped error value rather than a
15 : // GenericErrorResult on failure.
16 : #define TRY_VAR(target, expr) \
17 : do { \
18 : auto result = (expr); \
19 : if (result.isErr()) { \
20 : return result.unwrapErr(); \
21 : } \
22 : (target) = result.unwrap(); \
23 : } while (0)
24 :
25 : class SimpleChannel final : public nsBaseChannel
26 : {
27 : public:
28 : explicit SimpleChannel(UniquePtr<SimpleChannelCallbacks>&& aCallbacks);
29 :
30 : protected:
31 0 : virtual ~SimpleChannel() {}
32 :
33 : virtual nsresult OpenContentStream(bool async, nsIInputStream **streamOut,
34 : nsIChannel** channel) override;
35 :
36 : virtual nsresult BeginAsyncRead(nsIStreamListener* listener,
37 : nsIRequest** request) override;
38 :
39 : private:
40 : UniquePtr<SimpleChannelCallbacks> mCallbacks;
41 : };
42 :
43 0 : SimpleChannel::SimpleChannel(UniquePtr<SimpleChannelCallbacks>&& aCallbacks)
44 0 : : mCallbacks(Move(aCallbacks))
45 : {
46 0 : EnableSynthesizedProgressEvents(true);
47 0 : }
48 :
49 : nsresult
50 0 : SimpleChannel::OpenContentStream(bool async, nsIInputStream **streamOut, nsIChannel** channel)
51 : {
52 0 : NS_ENSURE_TRUE(mCallbacks, NS_ERROR_UNEXPECTED);
53 :
54 0 : nsCOMPtr<nsIInputStream> stream;
55 0 : TRY_VAR(stream, mCallbacks->OpenContentStream(async, this));
56 0 : MOZ_ASSERT(stream);
57 :
58 0 : mCallbacks = nullptr;
59 :
60 0 : *channel = nullptr;
61 0 : stream.forget(streamOut);
62 0 : return NS_OK;
63 : }
64 :
65 : nsresult
66 0 : SimpleChannel::BeginAsyncRead(nsIStreamListener* listener, nsIRequest** request)
67 : {
68 0 : NS_ENSURE_TRUE(mCallbacks, NS_ERROR_UNEXPECTED);
69 :
70 0 : nsCOMPtr<nsIRequest> req;
71 0 : TRY_VAR(req, mCallbacks->StartAsyncRead(listener, this));
72 :
73 0 : mCallbacks = nullptr;
74 :
75 0 : req.forget(request);
76 0 : return NS_OK;
77 : }
78 :
79 : #undef TRY_VAR
80 :
81 : already_AddRefed<nsIChannel>
82 0 : NS_NewSimpleChannelInternal(nsIURI* aURI, nsILoadInfo* aLoadInfo, UniquePtr<SimpleChannelCallbacks>&& aCallbacks)
83 : {
84 0 : RefPtr<SimpleChannel> chan = new SimpleChannel(Move(aCallbacks));
85 :
86 0 : chan->SetURI(aURI);
87 :
88 0 : MOZ_ALWAYS_SUCCEEDS(chan->SetLoadInfo(aLoadInfo));
89 :
90 0 : return chan.forget();
91 : }
92 :
93 : } // namespace net
94 : } // namespace mozilla
|