| OLD | NEW |
| (Empty) | |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "net/filter/fuzzed_source_stream.h" |
| 6 |
| 7 #include <algorithm> |
| 8 |
| 9 #include "base/test/fuzzed_data_provider.h" |
| 10 #include "base/threading/thread_task_runner_handle.h" |
| 11 #include "net/base/io_buffer.h" |
| 12 #include "net/base/net_errors.h" |
| 13 |
| 14 namespace net { |
| 15 |
| 16 namespace { |
| 17 |
| 18 // Common net error codes that can be returned by a SourceStream. |
| 19 const Error kReadErrors[] = {OK, ERR_FAILED, ERR_CONTENT_DECODING_FAILED}; |
| 20 |
| 21 } // namespace |
| 22 |
| 23 FuzzedSourceStream::FuzzedSourceStream(base::FuzzedDataProvider* data_provider) |
| 24 : SourceStream(SourceStream::TYPE_NONE), |
| 25 data_provider_(data_provider), |
| 26 read_pending_(false), |
| 27 end_returned_(false) {} |
| 28 |
| 29 FuzzedSourceStream::~FuzzedSourceStream() { |
| 30 DCHECK(!read_pending_); |
| 31 } |
| 32 |
| 33 int FuzzedSourceStream::Read(IOBuffer* buf, |
| 34 int buf_len, |
| 35 const CompletionCallback& callback) { |
| 36 DCHECK(!read_pending_); |
| 37 DCHECK(!end_returned_); |
| 38 DCHECK_LE(0, buf_len); |
| 39 |
| 40 bool sync = data_provider_->ConsumeBool(); |
| 41 int result = data_provider_->ConsumeUint32InRange(0, buf_len); |
| 42 std::string data = data_provider_->ConsumeBytes(result); |
| 43 result = data.size(); |
| 44 |
| 45 if (result <= 0) |
| 46 result = data_provider_->PickValueInArray(kReadErrors); |
| 47 |
| 48 if (sync) { |
| 49 if (result > 0) { |
| 50 std::copy(data.data(), data.data() + result, buf->data()); |
| 51 } else { |
| 52 end_returned_ = true; |
| 53 } |
| 54 return result; |
| 55 } |
| 56 |
| 57 scoped_refptr<IOBuffer> pending_read_buf = buf; |
| 58 |
| 59 read_pending_ = true; |
| 60 // |this| is owned by the caller so use base::Unretained is safe. |
| 61 base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 62 FROM_HERE, |
| 63 base::Bind(&FuzzedSourceStream::OnReadComplete, base::Unretained(this), |
| 64 callback, data, pending_read_buf, result)); |
| 65 return ERR_IO_PENDING; |
| 66 } |
| 67 |
| 68 std::string FuzzedSourceStream::Description() const { |
| 69 return ""; |
| 70 } |
| 71 |
| 72 void FuzzedSourceStream::OnReadComplete(const CompletionCallback& callback, |
| 73 const std::string& fuzzed_data, |
| 74 scoped_refptr<IOBuffer> read_buf, |
| 75 int result) { |
| 76 DCHECK(read_pending_); |
| 77 |
| 78 if (result > 0) { |
| 79 std::copy(fuzzed_data.data(), fuzzed_data.data() + result, |
| 80 read_buf->data()); |
| 81 } else { |
| 82 end_returned_ = true; |
| 83 } |
| 84 read_pending_ = false; |
| 85 callback.Run(result); |
| 86 } |
| 87 |
| 88 } // namespace net |
| OLD | NEW |