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