[Android WebView] Convert some more callbacks into embedder to be async
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
blob0e603195f3e23bf32765614c3b3595ee30f486f4
1 // Copyright (c) 2012 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.
5 #include "ipc/ipc_channel_win.h"
7 #include <windows.h>
9 #include "base/auto_reset.h"
10 #include "base/bind.h"
11 #include "base/compiler_specific.h"
12 #include "base/logging.h"
13 #include "base/pickle.h"
14 #include "base/process/process_handle.h"
15 #include "base/rand_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/threading/thread_checker.h"
19 #include "base/win/scoped_handle.h"
20 #include "ipc/ipc_listener.h"
21 #include "ipc/ipc_logging.h"
22 #include "ipc/ipc_message_utils.h"
24 namespace IPC {
26 ChannelWin::State::State(ChannelWin* channel) : is_pending(false) {
27 memset(&context.overlapped, 0, sizeof(context.overlapped));
28 context.handler = channel;
31 ChannelWin::State::~State() {
32 static_assert(offsetof(ChannelWin::State, context) == 0,
33 "ChannelWin::State should have context as its first data"
34 "member.");
37 ChannelWin::ChannelWin(const IPC::ChannelHandle& channel_handle,
38 Mode mode,
39 Listener* listener,
40 AttachmentBroker* broker)
41 : ChannelReader(listener),
42 input_state_(this),
43 output_state_(this),
44 peer_pid_(base::kNullProcessId),
45 waiting_connect_(mode & MODE_SERVER_FLAG),
46 processing_incoming_(false),
47 validate_client_(false),
48 client_secret_(0),
49 broker_(broker),
50 weak_factory_(this) {
51 CreatePipe(channel_handle, mode);
54 ChannelWin::~ChannelWin() {
55 Close();
58 void ChannelWin::Close() {
59 if (thread_check_.get())
60 DCHECK(thread_check_->CalledOnValidThread());
62 if (input_state_.is_pending || output_state_.is_pending)
63 CancelIo(pipe_.Get());
65 // Closing the handle at this point prevents us from issuing more requests
66 // form OnIOCompleted().
67 if (pipe_.IsValid())
68 pipe_.Close();
70 // Make sure all IO has completed.
71 base::Time start = base::Time::Now();
72 while (input_state_.is_pending || output_state_.is_pending) {
73 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE, this);
76 while (!output_queue_.empty()) {
77 Message* m = output_queue_.front();
78 output_queue_.pop();
79 delete m;
83 bool ChannelWin::Send(Message* message) {
84 DCHECK(!message->HasAttachments());
85 DCHECK(thread_check_->CalledOnValidThread());
86 DVLOG(2) << "sending message @" << message << " on channel @" << this
87 << " with type " << message->type()
88 << " (" << output_queue_.size() << " in queue)";
90 #ifdef IPC_MESSAGE_LOG_ENABLED
91 Logging::GetInstance()->OnSendMessage(message, "");
92 #endif
94 message->TraceMessageBegin();
95 output_queue_.push(message);
96 // ensure waiting to write
97 if (!waiting_connect_) {
98 if (!output_state_.is_pending) {
99 if (!ProcessOutgoingMessages(NULL, 0))
100 return false;
104 return true;
107 AttachmentBroker* ChannelWin::GetAttachmentBroker() {
108 return broker_;
111 base::ProcessId ChannelWin::GetPeerPID() const {
112 return peer_pid_;
115 base::ProcessId ChannelWin::GetSelfPID() const {
116 return GetCurrentProcessId();
119 // static
120 bool ChannelWin::IsNamedServerInitialized(
121 const std::string& channel_id) {
122 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
123 return true;
124 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
125 // connection.
126 return GetLastError() == ERROR_SEM_TIMEOUT;
129 ChannelWin::ReadState ChannelWin::ReadData(
130 char* buffer,
131 int buffer_len,
132 int* /* bytes_read */) {
133 if (!pipe_.IsValid())
134 return READ_FAILED;
136 DWORD bytes_read = 0;
137 BOOL ok = ReadFile(pipe_.Get(), buffer, buffer_len,
138 &bytes_read, &input_state_.context.overlapped);
139 if (!ok) {
140 DWORD err = GetLastError();
141 if (err == ERROR_IO_PENDING) {
142 input_state_.is_pending = true;
143 return READ_PENDING;
145 LOG(ERROR) << "pipe error: " << err;
146 return READ_FAILED;
149 // We could return READ_SUCCEEDED here. But the way that this code is
150 // structured we instead go back to the message loop. Our completion port
151 // will be signalled even in the "synchronously completed" state.
153 // This allows us to potentially process some outgoing messages and
154 // interleave other work on this thread when we're getting hammered with
155 // input messages. Potentially, this could be tuned to be more efficient
156 // with some testing.
157 input_state_.is_pending = true;
158 return READ_PENDING;
161 bool ChannelWin::WillDispatchInputMessage(Message* msg) {
162 // Make sure we get a hello when client validation is required.
163 if (validate_client_)
164 return IsHelloMessage(*msg);
165 return true;
168 void ChannelWin::HandleInternalMessage(const Message& msg) {
169 DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
170 // The hello message contains one parameter containing the PID.
171 base::PickleIterator it(msg);
172 int32 claimed_pid;
173 bool failed = !it.ReadInt(&claimed_pid);
175 if (!failed && validate_client_) {
176 int32 secret;
177 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
180 if (failed) {
181 NOTREACHED();
182 Close();
183 listener()->OnChannelError();
184 return;
187 peer_pid_ = claimed_pid;
188 // Validation completed.
189 validate_client_ = false;
190 listener()->OnChannelConnected(claimed_pid);
193 bool ChannelWin::DidEmptyInputBuffers() {
194 // We don't need to do anything here.
195 return true;
198 // static
199 const base::string16 ChannelWin::PipeName(
200 const std::string& channel_id, int32* secret) {
201 std::string name("\\\\.\\pipe\\chrome.");
203 // Prevent the shared secret from ending up in the pipe name.
204 size_t index = channel_id.find_first_of('\\');
205 if (index != std::string::npos) {
206 if (secret) // Retrieve the secret if asked for.
207 base::StringToInt(channel_id.substr(index + 1), secret);
208 return base::ASCIIToUTF16(name.append(channel_id.substr(0, index - 1)));
211 // This case is here to support predictable named pipes in tests.
212 if (secret)
213 *secret = 0;
214 return base::ASCIIToUTF16(name.append(channel_id));
217 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
218 Mode mode) {
219 DCHECK(!pipe_.IsValid());
220 base::string16 pipe_name;
221 // If we already have a valid pipe for channel just copy it.
222 if (channel_handle.pipe.handle) {
223 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
224 // favor of two independent entities (name/file), or it should be a move-
225 // only type with a base::File member. In any case, this code should not
226 // call DuplicateHandle.
227 DCHECK(channel_handle.name.empty());
228 pipe_name = L"Not Available"; // Just used for LOG
229 // Check that the given pipe confirms to the specified mode. We can
230 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
231 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
232 DWORD flags = 0;
233 GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
234 DCHECK(!(flags & PIPE_TYPE_MESSAGE));
235 if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
236 ((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
237 LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
238 return false;
240 HANDLE local_handle;
241 if (!DuplicateHandle(GetCurrentProcess(),
242 channel_handle.pipe.handle,
243 GetCurrentProcess(),
244 &local_handle,
246 FALSE,
247 DUPLICATE_SAME_ACCESS)) {
248 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
249 return false;
251 pipe_.Set(local_handle);
252 } else if (mode & MODE_SERVER_FLAG) {
253 DCHECK(!channel_handle.pipe.handle);
254 const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
255 FILE_FLAG_FIRST_PIPE_INSTANCE;
256 pipe_name = PipeName(channel_handle.name, &client_secret_);
257 validate_client_ = !!client_secret_;
258 pipe_.Set(CreateNamedPipeW(pipe_name.c_str(),
259 open_mode,
260 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
262 Channel::kReadBufferSize,
263 Channel::kReadBufferSize,
264 5000,
265 NULL));
266 } else if (mode & MODE_CLIENT_FLAG) {
267 DCHECK(!channel_handle.pipe.handle);
268 pipe_name = PipeName(channel_handle.name, &client_secret_);
269 pipe_.Set(CreateFileW(pipe_name.c_str(),
270 GENERIC_READ | GENERIC_WRITE,
272 NULL,
273 OPEN_EXISTING,
274 SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
275 FILE_FLAG_OVERLAPPED,
276 NULL));
277 } else {
278 NOTREACHED();
281 if (!pipe_.IsValid()) {
282 // If this process is being closed, the pipe may be gone already.
283 PLOG(WARNING) << "Unable to create pipe \"" << pipe_name << "\" in "
284 << (mode & MODE_SERVER_FLAG ? "server" : "client") << " mode";
285 return false;
288 // Create the Hello message to be sent when Connect is called
289 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
290 HELLO_MESSAGE_TYPE,
291 IPC::Message::PRIORITY_NORMAL));
293 // Don't send the secret to the untrusted process, and don't send a secret
294 // if the value is zero (for IPC backwards compatability).
295 int32 secret = validate_client_ ? 0 : client_secret_;
296 if (!m->WriteInt(GetCurrentProcessId()) ||
297 (secret && !m->WriteUInt32(secret))) {
298 pipe_.Close();
299 return false;
302 output_queue_.push(m.release());
303 return true;
306 bool ChannelWin::Connect() {
307 DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
309 if (!thread_check_.get())
310 thread_check_.reset(new base::ThreadChecker());
312 if (!pipe_.IsValid())
313 return false;
315 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_.Get(), this);
317 // Check to see if there is a client connected to our pipe...
318 if (waiting_connect_)
319 ProcessConnection();
321 if (!input_state_.is_pending) {
322 // Complete setup asynchronously. By not setting input_state_.is_pending
323 // to true, we indicate to OnIOCompleted that this is the special
324 // initialization signal.
325 base::MessageLoopForIO::current()->PostTask(
326 FROM_HERE,
327 base::Bind(&ChannelWin::OnIOCompleted,
328 weak_factory_.GetWeakPtr(),
329 &input_state_.context,
331 0));
334 if (!waiting_connect_)
335 ProcessOutgoingMessages(NULL, 0);
336 return true;
339 bool ChannelWin::ProcessConnection() {
340 DCHECK(thread_check_->CalledOnValidThread());
341 if (input_state_.is_pending)
342 input_state_.is_pending = false;
344 // Do we have a client connected to our pipe?
345 if (!pipe_.IsValid())
346 return false;
348 BOOL ok = ConnectNamedPipe(pipe_.Get(), &input_state_.context.overlapped);
349 DWORD err = GetLastError();
350 if (ok) {
351 // Uhm, the API documentation says that this function should never
352 // return success when used in overlapped mode.
353 NOTREACHED();
354 return false;
357 switch (err) {
358 case ERROR_IO_PENDING:
359 input_state_.is_pending = true;
360 break;
361 case ERROR_PIPE_CONNECTED:
362 waiting_connect_ = false;
363 break;
364 case ERROR_NO_DATA:
365 // The pipe is being closed.
366 return false;
367 default:
368 NOTREACHED();
369 return false;
372 return true;
375 bool ChannelWin::ProcessOutgoingMessages(
376 base::MessageLoopForIO::IOContext* context,
377 DWORD bytes_written) {
378 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
379 // no connection?
380 DCHECK(thread_check_->CalledOnValidThread());
382 if (output_state_.is_pending) {
383 DCHECK(context);
384 output_state_.is_pending = false;
385 if (!context || bytes_written == 0) {
386 DWORD err = GetLastError();
387 LOG(ERROR) << "pipe error: " << err;
388 return false;
390 // Message was sent.
391 CHECK(!output_queue_.empty());
392 Message* m = output_queue_.front();
393 output_queue_.pop();
394 delete m;
397 if (output_queue_.empty())
398 return true;
400 if (!pipe_.IsValid())
401 return false;
403 // Write to pipe...
404 Message* m = output_queue_.front();
405 DCHECK(m->size() <= INT_MAX);
406 BOOL ok = WriteFile(pipe_.Get(),
407 m->data(),
408 static_cast<uint32>(m->size()),
409 NULL,
410 &output_state_.context.overlapped);
411 if (!ok) {
412 DWORD write_error = GetLastError();
413 if (write_error == ERROR_IO_PENDING) {
414 output_state_.is_pending = true;
416 DVLOG(2) << "sent pending message @" << m << " on channel @" << this
417 << " with type " << m->type();
419 return true;
421 LOG(ERROR) << "pipe error: " << write_error;
422 return false;
425 DVLOG(2) << "sent message @" << m << " on channel @" << this
426 << " with type " << m->type();
428 output_state_.is_pending = true;
429 return true;
432 void ChannelWin::OnIOCompleted(
433 base::MessageLoopForIO::IOContext* context,
434 DWORD bytes_transfered,
435 DWORD error) {
436 bool ok = true;
437 DCHECK(thread_check_->CalledOnValidThread());
438 if (context == &input_state_.context) {
439 if (waiting_connect_) {
440 if (!ProcessConnection())
441 return;
442 // We may have some messages queued up to send...
443 if (!output_queue_.empty() && !output_state_.is_pending)
444 ProcessOutgoingMessages(NULL, 0);
445 if (input_state_.is_pending)
446 return;
447 // else, fall-through and look for incoming messages...
450 // We don't support recursion through OnMessageReceived yet!
451 DCHECK(!processing_incoming_);
452 base::AutoReset<bool> auto_reset_processing_incoming(
453 &processing_incoming_, true);
455 // Process the new data.
456 if (input_state_.is_pending) {
457 // This is the normal case for everything except the initialization step.
458 input_state_.is_pending = false;
459 if (!bytes_transfered)
460 ok = false;
461 else if (pipe_.IsValid())
462 ok = AsyncReadComplete(bytes_transfered);
463 } else {
464 DCHECK(!bytes_transfered);
467 // Request more data.
468 if (ok)
469 ok = ProcessIncomingMessages();
470 } else {
471 DCHECK(context == &output_state_.context);
472 CHECK(output_state_.is_pending);
473 ok = ProcessOutgoingMessages(context, bytes_transfered);
475 if (!ok && pipe_.IsValid()) {
476 // We don't want to re-enter Close().
477 Close();
478 listener()->OnChannelError();
482 //------------------------------------------------------------------------------
483 // Channel's methods
485 // static
486 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
487 Mode mode,
488 Listener* listener,
489 AttachmentBroker* broker) {
490 return scoped_ptr<Channel>(
491 new ChannelWin(channel_handle, mode, listener, broker));
494 // static
495 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
496 return ChannelWin::IsNamedServerInitialized(channel_id);
499 // static
500 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
501 // Windows pipes can be enumerated by low-privileged processes. So, we
502 // append a strong random value after the \ character. This value is not
503 // included in the pipe name, but sent as part of the client hello, to
504 // hijacking the pipe name to spoof the client.
506 std::string id = prefix;
507 if (!id.empty())
508 id.append(".");
510 int secret;
511 do { // Guarantee we get a non-zero value.
512 secret = base::RandInt(0, std::numeric_limits<int>::max());
513 } while (secret == 0);
515 id.append(GenerateUniqueRandomChannelID());
516 return id.append(base::StringPrintf("\\%d", secret));
519 } // namespace IPC