summaryrefslogtreecommitdiff
path: root/netwerk/base/nsAsyncStreamCopier.cpp
blob: 6eec29d61445a52d31dd0aa6990603fa072ec596 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsAsyncStreamCopier.h"
#include "nsIOService.h"
#include "nsIEventTarget.h"
#include "nsStreamUtils.h"
#include "nsThreadUtils.h"
#include "nsNetUtil.h"
#include "nsNetCID.h"
#include "nsIBufferedStreams.h"
#include "nsIRequestObserver.h"
#include "mozilla/Logging.h"

using namespace mozilla;

#undef LOG
//
// MOZ_LOG=nsStreamCopier:5
//
static LazyLogModule gStreamCopierLog("nsStreamCopier");
#define LOG(args) MOZ_LOG(gStreamCopierLog, mozilla::LogLevel::Debug, args)

/**
 * An event used to perform initialization off the main thread.
 */
class AsyncApplyBufferingPolicyEvent final: public Runnable
{
public:
    /**
     * @param aCopier
     *        The nsAsyncStreamCopier requesting the information.
     */
    explicit AsyncApplyBufferingPolicyEvent(nsAsyncStreamCopier* aCopier)
        : mCopier(aCopier)
      , mTarget(NS_GetCurrentThread())
      { }
    NS_IMETHOD Run() override
    {
      nsresult rv = mCopier->ApplyBufferingPolicy();
      if (NS_FAILED(rv)) {
          mCopier->Cancel(rv);
          return NS_OK;
      }

      rv = mTarget->Dispatch(NewRunnableMethod(mCopier,
					       &nsAsyncStreamCopier::AsyncCopyInternal),
			     NS_DISPATCH_NORMAL);
      MOZ_ASSERT(NS_SUCCEEDED(rv));

      if (NS_FAILED(rv)) {
          mCopier->Cancel(rv);
      }
      return NS_OK;
    }
private:
      RefPtr<nsAsyncStreamCopier> mCopier;
      nsCOMPtr<nsIEventTarget> mTarget;
};



//-----------------------------------------------------------------------------

nsAsyncStreamCopier::nsAsyncStreamCopier()
    : mLock("nsAsyncStreamCopier.mLock")
    , mMode(NS_ASYNCCOPY_VIA_READSEGMENTS)
    , mChunkSize(nsIOService::gDefaultSegmentSize)
    , mStatus(NS_OK)
    , mIsPending(false)
    , mShouldSniffBuffering(false)
{
    LOG(("Creating nsAsyncStreamCopier @%x\n", this));
}

nsAsyncStreamCopier::~nsAsyncStreamCopier()
{
    LOG(("Destroying nsAsyncStreamCopier @%x\n", this));
}

bool
nsAsyncStreamCopier::IsComplete(nsresult *status)
{
    MutexAutoLock lock(mLock);
    if (status)
        *status = mStatus;
    return !mIsPending;
}

nsIRequest*
nsAsyncStreamCopier::AsRequest()
{
    return static_cast<nsIRequest*>(static_cast<nsIAsyncStreamCopier*>(this));
}

void
nsAsyncStreamCopier::Complete(nsresult status)
{
    LOG(("nsAsyncStreamCopier::Complete [this=%p status=%x]\n", this, status));

    nsCOMPtr<nsIRequestObserver> observer;
    nsCOMPtr<nsISupports> ctx;
    {
        MutexAutoLock lock(mLock);
        mCopierCtx = nullptr;

        if (mIsPending) {
            mIsPending = false;
            mStatus = status;

            // setup OnStopRequest callback and release references...
            observer = mObserver;
            mObserver = nullptr;
        }
    }

    if (observer) {
        LOG(("  calling OnStopRequest [status=%x]\n", status));
        observer->OnStopRequest(AsRequest(), ctx, status);
    }
}

void
nsAsyncStreamCopier::OnAsyncCopyComplete(void *closure, nsresult status)
{
    nsAsyncStreamCopier *self = (nsAsyncStreamCopier *) closure;
    self->Complete(status);
    NS_RELEASE(self); // addref'd in AsyncCopy
}

//-----------------------------------------------------------------------------
// nsISupports

// We cannot use simply NS_IMPL_ISUPPORTSx as both
// nsIAsyncStreamCopier and nsIAsyncStreamCopier2 implement nsIRequest

