This source file includes following definitions.
- validate_client_
- Close
- Send
- IsNamedServerInitialized
- ReadData
- WillDispatchInputMessage
- HandleInternalMessage
- DidEmptyInputBuffers
- PipeName
- CreatePipe
- Connect
- ProcessConnection
- ProcessOutgoingMessages
- OnIOCompleted
- Connect
- Close
- peer_pid
- Send
- IsNamedServerInitialized
- GenerateVerifiedChannelID
#include "ipc/ipc_channel_win.h"
#include <windows.h>
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/pickle.h"
#include "base/process/process_handle.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_checker.h"
#include "base/win/scoped_handle.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_logging.h"
#include "ipc/ipc_message_utils.h"
namespace IPC {
Channel::ChannelImpl::State::State(ChannelImpl* channel) : is_pending(false) {
memset(&context.overlapped, 0, sizeof(context.overlapped));
context.handler = channel;
}
Channel::ChannelImpl::State::~State() {
COMPILE_ASSERT(!offsetof(Channel::ChannelImpl::State, context),
starts_with_io_context);
}
Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle &channel_handle,
Mode mode, Listener* listener)
: ChannelReader(listener),
input_state_(this),
output_state_(this),
pipe_(INVALID_HANDLE_VALUE),
peer_pid_(base::kNullProcessId),
waiting_connect_(mode & MODE_SERVER_FLAG),
processing_incoming_(false),
weak_factory_(this),
client_secret_(0),
validate_client_(false) {
CreatePipe(channel_handle, mode);
}
Channel::ChannelImpl::~ChannelImpl() {
Close();
}
void Channel::ChannelImpl::Close() {
if (thread_check_.get()) {
DCHECK(thread_check_->CalledOnValidThread());
}
if (input_state_.is_pending || output_state_.is_pending)
CancelIo(pipe_);
if (pipe_ != INVALID_HANDLE_VALUE) {
CloseHandle(pipe_);
pipe_ = INVALID_HANDLE_VALUE;
}
base::Time start = base::Time::Now();
while (input_state_.is_pending || output_state_.is_pending) {
base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE, this);
}
while (!output_queue_.empty()) {
Message* m = output_queue_.front();
output_queue_.pop();
delete m;
}
}
bool Channel::ChannelImpl::Send(Message* message) {
DCHECK(thread_check_->CalledOnValidThread());
DVLOG(2) << "sending message @" << message << " on channel @" << this
<< " with type " << message->type()
<< " (" << output_queue_.size() << " in queue)";
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging::GetInstance()->OnSendMessage(message, "");
#endif
message->TraceMessageBegin();
output_queue_.push(message);
if (!waiting_connect_) {
if (!output_state_.is_pending) {
if (!ProcessOutgoingMessages(NULL, 0))
return false;
}
}
return true;
}
bool Channel::ChannelImpl::IsNamedServerInitialized(
const std::string& channel_id) {
if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
return true;
return GetLastError() == ERROR_SEM_TIMEOUT;
}
Channel::ChannelImpl::ReadState Channel::ChannelImpl::ReadData(
char* buffer,
int buffer_len,
int* ) {
if (INVALID_HANDLE_VALUE == pipe_)
return READ_FAILED;
DWORD bytes_read = 0;
BOOL ok = ReadFile(pipe_, buffer, buffer_len,
&bytes_read, &input_state_.context.overlapped);
if (!ok) {
DWORD err = GetLastError();
if (err == ERROR_IO_PENDING) {
input_state_.is_pending = true;
return READ_PENDING;
}
LOG(ERROR) << "pipe error: " << err;
return READ_FAILED;
}
input_state_.is_pending = true;
return READ_PENDING;
}
bool Channel::ChannelImpl::WillDispatchInputMessage(Message* msg) {
if (validate_client_)
return IsHelloMessage(*msg);
return true;
}
void Channel::ChannelImpl::HandleInternalMessage(const Message& msg) {
DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
PickleIterator it(msg);
int32 claimed_pid;
bool failed = !it.ReadInt(&claimed_pid);
if (!failed && validate_client_) {
int32 secret;
failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
}
if (failed) {
NOTREACHED();
Close();
listener()->OnChannelError();
return;
}
peer_pid_ = claimed_pid;
validate_client_ = false;
listener()->OnChannelConnected(claimed_pid);
}
bool Channel::ChannelImpl::DidEmptyInputBuffers() {
return true;
}
const base::string16 Channel::ChannelImpl::PipeName(
const std::string& channel_id, int32* secret) {
std::string name("\\\\.\\pipe\\chrome.");
size_t index = channel_id.find_first_of('\\');
if (index != std::string::npos) {
if (secret)
base::StringToInt(channel_id.substr(index + 1), secret);
return base::ASCIIToWide(name.append(channel_id.substr(0, index - 1)));
}
if (secret)
*secret = 0;
return base::ASCIIToWide(name.append(channel_id));
}
bool Channel::ChannelImpl::CreatePipe(const IPC::ChannelHandle &channel_handle,
Mode mode) {
DCHECK_EQ(INVALID_HANDLE_VALUE, pipe_);
base::string16 pipe_name;
if (channel_handle.pipe.handle) {
DCHECK(channel_handle.name.empty());
pipe_name = L"Not Available";
DWORD flags = 0;
GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
DCHECK(!(flags & PIPE_TYPE_MESSAGE));
if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
return false;
}
if (!DuplicateHandle(GetCurrentProcess(),
channel_handle.pipe.handle,
GetCurrentProcess(),
&pipe_,
0,
FALSE,
DUPLICATE_SAME_ACCESS)) {
LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
return false;
}
} else if (mode & MODE_SERVER_FLAG) {
DCHECK(!channel_handle.pipe.handle);
const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
FILE_FLAG_FIRST_PIPE_INSTANCE;
pipe_name = PipeName(channel_handle.name, &client_secret_);
validate_client_ = !!client_secret_;
pipe_ = CreateNamedPipeW(pipe_name.c_str(),
open_mode,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
1,
Channel::kReadBufferSize,
Channel::kReadBufferSize,
5000,
NULL);
} else if (mode & MODE_CLIENT_FLAG) {
DCHECK(!channel_handle.pipe.handle);
pipe_name = PipeName(channel_handle.name, &client_secret_);
pipe_ = CreateFileW(pipe_name.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION |
FILE_FLAG_OVERLAPPED,
NULL);
} else {
NOTREACHED();
}
if (pipe_ == INVALID_HANDLE_VALUE) {
LOG(WARNING) << "Unable to create pipe \"" << pipe_name <<
"\" in " << (mode & MODE_SERVER_FLAG ? "server" : "client")
<< " mode. Error :" << GetLastError();
return false;
}
scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
HELLO_MESSAGE_TYPE,
IPC::Message::PRIORITY_NORMAL));
int32 secret = validate_client_ ? 0 : client_secret_;
if (!m->WriteInt(GetCurrentProcessId()) ||
(secret && !m->WriteUInt32(secret))) {
CloseHandle(pipe_);
pipe_ = INVALID_HANDLE_VALUE;
return false;
}
output_queue_.push(m.release());
return true;
}
bool Channel::ChannelImpl::Connect() {
DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
if (!thread_check_.get())
thread_check_.reset(new base::ThreadChecker());
if (pipe_ == INVALID_HANDLE_VALUE)
return false;
base::MessageLoopForIO::current()->RegisterIOHandler(pipe_, this);
if (waiting_connect_)
ProcessConnection();
if (!input_state_.is_pending) {
base::MessageLoopForIO::current()->PostTask(
FROM_HERE,
base::Bind(&Channel::ChannelImpl::OnIOCompleted,
weak_factory_.GetWeakPtr(),
&input_state_.context,
0,
0));
}
if (!waiting_connect_)
ProcessOutgoingMessages(NULL, 0);
return true;
}
bool Channel::ChannelImpl::ProcessConnection() {
DCHECK(thread_check_->CalledOnValidThread());
if (input_state_.is_pending)
input_state_.is_pending = false;
if (INVALID_HANDLE_VALUE == pipe_)
return false;
BOOL ok = ConnectNamedPipe(pipe_, &input_state_.context.overlapped);
DWORD err = GetLastError();
if (ok) {
NOTREACHED();
return false;
}
switch (err) {
case ERROR_IO_PENDING:
input_state_.is_pending = true;
break;
case ERROR_PIPE_CONNECTED:
waiting_connect_ = false;
break;
case ERROR_NO_DATA:
return false;
default:
NOTREACHED();
return false;
}
return true;
}
bool Channel::ChannelImpl::ProcessOutgoingMessages(
base::MessageLoopForIO::IOContext* context,
DWORD bytes_written) {
DCHECK(!waiting_connect_);
DCHECK(thread_check_->CalledOnValidThread());
if (output_state_.is_pending) {
DCHECK(context);
output_state_.is_pending = false;
if (!context || bytes_written == 0) {
DWORD err = GetLastError();
LOG(ERROR) << "pipe error: " << err;
return false;
}
CHECK(!output_queue_.empty());
Message* m = output_queue_.front();
output_queue_.pop();
delete m;
}
if (output_queue_.empty())
return true;
if (INVALID_HANDLE_VALUE == pipe_)
return false;
Message* m = output_queue_.front();
DCHECK(m->size() <= INT_MAX);
BOOL ok = WriteFile(pipe_,
m->data(),
static_cast<int>(m->size()),
&bytes_written,
&output_state_.context.overlapped);
if (!ok) {
DWORD err = GetLastError();
if (err == ERROR_IO_PENDING) {
output_state_.is_pending = true;
DVLOG(2) << "sent pending message @" << m << " on channel @" << this
<< " with type " << m->type();
return true;
}
LOG(ERROR) << "pipe error: " << err;
return false;
}
DVLOG(2) << "sent message @" << m << " on channel @" << this
<< " with type " << m->type();
output_state_.is_pending = true;
return true;
}
void Channel::ChannelImpl::OnIOCompleted(
base::MessageLoopForIO::IOContext* context,
DWORD bytes_transfered,
DWORD error) {
bool ok = true;
DCHECK(thread_check_->CalledOnValidThread());
if (context == &input_state_.context) {
if (waiting_connect_) {
if (!ProcessConnection())
return;
if (!output_queue_.empty() && !output_state_.is_pending)
ProcessOutgoingMessages(NULL, 0);
if (input_state_.is_pending)
return;
}
DCHECK(!processing_incoming_);
base::AutoReset<bool> auto_reset_processing_incoming(
&processing_incoming_, true);
if (input_state_.is_pending) {
input_state_.is_pending = false;
if (!bytes_transfered)
ok = false;
else if (pipe_ != INVALID_HANDLE_VALUE)
ok = AsyncReadComplete(bytes_transfered);
} else {
DCHECK(!bytes_transfered);
}
if (ok)
ok = ProcessIncomingMessages();
} else {
DCHECK(context == &output_state_.context);
ok = ProcessOutgoingMessages(context, bytes_transfered);
}
if (!ok && INVALID_HANDLE_VALUE != pipe_) {
Close();
listener()->OnChannelError();
}
}
Channel::Channel(const IPC::ChannelHandle &channel_handle, Mode mode,
Listener* listener)
: channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
}
Channel::~Channel() {
delete channel_impl_;
}
bool Channel::Connect() {
return channel_impl_->Connect();
}
void Channel::Close() {
if (channel_impl_)
channel_impl_->Close();
}
base::ProcessId Channel::peer_pid() const {
return channel_impl_->peer_pid();
}
bool Channel::Send(Message* message) {
return channel_impl_->Send(message);
}
bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
return ChannelImpl::IsNamedServerInitialized(channel_id);
}
std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
std::string id = prefix;
if (!id.empty())
id.append(".");
int secret;
do {
secret = base::RandInt(0, std::numeric_limits<int>::max());
} while (secret == 0);
id.append(GenerateUniqueRandomChannelID());
return id.append(base::StringPrintf("\\%d", secret));
}
}