| 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 "chromeos/dbus/pipe_string_writer.h" |
| 6 |
| 7 #include "base/bind.h" |
| 8 #include "base/posix/eintr_wrapper.h" |
| 9 #include "base/task_runner.h" |
| 10 #include "net/base/file_stream.h" |
| 11 #include "net/base/io_buffer.h" |
| 12 #include "net/base/net_errors.h" |
| 13 |
| 14 namespace chromeos { |
| 15 |
| 16 PipeStringWriter::PipeStringWriter( |
| 17 const std::string& data, |
| 18 const scoped_refptr<base::TaskRunner>& task_runner, |
| 19 const IOCompleteCallback& callback) |
| 20 : string_io_buffer_(new net::StringIOBuffer(data)), |
| 21 drainable_io_buffer_( |
| 22 new net::DrainableIOBuffer(string_io_buffer_.get(), |
| 23 string_io_buffer_->size())), |
| 24 task_runner_(task_runner), |
| 25 callback_(callback), |
| 26 weak_ptr_factory_(this) {} |
| 27 |
| 28 PipeStringWriter::~PipeStringWriter() {} |
| 29 |
| 30 base::ScopedFD PipeStringWriter::StartIO() { |
| 31 // Use a pipe to send data |
| 32 int pipe_fds[2]; |
| 33 const int status = HANDLE_EINTR(pipe(pipe_fds)); |
| 34 if (status < 0) { |
| 35 PLOG(ERROR) << "pipe"; |
| 36 return base::ScopedFD(); |
| 37 } |
| 38 base::ScopedFD pipe_read_end(pipe_fds[0]); |
| 39 // Pass ownership of pipe_fds[1] to data_stream_, which will close it. |
| 40 data_stream_.reset( |
| 41 new net::FileStream(base::File(pipe_fds[1]), task_runner_)); |
| 42 |
| 43 // Post an initial async write to setup data streaming |
| 44 int rv = data_stream_->Write(drainable_io_buffer_.get(), |
| 45 drainable_io_buffer_->BytesRemaining(), |
| 46 base::Bind(&PipeStringWriter::OnDataWritten, |
| 47 weak_ptr_factory_.GetWeakPtr())); |
| 48 if (rv != net::ERR_IO_PENDING) { |
| 49 LOG(ERROR) << "Unable to post initial write"; |
| 50 return base::ScopedFD(); |
| 51 } |
| 52 return pipe_read_end; |
| 53 } |
| 54 |
| 55 void PipeStringWriter::OnDataWritten(int byte_count) { |
| 56 DVLOG(1) << "OnDataWritten byte_count " << byte_count; |
| 57 if (byte_count < 0) { |
| 58 callback_.Run(byte_count); // signal creator of an error. |
| 59 return; |
| 60 } |
| 61 drainable_io_buffer_->DidConsume(byte_count); |
| 62 if (drainable_io_buffer_->BytesRemaining() > 0) { |
| 63 // Post another write |
| 64 int rv = data_stream_->Write(drainable_io_buffer_.get(), |
| 65 drainable_io_buffer_->BytesRemaining(), |
| 66 base::Bind(&PipeStringWriter::OnDataWritten, |
| 67 weak_ptr_factory_.GetWeakPtr())); |
| 68 if (rv != net::ERR_IO_PENDING) { |
| 69 LOG(ERROR) << "Unable to post another write"; |
| 70 } |
| 71 } else { |
| 72 callback_.Run(0); // success. |
| 73 } |
| 74 } |
| 75 |
| 76 } // namespace chromeos |
| OLD | NEW |