NS_IMPL_ADDREF(nsAsyncStreamCopier)
NS_IMPL_RELEASE(nsAsyncStreamCopier)
NS_INTERFACE_TABLE_HEAD(nsAsyncStreamCopier)
NS_INTERFACE_TABLE_BEGIN
NS_INTERFACE_TABLE_ENTRY(nsAsyncStreamCopier, nsIAsyncStreamCopier)
NS_INTERFACE_TABLE_ENTRY(nsAsyncStreamCopier, nsIAsyncStreamCopier2)
NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(nsAsyncStreamCopier, nsIRequest, nsIAsyncStreamCopier)
NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(nsAsyncStreamCopier, nsISupports, nsIAsyncStreamCopier)
NS_INTERFACE_TABLE_END
NS_INTERFACE_TABLE_TAIL

//-----------------------------------------------------------------------------
// nsIRequest

NS_IMETHODIMP
nsAsyncStreamCopier::GetName(nsACString &name)
{
    name.Truncate();
    return NS_OK;
}

NS_IMETHODIMP
nsAsyncStreamCopier::IsPending(bool *result)
{
    *result = !IsComplete();
    return NS_OK;
}

NS_IMETHODIMP
nsAsyncStreamCopier::GetStatus(nsresult *status)
{
    IsComplete(status);
    return NS_OK;
}

NS_IMETHODIMP
nsAsyncStreamCopier::Cancel(nsresult status)
{
    nsCOMPtr<nsISupports> copierCtx;
    {
        MutexAutoLock lock(mLock);
        if (!mIsPending)
            return NS_OK;
        copierCtx.swap(mCopierCtx);
    }

    if (NS_SUCCEEDED(status)) {
        NS_WARNING("cancel with non-failure status code");
        status = NS_BASE_STREAM_CLOSED;
    }

    if (copierCtx)
        NS_CancelAsyncCopy(copierCtx, status);

    return NS_OK;
}

