cros: Update enable-dev UI.
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
blob2ad638b2f67ee4b2f76e03ca7ba7d50117ef8e9b
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 COMPILE_ASSERT(!offsetof(ChannelWin::State, context),
33 starts_with_io_context);
36 ChannelWin::ChannelWin(const IPC::ChannelHandle &channel_handle,
37 Mode mode, Listener* listener)
38 : ChannelReader(listener),
39 input_state_(this),
40 output_state_(this),
41 peer_pid_(base::kNullProcessId),
42 waiting_connect_(mode & MODE_SERVER_FLAG),
43 processing_incoming_(false),
44 validate_client_(false),
45 client_secret_(0),
46 weak_factory_(this) {
47 CreatePipe(channel_handle, mode);
50 ChannelWin::~ChannelWin() {
51 Close();
54 void ChannelWin::Close() {
55 if (thread_check_.get())
56 DCHECK(thread_check_->CalledOnValidThread());
58 if (input_state_.is_pending || output_state_.is_pending)
59 CancelIo(pipe_.Get());
61 // Closing the handle at this point prevents us from issuing more requests
62 // form OnIOCompleted().
63 if (pipe_.IsValid())
64 pipe_.Close();
66 // Make sure all IO has completed.
67 base::Time start = base::Time::Now();
68 while (input_state_.is_pending || output_state_.is_pending) {
69 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE, this);
72 while (!output_queue_.empty()) {
73 Message* m = output_queue_.front();
74 output_queue_.pop();
75 delete m;
79 bool ChannelWin::Send(Message* message) {
80 DCHECK(thread_check_->CalledOnValidThread());
81 DVLOG(2) << "sending message @" << message << " on channel @" << this
82 << " with type " << message->type()
83 << " (" << output_queue_.size() << " in queue)";
85 #ifdef IPC_MESSAGE_LOG_ENABLED
86 Logging::GetInstance()->OnSendMessage(message, "");
87 #endif
89 message->TraceMessageBegin();
90 output_queue_.push(message);
91 // ensure waiting to write
92 if (!waiting_connect_) {
93 if (!output_state_.is_pending) {
94 if (!ProcessOutgoingMessages(NULL, 0))
95 return false;
99 return true;
102 base::ProcessId ChannelWin::GetPeerPID() const {
103 return peer_pid_;
106 base::ProcessId ChannelWin::GetSelfPID() const {
107 return GetCurrentProcessId();
110 // static
111 bool ChannelWin::IsNamedServerInitialized(
112 const std::string& channel_id) {
113 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
114 return true;
115 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
116 // connection.
117 return GetLastError() == ERROR_SEM_TIMEOUT;
120 ChannelWin::ReadState ChannelWin::ReadData(
121 char* buffer,
122 int buffer_len,
123 int* /* bytes_read */) {
124 if (!pipe_.IsValid())
125 return READ_FAILED;
127 DWORD bytes_read = 0;
128 BOOL ok = ReadFile(pipe_.Get(), buffer, buffer_len,
129 &bytes_read, &input_state_.context.overlapped);
130 if (!ok) {
131 DWORD err = GetLastError();
132 if (err == ERROR_IO_PENDING) {
133 input_state_.is_pending = true;
134 return READ_PENDING;
136 LOG(ERROR) << "pipe error: " << err;
137 return READ_FAILED;
140 // We could return READ_SUCCEEDED here. But the way that this code is
141 // structured we instead go back to the message loop. Our completion port
142 // will be signalled even in the "synchronously completed" state.
144 // This allows us to potentially process some outgoing messages and
145 // interleave other work on this thread when we're getting hammered with
146 // input messages. Potentially, this could be tuned to be more efficient
147 // with some testing.
148 input_state_.is_pending = true;
149 return READ_PENDING;
152 bool ChannelWin::WillDispatchInputMessage(Message* msg) {
153 // Make sure we get a hello when client validation is required.
154 if (validate_client_)
155 return IsHelloMessage(*msg);
156 return true;
159 void ChannelWin::HandleInternalMessage(const Message& msg) {
160 DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
161 // The hello message contains one parameter containing the PID.
162 PickleIterator it(msg);
163 int32 claimed_pid;
164 bool failed = !it.ReadInt(&claimed_pid);
166 if (!failed && validate_client_) {
167 int32 secret;
168 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
171 if (failed) {
172 NOTREACHED();
173 Close();
174 listener()->OnChannelError();
175 return;
178 peer_pid_ = claimed_pid;
179 // Validation completed.
180 validate_client_ = false;
181 listener()->OnChannelConnected(claimed_pid);
184 bool ChannelWin::DidEmptyInputBuffers() {
185 // We don't need to do anything here.
186 return true;
189 // static
190 const base::string16 ChannelWin::PipeName(
191 const std::string& channel_id, int32* secret) {
192 std::string name("\\\\.\\pipe\\chrome.");
194 // Prevent the shared secret from ending up in the pipe name.
195 size_t index = channel_id.find_first_of('\\');
196 if (index != std::string::npos) {
197 if (secret) // Retrieve the secret if asked for.
198 base::StringToInt(channel_id.substr(index + 1), secret);
199 return base::ASCIIToUTF16(name.append(channel_id.substr(0, index - 1)));
202 // This case is here to support predictable named pipes in tests.
203 if (secret)
204 *secret = 0;
205 return base::ASCIIToUTF16(name.append(channel_id));
208 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
209 Mode mode) {
210 DCHECK(!pipe_.IsValid());
211 base::string16 pipe_name;
212 // If we already have a valid pipe for channel just copy it.
213 if (channel_handle.pipe.handle) {
214 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
215 // favor of two independent entities (name/file), or it should be a move-
216 // only type with a base::File member. In any case, this code should not
217 // call DuplicateHandle.
218 DCHECK(channel_handle.name.empty());
219 pipe_name = L"Not Available"; // Just used for LOG
220 // Check that the given pipe confirms to the specified mode. We can
221 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
222 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
223 DWORD flags = 0;
224 GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
225 DCHECK(!(flags & PIPE_TYPE_MESSAGE));
226 if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
227 ((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
228 LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
229 return false;
231 HANDLE local_handle;
232 if (!DuplicateHandle(GetCurrentProcess(),
233 channel_handle.pipe.handle,
234 GetCurrentProcess(),
235 &local_handle,
237 FALSE,
238 DUPLICATE_SAME_ACCESS)) {
239 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
240 return false;
242 pipe_.Set(local_handle);
243 } else if (mode & MODE_SERVER_FLAG) {
244 DCHECK(!channel_handle.pipe.handle);
245 const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
246 FILE_FLAG_FIRST_PIPE_INSTANCE;
247 pipe_name = PipeName(channel_handle.name, &client_secret_);
248 validate_client_ = !!client_secret_;
249 pipe_.Set(CreateNamedPipeW(pipe_name.c_str(),
250 open_mode,
251 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
253 Channel::kReadBufferSize,
254 Channel::kReadBufferSize,
255 5000,
256 NULL));
257 } else if (mode & MODE_CLIENT_FLAG) {
258 DCHECK(!channel_handle.pipe.handle);
259 pipe_name = PipeName(channel_handle.name, &client_secret_);
260 pipe_.Set(CreateFileW(pipe_name.c_str(),
261 GENERIC_READ | GENERIC_WRITE,
263 NULL,
264 OPEN_EXISTING,
265 SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
266 FILE_FLAG_OVERLAPPED,
267 NULL));
268 } else {
269 NOTREACHED();
272 if (!pipe_.IsValid()) {
273 // If this process is being closed, the pipe may be gone already.
274 PLOG(WARNING) << "Unable to create pipe \"" << pipe_name << "\" in "
275 << (mode & MODE_SERVER_FLAG ? "server" : "client") << " mode";
276 return false;
279 // Create the Hello message to be sent when Connect is called
280 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
281 HELLO_MESSAGE_TYPE,
282 IPC::Message::PRIORITY_NORMAL));
284 // Don't send the secret to the untrusted process, and don't send a secret
285 // if the value is zero (for IPC backwards compatability).
286 int32 secret = validate_client_ ? 0 : client_secret_;
287 if (!m->WriteInt(GetCurrentProcessId()) ||
288 (secret && !m->WriteUInt32(secret))) {
289 pipe_.Close();
290 return false;
293 output_queue_.push(m.release());
294 return true;
297 bool ChannelWin::Connect() {
298 DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
300 if (!thread_check_.get())
301 thread_check_.reset(new base::ThreadChecker());
303 if (!pipe_.IsValid())
304 return false;
306 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_.Get(), this);
308 // Check to see if there is a client connected to our pipe...
309 if (waiting_connect_)
310 ProcessConnection();
312 if (!input_state_.is_pending) {
313 // Complete setup asynchronously. By not setting input_state_.is_pending
314 // to true, we indicate to OnIOCompleted that this is the special
315 // initialization signal.
316 base::MessageLoopForIO::current()->PostTask(
317 FROM_HERE,
318 base::Bind(&ChannelWin::OnIOCompleted,
319 weak_factory_.GetWeakPtr(),
320 &input_state_.context,
322 0));
325 if (!waiting_connect_)
326 ProcessOutgoingMessages(NULL, 0);
327 return true;
330 bool ChannelWin::ProcessConnection() {
331 DCHECK(thread_check_->CalledOnValidThread());
332 if (input_state_.is_pending)
333 input_state_.is_pending = false;
335 // Do we have a client connected to our pipe?
336 if (!pipe_.IsValid())
337 return false;
339 BOOL ok = ConnectNamedPipe(pipe_.Get(), &input_state_.context.overlapped);
340 DWORD err = GetLastError();
341 if (ok) {
342 // Uhm, the API documentation says that this function should never
343 // return success when used in overlapped mode.
344 NOTREACHED();
345 return false;
348 switch (err) {
349 case ERROR_IO_PENDING:
350 input_state_.is_pending = true;
351 break;
352 case ERROR_PIPE_CONNECTED:
353 waiting_connect_ = false;
354 break;
355 case ERROR_NO_DATA:
356 // The pipe is being closed.
357 return false;
358 default:
359 NOTREACHED();
360 return false;
363 return true;
366 bool ChannelWin::ProcessOutgoingMessages(
367 base::MessageLoopForIO::IOContext* context,
368 DWORD bytes_written) {
369 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
370 // no connection?
371 DCHECK(thread_check_->CalledOnValidThread());
373 if (output_state_.is_pending) {
374 DCHECK(context);
375 output_state_.is_pending = false;
376 if (!context || bytes_written == 0) {
377 DWORD err = GetLastError();
378 LOG(ERROR) << "pipe error: " << err;
379 return false;
381 // Message was sent.
382 CHECK(!output_queue_.empty());
383 Message* m = output_queue_.front();
384 output_queue_.pop();
385 delete m;
388 if (output_queue_.empty())
389 return true;
391 if (!pipe_.IsValid())
392 return false;
394 // Write to pipe...
395 Message* m = output_queue_.front();
396 DCHECK(m->size() <= INT_MAX);
397 BOOL ok = WriteFile(pipe_.Get(),
398 m->data(),
399 static_cast<uint32>(m->size()),
400 NULL,
401 &output_state_.context.overlapped);
402 if (!ok) {
403 DWORD write_error = GetLastError();
404 if (write_error == ERROR_IO_PENDING) {
405 output_state_.is_pending = true;
407 DVLOG(2) << "sent pending message @" << m << " on channel @" << this
408 << " with type " << m->type();
410 return true;
412 LOG(ERROR) << "pipe error: " << write_error;
413 return false;
416 DVLOG(2) << "sent message @" << m << " on channel @" << this
417 << " with type " << m->type();
419 output_state_.is_pending = true;
420 return true;
423 void ChannelWin::OnIOCompleted(
424 base::MessageLoopForIO::IOContext* context,
425 DWORD bytes_transfered,
426 DWORD error) {
427 bool ok = true;
428 DCHECK(thread_check_->CalledOnValidThread());
429 if (context == &input_state_.context) {
430 if (waiting_connect_) {
431 if (!ProcessConnection())
432 return;
433 // We may have some messages queued up to send...
434 if (!output_queue_.empty() && !output_state_.is_pending)
435 ProcessOutgoingMessages(NULL, 0);
436 if (input_state_.is_pending)
437 return;
438 // else, fall-through and look for incoming messages...
441 // We don't support recursion through OnMessageReceived yet!
442 DCHECK(!processing_incoming_);
443 base::AutoReset<bool> auto_reset_processing_incoming(
444 &processing_incoming_, true);
446 // Process the new data.
447 if (input_state_.is_pending) {
448 // This is the normal case for everything except the initialization step.
449 input_state_.is_pending = false;
450 if (!bytes_transfered)
451 ok = false;
452 else if (pipe_.IsValid())
453 ok = AsyncReadComplete(bytes_transfered);
454 } else {
455 DCHECK(!bytes_transfered);
458 // Request more data.
459 if (ok)
460 ok = ProcessIncomingMessages();
461 } else {
462 DCHECK(context == &output_state_.context);
463 CHECK(output_state_.is_pending);
464 ok = ProcessOutgoingMessages(context, bytes_transfered);
466 if (!ok && pipe_.IsValid()) {
467 // We don't want to re-enter Close().
468 Close();
469 listener()->OnChannelError();
473 //------------------------------------------------------------------------------
474 // Channel's methods
476 // static
477 scoped_ptr<Channel> Channel::Create(
478 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
479 return scoped_ptr<Channel>(
480 new ChannelWin(channel_handle, mode, listener));
483 // static
484 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
485 return ChannelWin::IsNamedServerInitialized(channel_id);
488 // static
489 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
490 // Windows pipes can be enumerated by low-privileged processes. So, we
491 // append a strong random value after the \ character. This value is not
492 // included in the pipe name, but sent as part of the client hello, to
493 // hijacking the pipe name to spoof the client.
495 std::string id = prefix;
496 if (!id.empty())
497 id.append(".");
499 int secret;
500 do { // Guarantee we get a non-zero value.
501 secret = base::RandInt(0, std::numeric_limits<int>::max());
502 } while (secret == 0);
504 id.append(GenerateUniqueRandomChannelID());
505 return id.append(base::StringPrintf("\\%d", secret));
508 } // namespace IPC