Lots of random cleanups, mostly for native_theme_win.cc:
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
blob9741dda05a13750f486d21f792f0c4aa6b3b7f65
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 {
26 enum DebugFlags {
27 INIT_DONE = 1 << 0,
28 CALLED_CONNECT = 1 << 1,
29 PENDING_CONNECT = 1 << 2,
30 CONNECT_COMPLETED = 1 << 3,
31 PIPE_CONNECTED = 1 << 4,
32 WRITE_MSG = 1 << 5,
33 READ_MSG = 1 << 6,
34 WRITE_COMPLETED = 1 << 7,
35 READ_COMPLETED = 1 << 8,
36 CLOSED = 1 << 9,
37 WAIT_FOR_READ = 1 << 10,
38 WAIT_FOR_WRITE = 1 << 11,
39 WAIT_FOR_READ_COMPLETE = 1 << 12,
40 WAIT_FOR_WRITE_COMPLETE = 1 << 13
43 } // namespace
45 namespace IPC {
47 ChannelWin::State::State(ChannelWin* channel) : is_pending(false) {
48 memset(&context.overlapped, 0, sizeof(context.overlapped));
49 context.handler = channel;
52 ChannelWin::State::~State() {
53 COMPILE_ASSERT(!offsetof(ChannelWin::State, context),
54 starts_with_io_context);
57 ChannelWin::ChannelWin(const IPC::ChannelHandle &channel_handle,
58 Mode mode, Listener* listener)
59 : ChannelReader(listener),
60 input_state_(this),
61 output_state_(this),
62 pipe_(INVALID_HANDLE_VALUE),
63 peer_pid_(base::kNullProcessId),
64 waiting_connect_(mode & MODE_SERVER_FLAG),
65 processing_incoming_(false),
66 weak_factory_(this),
67 validate_client_(false),
68 debug_flags_(0),
69 client_secret_(0) {
70 CreatePipe(channel_handle, mode);
73 ChannelWin::~ChannelWin() {
74 Close();
77 void ChannelWin::Close() {
78 if (thread_check_.get()) {
79 DCHECK(thread_check_->CalledOnValidThread());
81 debug_flags_ |= CLOSED;
83 if (input_state_.is_pending || output_state_.is_pending)
84 CancelIo(pipe_);
86 // Closing the handle at this point prevents us from issuing more requests
87 // form OnIOCompleted().
88 if (pipe_ != INVALID_HANDLE_VALUE) {
89 CloseHandle(pipe_);
90 pipe_ = INVALID_HANDLE_VALUE;
93 if (input_state_.is_pending)
94 debug_flags_ |= WAIT_FOR_READ;
96 if (output_state_.is_pending)
97 debug_flags_ |= WAIT_FOR_WRITE;
99 // Make sure all IO has completed.
100 base::Time start = base::Time::Now();
101 while (input_state_.is_pending || output_state_.is_pending) {
102 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE, this);
105 while (!output_queue_.empty()) {
106 Message* m = output_queue_.front();
107 output_queue_.pop();
108 delete m;
112 bool ChannelWin::Send(Message* message) {
113 DCHECK(thread_check_->CalledOnValidThread());
114 DVLOG(2) << "sending message @" << message << " on channel @" << this
115 << " with type " << message->type()
116 << " (" << output_queue_.size() << " in queue)";
118 #ifdef IPC_MESSAGE_LOG_ENABLED
119 Logging::GetInstance()->OnSendMessage(message, "");
120 #endif
122 message->TraceMessageBegin();
123 output_queue_.push(message);
124 // ensure waiting to write
125 if (!waiting_connect_) {
126 if (!output_state_.is_pending) {
127 if (!ProcessOutgoingMessages(NULL, 0))
128 return false;
132 return true;
135 base::ProcessId ChannelWin::GetPeerPID() const {
136 return peer_pid_;
139 // static
140 bool ChannelWin::IsNamedServerInitialized(
141 const std::string& channel_id) {
142 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
143 return true;
144 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
145 // connection.
146 return GetLastError() == ERROR_SEM_TIMEOUT;
149 ChannelWin::ReadState ChannelWin::ReadData(
150 char* buffer,
151 int buffer_len,
152 int* /* bytes_read */) {
153 if (INVALID_HANDLE_VALUE == pipe_)
154 return READ_FAILED;
156 debug_flags_ |= READ_MSG;
157 DWORD bytes_read = 0;
158 BOOL ok = ReadFile(pipe_, buffer, buffer_len,
159 &bytes_read, &input_state_.context.overlapped);
160 if (!ok) {
161 DWORD err = GetLastError();
162 if (err == ERROR_IO_PENDING) {
163 input_state_.is_pending = true;
164 return READ_PENDING;
166 LOG(ERROR) << "pipe error: " << err;
167 return READ_FAILED;
170 // We could return READ_SUCCEEDED here. But the way that this code is
171 // structured we instead go back to the message loop. Our completion port
172 // will be signalled even in the "synchronously completed" state.
174 // This allows us to potentially process some outgoing messages and
175 // interleave other work on this thread when we're getting hammered with
176 // input messages. Potentially, this could be tuned to be more efficient
177 // with some testing.
178 input_state_.is_pending = true;
179 return READ_PENDING;
182 bool ChannelWin::WillDispatchInputMessage(Message* msg) {
183 // Make sure we get a hello when client validation is required.
184 if (validate_client_)
185 return IsHelloMessage(*msg);
186 return true;
189 void ChannelWin::HandleInternalMessage(const Message& msg) {
190 DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
191 // The hello message contains one parameter containing the PID.
192 PickleIterator it(msg);
193 int32 claimed_pid;
194 bool failed = !it.ReadInt(&claimed_pid);
196 if (!failed && validate_client_) {
197 int32 secret;
198 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
201 if (failed) {
202 NOTREACHED();
203 Close();
204 listener()->OnChannelError();
205 return;
208 peer_pid_ = claimed_pid;
209 // Validation completed.
210 validate_client_ = false;
211 listener()->OnChannelConnected(claimed_pid);
214 bool ChannelWin::DidEmptyInputBuffers() {
215 // We don't need to do anything here.
216 return true;
219 // static
220 const base::string16 ChannelWin::PipeName(
221 const std::string& channel_id, int32* secret) {
222 std::string name("\\\\.\\pipe\\chrome.");
224 // Prevent the shared secret from ending up in the pipe name.
225 size_t index = channel_id.find_first_of('\\');
226 if (index != std::string::npos) {
227 if (secret) // Retrieve the secret if asked for.
228 base::StringToInt(channel_id.substr(index + 1), secret);
229 return base::ASCIIToWide(name.append(channel_id.substr(0, index - 1)));
232 // This case is here to support predictable named pipes in tests.
233 if (secret)
234 *secret = 0;
235 return base::ASCIIToWide(name.append(channel_id));
238 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
239 Mode mode) {
240 DCHECK_EQ(INVALID_HANDLE_VALUE, pipe_);
241 base::string16 pipe_name;
242 // If we already have a valid pipe for channel just copy it.
243 if (channel_handle.pipe.handle) {
244 DCHECK(channel_handle.name.empty());
245 pipe_name = L"Not Available"; // Just used for LOG
246 // Check that the given pipe confirms to the specified mode. We can
247 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
248 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
249 DWORD flags = 0;
250 GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
251 DCHECK(!(flags & PIPE_TYPE_MESSAGE));
252 if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
253 ((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
254 LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
255 return false;
257 if (!DuplicateHandle(GetCurrentProcess(),
258 channel_handle.pipe.handle,
259 GetCurrentProcess(),
260 &pipe_,
262 FALSE,
263 DUPLICATE_SAME_ACCESS)) {
264 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
265 return false;
267 } else if (mode & MODE_SERVER_FLAG) {
268 DCHECK(!channel_handle.pipe.handle);
269 const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
270 FILE_FLAG_FIRST_PIPE_INSTANCE;
271 pipe_name = PipeName(channel_handle.name, &client_secret_);
272 validate_client_ = !!client_secret_;
273 pipe_ = CreateNamedPipeW(pipe_name.c_str(),
274 open_mode,
275 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
277 Channel::kReadBufferSize,
278 Channel::kReadBufferSize,
279 5000,
280 NULL);
281 } else if (mode & MODE_CLIENT_FLAG) {
282 DCHECK(!channel_handle.pipe.handle);
283 pipe_name = PipeName(channel_handle.name, &client_secret_);
284 pipe_ = CreateFileW(pipe_name.c_str(),
285 GENERIC_READ | GENERIC_WRITE,
287 NULL,
288 OPEN_EXISTING,
289 SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION |
290 FILE_FLAG_OVERLAPPED,
291 NULL);
292 } else {
293 NOTREACHED();
296 if (pipe_ == INVALID_HANDLE_VALUE) {
297 // If this process is being closed, the pipe may be gone already.
298 PLOG(WARNING) << "Unable to create pipe \"" << pipe_name << "\" in "
299 << (mode & MODE_SERVER_FLAG ? "server" : "client") << " mode";
300 return false;
303 // Create the Hello message to be sent when Connect is called
304 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
305 HELLO_MESSAGE_TYPE,
306 IPC::Message::PRIORITY_NORMAL));
308 // Don't send the secret to the untrusted process, and don't send a secret
309 // if the value is zero (for IPC backwards compatability).
310 int32 secret = validate_client_ ? 0 : client_secret_;
311 if (!m->WriteInt(GetCurrentProcessId()) ||
312 (secret && !m->WriteUInt32(secret))) {
313 CloseHandle(pipe_);
314 pipe_ = INVALID_HANDLE_VALUE;
315 return false;
318 debug_flags_ |= INIT_DONE;
320 output_queue_.push(m.release());
321 return true;
324 bool ChannelWin::Connect() {
325 DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
327 if (!thread_check_.get())
328 thread_check_.reset(new base::ThreadChecker());
330 if (pipe_ == INVALID_HANDLE_VALUE)
331 return false;
333 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_, this);
335 // Check to see if there is a client connected to our pipe...
336 if (waiting_connect_)
337 ProcessConnection();
339 if (!input_state_.is_pending) {
340 // Complete setup asynchronously. By not setting input_state_.is_pending
341 // to true, we indicate to OnIOCompleted that this is the special
342 // initialization signal.
343 base::MessageLoopForIO::current()->PostTask(
344 FROM_HERE,
345 base::Bind(&ChannelWin::OnIOCompleted,
346 weak_factory_.GetWeakPtr(),
347 &input_state_.context,
349 0));
352 if (!waiting_connect_)
353 ProcessOutgoingMessages(NULL, 0);
354 return true;
357 bool ChannelWin::ProcessConnection() {
358 DCHECK(thread_check_->CalledOnValidThread());
359 if (input_state_.is_pending)
360 input_state_.is_pending = false;
362 // Do we have a client connected to our pipe?
363 if (INVALID_HANDLE_VALUE == pipe_)
364 return false;
366 BOOL ok = ConnectNamedPipe(pipe_, &input_state_.context.overlapped);
367 debug_flags_ |= CALLED_CONNECT;
369 DWORD err = GetLastError();
370 if (ok) {
371 // Uhm, the API documentation says that this function should never
372 // return success when used in overlapped mode.
373 NOTREACHED();
374 return false;
377 switch (err) {
378 case ERROR_IO_PENDING:
379 input_state_.is_pending = true;
380 debug_flags_ |= PENDING_CONNECT;
381 break;
382 case ERROR_PIPE_CONNECTED:
383 debug_flags_ |= PIPE_CONNECTED;
384 waiting_connect_ = false;
385 break;
386 case ERROR_NO_DATA:
387 // The pipe is being closed.
388 return false;
389 default:
390 NOTREACHED();
391 return false;
394 return true;
397 bool ChannelWin::ProcessOutgoingMessages(
398 base::MessageLoopForIO::IOContext* context,
399 DWORD bytes_written) {
400 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
401 // no connection?
402 DCHECK(thread_check_->CalledOnValidThread());
404 if (output_state_.is_pending) {
405 DCHECK(context);
406 output_state_.is_pending = false;
407 if (!context || bytes_written == 0) {
408 DWORD err = GetLastError();
409 LOG(ERROR) << "pipe error: " << err;
410 return false;
412 // Message was sent.
413 CHECK(!output_queue_.empty());
414 Message* m = output_queue_.front();
415 output_queue_.pop();
416 delete m;
419 if (output_queue_.empty())
420 return true;
422 if (INVALID_HANDLE_VALUE == pipe_)
423 return false;
425 // Write to pipe...
426 Message* m = output_queue_.front();
427 DCHECK(m->size() <= INT_MAX);
428 debug_flags_ |= WRITE_MSG;
429 BOOL ok = WriteFile(pipe_,
430 m->data(),
431 static_cast<int>(m->size()),
432 &bytes_written,
433 &output_state_.context.overlapped);
434 if (!ok) {
435 DWORD err = GetLastError();
436 if (err == ERROR_IO_PENDING) {
437 output_state_.is_pending = true;
439 DVLOG(2) << "sent pending message @" << m << " on channel @" << this
440 << " with type " << m->type();
442 return true;
444 LOG(ERROR) << "pipe error: " << err;
445 return false;
448 DVLOG(2) << "sent message @" << m << " on channel @" << this
449 << " with type " << m->type();
451 output_state_.is_pending = true;
452 return true;
455 void ChannelWin::OnIOCompleted(
456 base::MessageLoopForIO::IOContext* context,
457 DWORD bytes_transfered,
458 DWORD error) {
459 bool ok = true;
460 DCHECK(thread_check_->CalledOnValidThread());
461 if (context == &input_state_.context) {
462 if (waiting_connect_) {
463 debug_flags_ |= CONNECT_COMPLETED;
464 if (!ProcessConnection())
465 return;
466 // We may have some messages queued up to send...
467 if (!output_queue_.empty() && !output_state_.is_pending)
468 ProcessOutgoingMessages(NULL, 0);
469 if (input_state_.is_pending)
470 return;
471 // else, fall-through and look for incoming messages...
474 // We don't support recursion through OnMessageReceived yet!
475 DCHECK(!processing_incoming_);
476 base::AutoReset<bool> auto_reset_processing_incoming(
477 &processing_incoming_, true);
479 // Process the new data.
480 if (input_state_.is_pending) {
481 // This is the normal case for everything except the initialization step.
482 debug_flags_ |= READ_COMPLETED;
483 if (debug_flags_ & WAIT_FOR_READ) {
484 CHECK(!(debug_flags_ & WAIT_FOR_READ_COMPLETE));
485 debug_flags_ |= WAIT_FOR_READ_COMPLETE;
487 input_state_.is_pending = false;
488 if (!bytes_transfered)
489 ok = false;
490 else if (pipe_ != INVALID_HANDLE_VALUE)
491 ok = AsyncReadComplete(bytes_transfered);
492 } else {
493 DCHECK(!bytes_transfered);
496 // Request more data.
497 if (ok)
498 ok = ProcessIncomingMessages();
499 } else {
500 DCHECK(context == &output_state_.context);
501 debug_flags_ |= WRITE_COMPLETED;
502 if (debug_flags_ & WAIT_FOR_WRITE) {
503 CHECK(!(debug_flags_ & WAIT_FOR_WRITE_COMPLETE));
504 debug_flags_ |= WAIT_FOR_WRITE_COMPLETE;
506 ok = ProcessOutgoingMessages(context, bytes_transfered);
508 if (!ok && INVALID_HANDLE_VALUE != pipe_) {
509 // We don't want to re-enter Close().
510 Close();
511 listener()->OnChannelError();
515 //------------------------------------------------------------------------------
516 // Channel's methods
518 // static
519 scoped_ptr<Channel> Channel::Create(
520 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
521 return scoped_ptr<Channel>(
522 new ChannelWin(channel_handle, mode, listener));
525 // static
526 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
527 return ChannelWin::IsNamedServerInitialized(channel_id);
530 // static
531 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
532 // Windows pipes can be enumerated by low-privileged processes. So, we
533 // append a strong random value after the \ character. This value is not
534 // included in the pipe name, but sent as part of the client hello, to
535 // hijacking the pipe name to spoof the client.
537 std::string id = prefix;
538 if (!id.empty())
539 id.append(".");
541 int secret;
542 do { // Guarantee we get a non-zero value.
543 secret = base::RandInt(0, std::numeric_limits<int>::max());
544 } while (secret == 0);
546 id.append(GenerateUniqueRandomChannelID());
547 return id.append(base::StringPrintf("\\%d", secret));
550 } // namespace IPC