NS_IMETHODIMP
nsAsyncStreamCopier::Suspend()
{
    NS_NOTREACHED("nsAsyncStreamCopier::Suspend");
    return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
nsAsyncStreamCopier::Resume()
{
    NS_NOTREACHED("nsAsyncStreamCopier::Resume");
    return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
nsAsyncStreamCopier::GetLoadFlags(nsLoadFlags *aLoadFlags)
{
    *aLoadFlags = LOAD_NORMAL;
    return NS_OK;
}

NS_IMETHODIMP
nsAsyncStreamCopier::SetLoadFlags(nsLoadFlags aLoadFlags)
{
    return NS_OK;
}

NS_IMETHODIMP
nsAsyncStreamCopier::GetLoadGroup(nsILoadGroup **aLoadGroup)
{
    *aLoadGroup = nullptr;
    return NS_OK;
}

NS_IMETHODIMP
nsAsyncStreamCopier::SetLoadGroup(nsILoadGroup *aLoadGroup)
{
    return NS_OK;
}

nsresult
nsAsyncStreamCopier::InitInternal(nsIInputStream *source,
                                  nsIOutputStream *sink,
                                  nsIEventTarget *target,
                                  uint32_t chunkSize,
                                  bool closeSource,
                                  bool closeSink)
{
    NS_ASSERTION(!mSource && !mSink, "Init() called more than once");
    if (chunkSize == 0) {
        chunkSize = nsIOService::gDefaultSegmentSize;
    }
    mChunkSize = chunkSize;

    mSource = source;
    mSink = sink;
    mCloseSource = closeSource;
    mCloseSink = closeSink;

    if (target) {
        mTarget = target;
    } else {
        nsresult rv;
        mTarget = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID, &rv);
        if (NS_FAILED(rv)) {
            return rv;
        }
    }

    return NS_OK;
}

//-----------------------------------------------------------------------------
// nsIAsyncStreamCopier

NS_IMETHODIMP
nsAsyncStreamCopier::Init(nsIInputStream *source,
                          nsIOutputStream *sink,
                          nsIEventTarget *target,
                          bool sourceBuffered,
                          bool sinkBuffered,
                          uint32_t chunkSize,
                          bool closeSource,
                          bool closeSink)
{
    NS_ASSERTION(sourceBuffered || sinkBuffered, "at least one stream must be buffered");
    mMode = sourceBuffered ? NS_ASYNCCOPY_VIA_READSEGMENTS
                           : NS_ASYNCCOPY_VIA_WRITESEGMENTS;

    return InitInternal(source, sink, target, chunkSize, closeSource, closeSink);
}

//-----------------------------------------------------------------------------
// nsIAsyncStreamCopier2

NS_IMETHODIMP
nsAsyncStreamCopier::Init(nsIInputStream *source,
                          nsIOutputStream *sink,
                          nsIEventTarget *target,
                          uint32_t chunkSize,
                          bool closeSource,
                          bool closeSink)
{
    mShouldSniffBuffering = true;

    return InitInternal(source, sink, target, chunkSize, closeSource, closeSink);
}

/**
 * Detect whether the input or the output stream is buffered,
 * bufferize one of them if neither is buffered.
 */
nsresult
nsAsyncStreamCopier::ApplyBufferingPolicy()
{
    // This function causes I/O, it must not be executed on the main
    // thread.
    MOZ_ASSERT(!NS_IsMainThread());

    if (NS_OutputStreamIsBuffered(mSink)) {
      // Sink is buffered, no need to perform additional buffering
      mMode = NS_ASYNCCOPY_VIA_WRITESEGMENTS;
      return NS_OK;
    }
    if (NS_InputStreamIsBuffered(mSource)) {
      // Source is buffered, no need to perform additional buffering
      mMode = NS_ASYNCCOPY_VIA_READSEGMENTS;
      return NS_OK;
    }

    // No buffering, let's buffer the sink
    nsresult rv;
    nsCOMPtr<nsIBufferedOutputStream> sink =
      do_CreateInstance(NS_BUFFEREDOUTPUTSTREAM_CONTRACTID, &rv);
    if (NS_FAILED(rv)) {
      return rv;
    }

    rv = sink->Init(mSink, mChunkSize);
    if (NS_FAILED(rv)) {
      return rv;
    }

    mMode = NS_ASYNCCOPY_VIA_WRITESEGMENTS;
    mSink = sink;
    return NS_OK;
}

//-----------------------------------------------------------------------------
// Both nsIAsyncStreamCopier and nsIAsyncStreamCopier2

NS_IMETHODIMP
nsAsyncStreamCopier::AsyncCopy(nsIRequestObserver *observer, nsISupports *ctx)
{
    LOG(("nsAsyncStreamCopier::AsyncCopy [this=%p observer=%x]\n", this, observer));

    NS_ASSERTION(mSource && mSink, "not initialized");
    nsresult rv;

    if (observer) {
        // build proxy for observer events
        rv = NS_NewRequestObserverProxy(getter_AddRefs(mObserver), observer, ctx);
        if (NS_FAILED(rv)) return rv;
    }

    // from this point forward, AsyncCopy is going to return NS_OK.  any errors
    // will be reported via OnStopRequest.
    mIsPending = true;

    if (mObserver) {
        rv = mObserver->OnStartRequest(AsRequest(), nullptr);
        if (NS_FAILED(rv))
            Cancel(rv);
    }

    if (!mShouldSniffBuffering) {
        // No buffer sniffing required, let's proceed
        AsyncCopyInternal();
        return NS_OK;
    }

    if (NS_IsMainThread()) {
        // Don't perform buffer sniffing on the main thread
        nsCOMPtr<nsIRunnable> event = new AsyncApplyBufferingPolicyEvent(this);
        rv = mTarget->Dispatch(event, NS_DISPATCH_NORMAL);
        if (NS_FAILED(rv)) {
          Cancel(rv);
        }
        return NS_OK;
    }

    // We're not going to block the main thread, so let's sniff here
    rv = ApplyBufferingPolicy();
    if (NS_FAILED(rv)) {
        Cancel(rv);
    }
    AsyncCopyInternal();
    return NS_OK;
}

// Launch async copy.
// All errors are reported through the observer.
void
nsAsyncStreamCopier::AsyncCopyInternal()
{
  MOZ_ASSERT(mMode ==  NS_ASYNCCOPY_VIA_READSEGMENTS
             || mMode == NS_ASYNCCOPY_VIA_WRITESEGMENTS);

    nsresult rv;
    // we want to receive progress notifications; release happens in
    // OnAsyncCopyComplete.
    NS_ADDREF_THIS();
    {
      MutexAutoLock lock(mLock);
      rv = NS_AsyncCopy(mSource, mSink, mTarget, mMode, mChunkSize,
                        OnAsyncCopyComplete, this, mCloseSource, mCloseSink,
                        getter_AddRefs(mCopierCtx));
    }
    if (NS_FAILED(rv)) {
        NS_RELEASE_THIS();
        Cancel(rv);
    }
}