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